Example usage for org.jdom2.xpath XPathFactory compile

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

Introduction

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

Prototype

public <T> XPathExpression<T> compile(String expression, Filter<T> filter, Map<String, Object> variables,
        Collection<Namespace> namespaces) 

Source Link

Document

Create a XPathExpression<> instance from this factory.

Usage

From source file:AIR.Common.xml.XmlElement.java

License:Open Source License

public List<Element> selectNodes(String xpath, XmlNamespaceManager nsmgr) {
    XPathFactory factory = XPathFactory.instance();
    XPathExpression<Element> expr = factory.compile(xpath, Filters.element(), null, nsmgr.getNamespaceList());
    return expr.evaluate(_element);
}

From source file:AIR.Common.xml.XmlElement.java

License:Open Source License

public Element selectSingleNode(String xpath, XmlNamespaceManager nsmgr) {
    XPathFactory factory = XPathFactory.instance();
    XPathExpression<Element> expr = factory.compile(xpath, Filters.element(), null, nsmgr.getNamespaceList());
    return expr.evaluateFirst(_element);
}

From source file:com.globalsight.dispatcher.bo.JobTask.java

License:Apache License

private void createTargetFile(JobBO p_job, String[] p_targetSegments) throws IOException {
    OutputStream writer = null;//  ww  w. ja v  a  2 s . co m
    File fileStorage = CommonDAO.getFileStorage();
    File srcFile = p_job.getSrcFile();
    Account account = DispatcherDAOFactory.getAccountDAO().getAccount(p_job.getAccountId());
    File trgDir = CommonDAO.getFolder(fileStorage, account.getAccountName() + File.separator + p_job.getJobID()
            + File.separator + AppConstants.XLF_TARGET_FOLDER);
    File trgFile = new File(trgDir, srcFile.getName());
    FileUtils.copyFile(srcFile, trgFile);
    String encoding = FileUtil.getEncodingOfXml(trgFile);

    try {
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(p_job.getSrcFile());
        Element root = doc.getRootElement(); // Get root element
        Namespace namespace = root.getNamespace();
        Element fileElem = root.getChild("file", namespace);
        XPathFactory xFactory = XPathFactory.instance();
        XPathExpression<Element> expr = xFactory.compile("//trans-unit", Filters.element(), null, namespace);
        List<Element> tuList = expr.evaluate(fileElem.getChild("body", namespace));
        for (int tuIndex = 0, trgIndex = 0; tuIndex < tuList.size()
                && trgIndex < p_targetSegments.length; tuIndex++, trgIndex++) {
            if (p_targetSegments[trgIndex] == null) {
                continue;
            }

            Element elem = (Element) tuList.get(tuIndex);
            Element srcElem = elem.getChild("source", namespace);
            Element trgElem = elem.getChild("target", namespace);
            if (srcElem == null || srcElem.getContentSize() == 0) {
                trgIndex--;
                continue;
            }

            if (trgElem != null) {
                setTargetSegment(trgElem, p_targetSegments[trgIndex], encoding);
            } else {
                trgElem = new Element("target", namespace);
                setTargetSegment(trgElem, p_targetSegments[trgIndex], encoding);
                elem.addContent(trgElem);
            }

        }

        XMLOutputter xmlOutput = new XMLOutputter();
        Format format = Format.getRawFormat();
        format.setEncoding(encoding);
        writer = new FileOutputStream(trgFile);
        xmlOutput.setFormat(format);
        writeBOM(writer, format.getEncoding());
        xmlOutput.output(doc, writer);
        p_job.setTrgFile(trgFile);
        logger.info("Create Target File: " + trgFile);
    } catch (JDOMException e1) {
        logger.error("CreateTargetFile Error: ", e1);
    } catch (IOException e1) {
        logger.error("CreateTargetFile Error: ", e1);
    } finally {
        if (writer != null)
            writer.close();
    }
}

From source file:com.globalsight.dispatcher.controller.TranslateXLFController.java

License:Apache License

