001package jmri.server.json.power;
002
003import static jmri.server.json.JSON.GET;
004import static jmri.server.json.JSON.NAME;
005import static jmri.server.json.power.JsonPowerServiceFactory.POWER;
006
007import com.fasterxml.jackson.databind.JsonNode;
008import java.beans.PropertyChangeEvent;
009import java.beans.PropertyChangeListener;
010import java.io.IOException;
011import jmri.InstanceManager;
012import jmri.JmriException;
013import jmri.PowerManager;
014import jmri.server.json.JsonConnection;
015import jmri.server.json.JsonException;
016import jmri.server.json.JsonRequest;
017import jmri.server.json.JsonSocketService;
018
019/**
020 *
021 * @author Randall Wood
022 */
023public class JsonPowerSocketService extends JsonSocketService<JsonPowerHttpService> implements PropertyChangeListener {
024
025    private boolean listening = false;
026
027    public JsonPowerSocketService(JsonConnection connection) {
028        this(connection, new JsonPowerHttpService(connection.getObjectMapper()));
029    }
030
031    protected JsonPowerSocketService(JsonConnection connection, JsonPowerHttpService service) {
032        super(connection, service);
033    }
034
035    @Override
036    public void onMessage(String type, JsonNode data, JsonRequest request) throws IOException, JmriException, JsonException {
037        addListeners();
038        connection.sendMessage(service.doPost(type, data.path(NAME).asText(), data, request), request.id);
039    }
040
041    @Override
042    public void onList(String type, JsonNode data, JsonRequest request) throws JsonException, IOException {
043        addListeners();
044        connection.sendMessage(service.doGetList(type, data, request), request.id);
045    }
046
047    private void addListeners() {
048        if (!listening) {
049            InstanceManager.getList(PowerManager.class).forEach(manager -> manager.addPropertyChangeListener(this));
050            listening = true;
051        }
052    }
053
054    @Override
055    public void propertyChange(PropertyChangeEvent evt) {
056        try {
057            try {
058                String name = ((PowerManager) evt.getSource()).getUserName();
059                connection.sendMessage(service.doGet(POWER, name, connection.getObjectMapper().createObjectNode(), new JsonRequest(connection.getLocale(), connection.getVersion(), GET, 0)), 0);
060            } catch (JsonException ex) {
061                connection.sendMessage(ex.getJsonMessage(), 0);
062            }
063        } catch (IOException ex) {
064            // do nothing - we can only silently fail at this point
065        }
066    }
067
068    @Override
069    public void onClose() {
070        InstanceManager.getList(PowerManager.class).forEach(manager -> manager.removePropertyChangeListener(JsonPowerSocketService.this));
071    }
072
073}