Search in sources :

Example 46 with JmriException

use of jmri.JmriException in project JMRI by JMRI.

the class JsonRouteSocketServiceTest method testOnMessageChange.

public void testOnMessageChange() {
    // the route state on a sensorless route
    try {
        JsonMockConnection connection = new JsonMockConnection((DataOutputStream) null);
        JsonNode message;
        JsonRouteSocketService service = new JsonRouteSocketService(connection);
        RouteManager manager = InstanceManager.getDefault(RouteManager.class);
        Route route1 = manager.provideRoute("IR1", "Route1");
        Sensor sensor1 = InstanceManager.getDefault(SensorManager.class).provideSensor("IS1");
        Turnout turnout1 = InstanceManager.getDefault(TurnoutManager.class).provideTurnout("IT1");
        turnout1.setCommandedState(Turnout.CLOSED);
        route1.setTurnoutsAlignedSensor(sensor1.getSystemName());
        Assert.assertTrue(route1.addOutputTurnout(turnout1.getSystemName(), Turnout.THROWN));
        route1.activateRoute();
        Assert.assertNotNull(route1.getTurnoutsAlgdSensor());
        // Route ACTIVE - becomes ACTIVE
        message = connection.getObjectMapper().createObjectNode().put(JSON.NAME, "IR1").put(JSON.STATE, JSON.ACTIVE);
        service.onMessage(JsonRouteServiceFactory.ROUTE, message, Locale.ENGLISH);
        JUnitUtil.waitFor(() -> {
            return route1.getState() == Sensor.ACTIVE;
        }, "Route to activate");
        Assert.assertEquals(Sensor.ACTIVE, route1.getState());
        // Route INACTIVE - remains ACTIVE
        message = connection.getObjectMapper().createObjectNode().put(JSON.NAME, "IR1").put(JSON.STATE, JSON.INACTIVE);
        service.onMessage(JsonRouteServiceFactory.ROUTE, message, Locale.ENGLISH);
        Assert.assertEquals(Sensor.ACTIVE, route1.getState());
        // Route UNKNOWN - remains ACTIVE
        message = connection.getObjectMapper().createObjectNode().put(JSON.NAME, "IR1").put(JSON.STATE, JSON.UNKNOWN);
        service.onMessage(JsonRouteServiceFactory.ROUTE, message, Locale.ENGLISH);
        JUnitUtil.waitFor(() -> {
            return route1.getState() == Sensor.ACTIVE;
        }, "Route to activate");
        Assert.assertEquals(Sensor.ACTIVE, route1.getState());
        // Route TOGGLE - remains ACTIVE
        message = connection.getObjectMapper().createObjectNode().put(JSON.NAME, "IR1").put(JSON.STATE, JSON.TOGGLE);
        service.onMessage(JsonRouteServiceFactory.ROUTE, message, Locale.ENGLISH);
        JUnitUtil.waitFor(() -> {
            return route1.getState() == Sensor.ACTIVE;
        }, "Route to activate");
        Assert.assertEquals(Sensor.ACTIVE, route1.getState());
        // Route TOGGLE - becomes ACTIVE
        sensor1.setKnownState(Sensor.INACTIVE);
        message = connection.getObjectMapper().createObjectNode().put(JSON.NAME, "IR1").put(JSON.STATE, JSON.TOGGLE);
        service.onMessage(JsonRouteServiceFactory.ROUTE, message, Locale.ENGLISH);
        JUnitUtil.waitFor(() -> {
            return route1.getState() == Sensor.ACTIVE;
        }, "Route to activate");
        Assert.assertEquals(Sensor.ACTIVE, route1.getState());
        // Route Invalid State
        // invalid state
        message = connection.getObjectMapper().createObjectNode().put(JSON.NAME, "IR1").put(JSON.STATE, 42);
        JsonException exception = null;
        try {
            service.onMessage(JsonRouteServiceFactory.ROUTE, message, Locale.ENGLISH);
        } catch (JsonException ex) {
            exception = ex;
        }
        Assert.assertEquals(Sensor.ACTIVE, route1.getState());
        Assert.assertNotNull(exception);
        Assert.assertEquals(HttpServletResponse.SC_BAD_REQUEST, exception.getCode());
    } catch (IOException | JmriException | JsonException ex) {
        Assert.fail(ex.getMessage());
    }
}
Also used : JsonException(jmri.server.json.JsonException) JmriException(jmri.JmriException) JsonNode(com.fasterxml.jackson.databind.JsonNode) IOException(java.io.IOException) TurnoutManager(jmri.TurnoutManager) SensorManager(jmri.SensorManager) JsonMockConnection(jmri.server.json.JsonMockConnection) Turnout(jmri.Turnout) Route(jmri.Route) RouteManager(jmri.RouteManager) Sensor(jmri.Sensor)

