Example usage for org.jdom2.input SAXBuilder build

List of usage examples for org.jdom2.input SAXBuilder build

Introduction

In this page you can find the example usage for org.jdom2.input SAXBuilder build.

Prototype

@Override
public Document build(final String systemId) throws JDOMException, IOException 

Source Link

Document

This builds a document from the supplied URI.

Usage

From source file:edu.kit.trufflehog.model.configdata.SettingsDataModel.java

License:Open Source License

/**
 * <p>/*from   w  w w  .  j a  va 2s .co m*/
 *     Updates the settings xml file with the current value.
 * </p>
 *
 * @param typeClass The type of the value (i.e. String, Integer or Boolean are examples)
 * @param key The key mapped to the value, classic key value mapping.
 * @param oldValue The old value that should be updated.
 * @param newValue The new value, that should overwrite the old value.
 */
private synchronized void updateSettingsFile(final Class typeClass, final String key, final String oldValue,
        final String newValue) {
    // synchronized because this always runs in its own thread

    try {
        SAXBuilder saxBuilder = new SAXBuilder();
        Document document = saxBuilder.build(settingsFile);

        Element rootElement = document.getRootElement();

        // Get the "data" elements of the xml file
        Element data = rootElement.getChild("data");

        // Parse through all entries and find the right one
        List<Element> entries = data.getChildren();
        entries = entries.stream()
                .filter(entry -> entry.getAttribute("type").getValue().equals(typeClass.getName())
                        && entry.getChild("key").getValue().equals(key)
                        && entry.getChild("value").getValue().equals(oldValue))
                .collect(Collectors.toList());

        // Make sure we actually only found 1 entry
        if (entries.size() < 1) {
            logger.error("No entry was found for type: " + typeClass.getName() + ", key: " + key + ", value: "
                    + oldValue);
            return;
        } else if (entries.size() > 1) {
            logger.error("More than one entry was found for type: " + typeClass.getName() + ", key: " + key
                    + ", value: " + oldValue);
            return;
        }

        saveNewValue(typeClass, key, oldValue, newValue, document, entries.get(0));
    } catch (JDOMException | IOException e) {
        logger.error("Error updating the " + CONFIG_FILE_NAME + " file for key: " + key + " of type: "
                + typeClass.getName(), e);
    }
}

From source file:edu.pitt.apollo.runmanagerservice.methods.stage.StageExperimentMethod.java

License:Apache License

