Example usage for org.jdom2.input SAXBuilder SAXBuilder

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

Introduction

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

Prototype

public SAXBuilder() 

Source Link

Document

Creates a new JAXP-based SAXBuilder.

Usage

From source file:edu.kit.iks.cryptographicslib.framework.controller.StartController.java

License:MIT License

@Override
public void loadView() {
    this.view = new JPanel(new GridBagLayout());
    this.view.setName("start-controller-view");

    SAXBuilder saxBuilder = new SAXBuilder();

    // obtain file object
    InputStream is = this.getClass().getResourceAsStream("/start/startResources.xml");

    try {//from   w w  w  .  ja  v a 2  s  .c o m
        // converted file to document object
        Document document = saxBuilder.build(is);

        // get root node from xml
        this.startResources = document.getRootElement();
    } catch (JDOMException | IOException e) {
        Logger.error(e);
    }

    // Add welcome view and its layout
    GridBagConstraints welcomeViewLayout = new GridBagConstraints();
    welcomeViewLayout.fill = GridBagConstraints.HORIZONTAL;
    welcomeViewLayout.gridy = 0;
    welcomeViewLayout.weighty = 0.95f;
    this.welcomeView = new WelcomeView();
    this.view.add(this.welcomeView, welcomeViewLayout);

    String path = startResources.getChild("welcomeImage").getAttributeValue("path");

    GridBagConstraints imgConstraint = new GridBagConstraints();
    imgConstraint.gridx = 0;
    imgConstraint.gridy = 1;
    imgConstraint.insets = new Insets(0, 0, 50, 0);
    ImageView imageToSet = new ImageView(path);
    this.view.add(imageToSet, imgConstraint);

    // Add timeline view and its layout
    GridBagConstraints timelineViewLayout = new GridBagConstraints();
    timelineViewLayout.fill = GridBagConstraints.HORIZONTAL;
    timelineViewLayout.weightx = 1.0f;
    timelineViewLayout.weighty = 0.05f;
    timelineViewLayout.gridy = 2;
    this.timelineView = new TimelineView(visualizationInfos);
    this.view.add(this.timelineView, timelineViewLayout);

    // Add event handlers
    for (VisualizationButtonView button : this.timelineView.getButtons()) {
        button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                VisualizationButtonView button = (VisualizationButtonView) e.getSource();
                StartController.this.presentPopoverAction(button.getVisualizationInfo(), button);
            }

        });
    }

    this.view.validate();
}

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

License:Open Source License

/**
 * <p>//w  ww . j av a 2s.  c o m
 *     Loads all settings found on the hard drive into memory.
 * </p>
 */
public void load() {
    settingsMap.clear();

    try {
        // Set up the XML parser
        SAXBuilder saxBuilder = new SAXBuilder();
        Document document = saxBuilder.build(settingsFile);
        Element rootElement = document.getRootElement();

        if (!checkHead(rootElement.getChild("head"))) {
            logger.error("Settings file does not match specified type");
            return;
        }

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

        // Parse through all entries and add them to the map
        List<Element> entries = data.getChildren();
        entries.stream().forEach(entry -> {
            // Get the type, key and value. The type has to be specified as the whole class name, otherwise
            // it is set to java.lang.Object
            String type = entry.getAttribute("type").getValue();
            Class typeClass;
            try {
                typeClass = Class.forName(type);
            } catch (ClassNotFoundException e) {
                logger.error("Specified type class does not exist, setting the type class to java.lang.Object",
                        e);
                typeClass = Object.class;
            }
            String key = entry.getChild("key").getValue();
            String value = entry.getChild("value").getValue();

            // Finally add the data to the map
            addToMap(typeClass, key, value);
        });
    } catch (JDOMException | IOException e) {
        logger.error("Error while parsing the " + CONFIG_FILE_NAME + " file", e);
    }
}

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

License:Open Source License

/**
 * <p>//w  w  w  .  j a v a 2 s  .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  ava  2  s.  co  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 a 2 s . co  m*/
 */
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  ww  w .j  av  a2 s. co 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/* w ww.jav a 2s .  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  w ww . j av  a2 s. c  o  m*/

    // 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.dl.fedora.JobForwardingJMSListener.java

License:Apache License

@Override
public void onMessage(Message message) {

    log.debug("Received message");

    // If no jobs are listening, ignore the message
    if (listenerJobs.size() == 0)
        return;//from   w w  w . jav  a2s  . co m

    if (message instanceof TextMessage) {
        try {
            TextMessage msg = (TextMessage) message;

            String messageBody = msg.getText();
            Document msgDoc = new SAXBuilder().build(new StringReader(messageBody));

            log.debug("Message contents:\n{}", messageBody);

            // This does not need to be synchronized because it is using CopyOnWriteArrayList
            for (ListenerJob listener : listenerJobs) {
                listener.onEvent(msgDoc);
            }

        } catch (Exception e) {
            log.error("onMessage failed", e);
        }
    } else {
        throw new IllegalArgumentException("Message must be of type TextMessage");
    }
}

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  2s. c  om
 *       [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;
}