Search in sources :

Example 11 with XMLOutputter

use of org.jdom2.output.XMLOutputter in project JMRI by JMRI.

the class ProfileManager method writeProfiles.

private void writeProfiles() throws IOException {
    if (!(new File(FileUtil.getPreferencesPath()).canWrite())) {
        return;
    }
    FileWriter fw = null;
    Document doc = new Document();
    doc.setRootElement(new Element(PROFILECONFIG));
    Element profilesElement = new Element(PROFILES);
    Element pathsElement = new Element(SEARCH_PATHS);
    this.profiles.stream().map((p) -> {
        Element e = new Element(PROFILE);
        e.setAttribute(Profile.ID, p.getId());
        e.setAttribute(Profile.PATH, FileUtil.getPortableFilename(p.getPath(), true, true));
        return e;
    }).forEach((e) -> {
        profilesElement.addContent(e);
    });
    this.searchPaths.stream().map((f) -> {
        Element e = new Element(Profile.PATH);
        e.setAttribute(Profile.PATH, FileUtil.getPortableFilename(f.getPath(), true, true));
        e.setAttribute(DEFAULT, Boolean.toString(f.equals(this.defaultSearchPath)));
        return e;
    }).forEach((e) -> {
        pathsElement.addContent(e);
    });
    doc.getRootElement().addContent(profilesElement);
    doc.getRootElement().addContent(pathsElement);
    try {
        fw = new FileWriter(catalog);
        XMLOutputter fmt = new XMLOutputter();
        fmt.setFormat(Format.getPrettyFormat().setLineSeparator(System.getProperty("line.separator")).setTextMode(Format.TextMode.NORMALIZE));
        fmt.output(doc, fw);
        fw.close();
    } catch (IOException ex) {
        // close fw if possible
        if (fw != null) {
            fw.close();
        }
        // rethrow the error
        throw ex;
    }
}
Also used : ZipOutputStream(java.util.zip.ZipOutputStream) SAXBuilder(org.jdom2.input.SAXBuilder) Properties(java.util.Properties) Logger(org.slf4j.Logger) Format(org.jdom2.output.Format) Date(java.util.Date) FileWriter(java.io.FileWriter) LoggerFactory(org.slf4j.LoggerFactory) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) File(java.io.File) FileNotFoundException(java.io.FileNotFoundException) ArrayList(java.util.ArrayList) XMLOutputter(org.jdom2.output.XMLOutputter) Document(org.jdom2.Document) JDOMException(org.jdom2.JDOMException) FileUtil(jmri.util.FileUtil) Bean(jmri.beans.Bean) Roster(jmri.jmrit.roster.Roster) ZipEntry(java.util.zip.ZipEntry) Nonnull(javax.annotation.Nonnull) PropertyChangeEvent(java.beans.PropertyChangeEvent) Element(org.jdom2.Element) XMLOutputter(org.jdom2.output.XMLOutputter) FileWriter(java.io.FileWriter) Element(org.jdom2.Element) IOException(java.io.IOException) Document(org.jdom2.Document) File(java.io.File)

Example 12 with XMLOutputter

use of org.jdom2.output.XMLOutputter in project JMRI by JMRI.

the class ProfileManager method export.

/**
     * Export the {@link jmri.profile.Profile} to a zip file.
     *
     * @param profile                 The profile to export
     * @param target                  The file to export the profile into
     * @param exportExternalUserFiles If the User Files are not within the
     *                                profile directory, should they be
     *                                included?
     * @param exportExternalRoster    It the roster is not within the profile
     *                                directory, should it be included?
     * @throws java.io.IOException     if unable to write a file during the
     *                                 export
     * @throws org.jdom2.JDOMException if unable to create a new profile
     *                                 configuration file in the exported
     *                                 Profile
     */