@Override
public void runApolloService() {

    XMLSerializer serializer = new XMLSerializer();
    XMLDeserializer deserializer = new XMLDeserializer();

    InfectiousDiseaseScenario baseScenario = idtes.getInfectiousDiseaseScenarioWithoutIntervention();
    // clear all set control strategies in base
    baseScenario.getInfectiousDiseaseControlStrategies().clear();

    List<SoftwareIdentification> modelIds = idtes.getInfectiousDiseaseTransmissionModelIds();
    try {//from  w  w w  .j a  va2s .c  o m
        DataServiceAccessor dataServiceAccessor = new DataServiceAccessor();

        for (SoftwareIdentification modelId : modelIds) {

            // create a base scenario copy
            String baseXml = serializer.serializeObject(baseScenario);
            InfectiousDiseaseScenario baseScenarioCopy = deserializer.getObjectFromMessage(baseXml,
                    InfectiousDiseaseScenario.class);
            for (InfectiousDiseaseControlStrategy strategy : idtes.getInfectiousDiseaseControlStrategies()) {

                for (InfectiousDiseaseControlMeasure controlMeasure : strategy.getControlMeasures()) {
                    baseScenarioCopy.getInfectiousDiseaseControlStrategies().add(controlMeasure);
                }
            }

            List<SensitivityAnalysisSpecification> sensitivityAnalyses = idtes.getSensitivityAnalyses();
            for (SensitivityAnalysisSpecification sensitivityAnalysis : sensitivityAnalyses) {
                if (sensitivityAnalysis instanceof OneWaySensitivityAnalysisOfContinousVariableSpecification) {
                    OneWaySensitivityAnalysisOfContinousVariableSpecification owsaocv = (OneWaySensitivityAnalysisOfContinousVariableSpecification) sensitivityAnalysis;
                    double min = owsaocv.getMinimumValue();
                    double max = owsaocv.getMaximumValue();
                    double increment = (max - min) / owsaocv.getNumberOfDiscretizations().intValueExact();

                    String scenarioXML = serializer.serializeObject(baseScenarioCopy);

                    double val = min;
                    while (val <= max) {

                        String param = owsaocv.getUniqueApolloLabelOfParameter();

                        Document jdomDocument;
                        SAXBuilder jdomBuilder = new SAXBuilder();
                        try {
                            jdomDocument = jdomBuilder.build(
                                    new ByteArrayInputStream(scenarioXML.getBytes(StandardCharsets.UTF_8)));
                        } catch (JDOMException | IOException ex) {
                            ErrorUtils.reportError(runId,
                                    "Error inserting experiment run. Error was " + ex.getMessage(),
                                    authentication);
                            return;
                        }

                        Element e = jdomDocument.getRootElement();
                        List<Namespace> namespaces = e.getNamespacesInScope();

                        for (Namespace namespace : namespaces) {
                            if (namespace.getURI().contains("http://types.apollo.pitt.edu")) {
                                param = param.replaceAll("/", "/" + namespace.getPrefix() + ":");
                                param = param.replaceAll("\\[", "\\[" + namespace.getPrefix() + ":");
                                break;
                            }
                        }

                        XPathFactory xpf = XPathFactory.instance();
                        XPathExpression<Element> expr;
                        expr = xpf.compile(param, Filters.element(), null, namespaces);
                        List<Element> elements = expr.evaluate(jdomDocument);

                        for (Element element : elements) {
                            element.setText(Double.toString(val));
                        }

                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        XMLOutputter xmlOutputter = new XMLOutputter();
                        xmlOutputter.output(jdomDocument, baos);

                        InfectiousDiseaseScenario newScenario = deserializer.getObjectFromMessage(
                                new String(baos.toByteArray()), InfectiousDiseaseScenario.class);

                        // new scenario is ready to be staged
                        RunSimulationMessage runSimulationMessage = new RunSimulationMessage();
                        runSimulationMessage.setAuthentication(authentication);
                        runSimulationMessage
                                .setSimulatorTimeSpecification(message.getSimulatorTimeSpecification());
                        runSimulationMessage.setSoftwareIdentification(modelId);
                        runSimulationMessage.setInfectiousDiseaseScenario(newScenario);

                        StageMethod stageMethod = new StageMethod(runSimulationMessage, runId);
                        InsertRunResult result = stageMethod.stage();
                        BigInteger newRunId = result.getRunId();

                        MethodCallStatus status = dataServiceAccessor.getRunStatus(newRunId, authentication);
                        if (status.getStatus().equals(MethodCallStatusEnum.FAILED)) {
                            ErrorUtils.reportError(runId,
                                    "Error inserting run in experiment with run ID " + runId + ""
                                            + ". Error was for inserting ID " + newRunId + " with message "
                                            + status.getMessage(),
                                    authentication);
                            return;
                        }

                        val += increment;
                    }
                }
            }
        }

        dataServiceAccessor.updateStatusOfRun(runId, MethodCallStatusEnum.TRANSLATION_COMPLETED,
                "All runs for this experiment have been translated", authentication);
    } catch (DeserializationException | IOException | SerializationException | RunManagementException ex) {
        ErrorUtils.reportError(runId, "Error inserting experiment run. Error was " + ex.getMessage(),
                authentication);
        return;
    }
}

From source file:edu.ucla.loni.server.ServerUtils.java

License:Open Source License

/**
 * Parse an XML file into a Document/*from w ww. j a  v  a2 s  .c om*/
 */
