Search in sources :

Example 1 with Namespace.getNamespace

use of org.jdom2.Namespace.getNamespace in project JMRI by JMRI.

the class DecoderIndexFile method writeFile.

public void writeFile(String name, DecoderIndexFile oldIndex, String[] files) throws java.io.IOException {
    if (log.isDebugEnabled()) {
        log.debug("writeFile " + name);
    }
    // This is taken in large part from "Java and XML" page 368
    File file = new File(FileUtil.getUserFilesPath() + name);
    // create root element and document
    Element root = new Element("decoderIndex-config");
    root.setAttribute("noNamespaceSchemaLocation", "http://jmri.org/xml/schema/decoder.xsd", org.jdom2.Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"));
    Document doc = newDocument(root);
    // add XSLT processing instruction
    // <?xml-stylesheet type="text/xsl" href="XSLT/DecoderID.xsl"?>
    java.util.Map<String, String> m = new java.util.HashMap<>();
    m.put("type", "text/xsl");
    m.put("href", xsltLocation + "DecoderID.xsl");
    ProcessingInstruction p = new ProcessingInstruction("xml-stylesheet", m);
    doc.addContent(0, p);
    // add top-level elements
    Element index;
    root.addContent(index = new Element("decoderIndex"));
    index.setAttribute("version", Integer.toString(fileVersion));
    log.debug("version written to file as " + fileVersion);
    // add mfg list from existing DecoderIndexFile item
    Element mfgList = new Element("mfgList");
    // copy dates from original mfgList element
    if (oldIndex.nmraListDate != null) {
        mfgList.setAttribute("nmraListDate", oldIndex.nmraListDate);
    }
    if (oldIndex.updated != null) {
        mfgList.setAttribute("updated", oldIndex.updated);
    }
    if (oldIndex.lastAdd != null) {
        mfgList.setAttribute("lastadd", oldIndex.lastAdd);
    }
    // We treat "NMRA" special...
    Element mfg = new Element("manufacturer");
    mfg.setAttribute("mfg", "NMRA");
    mfg.setAttribute("mfgID", "999");
    mfgList.addContent(mfg);
    // start working on the rest of the entries
    List<String> keys = new ArrayList<>(oldIndex._mfgIdFromNameHash.keySet());
    Collections.sort(keys);
    for (Object item : keys) {
        String mfgName = (String) item;
        if (!mfgName.equals("NMRA")) {
            mfg = new Element("manufacturer");
            mfg.setAttribute("mfg", mfgName);
            mfg.setAttribute("mfgID", oldIndex._mfgIdFromNameHash.get(mfgName));
            mfgList.addContent(mfg);
        }
    }
    // add family list by scanning files
    Element familyList = new Element("familyList");
    for (String fileName : files) {
        DecoderFile d = new DecoderFile();
        try {
            Element droot = d.rootFromName(DecoderFile.fileLocation + fileName);
            Element family = droot.getChild("decoder").getChild("family").clone();
            family.setAttribute("file", fileName);
            familyList.addContent(family);
        } catch (org.jdom2.JDOMException exj) {
            log.error("could not parse " + fileName + ": " + exj.getMessage());
        } catch (java.io.FileNotFoundException exj) {
            log.error("could not read " + fileName + ": " + exj.getMessage());
        } catch (IOException exj) {
            log.error("other exception while dealing with " + fileName + ": " + exj.getMessage());
        }
    }
    index.addContent(mfgList);
    index.addContent(familyList);
    writeXML(file, doc);
    // force a read of the new file next time
    resetInstance();
}
Also used : HashMap(java.util.HashMap) Element(org.jdom2.Element) ArrayList(java.util.ArrayList) IOException(java.io.IOException) Document(org.jdom2.Document) JDOMException(org.jdom2.JDOMException) File(java.io.File) XmlFile(jmri.jmrit.XmlFile) ProcessingInstruction(org.jdom2.ProcessingInstruction)

Example 2 with Namespace.getNamespace

use of org.jdom2.Namespace.getNamespace 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 3 with Namespace.getNamespace

use of org.jdom2.Namespace.getNamespace 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 4 with Namespace.getNamespace

use of org.jdom2.Namespace.getNamespace in project JMRI by JMRI.

the class RevHistoryXml method loadRevision.

static void loadRevision(RevHistory r, Element e) {
    Element s;
    Namespace n = Namespace.getNamespace(NAMESPACE);
    int revnumber = 0;
    s = e.getChild("revnumber", n);
    if (s != null) {
        String c = s.getText();
        revnumber = Integer.parseInt(c);
    }
    String date = null;
    s = e.getChild("date", n);
    if (s != null) {
        date = s.getText();
    }
    String authorinitials = null;
    s = e.getChild("authorinitials", n);
    if (s != null) {
        authorinitials = s.getText();
    }
    String revremark = null;
    s = e.getChild("revremark", n);
    if (s != null) {
        revremark = s.getText();
    }
    r.addRevision(revnumber, date, authorinitials, revremark);
}
Also used : Element(org.jdom2.Element) Namespace(org.jdom2.Namespace)

Example 5 with Namespace.getNamespace

use of org.jdom2.Namespace.getNamespace in project scylla by bptlab.

the class ProcessModelParser method parseExtensions.

private Map<Integer, BatchActivity> parseExtensions(Element el, Namespace bpmnNamespace, Integer nodeId, Map<Integer, BatchActivity> batchActivities) throws ScyllaValidationException {
    // Check that only elements with extensions get parsed
    if (el.getChild("extensionElements", bpmnNamespace) == null)
        return batchActivities;
    String id = el.getAttributeValue("id");
    Namespace camundaNamespace = Namespace.getNamespace("camunda", "http://camunda.org/schema/1.0/bpmn");
    List<Namespace> namespaces = Arrays.asList(camundaNamespace, bpmnNamespace);
    Predicate<Namespace> isOneOfUsedNamespaces = namespace -> el.getChild("extensionElements", bpmnNamespace).getChild("properties", namespace) == null;
    if (namespaces.stream().allMatch(isOneOfUsedNamespaces))
        return batchActivities;
    Integer maxBatchSize = null;
    BatchClusterExecutionType executionType = BatchClusterExecutionType.PARALLEL;
    ActivationRule activationRule = null;
    List<String> groupingCharacteristic = new ArrayList<String>();
    for (Namespace namespace : namespaces) {
        if (el.getChild("extensionElements", bpmnNamespace).getChild("properties", namespace) == null)
            continue;
        List<Element> propertiesList = el.getChild("extensionElements", bpmnNamespace).getChild("properties", namespace).getChildren("property", namespace);
        for (Element property : propertiesList) {
            // maximum batch size
            switch(property.getAttributeValue("name")) {
                case "maxBatchSize":
                    maxBatchSize = Integer.parseInt(property.getAttributeValue("value"));
                    break;
                // execution type. if none is defined, take parallel as default
                case "executionType":
                    String tmpExecutionType = property.getAttributeValue("value");
                    /*if (!(tmpExecutionType.equals("parallel") || tmpExecutionType.equals("sequential-taskbased") || tmpExecutionType.equals("sequential-casebased"))){
                            throw new ScyllaValidationException("Execution type " + tmpExecutionType + " not supported. Pleause us either parallel or sequential (either task or case-based)");
                        }
                        BatchClusterExecutionType bce = BatchClusterExecutionType.PARALLEL;
                        executionType = property.getAttributeValue("value");*/
                    switch(property.getAttributeValue("value")) {
                        case "parallel":
                            executionType = BatchClusterExecutionType.PARALLEL;
                        case "sequential-taskbased":
                            executionType = BatchClusterExecutionType.SEQUENTIAL_TASKBASED;
                        case "sequential-casebased":
                            executionType = BatchClusterExecutionType.SEQUENTIAL_CASEBASED;
                    }
                    break;
                // grouping characteristic
                case "groupingCharacteristic":
                    List<Element> groupings = property.getChildren("property", namespace);
                    for (Element grouping : groupings) {
                        if (grouping.getAttributeValue("name").equals("processVariable")) {
                            groupingCharacteristic.add(grouping.getAttributeValue("value"));
                        }
                    }
                    break;
                // threshold capacity (minimum batch size) & timeout of activation rule
                case "activationRule":
                    List<Element> ruleElements = property.getChildren("property", namespace);
                    if (ruleElements.size() != 1) {
                        throw new ScyllaValidationException("There must be exactly one activation rule for batch activity " + id + ", but there are " + ruleElements.size() + ".");
                    }
                    Element ruleElement = property.getChild("property", namespace);
                    String ruleElementName = ruleElement.getName();
                    switch(ruleElement.getAttributeValue("name")) {
                        case "thresholdRule":
                            // parsing threshold, if it is defined
                            int threshold = 0;
                            String thresholdString = ruleElement.getAttributeValue("threshold");
                            if (thresholdString != null && !thresholdString.isEmpty()) {
                                threshold = Integer.parseInt(thresholdString);
                            }
                            // parsing timeout, if it is defined
                            Duration timeout = null;
                            String timeoutString = ruleElement.getAttributeValue("timeout");
                            if (timeoutString != null) {
                                timeout = Duration.parse(timeoutString);
                            }
                            // parsing dueDate, if it is defined
                            String dueDate = ruleElement.getAttributeValue("duedate");
                            // either timeout or dueDate should not be null --> two different Constructors for the ThresholdRule
                            if (timeout != null) {
                                activationRule = new ThresholdRule(threshold, timeout);
                            } else if (dueDate != null) {
                                activationRule = new ThresholdRule(threshold, dueDate);
                            } else {
                                throw new ScyllaValidationException("A threshold rule was selected for" + ruleElementName + " then either timeout or duedate must be specified.");
                            }
                            break;
                        case "minMaxRule":
                            int minInstances = Integer.parseInt(ruleElement.getAttributeValue("minInstances"));
                            Duration minTimeout = Duration.parse(ruleElement.getAttributeValue("minTimeout"));
                            int maxInstances = Integer.parseInt(ruleElement.getAttributeValue("maxInstances"));
                            Duration maxTimeout = Duration.parse(ruleElement.getAttributeValue("maxTimeout"));
                            activationRule = new MinMaxRule(minInstances, minTimeout, maxInstances, maxTimeout);
                            break;
                        default:
                            throw new ScyllaValidationException("Activation rule type" + ruleElementName + " for batch activity " + id + " not supported.");
                    }
                    break;
            }
        }
    }
    if (maxBatchSize == null) {
        throw new ScyllaValidationException("You have to specify a maxBatchSize at " + id + " .");
    }
    /*if (groupingCharacteristic.isEmpty()){
                        throw new ScyllaValidationException("You have to specify at least one groupingCharacteristic at "+ id +" .");
                    }*/
    BatchActivity ba = new BatchActivity(nodeId, maxBatchSize, executionType, activationRule, groupingCharacteristic);
    batchActivities.put(nodeId, ba);
    return batchActivities;
/*System.out.println(maxBatchSize);
        System.out.println(groupingCharacteristic);
        System.out.println(activationRule);*/
}
Also used : ProcessModel(de.hpi.bpt.scylla.model.process.ProcessModel) java.util(java.util) MessageFlow(de.hpi.bpt.scylla.model.process.node.MessageFlow) Name(javax.xml.soap.Name) Predicate(java.util.function.Predicate) SimulationManager(de.hpi.bpt.scylla.SimulationManager) GatewayType(de.hpi.bpt.scylla.model.process.node.GatewayType) NoStartNodeException(de.hpi.bpt.scylla.model.process.graph.exception.NoStartNodeException) de.hpi.bpt.scylla.plugin.batch(de.hpi.bpt.scylla.plugin.batch) MultipleStartNodesException(de.hpi.bpt.scylla.model.process.graph.exception.MultipleStartNodesException) DataObjectType(de.hpi.bpt.scylla.model.process.node.DataObjectType) CommonProcessElements(de.hpi.bpt.scylla.model.process.CommonProcessElements) TaskType(de.hpi.bpt.scylla.model.process.node.TaskType) ScyllaValidationException(de.hpi.bpt.scylla.exception.ScyllaValidationException) Attribute(org.jdom2.Attribute) NodeNotFoundException(de.hpi.bpt.scylla.model.process.graph.exception.NodeNotFoundException) Graph(de.hpi.bpt.scylla.model.process.graph.Graph) EventType(de.hpi.bpt.scylla.model.process.node.EventType) Duration(java.time.Duration) DebugLogger(de.hpi.bpt.scylla.logger.DebugLogger) EventDefinitionType(de.hpi.bpt.scylla.model.process.node.EventDefinitionType) Namespace(org.jdom2.Namespace) Element(org.jdom2.Element) Element(org.jdom2.Element) Duration(java.time.Duration) Namespace(org.jdom2.Namespace) ScyllaValidationException(de.hpi.bpt.scylla.exception.ScyllaValidationException)

Aggregations

Element (org.jdom2.Element)73 Namespace (org.jdom2.Namespace)55 Document (org.jdom2.Document)36 IOException (java.io.IOException)22 ArrayList (java.util.ArrayList)18 Attribute (org.jdom2.Attribute)17 SAXBuilder (org.jdom2.input.SAXBuilder)13 JDOMException (org.jdom2.JDOMException)12 XMLOutputter (org.jdom2.output.XMLOutputter)11 File (java.io.File)8 HashMap (java.util.HashMap)7 Test (org.junit.jupiter.api.Test)7 List (java.util.List)6 Context (gov.cms.qpp.conversion.Context)5 Node (gov.cms.qpp.conversion.model.Node)5 StringReader (java.io.StringReader)5 Writer (java.io.Writer)5 JaxenException (org.jaxen.JaxenException)5 Test (org.junit.Test)5 Path (java.nio.file.Path)4