Example usage for org.jdom2.xpath XPathFactory instance

List of usage examples for org.jdom2.xpath XPathFactory instance

Introduction

In this page you can find the example usage for org.jdom2.xpath XPathFactory instance.

Prototype

public static final XPathFactory instance() 

Source Link

Document

Obtain an instance of an XPathFactory using the default mechanisms to determine what XPathFactory implementation to use.

Usage

From source file:displayclient.DownloadManager.java

License:Open Source License

@Override
public void run() {
    int updateInterval = Integer.parseInt(DisplayClient.prop.getProperty("CollectInterval"));
    log.log(Level.INFO, "Run. Collection Interval = {0}", updateInterval);

    while (running) {
        // Update thread limits and updateInterval incase they changed on
        // instruction from the CMS
        this.numThreadsLimit = Integer.parseInt(DisplayClient.prop.getProperty("MaxConcurrentDownloads"));
        updateInterval = Integer.parseInt(DisplayClient.prop.getProperty("CollectInterval"));

        String response = "";
        try {/*from   w w w . j  a v  a2 s  . co m*/
            response = this.DC.XMDS.RequiredFiles(DisplayClient.prop.getProperty("ServerKey"),
                    DisplayClient.prop.getProperty("HardwareKey"));
            log.log(Level.FINE, "DownloadManager: xmds.requiredFiles => {0}", response);
        } catch (Exception ex) {
            log.log(Level.FINEST, "DownloadManager: xmds.requiredFiles => {0}", response);
            log.log(Level.WARNING, "DownloadManager: Could not connect to XMDS at {0}",
                    DisplayClient.prop.getProperty("ServerUri"));
            log.log(Level.WARNING, "DownloadManager: xmds.requiredFiles => {0}", ex);
            continue;
        }

        Document doc;
        Iterator iter;

        if (!response.equals("")) {
            // Code here to parse the returned XML
            SAXBuilder sb = new SAXBuilder();

            try {
                doc = sb.build(new StringReader(response));

                // Build an iterator over the files section of the response
                XPathFactory xFactory = XPathFactory.instance();

                XPathExpression<Element> expr = xFactory.compile("//file", Filters.element());
                List<Element> files = expr.evaluate(doc);
                for (Element n : files) {

                    FileFetcher f = null;

                    if (n.getAttributeValue("download").equalsIgnoreCase("http")) {
                        f = new HttpFileFetcher(this, n);
                    } else {
                        f = new XmdsFileFetcher(this, n);
                    }

                    Boolean skip = false;

                    // Check to see if there is already a download
                    // running for this file ID. If there is, skip it.
                    for (FileFetcher tmp : runningDownloads) {
                        try {
                            if (f.getID() == tmp.getID()) {
                                skip = true;
                                log.log(Level.FINEST,
                                        "DownloadManager: FileFetcher {0} is still running from previous collection. Skipping.",
                                        f.getID());
                            }
                        } catch (NullPointerException e) {
                            // The download completed while we were testing for it.
                            // Ignore it.
                            skip = true;
                        }
                    }

                    if (!skip) {
                        f.start();
                        this.runningDownloads.add(f);
                        this.numThreads++;
                    }

                    while (this.numThreads >= (this.numThreadsLimit - 1)) {
                        // Thread throttling
                        // Sleep until there is a spare space for a new thread.
                        try {
                            log.log(Level.FINE, "DownloadManager: {0} downloads in progress. Sleeping.",
                                    this.numThreadsLimit);
                            sleep(5000);
                        } catch (InterruptedException e) {
                        }
                    }
                }
            } catch (JDOMException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // Make sure updateInterval is sane.
        if (updateInterval < 30) {
            updateInterval = 30;
        }

        // Sleep for "updateInterval" seconds before trying again.
        try {
            sleep(updateInterval * 1000);
        } catch (InterruptedException e) {
        }
    }
}

From source file:ec.edu.cedia.redi.ldclient.provider.ScopusAuthorProvider.java

License:Apache License

/**
 * Parse each XML result of publications. Assings each publication resource
 * to its author. See//from w w w. j a  v  a2 s  .  c  o m
 * <a href="http://api.elsevier.com/documentation/SCOPUSSearchAPI.wadl">Scopus
 * Search API</a>.
 *
 * @param input
 * @param requestUrl
 * @param triples
 * @return list of publication resources
 * @throws DataRetrievalException
 */
private List<String> parseSearchPub(InputStream input, String requestUrl, final Model triples)
        throws DataRetrievalException {
    try {
        List<String> publications = new ArrayList<>();
        ValueFactory vf = ValueFactoryImpl.getInstance();
        String authorId = requestUrl.substring(requestUrl.indexOf("au-id(") + 6, requestUrl.indexOf(")&"));
        URI author = vf.createURI("http://api.elsevier.com/content/author/author_id/", authorId);

        final Document doc = new SAXBuilder(XMLReaders.NONVALIDATING).build(input);
        XPathExpression<Attribute> path = XPathFactory.instance().compile(
                "/atom:search-results/atom:entry/atom:link[@ref='self']/@href", Filters.attribute(), null,
                Namespace.getNamespace("atom", "http://www.w3.org/2005/Atom"));
        List<Attribute> publicationsFound = path.evaluate(doc);
        for (int i = 0; i < publicationsFound.size(); i++) {
            String pubResource = publicationsFound.get(i).getValue();
            triples.add(author, FOAF.PUBLICATIONS, vf.createURI(pubResource));
            publications.add(pubResource + "?apiKey=" + apiKey + "&httpAccept=application/rdf%2Bxml");
        }
        return publications;
    } catch (JDOMException | IOException ex) {
        throw new DataRetrievalException(ex);
    }
}

From source file:ec.edu.cedia.redi.ldclient.provider.ScopusAuthorProvider.java

License:Apache License

/**
 * Maps each author from XML to RDF using default implementation of
 * {@link AbstractXMLDataProvider#parseResponse}.
 *
 * @see/*from   www . jav a2  s.  c o  m*/
 * <a href="http://api.elsevier.com/documentation/AUTHORSearchAPI.wadl">Authors
 * search API.</a>
 *
 * @param input
 * @param resource
 * @param requestUrl
 * @param triples
 * @param contentType
 * @return list of resources of authors found.
 * @throws DataRetrievalException
 */
private List<String> parseResponseAuthorsSearch(InputStream input, String resource, String requestUrl,
        Model triples, String contentType) throws DataRetrievalException {
    try {

        // List of authors to extract perfil information such as publications, affiliations, etc.
        List<String> authorsFound = new ArrayList();
        ValueFactory vf = ValueFactoryImpl.getInstance();
        // Keep stream for various reads.
        byte[] response = IOUtils.toByteArray(input);
        final Document doc = new SAXBuilder(XMLReaders.NONVALIDATING).build(new ByteArrayInputStream(response));
        // get only URI of authors
        XPathExpression<Text> path = XPathFactory.instance().compile(
                "/atom:search-results/atom:entry/prism:url/text()", Filters.textOnly(), null,
                Namespace.getNamespace("atom", "http://www.w3.org/2005/Atom"),
                Namespace.getNamespace("prism", "http://prismstandard.org/namespaces/basic/2.0/"));
        // Map each author XML to RDF using default implementationf parseResponse method from AbstractXMLDataProvider.
        List<Text> auhtorsFound = path.evaluate(doc);
        for (int i = 0; i < auhtorsFound.size(); i++) {
            setAuthorXPathMappings(i);
            String authorsResource = auhtorsFound.get(i).getValue();
            super.parseResponse(authorsResource, requestUrl, triples, new ByteArrayInputStream(response),
                    contentType);
            authorsFound.add(
                    authorsResource + "?apiKey=" + apiKey + "&httpAccept=application/rdf%2Bxml&view=ENHANCED");
            triples.add(vf.createURI(authorsResource), OWL.ONEOF, vf.createURI(resource));
        }
        return authorsFound;
    } catch (JDOMException | IOException | DataRetrievalException ex) {
        throw new DataRetrievalException(ex);
    }
}

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 {// w w  w  . j a  v  a 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.ucsd.crbs.cws.workflow.WorkflowFromAnnotatedVersionTwoFourMomlXmlFactory.java

License:Open Source License

/**
 * Runs xpath query {@link #MOML_TEXT_ATTRIBUTE} to get TextAttribute 
 * elements from document.  The code then parses out the <b>name</b>, 
 * <b>coordinates<b/>, and <b>text</b> to generate {@link TextAttribute} 
 * objects.<p/>/*from ww w  . j a  v  a2 s  .  com*/
 * The <b>name</b> is the value from the {@link #NAME_ATTRIBUTE} attribute 
 * in the element returned from the xpath query<br/>
 * The <b>coordinates</b> is the value obtained from the 
 * {@link #VALUE_ATTRIBUTE} in the  child element whose value from the 
 * {@link #NAME_ATTRIBUTE} matches {@link #LOCATION_ATTRIBUTE}<br/>
 * The <b>text</b> is the value from the {@link #VALUE_ATTRIBUTE} attribute 
 * in the child element whose value from the {@link #NAME_ATTRIBUTE} matches 
 * {@link #TEXT}
 * 
 * @param doc
 * @return List of {@link TextAttribute} objects if found
 * @throws Exception 
 */
private List<TextAttribute> getTextAttributes(Document doc) throws Exception {
    XPathExpression<Element> xpath = XPathFactory.instance().compile(MOML_TEXT_ATTRIBUTE, Filters.element());

    List<Element> elements = xpath.evaluate(doc);
    ArrayList<TextAttribute> textAttributes = new ArrayList<>();
    for (Element e : elements) {
        TextAttribute ta = new TextAttribute();

        ta.setName(e.getAttributeValue(NAME_ATTRIBUTE));
        List<Element> children = e.getChildren();
        for (Element child : children) {
            if (child.getAttributeValue(NAME_ATTRIBUTE).equalsIgnoreCase(LOCATION_ATTRIBUTE)) {
                ta.setCoordinatesViaString(child.getAttributeValue(VALUE_ATTRIBUTE));
            } else if (child.getAttributeValue(NAME_ATTRIBUTE).equalsIgnoreCase(TEXT)) {
                ta.setText(child.getAttributeValue(VALUE_ATTRIBUTE));
            }
        }
        textAttributes.add(ta);
    }
    return textAttributes;
}

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

License:Open Source License

private List<ParameterAttribute> getParameterAttributes(Document doc) throws Exception {
    XPathExpression<Element> xpath = XPathFactory.instance().compile(MOML_CANVAS_PARAMETER, Filters.element());
    List<Element> elements = xpath.evaluate(doc);
    ArrayList<ParameterAttribute> parameters = new ArrayList<>();
    for (Element e : elements) {
        ParameterAttribute pa = new ParameterAttribute();
        pa.setName(e.getAttributeValue(NAME_ATTRIBUTE));
        pa.setType(e.getAttributeValue(CLASS));
        pa.setValue(e.getAttributeValue(VALUE_ATTRIBUTE));

        List<Element> children = e.getChildren();
        for (Element child : children) {
            if (child.getName().equals(DISPLAY_ELEMENT)) {
                pa.setDisplayName(child.getAttributeValue(NAME_ATTRIBUTE));
            } else if (child.getAttributeValue(NAME_ATTRIBUTE).equalsIgnoreCase(LOCATION_ATTRIBUTE)) {
                pa.setCoordinatesViaString(child.getAttributeValue(VALUE_ATTRIBUTE));
            }//  w w  w  .j  a  v a 2  s . c  o m

        }
        if (pa.getDisplayName() == null) {
            pa.setDisplayName(pa.getName());
        }
        parameters.add(pa);
    }
    return parameters;
}

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

License:Open Source License

private List<RectangleAttribute> getRectangleAttributes(Document doc) throws Exception {
    XPathExpression<Element> xpath = XPathFactory.instance().compile(MOML_RECTANGLE_ATTRIBUTE,
            Filters.element());//w  ww . ja  v a2 s  .c om

    List<Element> elements = xpath.evaluate(doc);
    ArrayList<RectangleAttribute> rectangles = new ArrayList<>();
    for (Element e : elements) {
        RectangleAttribute ra = new RectangleAttribute();
        boolean centered = false;
        ra.setName(e.getAttributeValue(NAME_ATTRIBUTE));
        List<Element> children = e.getChildren();
        for (Element child : children) {
            if (child.getName().equals(DISPLAY_ELEMENT)) {
                ra.setDisplayName(child.getAttributeValue(NAME_ATTRIBUTE));
            } else if (child.getAttributeValue(NAME_ATTRIBUTE).equalsIgnoreCase(WIDTH)) {
                ra.setWidth(Double.parseDouble(child.getAttributeValue(VALUE_ATTRIBUTE)));
            } else if (child.getAttributeValue(NAME_ATTRIBUTE).equalsIgnoreCase(HEIGHT)) {
                ra.setHeight(Double.parseDouble(child.getAttributeValue(VALUE_ATTRIBUTE)));
            } else if (child.getAttributeValue(NAME_ATTRIBUTE).equalsIgnoreCase(LOCATION_ATTRIBUTE)) {
                ra.setCoordinatesViaString(child.getAttributeValue(VALUE_ATTRIBUTE));
            } else if (child.getAttributeValue(NAME_ATTRIBUTE).equalsIgnoreCase(CENTERED_ATTRIBUTE)) {
                centered = Boolean.parseBoolean(child.getAttributeValue(VALUE_ATTRIBUTE));
            }
        }
        if (ra.getDisplayName() == null) {
            ra.setDisplayName(ra.getName());
        }

        //if centered we need to adjust x and y coordinate to be upper left corner
        if (centered == true) {
            ra.moveCoordinatesToUpperLeftCornerFromCenter();
        }

        rectangles.add(ra);
    }
    return rectangles;
}

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

License:Open Source License

/**
 * Using Xpath queries parses MOML to create Workflow object
 * @param doc Document to parse//from   ww  w. j  ava 2s  . c om
 * @return Workflow object upon success or null if none found
 * @throws Exception If there is a parsing error or format error
 */
private Workflow getWorkflowFromDocument(Document doc) throws Exception {

    // create the workflow object and set basic information
    Workflow workflow = new Workflow();

    addReleaseNotes(workflow, doc);
    addDescription(workflow, doc);
    addWorkflowName(workflow, doc);

    for (String keplerParameterType : _keplerParameterTypes.keySet()) {
        XPathExpression<Element> xpath = XPathFactory.instance()
                .compile(_keplerParameterTypes.get(keplerParameterType), Filters.element());

        List<Element> elements = xpath.evaluate(doc);
        if (elements != null && elements.isEmpty() == false) {
            addParametersToWorkflow(workflow, elements, keplerParameterType);
        }
    }
    return workflow;
}

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

License:Open Source License

private String getContentOfValueAttributeFromFirstElementInQuery(Document doc, final String query)
        throws Exception {
    XPathExpression<Element> xpath = XPathFactory.instance().compile(query, Filters.element());
    Element e = xpath.evaluateFirst(doc);
    if (e == null) {
        return null;
    }//from  ww  w.  j  a va 2  s.c om
    return e.getAttributeValue(ATTRIBUTE_VALUE_KEY);
}

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

License:Apache License

public DepartmentOntologyUtil() {
    addressPattern = Pattern.compile("([^,]+,)+\\s*[a-zA-Z ]*\\d+[a-zA-Z]*\\s*[^\\n]*");
    addressTrailingPattern = Pattern.compile("([^,]+,){2,}\\s*([a-zA-Z]+ ?){1,2}\\s*");
    addressSplit = Pattern.compile(
            "(,? *(and *)?(?=dep(t\\.?|artment(s)?)|school|division|section(s)?|program in|center for|university)(?= of)?)",
            Pattern.CASE_INSENSITIVE);
    trimLeading = Pattern.compile("^([.?;:*&^%$#@!\\-]|the |at |and |\\s)+");
    trimTrailing = Pattern.compile("([.?;:*&^%$#@!\\-]|the |at |\\s)+$");
    deptSplitPlural = Pattern.compile(
            "(and the |and (the )?(dep(t\\.?|artment(s)?)|school|division|section(s)?|program in|center for)( of)?|and )");
    trimSuffix = Pattern.compile("\\s*(department|doctoral|masters)$");
    trimUNC = Pattern.compile("\\b(unc|carolina)\\s+");
    splitSimple = Pattern.compile("(\\s*[:()]\\s*)+");

    try {/* ww w.  j  av a 2  s  .  co  m*/
        XPathFactory xFactory = XPathFactory.instance();
        namePath = xFactory.compile("mods:name", Filters.element(MODS_V3_NS), null, MODS_V3_NS);
    } catch (Exception e) {
        log.error("Failed to construct xpath", e);
    }
}