public static Document readXML(File pipe) throws Exception {
    SAXBuilder builder = new SAXBuilder();
    Document doc = (Document) builder.build(pipe);

    return doc;
}

From source file:edu.ucla.loni.server.ServerUtils.java

License:Open Source License

/**
 * Parse an XML file into a Document//from  w  w  w .j ava 2 s  . c o  m
 */
public static Document readXML(InputStream stream) throws Exception {
    SAXBuilder builder = new SAXBuilder();
    Document doc = (Document) builder.build(stream);

    return doc;
}

From source file:edu.ucsd.crbs.cws.workflow.WorkflowFromAnnotatedVersionTwoFourMomlXmlFactory.java

License:Open Source License

/**
 * Returns the root element of parsed XML document
 *
 * @param in XML document to parse//from  w w w  .ja  v  a 2  s.  c  o m
 * @return Root element of document
 * @throws Exception If there is a problem parsing the document
 */
private Document getDocument(InputStream in) throws Exception {
    SAXBuilder builder = new SAXBuilder();
    builder.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    return builder.build(in);
}

From source file:edu.unc.lib.deposit.normalize.Proquest2N3BagJob.java

License:Apache License

private void normalizePackage(File packageDir, Model model, Bag depositBag) {

    // Generate a uuid for the main object
    PID primaryPID = new PID("uuid:" + UUID.randomUUID());
    Resource primaryResource;/*from ww  w  .  ja va2 s  .  com*/

    // Identify the important files from the deposit
    File dataFile = null, contentFile = null, attachmentDir = null;

    File[] files = packageDir.listFiles();
    for (File file : files) {
        if (file.isDirectory()) {
            attachmentDir = file;
        } else if (file.getName().endsWith(DATA_SUFFIX)) {
            dataFile = file;
        } else {
            contentFile = file;
        }
    }

    long lastModified = -1;
    File zipFile = new File(packageDir.getAbsolutePath() + ".zip");
    try (ZipFile zip = new ZipFile(zipFile)) {
        ZipArchiveEntry entry = zip.getEntry(contentFile.getName());
        lastModified = entry.getTime();
    } catch (IOException e) {
        log.error("Failed to read zip file located at {}.zip", packageDir.getAbsolutePath(), e);
    }

    if (lastModified == -1) {
        lastModified = zipFile.lastModified();
    }

    DateTime modified = new DateTime(lastModified, DateTimeZone.UTC);

    // Deserialize the data document
    SAXBuilder builder = new SAXBuilder();
    Element dataRoot = null;
    Document mods = null;
    try {

        Document dataDocument = builder.build(dataFile);
        dataRoot = dataDocument.getRootElement();

        // Transform the data into MODS and store it to its final resting place
        mods = extractMods(primaryPID, dataRoot, modified);
    } catch (TransformerException e) {
        failJob(e, Type.NORMALIZATION, "Failed to transform metadata to MODS");
    } catch (Exception e) {
        failJob(e, Type.NORMALIZATION, "Unable to deserialize the metadata file");
    }

    // Detect if there are any attachments
    List<?> attachmentElements = dataRoot.getChild("DISS_content").getChildren("DISS_attachment");

    if (attachmentElements == null || attachmentElements.size() == 0) {

        // Simple object with the content as its source data
        primaryResource = populateSimple(model, primaryPID, contentFile);
    } else {
        String title = mods.getRootElement().getChild("titleInfo", MODS_V3_NS).getChildText("title",
                MODS_V3_NS);

        // Has attachments, so it is an aggregate
        primaryResource = populateAggregate(model, primaryPID, attachmentElements, attachmentDir, contentFile,
                title);
    }

    // Store primary resource as child of the deposit
    depositBag.add(primaryResource);

    // Add the data file as a metadata datastream of the primary object
    setSourceMetadata(model, primaryResource, dataFile);

    // Capture other metadata, like embargoes
    setEmbargoUntil(model, primaryResource, dataRoot);

    // Creation date for the content file
    model.add(primaryResource, cdrprop(model, dateCreated), modified.toString(), XSDDatatype.XSDdateTime);
}

