Search in sources :

Example 21 with ProcessingInstruction

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

the class NceConsistRoster method writeFile.

/**
     * Write the entire roster to a file. This does not do backup; that has to
     * be done separately. See writeRosterFile() for a function that finds the
     * default location, does a backup and then calls this.
     *
     * @param name Filename for new file, including path info as needed.
     * @throws java.io.FileNotFoundException when file not found
     * @throws java.io.IOException when fault accessing file
     */
void writeFile(String name) throws java.io.FileNotFoundException, java.io.IOException {
    if (log.isDebugEnabled()) {
        log.debug("writeFile " + name);
    }
    // This is taken in large part from "Java and XML" page 368
    File file = findFile(name);
    if (file == null) {
        file = new File(name);
    }
    // create root element
    Element root = new Element("consist-roster-config");
    Document doc = newDocument(root, dtdLocation + "consist-roster-config.dtd");
    // add XSLT processing instruction
    java.util.Map<String, String> m = new java.util.HashMap<String, String>();
    m.put("type", "text/xsl");
    m.put("href", xsltLocation + "consistRoster.xsl");
    ProcessingInstruction p = new ProcessingInstruction("xml-stylesheet", m);
    doc.addContent(0, p);
    //file version for writing
    for (int i = 0; i < numEntries(); i++) {
        //Extract the RosterEntry at this index and inspect the Comment and
        //Decoder Comment fields to change any \n characters to <?p?> processor
        //directives so they can be stored in the xml file and converted
        //back when the file is read.
        NceConsistRosterEntry r = _list.get(i);
        String tempComment = r.getComment();
        StringBuffer buf = new StringBuffer();
        //when \n is found.  In that case, insert <?p?>
        for (int k = 0; k < tempComment.length(); k++) {
            if (tempComment.startsWith("\n", k)) {
                buf.append("<?p?>");
            } else {
                buf.append(tempComment.substring(k, k + 1));
            }
        }
        r.setComment(buf.toString());
    }
    //All Comments and Decoder Comment line feeds have been changed to processor directives
    // add top-level elements
    Element values;
    root.addContent(values = new Element("roster"));
    // add entries
    for (int i = 0; i < numEntries(); i++) {
        values.addContent(_list.get(i).store());
    }
    writeXML(file, doc);
    //other parts of the program (e.g. in copying a roster)
    for (int i = 0; i < numEntries(); i++) {
        NceConsistRosterEntry r = _list.get(i);
        String xmlComment = r.getComment();
        StringBuffer buf = new StringBuffer();
        for (int k = 0; k < xmlComment.length(); k++) {
            if (xmlComment.startsWith("<?p?>", k)) {
                buf.append("\n");
                k = k + 4;
            } else {
                buf.append(xmlComment.substring(k, k + 1));
            }
        }
        r.setComment(buf.toString());
    }
    // done - roster now stored, so can't be dirty
    setDirty(false);
}
Also used : Element(org.jdom2.Element) Document(org.jdom2.Document) File(java.io.File) XmlFile(jmri.jmrit.XmlFile) ProcessingInstruction(org.jdom2.ProcessingInstruction)

Example 22 with ProcessingInstruction

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

the class BlockValueFile method writeBlockValues.

/*
     *  Writes out block values to a file in the user's preferences directory
     *  If there are no defined Blocks, no file is written.
     *  If none of the defined Blocks have values, no file is written.
     */
