Search in sources :

Example 41 with Document

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

the class Roster method writeFile.

/**
     * Write the entire roster to a file object. This does not do backup; that
     * has to be done separately. See writeRosterFile() for a public function
     * that finds the default location, does a backup and then calls this.
     *
     * @param file an op
     */
void writeFile(File file) throws java.io.IOException {
    // create root element
    // NOI18N
    Element root = new Element("roster-config");
    // NOI18N
    root.setAttribute(// NOI18N
    "noNamespaceSchemaLocation", // NOI18N
    "http://jmri.org/xml/schema/roster" + schemaVersion + ".xsd", // NOI18N
    org.jdom2.Namespace.getNamespace(// NOI18N
    "xsi", // NOI18N
    "http://www.w3.org/2001/XMLSchema-instance"));
    Document doc = newDocument(root);
    // add XSLT processing instruction
    // <?xml-stylesheet type="text/xsl" href="XSLT/roster.xsl"?>
    java.util.Map<String, String> m = new java.util.HashMap<>();
    // NOI18N
    m.put("type", "text/xsl");
    // NOI18N
    m.put("href", xsltLocation + "roster2array.xsl");
    // NOI18N
    ProcessingInstruction p = new ProcessingInstruction("xml-stylesheet", m);
    doc.addContent(0, p);
    String newLocoString = SymbolicProgBundle.getMessage("LabelNewDecoder");
    //file version for writing
    synchronized (_list) {
        _list.forEach((entry) -> {
            //back when the file is read.
            if (!entry.getId().equals(newLocoString)) {
                String tempComment = entry.getComment();
                String xmlComment = "";
                //when \n is found.  In that case, insert <?p?>
                for (int k = 0; k < tempComment.length(); k++) {
                    if (tempComment.startsWith("\n", k)) {
                        // NOI18N
                        // NOI18N
                        xmlComment = xmlComment + "<?p?>";
                    } else {
                        xmlComment = xmlComment + tempComment.substring(k, k + 1);
                    }
                }
                entry.setComment(xmlComment);
                //Now do the same thing for the decoderComment field
                String tempDecoderComment = entry.getDecoderComment();
                String xmlDecoderComment = "";
                for (int k = 0; k < tempDecoderComment.length(); k++) {
                    if (tempDecoderComment.startsWith("\n", k)) {
                        // NOI18N
                        // NOI18N
                        xmlDecoderComment = xmlDecoderComment + "<?p?>";
                    } else {
                        xmlDecoderComment = xmlDecoderComment + tempDecoderComment.substring(k, k + 1);
                    }
                }
                entry.setDecoderComment(xmlDecoderComment);
            } else {
                log.debug("skip unsaved roster entry with default name " + entry.getId());
            }
        });
    //All Comments and Decoder Comment line feeds have been changed to processor directives
    }
    // add top-level elements
    // NOI18N
    Element values = new Element("roster");
    root.addContent(values);
    // add entries
    synchronized (_list) {
        _list.stream().forEach((entry) -> {
            if (!entry.getId().equals(newLocoString)) {
                values.addContent(entry.store());
            } else {
                log.debug("skip unsaved roster entry with default name " + entry.getId());
            }
        });
    }
    if (!this.rosterGroups.isEmpty()) {
        // NOI18N
        Element rosterGroup = new Element("rosterGroup");
        rosterGroups.keySet().stream().forEach((name) -> {
            // NOI18N
            Element group = new Element("group");
            if (!name.equals(Roster.ALLENTRIES)) {
                group.addContent(name);
                rosterGroup.addContent(group);
            }
        });
        root.addContent(rosterGroup);
    }
    writeXML(file, doc);
    //other parts of the program (e.g. in copying a roster)
    synchronized (_list) {
        _list.stream().forEach((entry) -> {
            if (!entry.getId().equals(newLocoString)) {
                String xmlComment = entry.getComment();
                String tempComment = "";
                for (int k = 0; k < xmlComment.length(); k++) {
                    if (xmlComment.startsWith("<?p?>", k)) {
                        // NOI18N
                        // NOI18N
                        tempComment = tempComment + "\n";
                        k = k + 4;
                    } else {
                        tempComment = tempComment + xmlComment.substring(k, k + 1);
                    }
                }
                entry.setComment(tempComment);
                String xmlDecoderComment = entry.getDecoderComment();
                // NOI18N
                String tempDecoderComment = "";
                for (int k = 0; k < xmlDecoderComment.length(); k++) {
                    if (xmlDecoderComment.startsWith("<?p?>", k)) {
                        // NOI18N
                        // NOI18N
                        tempDecoderComment = tempDecoderComment + "\n";
                        k = k + 4;
                    } else {
                        tempDecoderComment = tempDecoderComment + xmlDecoderComment.substring(k, k + 1);
                    }
                }
                entry.setDecoderComment(tempDecoderComment);
            } else {
                log.debug("skip unsaved roster entry with default name " + entry.getId());
            }
        });
    }
    // done - roster now stored, so can't be dirty
    setDirty(false);
    firePropertyChange(SAVED, false, true);
}
Also used : HashMap(java.util.HashMap) Element(org.jdom2.Element) Document(org.jdom2.Document) ProcessingInstruction(org.jdom2.ProcessingInstruction)