From source file:edu.unc.lib.deposit.normalize.VocabularyEnforcementJob.java

License:Apache License

@Override
public void runJob() {
    Model model = getWritableModel();//from   w  w w .  j a  v a2s.  c  om

    // Get the list of all objects being ingested in this job
    List<String> resourcePIDs = new ArrayList<>();
    Bag deposit = model.getBag(getDepositPID().getURI());
    walkChildrenDepthFirst(deposit, resourcePIDs, true);

    SAXBuilder sb = new SAXBuilder(new XMLReaderSAX2Factory(false));

    // Vocabulary mappings need to be resolved against the destination since they are not in the hierarchy yet
    PID destinationPID = new PID(getDepositStatus().get(DepositField.containerId.name()));

    for (String resourcePID : resourcePIDs) {
        PID pid = new PID(resourcePID);
        File modsFile = new File(getDescriptionDir(), pid.getUUID() + ".xml");

        // Check if the resource has a description
        if (modsFile.exists()) {
            try {
                Document modsDoc = sb.build(modsFile);

                // Update the MODS document to use approved terms when possible if the vocabularies support remapping
                log.debug("Updating document terms for {} within destination {}", pid, destinationPID);
                boolean modified = updateDocumentTerms(destinationPID, modsDoc.getRootElement());

                // Update the mods document if it was changed
                if (modified) {
                    try (FileOutputStream fos = new FileOutputStream(modsFile)) {
                        new XMLOutputter(Format.getPrettyFormat()).output(modsDoc.getDocument(), fos);
                    }
                }

                // Capture any invalid affiliations as relations
                log.debug("Adding invalid terms for {} within destination {}", pid, destinationPID);
                addInvalidTerms(pid, destinationPID, modsDoc.getRootElement(), model);

            } catch (JDOMException | IOException e) {
                log.error("Failed to parse description file {}", modsFile.getAbsolutePath(), e);
            }
        }
    }
}

From source file:edu.unc.lib.dl.xml.DepartmentOntologyUtil.java

License:Apache License

/**
 * Parses a SKOS XML vocabulary located at filePath and populates a lookup index labels and alternative labels
 * referencing the authoritative version.
 *
 * @param ontologyURL/*from ww w  . ja  v a2 s .c om*/
 * @throws Exception
 */
private void parseVocabulary(byte[] content) throws Exception {
    departments = new HashMap<String, DepartmentConcept>();

    log.debug("Parsing and building Department vocabulary from {}", getVocabularyURI());

    SAXBuilder sb = new SAXBuilder(new XMLReaderSAX2Factory(false));
    Document skosDoc = sb.build(new ByteArrayInputStream(content));

    // Extract all of the concepts and store them to an index
    List<?> concepts = skosDoc.getRootElement().getChildren("Concept", SKOS_NS);
    Map<String, DepartmentConcept> tempDepts = new HashMap<String, DepartmentConcept>(concepts.size());
    for (Object conceptObj : concepts) {
        DepartmentConcept dept = new DepartmentConcept((Element) conceptObj);
        tempDepts.put(cleanLabel(dept.getIdentifier()), dept);
    }

    // Expand out all the alternative labels into an index and resolve references
    for (Iterator<Entry<String, DepartmentConcept>> deptIt = tempDepts.entrySet().iterator(); deptIt
            .hasNext();) {
        Entry<String, DepartmentConcept> deptEntry = deptIt.next();

        DepartmentConcept dept = deptEntry.getValue();

        // Check if this concept should be ignored in favor of a preferred concept
        if (dept.prefLabel != null) {
            if (departments.containsKey(dept.prefLabel)) {
                // The preferred concept has already been indexed, grab extra labels from this concept and reindex pref
                DepartmentConcept prefDept = departments.get(dept.prefLabel);
                prefDept.merge(dept);
                addLabels(prefDept);
            } else {
                // Since the preferred concept isn't indexed yet, just need to merge labels into it
                DepartmentConcept prefDept = tempDepts.get(dept.prefLabel);
                if (prefDept == null) {
                    log.warn("Preferred label {} referencing a concept which is not present", dept.prefLabel);
                } else {
                    prefDept.merge(dept);
                }
            }
            continue;
        }

        String identifier = cleanLabel(dept.identifier);
        if (departments.containsKey(identifier)
                && dept.identifier.equals(departments.get(identifier).identifier)) {
            log.error("Illegal state, multiple concepts share the identifier {}, ignoring duplicate",
                    identifier);
        } else {
            departments.put(identifier, dept);
        }

        addLabels(dept);
    }
}