public void export(Profile profile, File target, boolean exportExternalUserFiles, boolean exportExternalRoster) throws IOException, JDOMException {
    if (!target.exists() && !target.createNewFile()) {
        throw new IOException("Unable to create file " + target);
    }
    // NOI18N
    String tempDirPath = System.getProperty("java.io.tmpdir") + File.separator + "JMRI" + System.currentTimeMillis();
    FileUtil.createDirectory(tempDirPath);
    File tempDir = new File(tempDirPath);
    File tempProfilePath = new File(tempDir, profile.getPath().getName());
    FileUtil.copy(profile.getPath(), tempProfilePath);
    // NOI18N
    File config = new File(tempProfilePath, "ProfileConfig.xml");
    Document doc = (new SAXBuilder()).build(config);
    if (exportExternalUserFiles) {
        FileUtil.copy(new File(FileUtil.getUserFilesPath()), tempProfilePath);
        // NOI18N
        Element fileLocations = doc.getRootElement().getChild("fileLocations");
        for (Element fl : fileLocations.getChildren()) {
            if (fl.getAttribute("defaultUserLocation") != null) {
                // NOI18N
                // NOI18N
                fl.setAttribute("defaultUserLocation", "profile:");
            }
        }
    }
    if (exportExternalRoster) {
        // NOI18N
        FileUtil.copy(new File(Roster.getDefault().getRosterIndexPath()), new File(tempProfilePath, "roster.xml"));
        // NOI18N
        FileUtil.copy(new File(Roster.getDefault().getRosterLocation(), "roster"), new File(tempProfilePath, "roster"));
        // NOI18N
        Element roster = doc.getRootElement().getChild("roster");
        // NOI18N
        roster.removeAttribute("directory");
    }
    if (exportExternalUserFiles || exportExternalRoster) {
        try (FileWriter fw = new FileWriter(config)) {
            XMLOutputter fmt = new XMLOutputter();
            fmt.setFormat(Format.getPrettyFormat().setLineSeparator(System.getProperty("line.separator")).setTextMode(Format.TextMode.PRESERVE));
            fmt.output(doc, fw);
        }
    }
    try (FileOutputStream out = new FileOutputStream(target);
        ZipOutputStream zip = new ZipOutputStream(out)) {
        this.exportDirectory(zip, tempProfilePath, tempProfilePath.getPath());
    }
    FileUtil.delete(tempDir);
}
Also used : XMLOutputter(org.jdom2.output.XMLOutputter) SAXBuilder(org.jdom2.input.SAXBuilder) ZipOutputStream(java.util.zip.ZipOutputStream) Element(org.jdom2.Element) FileWriter(java.io.FileWriter) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) Document(org.jdom2.Document) File(java.io.File)

Example 13 with XMLOutputter

use of org.jdom2.output.XMLOutputter in project JMRI by JMRI.

the class NodeIdentity method saveIdentity.

/**
     * Save the current node identity and all former identities to file.
     */
private void saveIdentity() {
    Document doc = new Document();
    doc.setRootElement(new Element(ROOT_ELEMENT));
    Element identityElement = new Element(NODE_IDENTITY);
    Element formerIdentitiesElement = new Element(FORMER_IDENTITIES);
    if (this.identity == null) {
        this.getIdentity(false);
    }
    identityElement.setAttribute(NODE_IDENTITY, this.identity);
    this.formerIdentities.stream().forEach((formerIdentity) -> {
        log.debug("Retaining former node identity {}", formerIdentity);
        Element e = new Element(NODE_IDENTITY);
        e.setAttribute(NODE_IDENTITY, formerIdentity);
        formerIdentitiesElement.addContent(e);
    });
    doc.getRootElement().addContent(identityElement);
    doc.getRootElement().addContent(formerIdentitiesElement);
    try (Writer w = new OutputStreamWriter(new FileOutputStream(this.identityFile()), "UTF-8")) {
        // NOI18N
        XMLOutputter fmt = new XMLOutputter();
        fmt.setFormat(Format.getPrettyFormat().setLineSeparator(System.getProperty("line.separator")).setTextMode(Format.TextMode.PRESERVE));
        fmt.output(doc, w);
    } catch (IOException ex) {
        log.error("Unable to store node identities: {}", ex.getLocalizedMessage());
    }
}
Also used : XMLOutputter(org.jdom2.output.XMLOutputter) Element(org.jdom2.Element) FileOutputStream(java.io.FileOutputStream) OutputStreamWriter(java.io.OutputStreamWriter) IOException(java.io.IOException) Document(org.jdom2.Document) Writer(java.io.Writer) OutputStreamWriter(java.io.OutputStreamWriter)

Example 14 with XMLOutputter

use of org.jdom2.output.XMLOutputter in project JMRI by JMRI.

the class LayoutPanelServlet method getXmlPanel.

