Search in sources :

Example 16 with JDOMException

use of org.jdom2.JDOMException in project JMRI by JMRI.

the class ConfigXmlManager method loadOnSwingThread.

private boolean loadOnSwingThread(URL url, boolean registerDeferred) throws JmriConfigureXmlException {
    boolean result = true;
    Element root = null;
    /* We will put all the elements into a load list, along with the load order
         As XML files prior to 2.13.1 had no order to the store, beans would be stored/loaded
         before beans that they were dependant upon had been stored/loaded
         */
    Map<Element, Integer> loadlist = Collections.synchronizedMap(new LinkedHashMap<>());
    try {
        setValidate(validate);
        root = super.rootFromURL(url);
        // get the objects to load
        List<Element> items = root.getChildren();
        for (int i = 0; i < items.size(); i++) {
            //Put things into an ordered list
            Element item = items.get(i);
            if (item.getAttribute("class") == null) {
                // this is an element that we're not meant to read
                log.debug("skipping {}", item);
                continue;
            }
            String adapterName = item.getAttribute("class").getValue();
            if (log.isDebugEnabled()) {
                log.debug("attempt to get adapter {} for {}", adapterName, item);
            }
            adapterName = currentClassName(adapterName);
            XmlAdapter adapter = (XmlAdapter) Class.forName(adapterName).newInstance();
            int order = adapter.loadOrder();
            log.debug("add {} to load list with order id of {}", item, order);
            loadlist.put(item, order);
        }
        ArrayList<Map.Entry<Element, Integer>> l = new ArrayList<>(loadlist.entrySet());
        Collections.sort(l, (Map.Entry<Element, Integer> o1, Map.Entry<Element, Integer> o2) -> o1.getValue().compareTo(o2.getValue()));
        for (int i = 0; i < l.size(); i++) {
            Element item = l.get(i).getKey();
            String adapterName = item.getAttribute("class").getValue();
            adapterName = currentClassName(adapterName);
            if (log.isDebugEnabled()) {
                log.debug("load " + item + " via " + adapterName);
            }
            XmlAdapter adapter = null;
            try {
                adapter = (XmlAdapter) Class.forName(adapterName).newInstance();
                // and do it
                if (adapter.loadDeferred() && registerDeferred) {
                    // register in the list for deferred load
                    loadDeferredList.add(item);
                    if (log.isDebugEnabled()) {
                        log.debug("deferred load registered for " + item + " " + adapterName);
                    }
                } else {
                    boolean loadStatus = adapter.load(item, item);
                    if (log.isDebugEnabled()) {
                        log.debug("load status for " + item + " " + adapterName + " is " + loadStatus);
                    }
                    // if any adaptor load fails, then the entire load has failed
                    if (!loadStatus) {
                        result = false;
                    }
                }
            } catch (Exception e) {
                creationErrorEncountered(adapter, "load(" + url.getFile() + ")", "Unexpected error (Exception)", null, null, e);
                // keep going, but return false to signal problem
                result = false;
            } catch (Throwable et) {
                creationErrorEncountered(adapter, "in load(" + url.getFile() + ")", "Unexpected error (Throwable)", null, null, et);
                // keep going, but return false to signal problem
                result = false;
            }
        }
    } catch (java.io.FileNotFoundException e1) {
        // this returns false to indicate un-success, but not enough
        // of an error to require a message
        creationErrorEncountered(null, "opening file " + url.getFile(), "File not found", null, null, e1);
        result = false;
    } catch (org.jdom2.JDOMException e) {
        creationErrorEncountered(null, "parsing file " + url.getFile(), "Parse error", null, null, e);
        result = false;
    } catch (java.io.IOException e) {
        creationErrorEncountered(null, "loading from file " + url.getFile(), "IOException", null, null, e);
        result = false;
    } catch (ClassNotFoundException e) {
        creationErrorEncountered(null, "loading from file " + url.getFile(), "ClassNotFoundException", null, null, e);
        result = false;
    } catch (InstantiationException e) {
        creationErrorEncountered(null, "loading from file " + url.getFile(), "InstantiationException", null, null, e);
        result = false;
    } catch (IllegalAccessException e) {
        creationErrorEncountered(null, "loading from file " + url.getFile(), "IllegalAccessException", null, null, e);
        result = false;
    } finally {
        // no matter what, close error reporting
        handler.done();
    }
    // loading complete, as far as it got, make history entry
    FileHistory r = InstanceManager.getNullableDefault(FileHistory.class);
    if (r != null) {
        FileHistory included = null;
        if (root != null) {
            Element filehistory = root.getChild("filehistory");
            if (filehistory != null) {
                included = jmri.jmrit.revhistory.configurexml.FileHistoryXml.loadFileHistory(filehistory);
            }
        }
        r.addOperation((result ? "Load OK" : "Load with errors"), url.getFile(), included);
    } else {
        log.info("Not recording file history");
    }
    return result;
}
Also used : Element(org.jdom2.Element) ArrayList(java.util.ArrayList) InvocationTargetException(java.lang.reflect.InvocationTargetException) FileHistory(jmri.jmrit.revhistory.FileHistory)