Example 47 with JmriException

use of jmri.JmriException in project JMRI by JMRI.

the class LayoutBlockConnectivityTools method discoverValidBeanPairs.

/**
     * Discovers valid pairs of beans type T assigned to a layout editor. If no
     * bean type is provided, then either SignalMasts or Sensors are discovered
     * If no editor is provided, then all editors are considered
     *
     * @param pathMethod Determine whether or not we should reject pairs if
     *                   there are other beans in the way. Constant values of
     *                   NONE, ANY, MASTTOMAST, HEADTOHEAD
     */
public Hashtable<NamedBean, ArrayList<NamedBean>> discoverValidBeanPairs(LayoutEditor editor, Class<?> T, int pathMethod) {
    LayoutBlockManager lbm = InstanceManager.getDefault(LayoutBlockManager.class);
    Hashtable<NamedBean, ArrayList<NamedBean>> retPairs = new Hashtable<NamedBean, ArrayList<NamedBean>>();
    ArrayList<FacingProtecting> beanList = generateBlocksWithBeans(editor, T);
    for (FacingProtecting fp : beanList) {
        for (Block block : fp.getProtectingBlocks()) {
            if (log.isDebugEnabled()) {
                try {
                    log.debug("\nSource " + fp.getBean().getDisplayName());
                    log.debug("facing " + fp.getFacing().getDisplayName());
                    log.debug("protecting " + block.getDisplayName());
                } catch (java.lang.NullPointerException e) {
                //Can be considered normal if the signalmast is assigned to an end bumper.
                }
            }
            LayoutBlock lFacing = lbm.getLayoutBlock(fp.getFacing());
            LayoutBlock lProtecting = lbm.getLayoutBlock(block);
            NamedBean source = fp.getBean();
            try {
                retPairs.put(source, discoverPairDest(source, lProtecting, lFacing, beanList, pathMethod));
            } catch (JmriException ex) {
                log.error(ex.toString());
            }
        }
    }
    return retPairs;
}
Also used : NamedBean(jmri.NamedBean) Hashtable(java.util.Hashtable) ArrayList(java.util.ArrayList) Block(jmri.Block) JmriException(jmri.JmriException)

Example 48 with JmriException

use of jmri.JmriException in project JMRI by JMRI.

the class AppsBase method setAndLoadPreferenceFile.

/**
     * Invoked to load the preferences information, and in the process
     * configure the system.
     * The high-level steps are:
     *<ul>
     *  <li>Locate the preferences file based through
     *      {@link FileUtil#getFile(String)}
     *  <li>See if the preferences file exists, and handle it if it doesn't
     *  <li>Obtain a {@link jmri.ConfigureManager} from the {@link jmri.InstanceManager}
     *  <li>Ask that ConfigureManager to load the file, in the process loading information into existing and new managers.
     *  <li>Do any deferred loads that are needed
     *  <li>If needed, migrate older formats
     *</ul>
     * (There's additional handling for shared configurations)
     */
protected void setAndLoadPreferenceFile() {
    FileUtil.createDirectory(FileUtil.getUserFilesPath());
    final File file;
    File sharedConfig = null;
    try {
        sharedConfig = FileUtil.getFile(FileUtil.PROFILE + Profile.SHARED_CONFIG);
        if (!sharedConfig.canRead()) {
            sharedConfig = null;
        }
    } catch (FileNotFoundException ex) {
    // ignore - this only means that sharedConfig does not exist.
    }
    if (sharedConfig != null) {
        file = sharedConfig;
    } else if (!new File(getConfigFileName()).isAbsolute()) {
        // must be relative, but we want it to 
        // be relative to the preferences directory
        file = new File(FileUtil.getUserFilesPath() + getConfigFileName());
    } else {
        file = new File(getConfigFileName());
    }
    // don't try to load if doesn't exist, but mark as not OK
    if (!file.exists()) {
        preferenceFileExists = false;
        configOK = false;
        log.info("No pre-existing config file found, searched for '" + file.getPath() + "'");
        return;
    }
    preferenceFileExists = true;
    try {
        ConfigureManager cm = InstanceManager.getNullableDefault(jmri.ConfigureManager.class);
        if (cm != null) {
            configOK = cm.load(file);
        } else {
            configOK = false;
        }
        log.debug("end load config file {}, OK={}", file.getName(), configOK);
    } catch (JmriException e) {
        configOK = false;
    }
    if (sharedConfig != null) {
        // sharedConfigs do not need deferred loads
        configDeferredLoadOK = true;
    } else if (SwingUtilities.isEventDispatchThread()) {
        // To avoid possible locks, deferred load should be
        // performed on the Swing thread
        configDeferredLoadOK = doDeferredLoad(file);
    } else {
        try {
            // Use invokeAndWait method as we don't want to
            // return until deferred load is completed
            SwingUtilities.invokeAndWait(() -> {
                configDeferredLoadOK = doDeferredLoad(file);
            });
        } catch (InterruptedException | InvocationTargetException ex) {
            log.error("Exception creating system console frame: " + ex);
        }
    }
    if (sharedConfig == null && configOK == true && configDeferredLoadOK == true) {
        log.info("Migrating preferences to new format...");
        // migrate preferences
        InstanceManager.getOptionalDefault(TabbedPreferences.class).ifPresent(tp -> {
            tp.init();
            tp.saveContents();
            InstanceManager.getOptionalDefault(ConfigureManager.class).ifPresent(cm -> {
                cm.storePrefs();
            });
            log.info("Preferences have been migrated to new format.");
            log.info("New preferences format will be used after JMRI is restarted.");
        });
    }
}
Also used : ConfigureManager(jmri.ConfigureManager) FileNotFoundException(java.io.FileNotFoundException) JmriException(jmri.JmriException) BlockValueFile(jmri.jmrit.display.layoutEditor.BlockValueFile) File(java.io.File) TabbedPreferences(apps.gui3.TabbedPreferences)

