Example usage for javax.xml.xpath XPathFactory newXPath

List of usage examples for javax.xml.xpath XPathFactory newXPath

Introduction

In this page you can find the example usage for javax.xml.xpath XPathFactory newXPath.

Prototype

public abstract XPath newXPath();

Source Link

Document

Return a new XPath using the underlying object model determined when the XPathFactory was instantiated.

Usage

From source file:gov.nih.nci.ncicb.tcga.dcc.dam.util.TempClinicalDataLoader.java

private static void processBiospecimenXmlFile(final String xmlFile, final String archiveName,
        final String disease, final Date dateAdded) throws ParserConfigurationException, IOException,
        SAXException, SQLException, XPathExpressionException, InstantiationException, IllegalAccessException {

    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true);/*  ww  w. j  a  v  a  2s . c  om*/
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document doc = builder.parse(xmlFile);
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    Patient patient = new Patient();
    Pattern filePattern = Pattern.compile("(TCGA-[A-Z0-9]{2}-[A-Z0-9]{4})");
    Matcher matcher = filePattern.matcher(xmlFile);
    matcher.find();
    String patientBarcode = matcher.group(1);
    if (patientBarcode == null) {
        System.out.println("Failed to get patient barcode from filename!");
        System.exit(-1);
    }
    patient.setPatientID(Patient.getPatientIdForBarcode(patientBarcode));
    if (patient.getPatientID() < 1) {
        System.out.println("Could not find PATIENT record for " + patientBarcode + " saving it now...");
        patient.setAttribute("ARCHIVE_NAME", archiveName);
        patient.setAttribute("DISEASE", disease);
        patient.setDateAdded(dateAdded);
        patient.setAttribute("BCRPATIENTBARCODE", patientBarcode);
        patient.insertSelf(0);
    }
    String patientPath = "//" + patient.getXmlElementName() + "[1]";
    processSamples(doc, xpath, patient, patientPath);
}

From source file:gov.nih.nci.lmp.mimGpml.CommonHelper.java

/**
 * Gets the MIM-Vis XML object by ID./*from  w  ww.  j a v a  2 s .  co m*/
 * 
 * TODO: It does not appear possible to use the Saxon engine to process
 * XPath queries within Pathvisio; the plugin fails to load. The approach
 * taken instead relies on JDOM/Jaxen to process XPath.
 * 
 * @param doc
 *            the doc
 * @param elemId
 *            the element id
 * @return the vis xml object by id
 */