Example 17 with JDOMException

use of org.jdom2.JDOMException in project JMRI by JMRI.

the class SignalSpeedMap method loadRoot.

public void loadRoot(@Nonnull Element root) {
    try {
        Element e = root.getChild("interpretation");
        String sval = e.getText().toUpperCase();
        switch(sval) {
            case "PERCENTNORMAL":
                _interpretation = PERCENT_NORMAL;
                break;
            case "PERCENTTHROTTLE":
                _interpretation = PERCENT_THROTTLE;
                break;
            default:
                throw new JDOMException("invalid content for interpretation: " + sval);
        }
        log.debug("_interpretation= {}", _interpretation);
        e = root.getChild("msPerIncrement");
        _sStepDelay = 1000;
        try {
            _sStepDelay = Integer.parseInt(e.getText());
        } catch (NumberFormatException nfe) {
            throw new JDOMException("invalid content for msPerIncrement: " + e.getText());
        }
        if (_sStepDelay < 200) {
            _sStepDelay = 200;
            log.warn("\"msPerIncrement\" must be at least 200 milliseconds.");
        }
        log.debug("_sStepDelay = {}", _sStepDelay);
        e = root.getChild("stepsPerIncrement");
        try {
            _numSteps = Integer.parseInt(e.getText());
        } catch (NumberFormatException nfe) {
            throw new JDOMException("invalid content for stepsPerIncrement: " + e.getText());
        }
        if (_numSteps < 1) {
            _numSteps = 1;
        }
        List<Element> list = root.getChild("aspectSpeeds").getChildren();
        _table.clear();
        for (int i = 0; i < list.size(); i++) {
            String name = list.get(i).getName();
            Float speed;
            try {
                speed = Float.valueOf(list.get(i).getText());
            } catch (NumberFormatException nfe) {
                log.error("invalid content for {} = {}", name, list.get(i).getText());
                throw new JDOMException("invalid content for " + name + " = " + list.get(i).getText());
            }
            log.debug("Add {}, {} to AspectSpeed Table", name, speed);
            _table.put(name, speed);
        }
        synchronized (this._headTable) {
            _headTable.clear();
            List<Element> l = root.getChild("appearanceSpeeds").getChildren();
            for (int i = 0; i < l.size(); i++) {
                String name = l.get(i).getName();
                String speed = l.get(i).getText();
                _headTable.put(Bundle.getMessage(name), speed);
                log.debug("Add {}={}, {} to AppearanceSpeed Table", name, Bundle.getMessage(name), speed);
            }
        }
    } catch (org.jdom2.JDOMException e) {
        log.error("error reading speed map elements due to: {}", e);
    }
}
Also used : JDOMException(org.jdom2.JDOMException) Element(org.jdom2.Element) JDOMException(org.jdom2.JDOMException)

Example 18 with JDOMException

use of org.jdom2.JDOMException in project JMRI by JMRI.

the class SignalSpeedMap method loadMap.

void loadMap() {
    URL path = FileUtil.findURL("signalSpeeds.xml", new String[] { "", "xml/signals" });
    jmri.jmrit.XmlFile xf = new jmri.jmrit.XmlFile() {
    };
    try {
        loadRoot(xf.rootFromURL(path));
    } catch (java.io.FileNotFoundException e) {
        log.warn("signalSpeeds file ({}) doesn't exist in XmlFile search path.", path);
        throw new IllegalArgumentException("signalSpeeds file (" + path + ") doesn't exist in XmlFile search path.");
    } catch (org.jdom2.JDOMException | java.io.IOException e) {
        log.error("error reading file \"{}\" due to: {}", path, e);
    }
}
Also used : JDOMException(org.jdom2.JDOMException) URL(java.net.URL)

Example 19 with JDOMException

use of org.jdom2.JDOMException in project JMRI by JMRI.

the class AbstractServerPreferences method openFile.

public final void openFile(String fileName) {
    this.fileName = fileName;
    AbstractServerPreferencesXml prefsXml = new AbstractServerPreferences.AbstractServerPreferencesXml();
    File file = new File(this.fileName);
    Element root;
    try {
        root = prefsXml.rootFromFile(file);
    } catch (java.io.FileNotFoundException ea) {
        log.info("Could not find Server preferences file.  Normal if preferences have not been saved before.");
        root = null;
    } catch (IOException | JDOMException eb) {
        log.error("Exception while loading server preferences: {}", eb.getLocalizedMessage());
        root = null;
    }
    if (root != null) {
        this.load(root);
    }
}
Also used : Element(org.jdom2.Element) IOException(java.io.IOException) JDOMException(org.jdom2.JDOMException) File(java.io.File) XmlFile(jmri.jmrit.XmlFile)