private String parseXLF(JobBO p_job, File p_srcFile) {
    if (p_srcFile == null || !p_srcFile.exists())
        return "File not exits.";

    String srcLang, trgLang;//from w w w  .j ava  2 s.  c  o  m
    List<String> srcSegments = new ArrayList<String>();

    try {
        SAXBuilder builder = new SAXBuilder();
        Document read_doc = builder.build(p_srcFile);
        // Get Root Element
        Element root = read_doc.getRootElement();
        Namespace namespace = root.getNamespace();
        Element fileElem = root.getChild("file", namespace);
        // Get Source/Target Language
        srcLang = fileElem.getAttributeValue(XLF_SOURCE_LANGUAGE);
        trgLang = fileElem.getAttributeValue(XLF_TARGET_LANGUAGE);
        XPathFactory xFactory = XPathFactory.instance();
        XPathExpression<Element> expr = xFactory.compile("//trans-unit", Filters.element(), null, namespace);
        List<Element> list = expr.evaluate(fileElem.getChild("body", namespace));
        for (int i = 0; i < list.size(); i++) {
            Element tuElem = (Element) list.get(i);
            Element srcElem = tuElem.getChild("source", namespace);
            // Get Source Segment 
            if (srcElem != null && srcElem.getContentSize() > 0) {
                String source = getInnerXMLString(srcElem);
                srcSegments.add(source);
            }
        }

        p_job.setSourceLanguage(srcLang);
        p_job.setTargetLanguage(trgLang);
        p_job.setSourceSegments(srcSegments);
    } catch (Exception e) {
        String msg = "Parse XLIFF file error.";
        logger.error(msg, e);
        return msg;
    }

    return null;
}

From source file:com.mycompany.hr.ws.HolidayEndpoint.java

License:Apache License

@Autowired
public HolidayEndpoint(HumanResourceService humanResourceService) throws JDOMException {
    this.humanResourceService = humanResourceService;
    Namespace namespace = Namespace.getNamespace("hr", NAMESPACE_URI);
    XPathFactory xPathFactory = XPathFactory.instance();
    startDateExpression = xPathFactory.compile("//hr:StartDate", Filters.element(), null, namespace);
    endDateExpression = xPathFactory.compile("//hr:EndDate", Filters.element(), null, namespace);
    firstNameExpression = xPathFactory.compile("//hr:FirstName", Filters.element(), null, namespace);
    lastNameExpression = xPathFactory.compile("//hr:LastName", Filters.element(), null, namespace);
}

From source file:dibl.diagrams.Template.java

License:Open Source License

private void collectTileElements() {
    final XPathFactory f = XPathFactory.instance();
    // TODO extend xpath with condition inside for-loop
    final XPathExpression<Element> xpath = f.compile("//*[@inkscape:label='base tile']/*", Filters.element(),
            null, NS_INKSCAPE);/*ww  w  .  ja  va 2  s  .c o  m*/
    for (final Element el : xpath.evaluate(doc)) {
        if (el.getName().equals("use")) {
            final String cellID = el.getAttributeValue("label", NS_INKSCAPE);
            if (cellID != null && cellID.trim().length() > 0) {
                if (!tileElements.containsKey(cellID.trim()))
                    tileElements.put(cellID.trim(), new HashSet<Element>());
                tileElements.get(cellID.trim()).add((el));
            }
            final int r = cellID.toCharArray()[1] - '1';
            final int c = cellID.toCharArray()[0] - 'A';
            if (r >= getNrOfRows())
                nrOfRows = r + 1;
            if (c >= getNrOfCols())
                nrOfCols = c + 1;
        }
    }
}

From source file:dibl.diagrams.Template.java

License:Open Source License

private void collectStitches() {
    final XPathFactory f = XPathFactory.instance();
    final XPathExpression<Element> xpath = f.compile("//*[@inkscape:label='pile']/*", Filters.element(), null,
            NS_INKSCAPE);//from  ww w  . j av  a2 s .c  o  m
    for (final Element el : xpath.evaluate(doc)) {
        final String label = el.getAttributeValue("label", NS_INKSCAPE);
        final String id = el.getAttributeValue("id");
        idsByLabels.put(label, id);
        labelsByIDs.put("#" + id, label);
    }
}

From source file:dibl.diagrams.Template.java

License:Open Source License

private void addAppliedMatrixToTextObject(final String[][] newValues) {
    final XPathFactory f = XPathFactory.instance();
    final XPathExpression<Element> xpath = f.compile("//*[@inkscape:label='trace']/*", Filters.element(), null,
            NS_INKSCAPE);/*w  w w.  j  a v  a 2s . c  o  m*/
    List<Element> traceElements = xpath.evaluate(doc);
    if (!traceElements.isEmpty())
        traceElements.iterator().next().addContent(Arrays.deepToString(newValues));
}

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  . jav  a2 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.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 {/*from w  w w .  j  a va 2s .  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);
    }
}