@Override
protected String getXmlPanel(String name) {
    log.debug("Getting {} for {}", getPanelType(), name);
    try {
        LayoutEditor editor = (LayoutEditor) getEditor(name);
        Element panel = new Element("panel");
        panel.setAttribute("name", name);
        panel.setAttribute("paneltype", getPanelType());
        panel.setAttribute("height", Integer.toString(editor.getLayoutHeight()));
        panel.setAttribute("width", Integer.toString(editor.getLayoutWidth()));
        panel.setAttribute("panelheight", Integer.toString(editor.getLayoutHeight()));
        panel.setAttribute("panelwidth", Integer.toString(editor.getLayoutWidth()));
        panel.setAttribute("showtooltips", (editor.showTooltip()) ? "yes" : "no");
        panel.setAttribute("controlling", (editor.allControlling()) ? "yes" : "no");
        panel.setAttribute("xscale", Float.toString((float) editor.getXScale()));
        panel.setAttribute("yscale", Float.toString((float) editor.getYScale()));
        panel.setAttribute("mainlinetrackwidth", Integer.toString(editor.getMainlineTrackWidth()));
        panel.setAttribute("sidetrackwidth", Integer.toString(editor.getSideTrackWidth()));
        panel.setAttribute("turnoutcircles", (editor.getTurnoutCircles()) ? "yes" : "no");
        panel.setAttribute("turnoutcirclesize", Integer.toString(editor.getTurnoutCircleSize()));
        panel.setAttribute("turnoutdrawunselectedleg", (editor.getTurnoutDrawUnselectedLeg()) ? "yes" : "no");
        if (editor.getBackgroundColor() == null) {
            panel.setAttribute("backgroundcolor", ColorUtil.colorToString(Color.lightGray));
        } else {
            panel.setAttribute("backgroundcolor", ColorUtil.colorToString(editor.getBackgroundColor()));
        }
        panel.setAttribute("defaulttrackcolor", editor.getDefaultTrackColor());
        panel.setAttribute("defaultoccupiedtrackcolor", editor.getDefaultOccupiedTrackColor());
        panel.setAttribute("defaultalternativetrackcolor", editor.getDefaultAlternativeTrackColor());
        panel.setAttribute("defaulttextcolor", editor.getDefaultTextColor());
        panel.setAttribute("turnoutcirclecolor", editor.getTurnoutCircleColor());
        // include positionable elements
        List<Positionable> contents = editor.getContents();
        log.debug("N positionable elements: {}", contents.size());
        for (Positionable sub : contents) {
            if (sub != null) {
                try {
                    Element e = ConfigXmlManager.elementFromObject(sub);
                    if (e != null) {
                        if ("signalmasticon".equals(e.getName())) {
                            //insert icon details into signalmast
                            e.addContent(getSignalMastIconsElement(e.getAttributeValue("signalmast")));
                        }
                        try {
                            e.setAttribute(JSON.ID, sub.getNamedBean().getSystemName());
                        } catch (NullPointerException ex) {
                            if (sub.getNamedBean() == null) {
                                log.debug("{} {} does not have an associated NamedBean", e.getName(), e.getAttribute(JSON.NAME));
                            } else {
                                log.debug("{} {} does not have a SystemName", e.getName(), e.getAttribute(JSON.NAME));
                            }
                        }
                        parsePortableURIs(e);
                        panel.addContent(e);
                    }
                } catch (Exception ex) {
                    log.error("Error storing panel element: " + ex, ex);
                }
            }
        }
        // include PositionablePoints
        int num = editor.pointList.size();
        log.debug("N positionablepoint elements: {}", num);
        if (num > 0) {
            for (int i = 0; i < num; i++) {
                Object sub = editor.pointList.get(i);
                try {
                    Element e = jmri.configurexml.ConfigXmlManager.elementFromObject(sub);
                    if (e != null) {
                        panel.addContent(e);
                    }
                } catch (Exception e) {
                    log.error("Error storing panel positionalpoint element: " + e);
                }
            }
        }
        // include LayoutBlocks
        LayoutBlockManager tm = InstanceManager.getDefault(LayoutBlockManager.class);
        java.util.Iterator<String> iter = tm.getSystemNameList().iterator();
        SensorManager sm = InstanceManager.sensorManagerInstance();
        num = 0;
        while (iter.hasNext()) {
            String sname = iter.next();
            if (sname == null) {
                log.error("System name null during LayoutBlock store");
            }
            LayoutBlock b = tm.getBySystemName(sname);
            if (b.getUseCount() > 0) {
                // save only those LayoutBlocks that are in use--skip abandoned ones
                Element elem = new Element("layoutblock").setAttribute("systemname", sname);
                String uname = b.getUserName();
                if (uname != null && !uname.isEmpty()) {
                    elem.setAttribute("username", uname);
                }
                // get occupancy sensor from layoutblock if it is valid
                if (!b.getOccupancySensorName().isEmpty()) {
                    Sensor s = sm.getSensor(b.getOccupancySensorName());
                    if (s != null) {
                        //send systemname
                        elem.setAttribute("occupancysensor", s.getSystemName());
                    }
                //if layoutblock has no occupancy sensor, use one from block, if it is populated
                } else {
                    Sensor s = b.getBlock().getSensor();
                    if (s != null) {
                        //send systemname
                        elem.setAttribute("occupancysensor", s.getSystemName());
                    }
                }
                elem.setAttribute("occupiedsense", Integer.toString(b.getOccupiedSense()));
                elem.setAttribute("trackcolor", ColorUtil.colorToString(b.getBlockTrackColor()));
                elem.setAttribute("occupiedcolor", ColorUtil.colorToString(b.getBlockOccupiedColor()));
                elem.setAttribute("extracolor", ColorUtil.colorToString(b.getBlockExtraColor()));
                if (!b.getMemoryName().isEmpty()) {
                    elem.setAttribute("memory", b.getMemoryName());
                }
                if (!b.useDefaultMetric()) {
                    elem.addContent(new Element("metric").addContent(Integer.toString(b.getBlockMetric())));
                }
                //add to the panel xml
                panel.addContent(elem);
                num++;
            }
        }
        log.debug("N layoutblock elements: {}", num);
        // include LevelXings
        num = editor.xingList.size();
        log.debug("N levelxing elements: {}", num);
        if (num > 0) {
            for (int i = 0; i < num; i++) {
                Object sub = editor.xingList.get(i);
                try {
                    Element e = jmri.configurexml.ConfigXmlManager.elementFromObject(sub);
                    if (e != null) {
                        panel.addContent(e);
                    }
                } catch (Exception e) {
                    log.error("Error storing panel levelxing element: " + e);
                }
            }
        }
        // include LayoutTurnouts
        num = editor.turnoutList.size();
        log.debug("N layoutturnout elements: {}", num);
        if (num > 0) {
            for (int i = 0; i < num; i++) {
                Object sub = editor.turnoutList.get(i);
                try {
                    Element e = jmri.configurexml.ConfigXmlManager.elementFromObject(sub);
                    if (e != null) {
                        panel.addContent(e);
                    }
                } catch (Exception e) {
                    log.error("Error storing panel layoutturnout element: " + e);
                }
            }
        }
        // include TrackSegments
        num = editor.trackList.size();
        log.debug("N tracksegment elements: {}", num);
        if (num > 0) {
            for (int i = 0; i < num; i++) {
                Object sub = editor.trackList.get(i);
                try {
                    Element e = jmri.configurexml.ConfigXmlManager.elementFromObject(sub);
                    if (e != null) {
                        panel.addContent(e);
                    }
                } catch (Exception e) {
                    log.error("Error storing panel tracksegment element: " + e);
                }
            }
        }
        // include LayoutSlips
        num = editor.slipList.size();
        log.debug("N layoutSlip elements: {}", num);
        if (num > 0) {
            for (int i = 0; i < num; i++) {
                Object sub = editor.slipList.get(i);
                try {
                    Element e = jmri.configurexml.ConfigXmlManager.elementFromObject(sub);
                    if (e != null) {
                        panel.addContent(e);
                    }
                } catch (Exception e) {
                    log.error("Error storing panel layoutSlip element: " + e);
                }
            }
        }
        // include LayoutTurntables
        num = editor.turntableList.size();
        log.debug("N turntable elements: {}", num);
        if (num > 0) {
            for (int i = 0; i < num; i++) {
                Object sub = editor.turntableList.get(i);
                try {
                    Element e = jmri.configurexml.ConfigXmlManager.elementFromObject(sub);
                    if (e != null) {
                        panel.addContent(e);
                    }
                } catch (Exception e) {
                    log.error("Error storing panel turntable element: " + e);
                }
            }
        }
        //write out formatted document
        Document doc = new Document(panel);
        XMLOutputter fmt = new XMLOutputter();
        fmt.setFormat(Format.getPrettyFormat().setLineSeparator(System.getProperty("line.separator")).setTextMode(Format.TextMode.TRIM));
        return fmt.outputString(doc);
    } catch (NullPointerException ex) {
        log.warn("Requested Layout panel [" + name + "] does not exist.");
        return "ERROR Requested panel [" + name + "] does not exist.";
    }
}
Also used : XMLOutputter(org.jdom2.output.XMLOutputter) LayoutEditor(jmri.jmrit.display.layoutEditor.LayoutEditor) Element(org.jdom2.Element) Document(org.jdom2.Document) LayoutBlock(jmri.jmrit.display.layoutEditor.LayoutBlock) SensorManager(jmri.SensorManager) LayoutBlockManager(jmri.jmrit.display.layoutEditor.LayoutBlockManager) Positionable(jmri.jmrit.display.Positionable) Sensor(jmri.Sensor)