public void writeBlockValues() throws java.io.IOException {
    log.debug("entered writeBlockValues");
    List<String> blocks = blockManager.getSystemNameList();
    if (blocks.size() > 0) {
        // there are blocks defined, create root element
        root = new Element("block_values");
        doc = newDocument(root, dtdLocation + "block-values.dtd");
        boolean valuesFound = false;
        // add XSLT processing instruction
        // <?xml-stylesheet type="text/xsl" href="XSLT/block-values.xsl"?>
        java.util.Map<String, String> m = new java.util.HashMap<String, String>();
        m.put("type", "text/xsl");
        m.put("href", xsltLocation + "blockValues.xsl");
        org.jdom2.ProcessingInstruction p = new org.jdom2.ProcessingInstruction("xml-stylesheet", m);
        doc.addContent(0, p);
        // save block values in xml format
        Element values = new Element("blockvalues");
        for (int i = 0; i < blocks.size(); i++) {
            String sname = blocks.get(i);
            Block b = blockManager.getBySystemName(sname);
            if (b != null) {
                Object o = b.getValue();
                if (o != null) {
                    // block has value, save it
                    Element val = new Element("block");
                    val.setAttribute("systemname", sname);
                    if (o instanceof jmri.jmrit.roster.RosterEntry) {
                        val.setAttribute("value", ((jmri.jmrit.roster.RosterEntry) o).getId());
                        val.setAttribute("valueClass", "jmri.jmrit.roster.RosterEntry");
                    } else {
                        val.setAttribute("value", o.toString());
                    }
                    int v = b.getDirection();
                    if (v != jmri.Path.NONE) {
                        val.setAttribute("dir", "" + v);
                    }
                    values.addContent(val);
                    valuesFound = true;
                }
            } else {
                log.error("Block " + sname + " was not found.");
            }
        }
        root.addContent(values);
        // write out the file if values were found
        if (valuesFound) {
            try {
                if (!checkFile(defaultFileName)) {
                    // file does not exist, create it
                    File file = new File(defaultFileName);
                    if (// create and check result
                    !file.createNewFile()) {
                        log.error("createNewFile failed");
                    }
                }
                // write content to file
                writeXML(findFile(defaultFileName), doc);
            } catch (java.io.IOException ioe) {
                log.error("IO Exception " + ioe);
                throw (ioe);
            }
        }
    }
}
Also used : Element(org.jdom2.Element) Block(jmri.Block) File(java.io.File) XmlFile(jmri.jmrit.XmlFile)

Example 23 with ProcessingInstruction

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

the class ConfigXmlManager method finalStore.

protected boolean finalStore(Element root, File file) {
    try {
        // Document doc = newDocument(root, dtdLocation+"layout-config-"+dtdVersion+".dtd");
        Document doc = newDocument(root);
        // add XSLT processing instruction
        // <?xml-stylesheet type="text/xsl" href="XSLT/panelfile"+schemaVersion+".xsl"?>
        java.util.Map<String, String> m = new java.util.HashMap<>();
        m.put("type", "text/xsl");
        m.put("href", xsltLocation + "panelfile" + schemaVersion + ".xsl");
        ProcessingInstruction p = new ProcessingInstruction("xml-stylesheet", m);
        doc.addContent(0, p);
        // add version at front
        storeVersion(root);
        writeXML(file, doc);
    } catch (java.io.FileNotFoundException ex3) {
        storingErrorEncountered(null, "storing to file " + file.getName(), "File not found " + file.getName(), null, null, ex3);
        log.error("FileNotFound error writing file: " + ex3.getLocalizedMessage());
        return false;
    } catch (java.io.IOException ex2) {
        storingErrorEncountered(null, "storing to file " + file.getName(), "IO error writing file " + file.getName(), null, null, ex2);
        log.error("IO error writing file: " + ex2.getLocalizedMessage());
        return false;
    }
    return true;
}
Also used : LinkedHashMap(java.util.LinkedHashMap) Document(org.jdom2.Document) ProcessingInstruction(org.jdom2.ProcessingInstruction)

Example 24 with ProcessingInstruction

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

the class ThrottleFrame method saveThrottle.

private void saveThrottle(String sfile) {
    // Save throttle: title / window position
    // as strongly linked to extended throttles and roster presence, do not save function buttons and background window as they're stored in the roster entry
    XmlFile xf = new XmlFile() {
    };
    // odd syntax is due to XmlFile being abstract
    xf.makeBackupFile(sfile);
    File file = new File(sfile);
    try {
        //The file does not exist, create it before writing
        File parentDir = file.getParentFile();
        if (!parentDir.exists()) {
            if (// make directory and check result
            !parentDir.mkdir()) {
                log.error("could not make parent directory");
            }
        }
        if (// create file, check success
        !file.createNewFile()) {
            log.error("createNewFile failed");
        }
    } catch (Exception exp) {
        log.error("Exception while writing the throttle file, may not be complete: " + exp);
    }
    try {
        Element root = new Element("throttle-config");
        Document doc = XmlFile.newDocument(root, XmlFile.getDefaultDtdLocation() + "throttle-config.dtd");
        // add XSLT processing instruction
        // <?xml-stylesheet type="text/xsl" href="XSLT/throttle.xsl"?>
        /*   java.util.Map<String,String> m = new java.util.HashMap<String,String>();
             m.put("type", "text/xsl");
             m.put("href", jmri.jmrit.XmlFile.xsltLocation+"throttle.xsl");
             ProcessingInstruction p = new ProcessingInstruction("xml-stylesheet", m);
             doc.addContent(0,p);*/
        Element throttleElement = getXml();
        //   throttleElement.getChild("AddressPanel").removeChild("locoaddress");
        if (// don't save function buttons labels, they're in roster entry 
        (this.getRosterEntry() != null) && (getDefaultThrottleFolder() + addressPanel.getRosterEntry().getId().trim() + ".xml").compareTo(sfile) == 0) {
            throttleElement.getChild("FunctionPanel").removeChildren("FunctionButton");
        }
        root.setContent(throttleElement);
        xf.writeXML(file, doc);
        setLastUsedSaveFile(sfile);
    } catch (Exception ex) {
        log.warn("Exception while storing throttle xml: " + ex);
    }
}
Also used : XmlFile(jmri.jmrit.XmlFile) Element(org.jdom2.Element) Document(org.jdom2.Document) File(java.io.File) XmlFile(jmri.jmrit.XmlFile)