Example 49 with JmriException

use of jmri.JmriException in project JMRI by JMRI.

the class AppsBase method doDeferredLoad.

//abstract protected void addToActionModel();
private boolean doDeferredLoad(File file) {
    boolean result;
    log.debug("start deferred load from config file {}", file.getName());
    try {
        ConfigureManager cm = InstanceManager.getNullableDefault(jmri.ConfigureManager.class);
        if (cm != null) {
            result = cm.loadDeferred(file);
        } else {
            log.error("Failed to get default configure manager");
            result = false;
        }
    } catch (JmriException e) {
        log.error("Unhandled problem loading deferred configuration: " + e);
        result = false;
    }
    log.debug("end deferred load from config file {}, OK={}", file.getName(), result);
    return result;
}
Also used : ConfigureManager(jmri.ConfigureManager) JmriException(jmri.JmriException)

Example 50 with JmriException

use of jmri.JmriException in project JMRI by JMRI.

the class AbstractActionModel method performAction.

@Override
public void performAction() throws JmriException {
    log.debug("Invoke Action from {}", className);
    try {
        Action action = (Action) Class.forName(className).newInstance();
        if (SystemConnectionAction.class.isAssignableFrom(action.getClass())) {
            SystemConnectionMemo memo = ConnectionNameFromSystemName.getSystemConnectionMemoFromSystemPrefix(this.getSystemPrefix());
            if (memo != null) {
                ((SystemConnectionAction) action).setSystemConnectionMemo(memo);
            } else {
                log.warn("Connection \"{}\" does not exist and cannot be assigned to action {}\nThis warning can be silenced by configuring the connection associated with the startup action.", this.getSystemPrefix(), className);
            }
        }
        this.performAction(action);
    } catch (ClassNotFoundException ex) {
        log.error("Could not find specified class: {}", className);
    } catch (IllegalAccessException ex) {
        log.error("Unexpected access exception for class: {}", className, ex);
        throw new JmriException(ex);
    } catch (InstantiationException ex) {
        log.error("Could not instantiate specified class: {}", className, ex);
        throw new JmriException(ex);
    } catch (Exception ex) {
        log.error("Error while performing startup action for class: {}", className, ex);
        throw new JmriException(ex);
    }
}
Also used : SystemConnectionAction(jmri.jmrix.swing.SystemConnectionAction) Action(javax.swing.Action) SystemConnectionMemo(jmri.jmrix.SystemConnectionMemo) JmriException(jmri.JmriException) SystemConnectionAction(jmri.jmrix.swing.SystemConnectionAction) JmriException(jmri.JmriException)

Aggregations

JmriException (jmri.JmriException)80 Sensor (jmri.Sensor)22 JsonException (jmri.server.json.JsonException)22 IOException (java.io.IOException)20 JsonNode (com.fasterxml.jackson.databind.JsonNode)19 JsonMockConnection (jmri.server.json.JsonMockConnection)18 ArrayList (java.util.ArrayList)10 NamedBean (jmri.NamedBean)10 Turnout (jmri.Turnout)10 Test (org.junit.Test)7 SignalMast (jmri.SignalMast)6 ConfigureManager (jmri.ConfigureManager)5 SensorManager (jmri.SensorManager)5 File (java.io.File)4 PowerManager (jmri.PowerManager)4 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)3 Light (jmri.Light)3 SignalHead (jmri.SignalHead)3 FileNotFoundException (java.io.FileNotFoundException)2 Hashtable (java.util.Hashtable)2