public static XmlObject getVisXmlObjectById(DiagramDocument doc, String elemId) {

    // TODO: Account for bioId
    // String queryExpression =
    // "/mimVis:Diagram/mimVis:InteractionGlyph[@visId='" + elemId + "']";
    String queryExpression = "//*[@visId='" + elemId + "']";

    Logger.log.debug("elemId:" + elemId);
    Logger.log.debug("queryExpression:" + queryExpression);

    try {
        org.w3c.dom.Document wDoc = (org.w3c.dom.Document) doc.getDomNode();
        javax.xml.xpath.XPathFactory factory = XPathFactory.newInstance();
        javax.xml.xpath.XPath wXpath = factory.newXPath();
        javax.xml.xpath.XPathExpression expr = wXpath.compile(queryExpression);

        Object result = expr.evaluate(wDoc, javax.xml.xpath.XPathConstants.NODESET);
        org.w3c.dom.NodeList nodes = (org.w3c.dom.NodeList) result;

        Logger.log.debug("NodeList size: " + nodes.getLength());

        /**
         * If the size is not one, then there is a duplicate key issue that
         * needs to be dealt with. Treat it as an error and return null.
         */
        if (nodes.getLength() == 1) {
            XmlObject xmlObj = XmlObject.Factory.parse(nodes.item(0));
            Logger.log.debug("glyph.xmlText: " + xmlObj.xmlText(getXmlOptions()));

            // Logger.log.debug("doc.xmlText: " +
            // doc.xmlText(getXmlOptions()));

            String elemStr = xmlObj.xmlText(getXmlOptions());

            Logger.log.debug("getVisXmlObjectById XML String:" + elemStr);

            /**
             * Sample of the way an XML fragment is represented with
             * <xml-fragment> tags. This necessitates a modification from
             * the nodes returned by selectNodes.
             * 
             * <xml-fragment mimVis:visId="ca53d" mimVis:displayName="CAMK"
             * centerX="166.0" centerY="167.0" mimVis:width="80.0"
             * mimVis:height="20.0"
             * xmlns:mimVis="http://lmp.nci.nih.gov/mim/mimVisLevel1">
             * <mimVis:mimBioRef>b9044</mimVis:mimBioRef></xml-fragment>
             */
            // Pattern/matcher
            Pattern mimStartElemTag = Pattern.compile("mimVis:[A-Z][A-Za-z]+");
            Matcher matcherStart = mimStartElemTag.matcher(elemStr);

            // System.out.println("matcherStart count: "
            // + matcherStart.groupCount());

            String match = null;

            // Find all matches
            while (matcherStart.find()) {
                // Get the matching string
                match = matcherStart.group();
                // System.out.println("matcherStart.group(): "
                // + matcherStart.group());
            }

            final int prefixLength = "mimVis:".length();

            // String localPart = xmlFrag + "Type";
            String localPart = match.substring(prefixLength) + "Type";

            // Match: mimVis:SimplePhysicalEntityGlyph
            // SPE URI QName: http://lmp.nci.nih.gov/mim/mimVisLevel1
            // SPE Local QName: SimplePhysicalEntityGlyphType

            QName objQName = new QName(MIM_VIS_NS, localPart);

            SchemaTypeLoader schemaTypeLoader = XmlBeans.getContextTypeLoader();
            SchemaType objType = schemaTypeLoader.findType(objQName);

            XmlOptions opts = new XmlOptions();
            opts.setLoadReplaceDocumentElement(null);

            /**
             * Taken from the XMLBeans autogenerated code of a XSD complex
             * type. For parsing a XML fragment given the SchemaType.
             */
            xmlObj = XmlBeans.getContextTypeLoader().parse(elemStr, objType, opts);

            return xmlObj;
        } else {
            Logger.log.info("ERROR: Most likely a duplicate ID.");
        }
    } catch (XmlException e) {
        e.printStackTrace();
    } catch (XPathExpressionException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:gov.nih.nci.ncicb.tcga.dcc.dam.util.TempClinicalDataLoader.java

private static void processClinicalXmlFile(final String xmlFile, final String archiveName, final String disease,
        final Date dateAdded) throws ParserConfigurationException, IOException, SAXException,
        XPathExpressionException, InstantiationException, IllegalAccessException {
    Patient.setDBConnection(dbConnection);

    // get all patient barcodes
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true);//from ww w . j a va2 s . c o m
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document doc = builder.parse(xmlFile);
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();

    Patient p = new Patient();
    p.setAttribute("ARCHIVE_NAME", archiveName);
    p.setAttribute("DISEASE", disease);
    p.setDateAdded(dateAdded);
    String basePath = "//TCGA_BCR";
    ClinicalBean[] patients = processElementGroup(basePath, doc, xpath, p, 0);
    // for each patient, process its samples
    for (int patient_i = 0; patient_i < patients.length; patient_i++) {
        Patient patient = (Patient) patients[patient_i];

        Sample s = new Sample();
        String patientPath = basePath + "/" + patient.getXmlElementName() + "[" + (patient_i + 1) + "]";

        // patients > drugs
        processElementGroup(patientPath, doc, xpath, new Drug(), patient.getPatientID());

        // patients > radiations
        processElementGroup(patientPath, doc, xpath, new Radiation(), patient.getPatientID());

        // patients > examinations
        processElementGroup(patientPath, doc, xpath, new Examination(), patient.getPatientID());

        // patients > surgeries
        processElementGroup(patientPath, doc, xpath, new Surgery(), patient.getPatientID());
    }
}

From source file:gov.tva.sparky.hbase.RestProxy.java

/**
 * //from  w  w w . ja  v a2 s . c  o m
 * @param strTablename
 * @param strRowKey
 * @param strColumn
 * @param strQualifier
 * @return Returns the values from a data cell in HBase.
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 */
public static byte[] QueryHBaseForCell(String strTablename, String strRowKey, String strColumn,
        String strQualifier) throws ParserConfigurationException, SAXException, IOException {
    // Configuration
    Configuration conf = new Configuration(false);
    conf.addResource("hadoop-default.xml");
    conf.addResource("sparky-site.xml");
    int port = conf.getInt("sparky.hbase.restPort", 8092);
    String uri = conf.get("sparky.hbase.restURI", "http://socdvmhbase");

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    // never forget this!
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();

    String strRestPath = uri + ":" + port + "/" + strTablename + "/" + strRowKey + "/" + strColumn + ":"
            + strQualifier;

    Document doc = null;

    try {
        doc = builder.parse(strRestPath);

    } catch (FileNotFoundException e) {
        //System.out.println("RestProxy > Exception: ( " + strRestPath + " )");
    }

    if (null == doc)
        return null;

    XPathFactory xpath_factory = XPathFactory.newInstance();
    XPath xpath = xpath_factory.newXPath();

    XPathExpression expr = null;

    try {
        expr = xpath.compile("/CellSet/Row/Cell/text()");
    } catch (XPathExpressionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    Object result = null;
    try {
        result = expr.evaluate(doc, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    NodeList nodes = (NodeList) result;
    String cell_value = nodes.item(0).getNodeValue();

    Base64 decoder = new Base64();
    byte[] decodedValue = decoder.decode(cell_value.getBytes());

    return decodedValue;
}

From source file:gov.nih.nci.ncicb.tcga.dcc.dam.util.TempClinicalDataLoader.java

private static void processFullXmlFile(final String xmlFile, final String archiveName, final String disease,
        final Date dateAdded) throws ParserConfigurationException, IOException, SAXException,
        XPathExpressionException, InstantiationException, IllegalAccessException {

    Patient.setDBConnection(dbConnection);

    // Create an XPath object from this xml file
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true);//from  w  ww . j  a v  a  2s . co  m
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document doc = builder.parse(xmlFile);
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();

    // create the Patient bean for this file
    Patient p = new Patient();
    p.setAttribute("ARCHIVE_NAME", archiveName);
    p.setAttribute("DISEASE", disease);
    p.setDateAdded(dateAdded);
    String basePath = "//TCGA_BCR";

    // process all patients in this file (currently is only 1 but this should work even with multiples)
    ClinicalBean[] patients = processElementGroup(basePath, doc, xpath, p, 0);
    // for each patient, process its clinical elements
    for (int patient_i = 0; patient_i < patients.length; patient_i++) {
        Patient patient = (Patient) patients[patient_i];
        String patientPath = basePath + "/" + patient.getXmlElementName() + "[" + (patient_i + 1) + "]";
        processSamples(doc, xpath, patient, patientPath);
        // patients > drugs
        processElementGroup(patientPath, doc, xpath, new Drug(), patient.getPatientID());

        // patients > radiations
        processElementGroup(patientPath, doc, xpath, new Radiation(), patient.getPatientID());

        // patients > examinations
        processElementGroup(patientPath, doc, xpath, new Examination(), patient.getPatientID());

        // patients > surgeries
        processElementGroup(patientPath, doc, xpath, new Surgery(), patient.getPatientID());
    }

}

From source file:com.fluidops.iwb.luxid.LuxidExtractor.java

/**
 * returns the name of a XCAS- document//from ww w . ja  va2 s.  c o  m
 * 
 * @param input
 * @param stmts
 * @param vf
 * @param id
 * @param f
 * @throws Exception
 */
public static void getDocumentTitle(String input, Set<Statement> stmts, ValueFactory vf, String id, File f)
        throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();

    Document doc = db.parse(f);

    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    XPathExpression expr = xpath.compile("//com.temis.uima.Zone[@name='title']");

    NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
    for (int i = 0, n = nodes.getLength(); i < n; i++) {
        String begin = nodes.item(i).getAttributes().getNamedItem("begin").getTextContent();
        String end = nodes.item(i).getAttributes().getNamedItem("end").getTextContent();

        stmts.add(vf.createStatement(
                vf.createURI(EndpointImpl.api().getNamespaceService().defaultNamespace() + id), RDFS.LABEL,
                vf.createLiteral(input.substring(Integer.parseInt(begin), Integer.parseInt(end)))));
    }
}

From source file:Main.java

/**
 * Create a new {@link XPath} with the passed variable resolver, function
 * resolver and namespace context.//from w w w  . j a v a  2s  .c om
 * 
 * @param aXPathFactory
 *        The XPath factory object to use. May not be <code>null</code>.
 * @param aVariableResolver
 *        Variable resolver to be used. May be <code>null</code>.
 * @param aFunctionResolver
 *        Function resolver to be used. May be <code>null</code>.
 * @param aNamespaceContext
 *        Namespace context to be used. May be <code>null</code>.
 * @return The created non-<code>null</code> {@link XPath} object
 */
@Nonnull
public static XPath createNewXPath(@Nonnull final XPathFactory aXPathFactory,
        @Nullable final XPathVariableResolver aVariableResolver,
        @Nullable final XPathFunctionResolver aFunctionResolver,
        @Nullable final NamespaceContext aNamespaceContext) {
    if (aXPathFactory == null)
        throw new NullPointerException("XPathFactory");

    final XPath aXPath = aXPathFactory.newXPath();
    if (aVariableResolver != null)
        aXPath.setXPathVariableResolver(aVariableResolver);
    if (aFunctionResolver != null)
        aXPath.setXPathFunctionResolver(aFunctionResolver);
    if (aNamespaceContext != null)
        aXPath.setNamespaceContext(aNamespaceContext);
    return aXPath;
}

From source file:eu.europeana.uim.sugarcrmclient.internal.helpers.ClientUtils.java

/**
 * @param responseString// w w  w . ja  v a  2 s .co  m
 * @return
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 * @throws XPathExpressionException
 */
public static HashMap<String, HashMap<String, String>> responseFactory(String responseString)
        throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {

    HashMap<String, HashMap<String, String>> returnMap = new HashMap<String, HashMap<String, String>>();

    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

    Document document = documentBuilder.parse(new InputSource(new StringReader(responseString)));

    //String messageName = document.getFirstChild().getNodeName();

    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();

    xpath.setNamespaceContext(new SugarCRMNamespaceContext());
    XPathExpression expr = xpath.compile("//ns1:get_entry_listResponse/return/entry_list/item");

    Object result = expr.evaluate(document, XPathConstants.NODESET);
    NodeList nodes = (NodeList) result;

    for (int i = 0; i < nodes.getLength(); i++) {

        NodeList innerNodes = nodes.item(i).getChildNodes();

        String id = innerNodes.item(0).getTextContent();

        HashMap<String, String> elementData = new HashMap<String, String>();

        NodeList infoNodes = innerNodes.item(2).getChildNodes();

        for (int z = 0; z < infoNodes.getLength(); z++) {
            String name = infoNodes.item(z).getFirstChild().getTextContent();
            String value = infoNodes.item(z).getLastChild().getTextContent();

            elementData.put(name, value);
        }
        returnMap.put(id, elementData);
    }
    return returnMap;
}

From source file:se.vgregion.usdservice.USDServiceImpl.java

/**
 * Convenience method./*ww  w .  j  a  va 2 s  .co  m*/
 * <p/>
 * Neither XPathFactory nor XPath are thread safe. Further more XPath is not re-entrant,
 * so a new instance has to be created for every evaluation.
 * The generic marker make this more convenient to use - however QName has to match the expected return type.
 *
 * @param xPath,  the xPath to be evaluated.
 * @param source, the source document to evaluate on.
 * @param qName,  the node type the evaluation returns.
 * @param <T>,    matching return type.
 * @return the evaluated result.
 * @throws XPathExpressionException
 */
private static <T> T evaluate(String xPath, Document source, QName qName) throws XPathExpressionException {
    XPathFactory factory = XPathFactory.newInstance();
    XPath processor = factory.newXPath();
    return (T) processor.evaluate(xPath, source, qName);
}

From source file:edu.virginia.speclab.juxta.author.model.JuxtaXMLParser.java

static public String getIndexBasedXPathForGeneralXPath(String xpathString, String xml) {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    try {/*w w  w. j ava  2  s  .co  m*/
        factory.setNamespaceAware(false); // ignore the horrible issues of namespacing
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(new InputSource(new StringReader(xml)));
        XPathFactory xpathFactory = XPathFactory.newInstance();
        XPath xpath = xpathFactory.newXPath();
        Node root = doc.getFirstChild();
        XPathExpression expr = xpath.compile(xpathString);
        Node node = (Node) expr.evaluate(doc, XPathConstants.NODE);
        return nodeToSimpleXPath(node, root);
    } catch (SAXException ex) {
    } catch (IOException ex) {
    } catch (XPathExpressionException ex) {
    } catch (ParserConfigurationException ex) {
    }
    return null;
}