Example usage for org.jdom2 Element getNamespacesInScope

List of usage examples for org.jdom2 Element getNamespacesInScope

Introduction

In this page you can find the example usage for org.jdom2 Element getNamespacesInScope.

Prototype

@Override
public List<Namespace> getNamespacesInScope() 

Source Link

Document

Get the Namespaces that are in-scope on this Element.

Usage

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 {//www.  j av  a2s  .  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:es.upm.dit.xsdinferencer.extraction.extractorImpl.TypesExtractorImpl.java

License:Apache License

/**
 * This method traverses all the elements of each input document in order to find all the namespace URI to prefix mappings present at the documents.
 * With that information, the map between namespace URIs and their known prefixes is filled. It is used later to solve which prefix should be bound 
 * to each namespace URI.//from   w w  w. j av  a  2s.  c o  m
 */
private void fillKnownNamespaceToPrefixMappings() {
    Filter<Element> elementFilter = Filters.element();
    for (int i = 0; i < xmlDocuments.size(); i++) {
        for (Element element : xmlDocuments.get(i).getDescendants(elementFilter)) {
            for (Namespace namespace : element.getNamespacesInScope()) {
                //We do not add XSI to the known namespaces 
                if (namespace.getURI().equalsIgnoreCase(XSI_NAMESPACE_URI))
                    continue;
                String uri = namespace.getURI();
                String prefix = namespace.getPrefix();
                SortedSet<String> currentPrefixes = prefixNamespaceMapping.get(uri);
                if (currentPrefixes == null) {
                    currentPrefixes = new TreeSet<String>();
                    prefixNamespaceMapping.put(uri, currentPrefixes);
                }
                currentPrefixes.add(prefix);
            }
            //If the element belongs to the empty namespace (empty string) with no prefix, we must add 
            //this to the prefix-namespace mapping explicitly
            if (element.getNamespacePrefix().equals("") && element.getNamespaceURI().equals("")) {
                String uri = "";
                String prefix = "";
                SortedSet<String> currentPrefixes = prefixNamespaceMapping.get(uri);
                if (currentPrefixes == null) {
                    currentPrefixes = new TreeSet<>();
                    prefixNamespaceMapping.put(uri, currentPrefixes);
                }
                currentPrefixes.add(prefix);
            }
        }
    }
}

From source file:net.exclaimindustries.paste.braket.server.TeamDownloader.java

License:Open Source License

public static Team parseTeam(Document document) throws MalformedURLException {
    // Parse out the details
    Element rootNode = document.getRootElement();

    // I need the espn namespace
    List<Namespace> namespaceList = rootNode.getNamespacesInScope();
    Namespace ns = Namespace.NO_NAMESPACE;
    for (Namespace namespace : namespaceList) {
        if (namespace.getPrefix() == "espn") {
            ns = namespace;/*from  w w w  . j a va2 s. c  om*/
            break;
        }
    }

    // Find the "item" element that has the right stuff in it
    Element channel = rootNode.getChild("channel");
    List<Element> items = channel.getChildren("item");
    Element teamElement = null;
    for (Element item : items) {
        if (item.getChild("teamAbbrev", ns) != null) {
            teamElement = item.clone();
            break;
        }
    }

    if (teamElement == null) {
        // Couldn't find any info about the team, so skip it.
        return null;
    }

    // Make sure that the given ID matches the ID in the team (else this
    // is not a real team)
    Long teamId = Long.valueOf(teamElement.getChildText("teamId", ns));

    Team team = new Team();
    team.setId(teamId);

    String abbreviation = digOutCDATA(teamElement, "teamAbbrev", ns);
    String displayName = digOutCDATA(teamElement, "teamDisplayName", ns);
    String location = digOutCDATA(teamElement, "teamLocation", ns);
    String nickname = digOutCDATA(teamElement, "teamNickname", ns);
    String teamNameString = teamElement.getChildText("teamName", ns);
    String teamColorString = "#" + teamElement.getChildText("teamColor", ns);
    String teamLogoUrl = teamElement.getChildText("teamLogo", ns);

    TeamName teamName = new TeamName(location, teamNameString, displayName, nickname, abbreviation);
    team.setName(teamName);

    try {
        if (teamColorString != null) {
            RGBAColor color = RGBAColor.fromCSSString(teamColorString);
            team.setColor(color);
        }
    } catch (Exception e) {
        // TODO Is this okay?
    }

    // Save the image name (should be the same as the downloaded version)
    URL url = new URL(teamLogoUrl);
    File file = new File(url.getPath());
    String teamLogoName = file.getName();
    team.setPicture(teamLogoName);

    return team;
}