Example 42 with Document

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

the class SpeedometerFrame method doStore.

private void doStore() {
    log.debug("Check if there's anything to store");
    int verify = verifyInputs(false);
    if (verify == 0) {
        if (JOptionPane.showConfirmDialog(this, Bundle.getMessage("QuestionNothingToStore"), Bundle.getMessage("TitleStoreQuestion"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.NO_OPTION) {
            return;
        }
    }
    log.debug("Start storing speedometer settings...");
    SpeedometerXml x = new SpeedometerXml();
    x.makeBackupFile(SpeedometerXml.getDefaultFileName());
    File file = x.getFile(true);
    // Create root element
    Element root = new Element("speedometer-config");
    root.setAttribute("noNamespaceSchemaLocation", "http://jmri.org/xml/schema/speedometer-3-9-3.xsd", org.jdom2.Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"));
    Document doc = new Document(root);
    // add XSLT processing instruction
    java.util.Map<String, String> m = new java.util.HashMap<String, String>();
    m.put("type", "text/xsl");
    m.put("href", SpeedometerXml.xsltLocation + "speedometer.xsl");
    ProcessingInstruction p = new ProcessingInstruction("xml-stylesheet", m);
    doc.addContent(0, p);
    Element values;
    // Store configuration
    root.addContent(values = new Element("configuration"));
    values.addContent(new Element("useMetric").addContent(dim ? "yes" : "no"));
    // Store values
    if (verify > 0 || startSensor.getText().length() > 0) {
        // Create sensors element
        root.addContent(values = new Element("sensors"));
        // Store start sensor
        Element e = new Element("sensor");
        e.addContent(new Element("sensorName").addContent(startSensor.getText()));
        e.addContent(new Element("type").addContent("StartSensor"));
        e.addContent(new Element("trigger").addContent(startOnEntry.isSelected() ? "entry" : "exit"));
        values.addContent(e);
        // If valid, store stop sensor 1
        if (verify > 0) {
            e = new Element("sensor");
            e.addContent(new Element("sensorName").addContent(stopSensor1.getText()));
            e.addContent(new Element("type").addContent("StopSensor1"));
            e.addContent(new Element("trigger").addContent(stopOnEntry1.isSelected() ? "entry" : "exit"));
            try {
                e.addContent(new Element("distance").addContent(String.valueOf(IntlUtilities.floatValue(distance1.getText()))));
            } catch (java.text.ParseException ex) {
                log.error("Distance isn't a valid floating number: " + distance1.getText());
            }
            values.addContent(e);
        }
        // If valid, store stop sensor 2
        if (verify > 1) {
            e = new Element("sensor");
            e.addContent(new Element("sensorName").addContent(stopSensor2.getText()));
            e.addContent(new Element("type").addContent("StopSensor2"));
            e.addContent(new Element("trigger").addContent(stopOnEntry2.isSelected() ? "entry" : "exit"));
            try {
                e.addContent(new Element("distance").addContent(String.valueOf(IntlUtilities.floatValue(distance2.getText()))));
            } catch (java.text.ParseException ex) {
                log.error("Distance isn't a valid floating number: " + distance2.getText());
            }
            values.addContent(e);
        }
    }
    try {
        x.writeXML(file, doc);
    } catch (FileNotFoundException ex) {
        log.error("File not found when writing: " + ex);
    } catch (IOException ex) {
        log.error("IO Exception when writing: " + ex);
    }
    log.debug("...done");
}
Also used : Element(org.jdom2.Element) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) Document(org.jdom2.Document) File(java.io.File) XmlFile(jmri.jmrit.XmlFile) ProcessingInstruction(org.jdom2.ProcessingInstruction)

Example 43 with Document

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

the class SymbolicProgFrame method writeFile.

// dead class doesn't need this fixed right now
@SuppressFBWarnings(value = "REC_CATCH_EXCEPTION")
void writeFile() {
    log.warn("SymbolicProgFrame writeFile invoked - is this still right, or should the LocoFile method be used?");
    log.warn("Note use of VersionID attribute...");
    try {
        // get the file
        int retVal = fco.showSaveDialog(this);
        // handle selection or cancel
        if (retVal != JFileChooser.APPROVE_OPTION) {
            // leave early
            return;
        }
        File file = fco.getSelectedFile();
        // This is taken in large part from "Java and XML" page 368
        // create root element
        Element root = new Element("locomotive-config");
        Document doc = jmri.jmrit.XmlFile.newDocument(root, jmri.jmrit.XmlFile.getDefaultDtdLocation() + "locomotive-config.dtd");
        // add XSLT processing instruction
        // <?xml-stylesheet type="text/xsl" href="XSLT/locomotive.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 + "locomotive.xsl");
        ProcessingInstruction p = new ProcessingInstruction("xml-stylesheet", m);
        doc.addContent(0, p);
        // add top-level elements
        Element values;
        root.addContent(// locomotive values are first item
        new Element("locomotive").setAttribute("roadNumber", locoRoadNumber.getText()).setAttribute("roadName", locoRoadName.getText()).setAttribute("mfg", locoMfg.getText()).setAttribute("model", locoModel.getText()).addContent(new Element("decoder").setAttribute("model", decoderModel.getText()).setAttribute("mfg", decoderMfg.getText()).setAttribute("versionID", "").setAttribute("mfgID", "")).addContent(values = new Element("values")));
        // Append a decoderDef element to values
        Element decoderDef;
        values.addContent(decoderDef = new Element("decoderDef"));
        // add the variable values to the decoderDef Element
        for (int i = 0; i < variableModel.getRowCount(); i++) {
            decoderDef.addContent(new Element("varValue").setAttribute("item", variableModel.getLabel(i)).setAttribute("value", variableModel.getValString(i)));
        }
        // add the CV values to the values Element
        for (int i = 0; i < cvModel.getRowCount(); i++) {
            values.addContent(new Element("CVvalue").setAttribute("name", cvModel.getName(i)).setAttribute("value", cvModel.getValString(i)));
        }
        // write the result to selected file
        java.io.FileOutputStream o = new java.io.FileOutputStream(file);
        try {
            XMLOutputter fmt = new XMLOutputter();
            fmt.setFormat(Format.getPrettyFormat().setLineSeparator(System.getProperty("line.separator")).setTextMode(Format.TextMode.PRESERVE));
            fmt.output(doc, o);
        } finally {
            o.close();
        }
        // mark file as OK
        variableModel.setFileDirty(false);
    } catch (Exception e) {
        log.error(e.getLocalizedMessage(), e);
    }
}
Also used : XMLOutputter(org.jdom2.output.XMLOutputter) Element(org.jdom2.Element) Document(org.jdom2.Document) DecoderFile(jmri.jmrit.decoderdefn.DecoderFile) File(java.io.File) ProcessingInstruction(org.jdom2.ProcessingInstruction) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings)

Example 44 with Document

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

the class RouteManagerXml method writeFile.

@Override
public void writeFile(String name) throws java.io.FileNotFoundException, java.io.IOException {
    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
    // NOI18N
    Element root = new Element("operations-config");
    // NOI18N
    Document doc = newDocument(root, dtdLocation + "operations-routes.dtd");
    // add XSLT processing instruction
    java.util.Map<String, String> m = new java.util.HashMap<String, String>();
    // NOI18N
    m.put("type", "text/xsl");
    // NOI18N
    m.put("href", xsltLocation + "operations-routes.xsl");
    // NOI18N
    ProcessingInstruction p = new ProcessingInstruction("xml-stylesheet", m);
    doc.addContent(0, p);
    RouteManager.instance().store(root);
    writeXML(file, doc);
    // done - route file now stored, so can't be dirty
    setDirty(false);
}
Also used : Element(org.jdom2.Element) Document(org.jdom2.Document) File(java.io.File) ProcessingInstruction(org.jdom2.ProcessingInstruction)

Example 45 with Document

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

the class StoreXmlVSDecoderAction method saveVSDecoderProfile.

public void saveVSDecoderProfile(java.io.File f) {
    try {
        Element root = new Element("VSDecoderConfig");
        Document doc = XmlFile.newDocument(root, XmlFile.getDefaultDtdLocation() + "vsdecoder-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);
        for (java.util.Iterator<VSDecoder> i = VSDecoderManager.instance().getVSDecoderList().iterator(); i.hasNext(); ) {
            VSDecoder vsd = i.next();
            children.add(vsd.getXml());
        }
        // Throttle-specific stuff below.  Kept for reference
        /*
             // 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);
             }
             */
        // End Throttle-specific stuff.
        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 VSDecoder xml: " + ex);
        } finally {
            o.close();
        }
    } catch (FileNotFoundException ex) {
        log.warn("Exception in storing VSDecoder xml: " + ex);
    } catch (IOException ex) {
        log.warn("Exception in storing VSDecoder 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

Document (org.jdom2.Document)86 Element (org.jdom2.Element)76 Test (org.junit.Test)33 File (java.io.File)29 DocType (org.jdom2.DocType)24 SAXBuilder (org.jdom2.input.SAXBuilder)21 IOException (java.io.IOException)16 XMLOutputter (org.jdom2.output.XMLOutputter)15 ProcessingInstruction (org.jdom2.ProcessingInstruction)13 XmlFile (jmri.jmrit.XmlFile)11 Document (com.google.cloud.language.v1beta2.Document)10 ApiException (com.google.api.gax.grpc.ApiException)9 Document (com.google.cloud.language.v1.Document)9 GeneratedMessageV3 (com.google.protobuf.GeneratedMessageV3)9 StatusRuntimeException (io.grpc.StatusRuntimeException)9 ArrayList (java.util.ArrayList)9 EncodingType (com.google.cloud.language.v1beta2.EncodingType)8 FileOutputStream (java.io.FileOutputStream)8 JLabel (javax.swing.JLabel)7 EncodingType (com.google.cloud.language.v1.EncodingType)6