Example 20 with JDOMException

use of org.jdom2.JDOMException in project JMRI by JMRI.

the class AddSignalMastPanel method loadMastDefinitions.

void loadMastDefinitions() {
    // need to remove itemListener before addItem() or item event will occur
    if (mastBox.getItemListeners().length > 0) {
        // should this be a while loop?
        mastBox.removeItemListener(mastBox.getItemListeners()[0]);
    }
    mastBox.removeAllItems();
    try {
        mastNames = new ArrayList<File>();
        SignalSystemManager man = InstanceManager.getDefault(jmri.SignalSystemManager.class);
        // get the signals system name from the user name in combo box
        String u = (String) sigSysBox.getSelectedItem();
        sigsysname = man.getByUserName(u).getSystemName();
        map = new HashMap<String, Integer>();
        // do file IO to get all the appearances
        // gather all the appearance files
        //Look for the default system defined ones first
        URL path = FileUtil.findURL("xml/signals/" + sigsysname, FileUtil.Location.INSTALLED);
        if (path != null) {
            File[] apps = new File(path.toURI()).listFiles();
            for (File app : apps) {
                if (app.getName().startsWith("appearance") && app.getName().endsWith(".xml")) {
                    log.debug("   found file: " + app.getName());
                    // load it and get name
                    mastNames.add(app);
                    jmri.jmrit.XmlFile xf = new jmri.jmrit.XmlFile() {
                    };
                    Element root = xf.rootFromFile(app);
                    String name = root.getChild("name").getText();
                    mastBox.addItem(name);
                    map.put(name, root.getChild("appearances").getChild("appearance").getChildren("show").size());
                }
            }
        }
    } catch (org.jdom2.JDOMException e) {
        mastBox.addItem("Failed to create definition, did you select a system?");
        log.warn("in loadMastDefinitions", e);
    } catch (java.io.IOException | URISyntaxException e) {
        mastBox.addItem("Failed to read definition, did you select a system?");
        log.warn("in loadMastDefinitions", e);
    }
    try {
        URL path = FileUtil.findURL("signals/" + sigsysname, FileUtil.Location.USER, "xml", "resources");
        if (path != null) {
            File[] apps = new File(path.toURI()).listFiles();
            for (File app : apps) {
                if (app.getName().startsWith("appearance") && app.getName().endsWith(".xml")) {
                    log.debug("   found file: " + app.getName());
                    // If the mast file name already exists no point in re-adding it
                    if (!mastNames.contains(app)) {
                        mastNames.add(app);
                        jmri.jmrit.XmlFile xf = new jmri.jmrit.XmlFile() {
                        };
                        Element root = xf.rootFromFile(app);
                        String name = root.getChild("name").getText();
                        //if the mast name already exist no point in readding it.
                        if (!map.containsKey(name)) {
                            mastBox.addItem(name);
                            map.put(name, root.getChild("appearances").getChild("appearance").getChildren("show").size());
                        }
                    }
                }
            }
        }
    } catch (org.jdom2.JDOMException | java.io.IOException | URISyntaxException e) {
        log.warn("in loadMastDefinitions", e);
    }
    mastBox.addItemListener(new ItemListener() {

        @Override
        public void itemStateChanged(ItemEvent e) {
            updateSelectedDriver();
        }
    });
    updateSelectedDriver();
    if (prefs.getComboBoxLastSelection(mastSelectionCombo + ":" + ((String) sigSysBox.getSelectedItem())) != null) {
        mastBox.setSelectedItem(prefs.getComboBoxLastSelection(mastSelectionCombo + ":" + ((String) sigSysBox.getSelectedItem())));
    }
}
Also used : ItemEvent(java.awt.event.ItemEvent) Element(org.jdom2.Element) URISyntaxException(java.net.URISyntaxException) URL(java.net.URL) SignalSystemManager(jmri.SignalSystemManager) ItemListener(java.awt.event.ItemListener) File(java.io.File)

Aggregations

Element (org.jdom2.Element)154 Document (org.jdom2.Document)113 JDOMException (org.jdom2.JDOMException)89 IOException (java.io.IOException)75 SAXBuilder (org.jdom2.input.SAXBuilder)67 Test (org.junit.Test)36 File (java.io.File)32 ArrayList (java.util.ArrayList)22 InputStream (java.io.InputStream)17 Attribute (org.jdom2.Attribute)16 StringReader (java.io.StringReader)15 MCRNodeBuilder (org.mycore.common.xml.MCRNodeBuilder)14 HashMap (java.util.HashMap)13 XMLOutputter (org.jdom2.output.XMLOutputter)13 SAXException (org.xml.sax.SAXException)13 URL (java.net.URL)12 XmlFile (jmri.jmrit.XmlFile)12 List (java.util.List)11 MCRObject (org.mycore.datamodel.metadata.MCRObject)11 MCRException (org.mycore.common.MCRException)10