001package jmri.server.json.time;
002
003import com.fasterxml.jackson.databind.JsonNode;
004import java.beans.PropertyChangeEvent;
005import java.beans.PropertyChangeListener;
006import java.io.IOException;
007import java.util.Date;
008import javax.servlet.http.HttpServletResponse;
009import jmri.InstanceManager;
010import jmri.JmriException;
011import jmri.Timebase;
012import jmri.server.json.JsonConnection;
013import jmri.server.json.JsonException;
014import jmri.server.json.JsonRequest;
015import jmri.server.json.JsonSocketService;
016
017/**
018 *
019 * @author Randall Wood
020 */
021public class JsonTimeSocketService extends JsonSocketService<JsonTimeHttpService> implements PropertyChangeListener {
022
023    private boolean listening = false;
024
025    public JsonTimeSocketService(JsonConnection connection) {
026        this(connection, new JsonTimeHttpService(connection.getObjectMapper()));
027    }
028
029    // package protected
030    JsonTimeSocketService(JsonConnection connection, JsonTimeHttpService service) {
031        super(connection, service);
032    }
033
034    @Override
035    public void onMessage(String type, JsonNode data, JsonRequest request) throws IOException, JmriException, JsonException {
036        if (!listening) {
037            Timebase manager = InstanceManager.getDefault(Timebase.class);
038            manager.addPropertyChangeListener(this);
039            listening = true;
040        }
041        connection.sendMessage(service.doPost(type, null, data, request), request.id);
042    }
043
044    @Override
045    public void onList(String type, JsonNode data, JsonRequest request) throws JsonException {
046        throw new JsonException(HttpServletResponse.SC_BAD_REQUEST, Bundle.getMessage(request.locale, "UnlistableService", type), request.id);
047    }
048
049    @Override
050    public void onClose() {
051        if (listening) {
052            Timebase manager = InstanceManager.getDefault(Timebase.class);
053            manager.removePropertyChangeListener(this);
054        }
055    }
056
057    @Override
058    public void propertyChange(PropertyChangeEvent evt) {
059        try {
060            Timebase manager = InstanceManager.getDefault(Timebase.class);
061            Date time = manager.getTime();
062            if (evt.getPropertyName().equals("time")) {
063                time = (Date) evt.getNewValue();
064            }
065            connection.sendMessage(service.doGet(manager, time, 0), 0);
066        } catch (IOException ex) {
067            onClose();
068        }
069    }
070
071}