From source file:edu.utep.cs.jasg.Frontend.java

License:Open Source License

/** Parse build XML file. Returns a String array with the following content:
 *       [0] = target module name//from w  w  w  .j  a v a 2 s  . c o m
 *       [1] = target module main scanner specification file
 *       [2] = target module main parser specification file
 * */
public String[] parseBuildFile(String filePath) {
    String[] result = { "", "", "" };

    if (Files.exists(Paths.get(filePath))) {

        try {
            SAXBuilder builder = new SAXBuilder();
            Document doc = (Document) builder.build(filePath);
            Element root = doc.getRootElement();

            if (root != null) {
                List<Element> propertyList = root.getChildren("property");
                Iterator<Element> propertiesIterator = propertyList.iterator();

                //Get module name
                String moduleName = root.getAttributeValue("name");
                if (moduleName != null)
                    result[0] = moduleName;

                //Get specification name properties
                while (propertiesIterator.hasNext()) {
                    Element property = propertiesIterator.next();
                    String propertyName = property.getAttributeValue("name");
                    String propertyValue = property.getAttributeValue("value");

                    if (propertyName != null) {
                        //Get scanner name
                        if (propertyName.equals("scannerName")) {
                            if (propertyValue != null)
                                result[1] = propertyValue;
                        }
                        //Get scanner name
                        else if (propertyName.equals("parserName")) {
                            if (propertyValue != null)
                                result[2] = propertyValue;
                        }
                    }
                }
            }
        } catch (IOException io) {
            System.out.println(io.getMessage());
        } catch (JDOMException jdomex) {
            System.out.println(jdomex.getMessage());
        }
    }
    return result;
}

From source file:edu.utep.cs.jasg.specificationGenerator.XMLParser.java

License:Open Source License

/** Parser XML file. */
public void parse(String filePath) {
    if (Files.exists(Paths.get(filePath)) && DOMValidateDTD.validateXML(filePath)) {
        try {//ww w . j a v  a  2s .  c o  m
            SAXBuilder builder = new SAXBuilder();
            Document doc = (Document) builder.build(filePath);
            Element root = doc.getRootElement();

            nameSpace = root.getChild("nameSpace").getText();

            //TODO: should I replace all files? Like compiling new files
            //check existing name spaces
            if (!Files.exists(Paths.get(workspace + File.separator + nameSpace))) {
                fileFactory.createDirectory(nameSpace);
            }

            specificationGenerator = new SpecificationGenerator(fileFactory, nameSpace);

            //get root element declarations
            Element parserElement = root.getChild("parser");

            Element scannerElement = root.getChild("scanner");

            Element ASTNodeElement = root.getChild("AST");

            Element ASTBehaviorElement = root.getChild("ASTBehavior");

            //parse root elements (document specifications)
            if (parserElement != null)
                parseRootElement("parser", parserElement);

            if (scannerElement != null)
                parseRootElement("scanner", scannerElement);

            if (ASTNodeElement != null)
                parseRootElement("AST", ASTNodeElement);

            if (ASTBehaviorElement != null)
                parseRootElement("ASTBehavior", ASTBehaviorElement);

        } catch (IOException io) {
            System.out.println(io.getMessage());
        } catch (JDOMException jdomex) {
            System.out.println(jdomex.getMessage());

        }
    }
}