Example usage for org.jdom2 Document getRootElement

List of usage examples for org.jdom2 Document getRootElement

Introduction

In this page you can find the example usage for org.jdom2 Document getRootElement.

Prototype

public Element getRootElement() 

Source Link

Document

This will return the root Element for this Document

Usage

From source file:edu.kit.iks.cryptographicslib.common.view.InformationView.java

License:MIT License

/**
 * Helper to init the resources./*from  ww w . j  av a  2 s  .co  m*/
 */
private void initResources() {
    SAXBuilder saxBuilder = new SAXBuilder();

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

    try {
        // converted file to document object
        Document document = saxBuilder.build(is);

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

From source file:edu.kit.iks.cryptographicslib.common.view.partial.KeyboardView.java

License:MIT License

/**
 * Helper to init the resources./*w  w w .ja  v a  2s  .co  m*/
 */
private void initResources() {
    SAXBuilder saxBuilder = new SAXBuilder();

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

    try {
        // converted file to document object
        Document document = saxBuilder.build(is);

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

From source file:edu.kit.iks.cryptographicslib.common.view.partial.NumpadView.java

License:MIT License

private void initResources() {
    SAXBuilder saxBuilder = new SAXBuilder();

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

    try {/*w  w  w.  j  a  v a  2  s. c om*/
        // converted file to document object
        Document document = saxBuilder.build(is);

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

From source file:edu.kit.iks.CryptographicsLib.Configuration.java

License:MIT License

/**
 * Marked as private to enforce singleton pattern.
 *//*from w ww .ja va  2 s.  com*/
private Configuration(String path) {
    try {
        // Load document.
        SAXBuilder saxBuilder = new SAXBuilder();
        Document document = saxBuilder.build(new File(path));

        // Get root element.
        Element element = document.getRootElement();
        for (Element child : element.getChildren()) {
            parseConfigElement(child);
        }
    } catch (JDOMException | IOException e) {
        // Could not read configuration. Use default values and print stack
        // trace.
        e.printStackTrace();
    }
}

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  . j  a 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  2  s . 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>/*from   w  w w.  j  av 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 {// ww  w .  j av a2s.  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

/** 
 * Get the main element (who has the attributes and children we care about)
 * from a document//from   www.  ja v a2s .c o  m
 */
private static Element getMainElement(Document doc) throws Exception {
    Element pipeline = doc.getRootElement();

    Element moduleGroup = pipeline.getChild("moduleGroup");
    if (moduleGroup == null) {
        throw new Exception("Pipefile does not have moduleGroup");
    } else {
        List<Element> data = moduleGroup.getChildren("dataModule");
        List<Element> module = moduleGroup.getChildren("module");

        if (data.size() == 1 && module.size() == 0) {
            return data.get(0);
        } else if (module.size() == 1 && data.size() == 0) {
            return module.get(0);
        } else {
            return moduleGroup;
        }
    }
}

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

License:Open Source License

/**
 * Reads the access file for the root directory
 * Side Effect: Updates accessFileModified in the database
 *//*from  w  w  w.  jav  a  2s  .  c  o m*/
public static void readAccessFile(Directory root) throws Exception {
    File accessFile = ServerUtils.getAccessFile(root);
    if (!accessFile.exists()) {
        return;
    }

    Document doc = readXML(accessFile);
    Element access = doc.getRootElement();
    Element filesRoot = access.getChild("files");
    Element groupsRoot = access.getChild("groups");

    if (filesRoot.getChildren() != null) {
        for (Element pipe : filesRoot.getChildren()) {
            String packageName = pipe.getAttributeValue("package");
            String type = pipe.getAttributeValue("type");
            String name = pipe.getAttributeValue("name");

            Pipefile thisPipe = Database.selectPipefileByHierarchy(root.dirId, packageName, type, name);

            if (thisPipe != null) {
                thisPipe.access = readAccessFileGroup(pipe);
                ;
                Database.updatePipefile(thisPipe);
            }
        }
    }

    if (groupsRoot.getChildren() != null) {
        for (Element group : groupsRoot.getChildren()) {
            String name = group.getAttributeValue("name");
            String userString = readAccessFileGroup(group);

            Group thisGroup = Database.selectGroupByName(root.dirId, name);

            if (thisGroup == null) {
                thisGroup = new Group();
                thisGroup.name = name;
                thisGroup.users = userString;
                Database.insertGroup(root.dirId, thisGroup);
            } else {
                thisGroup.users = userString;
                Database.updateGroup(thisGroup);
            }
        }
    }

    // Update when the access file was written
    root.accessModified = new Timestamp(accessFile.lastModified());
    Database.updateDirectory(root);
}