Example 15 with XMLOutputter

use of org.jdom2.output.XMLOutputter in project JMRI by JMRI.

the class PanelServlet method getXmlPanel.

@Override
protected String getXmlPanel(String name) {
    log.debug("Getting {} for {}", getPanelType(), name);
    try {
        PanelEditor editor = (PanelEditor) getEditor(name);
        Element panel = new Element("panel");
        JFrame frame = editor.getTargetFrame();
        panel.setAttribute("name", name);
        panel.setAttribute("height", Integer.toString(frame.getContentPane().getHeight()));
        panel.setAttribute("width", Integer.toString(frame.getContentPane().getWidth()));
        panel.setAttribute("panelheight", Integer.toString(editor.getTargetPanel().getHeight()));
        panel.setAttribute("panelwidth", Integer.toString(editor.getTargetPanel().getWidth()));
        panel.setAttribute("showtooltips", (editor.showTooltip()) ? "yes" : "no");
        panel.setAttribute("controlling", (editor.allControlling()) ? "yes" : "no");
        if (editor.getBackgroundColor() != null) {
            Element color = new Element("backgroundColor");
            color.setAttribute("red", Integer.toString(editor.getBackgroundColor().getRed()));
            color.setAttribute("green", Integer.toString(editor.getBackgroundColor().getGreen()));
            color.setAttribute("blue", Integer.toString(editor.getBackgroundColor().getBlue()));
            panel.addContent(color);
        }
        // include contents
        List<Positionable> contents = editor.getContents();
        log.debug("Panel has {} elements", contents.size());
        for (Positionable sub : contents) {
            if (sub != null) {
                try {
                    Element e = ConfigXmlManager.elementFromObject(sub);
                    if (e != null) {
                        if ("signalmasticon".equals(e.getName())) {
                            //insert icon details into signalmast
                            e.addContent(getSignalMastIconsElement(e.getAttributeValue("signalmast")));
                        }
                        try {
                            e.setAttribute(JSON.ID, sub.getNamedBean().getSystemName());
                        } catch (NullPointerException ex) {
                            if (sub.getNamedBean() == null) {
                                log.debug("{} {} does not have an associated NamedBean", e.getName(), e.getAttribute(JSON.NAME));
                            } else {
                                log.debug("{} {} does not have a SystemName", e.getName(), e.getAttribute(JSON.NAME));
                            }
                        }
                        parsePortableURIs(e);
                        panel.addContent(e);
                    }
                } catch (Exception ex) {
                    log.error("Error storing panel element: {}", ex.getMessage(), ex);
                }
            }
        }
        Document doc = new Document(panel);
        XMLOutputter out = new XMLOutputter();
        out.setFormat(Format.getPrettyFormat().setLineSeparator(System.getProperty("line.separator")).setTextMode(Format.TextMode.TRIM));
        return out.outputString(doc);
    } catch (NullPointerException ex) {
        log.warn("Requested Panel [" + name + "] does not exist.");
        return "ERROR Requested panel [" + name + "] does not exist.";
    }
}
Also used : XMLOutputter(org.jdom2.output.XMLOutputter) JFrame(javax.swing.JFrame) Element(org.jdom2.Element) Positionable(jmri.jmrit.display.Positionable) Document(org.jdom2.Document) PanelEditor(jmri.jmrit.display.panelEditor.PanelEditor) IOException(java.io.IOException) JsonGenerationException(com.fasterxml.jackson.core.JsonGenerationException) JsonMappingException(com.fasterxml.jackson.databind.JsonMappingException)

Aggregations

Document (org.jdom2.Document)17 XMLOutputter (org.jdom2.output.XMLOutputter)15 Element (org.jdom2.Element)14 FileOutputStream (java.io.FileOutputStream)7 IOException (java.io.IOException)7 FileWriter (java.io.FileWriter)4 File (java.io.File)3 FileNotFoundException (java.io.FileNotFoundException)3 JFrame (javax.swing.JFrame)3 Positionable (jmri.jmrit.display.Positionable)3 DocType (org.jdom2.DocType)3 SAXBuilder (org.jdom2.input.SAXBuilder)3 FileInputStream (java.io.FileInputStream)2 Writer (java.io.Writer)2 ZipOutputStream (java.util.zip.ZipOutputStream)2 JDOMException (org.jdom2.JDOMException)2 Format (org.jdom2.output.Format)2 JsonGenerationException (com.fasterxml.jackson.core.JsonGenerationException)1 JsonMappingException (com.fasterxml.jackson.databind.JsonMappingException)1 SuppressFBWarnings (edu.umd.cs.findbugs.annotations.SuppressFBWarnings)1