Example 25 with ProcessingInstruction

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

the class StoreXmlThrottlesLayoutAction method saveThrottlesLayout.

public void saveThrottlesLayout(java.io.File f) {
    try {
        Element root = new Element("throttle-layout-config");
        Document doc = XmlFile.newDocument(root, XmlFile.getDefaultDtdLocation() + "throttle-layout-config.dtd");
        // add XSLT processing instruction
        // <?xml-stylesheet type="text/xsl" href="XSLT/throttle-layout-config.xsl"?>
        /*TODO   java.util.Map<String,String> m = new java.util.HashMap<String,String>();
             m.put("type", "text/xsl");
             m.put("href", jmri.jmrit.XmlFile.xsltLocation + "throttle-layout-config.xsl");
             ProcessingInstruction p = new ProcessingInstruction("xml-stylesheet", m);
             doc.addContent(0, p); */
        java.util.ArrayList<Element> children = new java.util.ArrayList<Element>(5);
        // throttle list window
        children.add(ThrottleFrameManager.instance().getThrottlesListPanel().getXml());
        // throttle windows
        for (Iterator<ThrottleWindow> i = ThrottleFrameManager.instance().getThrottleWindows(); i.hasNext(); ) {
            ThrottleWindow tw = i.next();
            Element throttleElement = tw.getXml();
            children.add(throttleElement);
        }
        root.setContent(children);
        FileOutputStream o = new java.io.FileOutputStream(f);
        try {
            XMLOutputter fmt = new XMLOutputter();
            fmt.setFormat(Format.getPrettyFormat().setLineSeparator(System.getProperty("line.separator")).setTextMode(Format.TextMode.PRESERVE));
            fmt.output(doc, o);
        } catch (IOException ex) {
            log.warn("Exception in storing throttle xml: " + ex);
        } finally {
            o.close();
        }
    } catch (FileNotFoundException ex) {
        log.warn("Exception in storing throttle xml: " + ex);
    } catch (IOException ex) {
        log.warn("Exception in storing throttle xml: " + ex);
    }
}
Also used : XMLOutputter(org.jdom2.output.XMLOutputter) Element(org.jdom2.Element) FileOutputStream(java.io.FileOutputStream) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) Document(org.jdom2.Document)

Aggregations

Element (org.jdom2.Element)23 Document (org.jdom2.Document)20 File (java.io.File)18 ProcessingInstruction (org.jdom2.ProcessingInstruction)15 XmlFile (jmri.jmrit.XmlFile)9 IOException (java.io.IOException)5 FileNotFoundException (java.io.FileNotFoundException)3 HashMap (java.util.HashMap)3 XMLOutputter (org.jdom2.output.XMLOutputter)3 FileOutputStream (java.io.FileOutputStream)2 SuppressFBWarnings (edu.umd.cs.findbugs.annotations.SuppressFBWarnings)1 BufferedInputStream (java.io.BufferedInputStream)1 FileInputStream (java.io.FileInputStream)1 ArrayList (java.util.ArrayList)1 LinkedHashMap (java.util.LinkedHashMap)1 Block (jmri.Block)1 CatalogTree (jmri.CatalogTree)1 CatalogTreeManager (jmri.CatalogTreeManager)1 Consist (jmri.Consist)1 CatalogTreeNode (jmri.jmrit.catalog.CatalogTreeNode)1