Example usage for javax.xml.xpath XPathConstants NODE

List of usage examples for javax.xml.xpath XPathConstants NODE

Introduction

In this page you can find the example usage for javax.xml.xpath XPathConstants NODE.

Prototype

QName NODE

To view the source code for javax.xml.xpath XPathConstants NODE.

Click Source Link

Document

The XPath 1.0 NodeSet data type.

Usage

From source file:org.ambraproject.article.service.FetchArticleServiceImpl.java

/**
 * Returns abbreviated journal name//from w  w w  . j a v  a  2 s .c  o m
 * @param doc article xml
 * @return abbreviated journal name
 */
public String getJournalAbbreviation(Document doc) {
    String journalAbbrev = "";

    if (doc == null) {
        return journalAbbrev;
    }

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

        XPathExpression expr = xpath.compile("//journal-meta/journal-id[@journal-id-type='nlm-ta']");
        Object resultObj = expr.evaluate(doc, XPathConstants.NODE);
        Node resultNode = (Node) resultObj;
        if (resultNode != null) {
            journalAbbrev = resultNode.getTextContent();
        }
    } catch (Exception e) {
        log.error("Error occurred while getting abbreviated journal name.", e);
    }

    return journalAbbrev;
}

From source file:com.inbravo.scribe.rest.service.crm.ZHRESTCRMService.java

@Override
public final ScribeCommandObject getObjects(final ScribeCommandObject cADCommandObject, final String query)
        throws Exception {
    logger.debug("----Inside getObjects, query: " + query);

    /* Transfer the call to second method */
    if (query != null && query.toUpperCase().startsWith(queryPhoneFieldConst.toUpperCase())) {

        ScribeCommandObject returnObject = null;

        try {//from   ww  w  .  ja va2 s  .c o m
            /* Query CRM object by Phone field */
            returnObject = this.getObjectsByPhoneField(cADCommandObject, query, null, null, "Phone");

        } catch (final ScribeException firstE) {

            /* Check if record is not found */
            if (firstE.getMessage().contains(ScribeResponseCodes._1004)) {

                try {
                    /* Query CRM object by Mobile field */
                    returnObject = this.getObjectsByPhoneField(cADCommandObject, query, null, null, "Mobile");
                } catch (final ScribeException secondE) {

                    /* Check if record is again not found */
                    if (secondE.getMessage().contains(ScribeResponseCodes._1004)) {

                        try {
                            /* Query CRM object by Home Phone field */
                            returnObject = this.getObjectsByPhoneField(cADCommandObject, query, null, null,
                                    "Home Phone");
                        } catch (final ScribeException thirdE) {

                            /* Check if record is again not found */
                            if (thirdE.getMessage().contains(ScribeResponseCodes._1004)) {

                                try {
                                    /* Query CRM object by Other Phone field */
                                    returnObject = this.getObjectsByPhoneField(cADCommandObject, query, null,
                                            null, "Other Phone");
                                } catch (final ScribeException fourthE) {

                                    /* Throw the error to user */
                                    throw fourthE;
                                }
                            }
                        }
                    }
                }
            }
        }

        return returnObject;
    } else {

        /* Get user from session manager */
        final ScribeCacheObject user = (ScribeCacheObject) cRMSessionManager
                .getSessionInfo(cADCommandObject.getCrmUserId());

        PostMethod postMethod = null;
        try {

            /* Get CRM information from user */
            final String serviceURL = user.getScribeMetaObject().getCrmServiceURL();
            final String serviceProtocol = user.getScribeMetaObject().getCrmServiceProtocol();
            final String sessionId = user.getScribeMetaObject().getCrmSessionId();
            /* Create Zoho URL */
            final String zohoURL = serviceProtocol + "://" + serviceURL + "/crm/private/xml/"
                    + cADCommandObject.getObjectType() + "s/getSearchRecords";

            logger.debug("----Inside getObjects zohoURL: " + zohoURL + " & sessionId: " + sessionId);

            /* Instantiate post method */
            postMethod = new PostMethod(zohoURL);

            /* Set request parameters */
            postMethod.setParameter("authtoken", sessionId.trim());
            postMethod.setParameter("scope", "crmapi");

            if (!query.equalsIgnoreCase("NONE")) {

                /* Create ZH query */
                final String zhQuery = ZHCRMMessageFormatUtils.createZHQuery(query);

                if (zhQuery != null && !"".equals(zhQuery)) {

                    /* Set search parameter in request */
                    postMethod.setParameter("searchCondition", "(" + zhQuery + ")");
                }
            } else {

                /* Without query param this method is not applicable */
                return this.getObjects(cADCommandObject);
            }

            /* Set request param to select all fields */
            postMethod.setParameter("selectColumns", "All");

            final HttpClient httpclient = new HttpClient();

            /* Execute method */
            int result = httpclient.executeMethod(postMethod);
            logger.debug("----Inside getObjects response code: " + result + " & body: "
                    + postMethod.getResponseBodyAsString());

            /* Check if response if SUCCESS */
            if (result == HttpStatus.SC_OK) {

                /* Create XML document from response */
                final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                final DocumentBuilder builder = factory.newDocumentBuilder();
                final Document document = builder.parse(postMethod.getResponseBodyAsStream());

                /* Create new XPath object to query XML document */
                final XPath xpath = XPathFactory.newInstance().newXPath();

                /* XPath Query for showing all nodes value */
                final XPathExpression expr = xpath
                        .compile("/response/result/" + cADCommandObject.getObjectType() + "s/row");

                /* Get node list from response document */
                final NodeList nodeList = (NodeList) expr.evaluate(document, XPathConstants.NODESET);

                /* Check if records founds */
                if (nodeList != null && nodeList.getLength() == 0) {

                    /* XPath Query for showing error message */
                    XPathExpression errorExpression = xpath.compile("/response/error/message");

                    /* Get erroe message from response document */
                    Node errorMessage = (Node) errorExpression.evaluate(document, XPathConstants.NODE);

                    /* Check if error message is found */
                    if (errorMessage != null) {

                        /* Send user error */
                        throw new ScribeException(ScribeResponseCodes._1004 + "No records found at Zoho CRM : "
                                + errorMessage.getTextContent());
                    } else {

                        /* XPath Query for showing error message */
                        errorExpression = xpath.compile("/response/nodata/message");

                        /* Get erroe message from response document */
                        errorMessage = (Node) errorExpression.evaluate(document, XPathConstants.NODE);

                        /* Send user error */
                        throw new ScribeException(ScribeResponseCodes._1004 + "No records found at Zoho CRM : "
                                + errorMessage.getTextContent());
                    }

                } else {

                    /* Create new Scribe object list */
                    final List<ScribeObject> cADbjectList = new ArrayList<ScribeObject>();

                    /* Iterate over node list */
                    for (int i = 0; i < nodeList.getLength(); i++) {

                        /* Create list of elements */
                        final List<Element> elementList = new ArrayList<Element>();

                        /* Get node from node list */
                        final Node node = nodeList.item(i);

                        /* Create new Scribe object */
                        final ScribeObject cADbject = new ScribeObject();

                        /* Check if node has child nodes */
                        if (node.hasChildNodes()) {

                            final NodeList subNodeList = node.getChildNodes();

                            /* Create new map for attributes */
                            final Map<String, String> attributeMap = new HashMap<String, String>();

                            /*
                             * Iterate over sub node list and create elements
                             */
                            for (int j = 0; j < subNodeList.getLength(); j++) {

                                final Node subNode = subNodeList.item(j);

                                /* This trick is to avoid empty nodes */
                                if (!subNode.getNodeName().contains("#text")) {

                                    /* Create element from response */
                                    final Element element = (Element) subNode;

                                    /* Populate label map */
                                    attributeMap.put("label", element.getAttribute("val"));

                                    /* Get node name */
                                    final String nodeName = element.getAttribute("val").replace(" ",
                                            spaceCharReplacement);

                                    /* Validate the node name */
                                    if (XMLChar.isValidName(nodeName)) {

                                        /* Add element in list */
                                        elementList.add(ZHCRMMessageFormatUtils.createMessageElement(nodeName,
                                                element.getTextContent(), attributeMap));
                                    } else {
                                        logger.debug(
                                                "----Inside getObjects, found invalid XML node; ignoring field: "
                                                        + element.getAttribute("val"));
                                    }
                                }
                            }
                        }
                        /* Add all CRM fields */
                        cADbject.setXmlContent(elementList);

                        /* Set type information in object */
                        cADbject.setObjectType(cADCommandObject.getObjectType());

                        /* Add Scribe object in list */
                        cADbjectList.add(cADbject);
                    }

                    /* Check if no record found */
                    if (cADbjectList.size() == 0) {
                        throw new ScribeException(ScribeResponseCodes._1004 + "No records found at Zoho CRM");
                    }

                    /* Set the final object in command object */
                    cADCommandObject.setObject(cADbjectList.toArray(new ScribeObject[cADbjectList.size()]));
                }
            } else if (result == HttpStatus.SC_FORBIDDEN) {
                throw new ScribeException(ScribeResponseCodes._1022 + "Query is forbidden by Zoho CRM");
            } else if (result == HttpStatus.SC_BAD_REQUEST) {
                throw new ScribeException(ScribeResponseCodes._1003 + "Invalid request content");
            } else if (result == HttpStatus.SC_UNAUTHORIZED) {
                throw new ScribeException(ScribeResponseCodes._1012 + "Anauthorized by Zoho CRM");
            } else if (result == HttpStatus.SC_NOT_FOUND) {
                throw new ScribeException(ScribeResponseCodes._1004 + "Requested data not found at Zoho CRM");
            } else if (result == HttpStatus.SC_INTERNAL_SERVER_ERROR) {

                /* Create XML document from response */
                final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                final DocumentBuilder builder = factory.newDocumentBuilder();
                final Document document = builder.parse(postMethod.getResponseBodyAsStream());

                /* Create new XPath object to query XML document */
                final XPath xpath = XPathFactory.newInstance().newXPath();

                /* XPath Query for showing error message */
                final XPathExpression errorExpression = xpath.compile("/response/error/message");

                /* Get erroe message from response document */
                final Node errorMessage = (Node) errorExpression.evaluate(document, XPathConstants.NODE);

                if (errorMessage != null) {

                    /* Send user error */
                    throw new ScribeException(ScribeResponseCodes._1004
                            + "Requested data not found at Zoho CRM : " + errorMessage.getTextContent());
                } else {

                    /* Send user error */
                    throw new ScribeException(
                            ScribeResponseCodes._1004 + "Requested data not found at Zoho CRM");
                }
            }
        } catch (final ScribeException exception) {
            throw exception;
        } catch (final ParserConfigurationException exception) {
            throw new ScribeException(ScribeResponseCodes._1022 + "Recieved an invalid XML from Zoho CRM");
        } catch (final SAXException exception) {
            throw new ScribeException(ScribeResponseCodes._1022 + "Recieved an invalid XML from Zoho CRM");
        } catch (final IOException exception) {
            throw new ScribeException(
                    ScribeResponseCodes._1022 + "Communication error while communicating with Zoho CRM");
        } finally {
            /* Release connection socket */
            if (postMethod != null) {
                postMethod.releaseConnection();
            }
        }
        return cADCommandObject;
    }
}

From source file:gov.nij.bundles.intermediaries.ers.EntityResolutionMessageHandlerTest.java

@Test
public void testPerformEntityResolution() throws Exception {

    XPath xp = XPathFactory.newInstance().newXPath();
    xp.setNamespaceContext(testNamespaceContext);

    XmlConverter converter = new XmlConverter();
    converter.getDocumentBuilderFactory().setNamespaceAware(true);
    Document testRequestMessage = converter.toDOMDocument(testRequestMessageInputStream);
    // LOG.info(converter.toString(testRequestMessage));

    Node entityContainerNode = testRequestMessage
            .getElementsByTagNameNS(EntityResolutionNamespaceContext.ER_EXT_NAMESPACE, "EntityContainer")
            .item(0);//ww  w.j  av  a2  s  .com
    assertNotNull(entityContainerNode);

    List<String> lastNames = new ArrayList<String>();
    List<String> firstNames = new ArrayList<String>();
    List<String> sids = new ArrayList<String>();

    NodeList inputEntityNodes = (NodeList) testRequestMessage
            .getElementsByTagNameNS(EntityResolutionNamespaceContext.ER_EXT_NAMESPACE, "Entity");
    int inputEntityNodeCount = 6;
    assertEquals(inputEntityNodeCount, inputEntityNodes.getLength());

    for (int i = 0; i < inputEntityNodeCount; i++) {
        Node entityNode = inputEntityNodes.item(i);
        lastNames.add(
                xp.evaluate("ext:PersonSearchResult/ext:Person/nc:PersonName/nc:PersonSurName", entityNode));
        firstNames.add(
                xp.evaluate("ext:PersonSearchResult/ext:Person/nc:PersonName/nc:PersonGivenName", entityNode));
        sids.add(xp.evaluate(
                "ext:PersonSearchResult/ext:Person/jxdm:PersonAugmentation/jxdm:PersonStateFingerprintIdentification/nc:IdentificationID",
                entityNode));
    }

    Map<String, Integer> lastNameCountMap = new HashMap<String, Integer>();
    for (String lastName : lastNames) {
        Integer count = lastNameCountMap.get(lastName);
        if (count == null) {
            count = 0;
        }
        lastNameCountMap.put(lastName, ++count);
    }
    Map<String, Integer> firstNameCountMap = new HashMap<String, Integer>();
    for (String firstName : firstNames) {
        Integer count = firstNameCountMap.get(firstName);
        if (count == null) {
            count = 0;
        }
        firstNameCountMap.put(firstName, ++count);
    }
    Map<String, Integer> sidCountMap = new HashMap<String, Integer>();
    for (String sid : sids) {
        Integer count = sidCountMap.get(sid);
        if (count == null) {
            count = 0;
        }
        sidCountMap.put(sid, ++count);
    }

    Document resultDocument = entityResolutionMessageHandler.performEntityResolution(entityContainerNode, null,
            null);

    resultDocument.normalizeDocument();
    // LOG.info(converter.toString(resultDocument));
    NodeList entityNodes = (NodeList) xp.evaluate("//merge-result:EntityContainer/merge-result-ext:Entity",
            resultDocument, XPathConstants.NODESET);
    assertEquals(inputEntityNodeCount, entityNodes.getLength());
    entityNodes = (NodeList) xp.evaluate("//merge-result-ext:MergedRecord", resultDocument,
            XPathConstants.NODESET);
    assertEquals(3, entityNodes.getLength());
    entityNodes = (NodeList) xp.evaluate("//merge-result-ext:OriginalRecordReference", resultDocument,
            XPathConstants.NODESET);
    assertEquals(inputEntityNodeCount, entityNodes.getLength());
    for (int i = 0; i < entityNodes.getLength(); i++) {
        Element e = (Element) entityNodes.item(i);
        String entityIdRef = e.getAttributeNS(EntityResolutionNamespaceContext.STRUCTURES_NAMESPACE, "ref");
        assertNotNull(entityIdRef);
        assertNotNull(xp.evaluate("//merge-result-ext:Entity[@s:id='" + entityIdRef + "']", resultDocument,
                XPathConstants.NODE));
    }
    for (String lastName : lastNameCountMap.keySet()) {
        assertEquals(lastNameCountMap.get(lastName).intValue(), ((Number) xp.evaluate(
                "count(//merge-result-ext:Entity[ext:PersonSearchResult/ext:Person/nc:PersonName/nc:PersonSurName='"
                        + lastName + "'])",
                resultDocument, XPathConstants.NUMBER)).intValue());
    }
    for (String firstName : firstNames) {
        assertEquals(firstNameCountMap.get(firstName).intValue(), ((Number) xp.evaluate(
                "count(//merge-result-ext:Entity[ext:PersonSearchResult/ext:Person/nc:PersonName/nc:PersonGivenName='"
                        + firstName + "'])",
                resultDocument, XPathConstants.NUMBER)).intValue());
    }
    for (String sid : sids) {
        assertEquals(sidCountMap.get(sid).intValue(), ((Number) xp.evaluate(
                "count(//merge-result-ext:Entity[ext:PersonSearchResult/ext:Person/jxdm:PersonAugmentation/jxdm:PersonStateFingerprintIdentification/nc:IdentificationID='"
                        + sid + "'])",
                resultDocument, XPathConstants.NUMBER)).intValue());
    }

    String recordLimitExceeded = xp.evaluate(
            "/merge-result:EntityMergeResultMessage/merge-result:RecordLimitExceededIndicator", resultDocument);
    assertEquals("false", recordLimitExceeded);

}

From source file:net.di2e.ecdr.describe.generator.DescribeGeneratorImpl.java

private void populateSecurityCoverage(String sourceId, ConcurrentHashMap<SecurityType, Long> secCounter,
        Metacard metacard, XPathHelper xpathHelper) throws XPathExpressionException {
    Node securityNode = (Node) xpathHelper.evaluate(XPATH_SECURITY, XPathConstants.NODE);
    LOGGER.trace("Security info from site {} record {}: {}", sourceId, metacard.getId(), securityNode);
    if (securityNode != null) {
        SecurityType secType = new SecurityType();
        String value = getAttributeValue(securityNode, ICISM_NAMESPACE, "classification");
        if (value != null) {
            secType.setClassification(CVEnumISMClassificationAll.fromValue(value));
        }/*from www . j av  a  2  s  . c  o m*/

        value = getAttributeValue(securityNode, ICISM_NAMESPACE, "ownerProducer");
        if (value != null) {
            secType.setOwnerProducer(Arrays.asList(value.split(" ")));
        }

        value = getAttributeValue(securityNode, ICISM_NAMESPACE, "releasableTo");
        if (value != null) {
            secType.setReleasableTo(Arrays.asList(value.split(" ")));
        }

        value = getAttributeValue(securityNode, ICISM_NAMESPACE, "disseminationControls");
        if (value != null) {
            secType.setDisseminationControls(Arrays.asList(value.split(" ")));
        }

        secCounter.compute(secType, (k, v) -> {
            return Long.valueOf(v == null ? 1L : v.longValue() + 1L);
        });
    }
}

From source file:org.jasig.portal.security.provider.saml.SAMLDelegatedAuthenticationService.java

/**
 * This method processes the SOAP response from the IdP, and converts it
 * for presenting it back to the WSP that requested a delegated SAML
 * assertion./*from w  ww.  j a v  a  2 s.c  o  m*/
 * 
 * @param samlSession SAML session
 * @param authnState 
 * @return true, if successful
 */
private boolean processSOAPResponse(SAMLSession samlSession, DelegatedSAMLAuthenticationState authnState) {
    this.logger.debug("Step 5 of 5: Processing SOAP response");

    try {
        String expression = "/soap:Envelope/soap:Header/ecp:Response";
        InputStream is = new ByteArrayInputStream(authnState.getSoapResponse().getBytes());
        InputSource source = new InputSource(is);
        DOMParser parser = new DOMParser();
        parser.setFeature("http://xml.org/sax/features/namespaces", true);
        parser.parse(source);
        Document doc = parser.getDocument();
        Node node = EXPRESSION_POOL.evaluate(expression, doc, XPathConstants.NODE);

        if (node != null) {
            String responseConsumerURL = node.getAttributes().getNamedItem("AssertionConsumerServiceURL")
                    .getTextContent();

            logger.debug("Found {} node found in SOAP response.", expression);

            if (responseConsumerURL != null
                    && responseConsumerURL.equals(authnState.getResponseConsumerURL())) {
                logger.debug("responseConsumerURL {} matches {}", responseConsumerURL,
                        authnState.getResponseConsumerURL());

                // Retrieve and save the SOAP prefix used
                String soapPrefix = node.getParentNode().getPrefix();
                Element ecpResponse = (Element) node;
                Element soapHeader = (Element) ecpResponse.getParentNode();
                removeAllChildren(soapHeader);

                // Now on to the PAOS Response
                Element paosResponse = doc.createElementNS("urn:liberty:paos:2003-08", "paos:Response");
                paosResponse.setAttribute(soapPrefix + ":mustUnderstand", "1");
                paosResponse.setAttribute(soapPrefix + ":actor", "http://schemas.xmlsoap.org/soap/actor/next");

                // messageID is optional
                if (authnState.getPaosMessageID() != null)
                    paosResponse.setAttribute("refToMessageID", authnState.getPaosMessageID());

                soapHeader.appendChild(paosResponse);

                if (authnState.getRelayStateElement() != null) {
                    Node relayState = doc.importNode(authnState.getRelayStateElement(), true);
                    soapHeader.appendChild(relayState);
                }

                // Store the modified SOAP Request in the SAML Session
                String modifiedSOAPResponse = writeDomToString(doc);
                authnState.setModifiedSOAPResponse(modifiedSOAPResponse);
                return true;
            }

            logger.debug("responseConsumerURL {} does not match {}", responseConsumerURL,
                    authnState.getResponseConsumerURL());
            Document soapFaultMessage = createSOAPFaultDocument(
                    "AssertionConsumerServiceURL attribute missing or not matching the expected value.");
            Element soapHeader = (Element) soapFaultMessage.getFirstChild().getFirstChild();
            // Now on to the PAOS Response
            Element paosResponse = soapFaultMessage.createElementNS("urn:liberty:paos:2003-08",
                    "paos:Response");
            paosResponse.setAttribute(SOAP_PREFIX + ":mustUnderstand", "1");
            paosResponse.setAttribute(SOAP_PREFIX + ":actor", "http://schemas.xmlsoap.org/soap/actor/next");

            // messageID is optional
            if (authnState.getPaosMessageID() != null) {
                paosResponse.setAttribute("refToMessageID", authnState.getPaosMessageID());
            }

            soapHeader.appendChild(paosResponse);

            if (authnState.getRelayStateElement() != null) {
                Node relayState = soapFaultMessage.importNode(authnState.getRelayStateElement(), true);
                soapHeader.appendChild(relayState);
            }
            // Store the SOAP Fault in the SAML Session
            String modifiedSOAPResponse = writeDomToString(soapFaultMessage);
            authnState.setModifiedSOAPResponse(modifiedSOAPResponse);
            sendSOAPFault(samlSession, authnState);
            return false;

        }

        // There was no response for the ECP.  Look for and propagate an error.
        String errorMessage = getSOAPFaultAsString(is);

        logger.warn("No {} node found in SOAP response. Error: {}", expression, errorMessage);

        if (errorMessage != null) {
            throw new DelegatedAuthenticationRuntimeException(errorMessage);
        }

        return false;
    } catch (XPathExpressionException ex) {
        logger.error("XPath programming error.", ex);
        throw new DelegatedAuthenticationRuntimeException("XPath programming error.", ex);
    } catch (SAXNotRecognizedException ex) {
        logger.error("Exception caught when trying to process the SOAP esponse from the IdP.", ex);
        throw new DelegatedAuthenticationRuntimeException("XPath programming error.", ex);
    } catch (SAXNotSupportedException ex) {
        logger.error("Exception caught when trying to process the SOAP esponse from the IdP.", ex);
        throw new DelegatedAuthenticationRuntimeException(
                "Exception caught when trying to process the SOAP esponse from the IdP.", ex);
    } catch (SAXException ex) {
        logger.error("Exception caught when trying to process the SOAP esponse from the IdP.", ex);
        throw new DelegatedAuthenticationRuntimeException(
                "Exception caught when trying to process the SOAP esponse from the IdP.", ex);
    } catch (DOMException ex) {
        logger.error("Exception caught when trying to process the SOAP esponse from the IdP.", ex);
        throw new DelegatedAuthenticationRuntimeException(
                "Exception caught when trying to process the SOAP esponse from the IdP.", ex);
    } catch (IOException ex) {
        logger.error(
                "This exception should not ever really occur, as the only I/O this method performs is on a ByteArrayInputStream.",
                ex);
        throw new DelegatedAuthenticationRuntimeException(
                "This exception should not ever really occur, as the only I/O this method performs is on a ByteArrayInputStream.",
                ex);
    } catch (SOAPException ex) {
        logger.error("Error processing a SOAP message.", ex);
        throw new DelegatedAuthenticationRuntimeException("Error processing a SOAP message.", ex);
    }
}

From source file:com.amalto.core.util.Util.java

/**
 * Executes a BeforeDeleting process if any
 * //from   ww  w. jav a 2s  .c  o m
 * @param clusterName A data cluster name
 * @param concept A concept/type name
 * @param ids Id of the document being deleted
 * @throws Exception If something went wrong
 */
@SuppressWarnings("unchecked")
public static BeforeDeleteResult beforeDeleting(String clusterName, String concept, String[] ids,
        String operationType) throws Exception {
    // check before deleting transformer
    boolean isBeforeDeletingTransformerExist = false;
    Collection<TransformerV2POJOPK> transformers = getTransformerV2CtrlLocal().getTransformerPKs("*");
    for (TransformerV2POJOPK id : transformers) {
        if (id.getIds()[0].equals("beforeDeleting_" + concept)) {
            isBeforeDeletingTransformerExist = true;
            break;
        }
    }
    if (isBeforeDeletingTransformerExist) {
        try {
            // call before deleting transformer
            // load the item
            ItemPOJOPK itemPk = new ItemPOJOPK(new DataClusterPOJOPK(clusterName), concept, ids);
            ItemPOJO pojo = ItemPOJO.load(itemPk);
            String xml = null;
            if (pojo == null) {// load from recycle bin
                DroppedItemPOJOPK droppedItemPk = new DroppedItemPOJOPK(itemPk, "/");//$NON-NLS-1$
                DroppedItemPOJO droppedItem = Util.getDroppedItemCtrlLocal().loadDroppedItem(droppedItemPk);
                if (droppedItem != null) {
                    xml = droppedItem.getProjection();
                    Document doc = Util.parse(xml);
                    Node item = (Node) XPathFactory.newInstance().newXPath().evaluate("//ii/p", doc, //$NON-NLS-1$
                            XPathConstants.NODE);
                    if (item != null && item instanceof Element) {
                        NodeList list = item.getChildNodes();
                        Node node = null;
                        for (int i = 0; i < list.getLength(); i++) {
                            if (list.item(i) instanceof Element) {
                                node = list.item(i);
                                break;
                            }
                        }
                        if (node != null) {
                            xml = Util.nodeToString(node);
                        }
                    }
                }
            } else {
                xml = pojo.getProjectionAsString();
            }
            // Create before deleting update report
            String username;
            try {
                username = LocalUser.getLocalUser().getUsername();
            } catch (Exception e1) {
                LOGGER.error(e1);
                throw e1;
            }
            String key = "";
            if (ids != null) {
                for (int i = 0; i < ids.length; i++) {
                    key += ids[i];
                    if (i != ids.length - 1) {
                        key += ".";
                    }
                }
            }
            String resultUpdateReport = "" + "<Update>" + "<UserName>" + username + "</UserName>" + "<Source>"
                    + UpdateReportPOJO.GENERIC_UI_SOURCE + "</Source>" + "<TimeInMillis>"
                    + System.currentTimeMillis() + "</TimeInMillis>" + "<OperationType>"
                    + StringEscapeUtils.escapeXml(operationType) + "</OperationType>" + "<DataCluster>"
                    + clusterName + "</DataCluster>" + "<DataModel>" + StringUtils.EMPTY + "</DataModel>"
                    + "<Concept>" + StringEscapeUtils.escapeXml(concept) + "</Concept>" + "<Key>"
                    + StringEscapeUtils.escapeXml(key) + "</Key>";
            resultUpdateReport += "</Update>";
            // Proceed with execution
            String exchangeData = mergeExchangeData(xml, resultUpdateReport);
            final String runningKey = "XtentisWSBean.executeTransformerV2.beforeDeleting.running";
            TransformerContext context = new TransformerContext(
                    new TransformerV2POJOPK("beforeDeleting_" + concept));
            context.put(runningKey, Boolean.TRUE);
            com.amalto.core.server.api.Transformer ctrl = getTransformerV2CtrlLocal();
            TypedContent wsTypedContent = new TypedContent(exchangeData.getBytes("UTF-8"),
                    "text/xml; charset=utf-8");
            ctrl.execute(context, wsTypedContent, new TransformerCallBack() {

                @Override
                public void contentIsReady(TransformerContext context) throws XtentisException {
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("XtentisWSBean.executeTransformerV2.beforeDeleting.contentIsReady() ");
                    }
                }

                @Override
                public void done(TransformerContext context) throws XtentisException {
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("XtentisWSBean.executeTransformerV2.beforeDeleting.done() ");
                    }
                    context.put(runningKey, Boolean.FALSE);
                }
            });
            while ((Boolean) context.get(runningKey)) { // TODO Poor-man synchronization here
                Thread.sleep(100);
            }
            // TODO process no plug-in issue
            String outputErrorMessage = null;
            // Scan the entries - in priority, aka the content of the 'output_error_message' entry.
            for (Entry<String, TypedContent> entry : context.getPipelineClone().entrySet()) {
                if (ITransformerConstants.VARIABLE_OUTPUT_OF_BEFORESAVINGTRANFORMER.equals(entry.getKey())) {
                    outputErrorMessage = new String(entry.getValue().getContentBytes(), "UTF-8");
                    break;
                }
            }
            // handle error message
            BeforeDeleteResult result = new BeforeDeleteResult();
            if (outputErrorMessage == null) {
                LOGGER.warn("No message generated by before delete process.");
                result.type = "info"; //$NON-NLS-1$
                result.message = StringUtils.EMPTY;
            } else {
                if (outputErrorMessage.length() > 0) {
                    Document doc = Util.parse(outputErrorMessage);
                    // TODO what if multiple error nodes ?
                    String xpath = "//report/message"; //$NON-NLS-1$
                    Node errorNode = (Node) XPathFactory.newInstance().newXPath().evaluate(xpath, doc,
                            XPathConstants.NODE);
                    if (errorNode instanceof Element) {
                        Element errorElement = (Element) errorNode;
                        result.type = errorElement.getAttribute("type"); //$NON-NLS-1$
                        Node child = errorElement.getFirstChild();
                        if (child instanceof Text) {
                            result.message = child.getTextContent();
                        }
                    }
                } else {
                    result.type = "error"; //$NON-NLS-1$
                    result.message = "<report><message type=\"error\"/></report>"; //$NON-NLS-1$
                }
            }
            return result;
        } catch (Exception e) {
            LOGGER.error(e);
            throw e;
        }
    }
    return null;
}

From source file:com.esri.gpt.server.csw.provider3.GetRecordsProvider.java

/**
 * Handles an XML based request (normally HTTP POST).
 * @param context the operation context//  w w w  . java2  s.c  o  m
 * @param root the root node
 * @param xpath an XPath to enable queries (properly configured with name spaces)
 * @throws Exception if a processing exception occurs
 */
public void handleXML(OperationContext context, Node root, XPath xpath) throws Exception {

    // initialize
    LOGGER.finer("Handling csw:GetRecords request XML...");
    QueryOptions qOptions = context.getRequestOptions().getQueryOptions();
    qOptions.setMaxRecordsThreshold(getMaxRecordsThreshold());
    ServiceProperties svcProps = context.getServiceProperties();
    ParseHelper pHelper = new ParseHelper();
    ValidationHelper vHelper = new ValidationHelper();
    String locator;
    String[] parsed;
    ISupportedValues supported;
    IProviderFactory factory = context.getProviderFactory();

    // service and version are parsed by the parent RequestHandler

    // TODO requestId
    locator = "@outputFormat";
    parsed = pHelper.getParameterValues(root, xpath, locator);
    supported = svcProps.getSupportedValues(CswConstants.Parameter_OutputFormat);
    try {
        context.getOperationResponse()
                .setOutputFormat(vHelper.validateValue(supported, locator, parsed, false));
    } catch (OwsException ex) {
        context.getOperationResponse().setResponseCode(HttpServletResponse.SC_BAD_REQUEST);
        throw ex;
    }

    // output schema
    locator = "@outputSchema";
    parsed = pHelper.getParameterValues(root, xpath, locator);
    supported = svcProps.getSupportedValues(CswConstants.Parameter_OutputSchema);
    try {
        qOptions.setOutputSchema(vHelper.validateValue(supported, locator, parsed, false));
    } catch (OwsException ex) {
        context.getOperationResponse().setResponseCode(HttpServletResponse.SC_BAD_REQUEST);
        throw ex;
    }

    // start and max records
    qOptions.setStartRecord(Math.max(Val.chkInt(xpath.evaluate("@startPosition", root), 1), 1));
    qOptions.setMaxRecords(Val.chkInt(xpath.evaluate("@maxRecords", root), 10));

    // result type
    locator = "@resultType";
    parsed = pHelper.getParameterValues(root, xpath, locator);
    supported = svcProps.getSupportedValues(CswConstants.Parameter_ResultType);
    qOptions.setResultType(vHelper.validateValue(supported, locator, parsed, false));
    if (qOptions.getResultType() == null) {
        qOptions.setResultType(CswConstants.ResultType_Results);
    }

    // find the query node
    locator = "csw:Query";
    Node ndQuery = (Node) xpath.evaluate(locator, root, XPathConstants.NODE);
    if (ndQuery != null) {

        // query type names
        locator = "csw:Query/@typeNames";
        parsed = pHelper.getParameterValues(root, xpath, "@typeNames");
        qOptions.setQueryTypeNames(vHelper.validateValues(locator, parsed, false));

        // response element set type
        locator = "csw:ElementSetName";
        parsed = pHelper.getParameterValues(ndQuery, xpath, locator);
        supported = svcProps.getSupportedValues(CswConstants.Parameter_ElementSetType);
        qOptions.setElementSetType(vHelper.validateValue(supported, locator, parsed, false));

        // response element set type names
        String elementSetType = qOptions.getElementSetType();
        if (elementSetType != null) {
            locator = "csw:ElementSetName/@typeNames";
            parsed = pHelper.getParameterValues(ndQuery, xpath, locator);
            qOptions.setElementSetTypeNames(vHelper.validateValues(locator, parsed, false));
        }

        locator = "csw:ElementName";
        parsed = pHelper.getParameterValues(ndQuery, xpath, locator);
        if (parsed != null && qOptions.getElementSetType() != null) {
            String msg = "GetRecordsProvider:handleGet: elementName not allowed if elementSetName present.";
            context.getOperationResponse().setResponseCode(HttpServletResponse.SC_BAD_REQUEST);
            throw new OwsException(OwsException.OWSCODE_NoApplicableCode, locator, msg);
        }
        supported = svcProps.getSupportedValues(CswConstants.Parameter_ElementName);
        qOptions.setElementNames(vHelper.validateValues(supported, locator, parsed, false));

        // find the constraint node
        Node ndConstraint = (Node) xpath.evaluate("csw:Constraint", ndQuery, XPathConstants.NODE);
        if (ndConstraint != null) {

            // constraint version
            String constraintVersion = xpath.evaluate("@version", ndConstraint);
            qOptions.setQueryConstraintVersion(constraintVersion);

            // csw:CqlText
            locator = "csw:CqlText";
            Node ndCql = (Node) xpath.evaluate(locator, ndConstraint, XPathConstants.NODE);
            if (ndCql != null) {
                String cql = Val.chkStr(ndCql.getTextContent());
                qOptions.setQueryConstraintCql(cql);
                ICqlParser parser = factory.makeCqlParser(context, constraintVersion);
                if (parser == null) {
                    String msg = "IProviderFactory.makeCqlParser: instantiation failed.";
                    throw new OwsException(OwsException.OWSCODE_NoApplicableCode, locator, msg);
                } else {
                    parser.parseCql(context, cql);
                }
            } else {

                // ogc:Filter
                locator = "fes:Filter";
                Node ndFilter = (Node) xpath.evaluate(locator, ndConstraint, XPathConstants.NODE);
                if (ndFilter != null) {
                    IFilterParser parser = factory.makeFilterParser(context, constraintVersion);
                    if (parser == null) {
                        String msg = "IProviderFactory.makeFilterParser: instantiation failed.";
                        throw new OwsException(OwsException.OWSCODE_NoApplicableCode, locator, msg);
                    } else {
                        parser.parseFilter(context, ndFilter, xpath);
                    }
                } else {
                    String msg = "An OGC filter for the CSW constraint is required.";
                    throw new OwsException(OwsException.OWSCODE_NoApplicableCode, locator, msg);
                }
            }
        }

        // ogc:SortBy
        locator = "ogc:SortBy";
        Node ndSortBy = (Node) xpath.evaluate(locator, ndQuery, XPathConstants.NODE);
        if (ndSortBy != null) {
            ISortByParser parser = factory.makeSortByParser(context);
            if (parser == null) {
                String msg = "IProviderFactory.makeSortByParser: instantiation failed.";
                throw new OwsException(OwsException.OWSCODE_NoApplicableCode, locator, msg);
            } else {
                parser.parseSortBy(context, ndSortBy, xpath);
            }
        }
    }

    // execute the request
    this.execute(context);
}

From source file:org.apache.zeppelin.sap.universe.UniverseClient.java

private String getValue(String response, String xPathString)
        throws ParserConfigurationException, IOException, SAXException, XPathExpressionException {
    try (InputStream xmlStream = new ByteArrayInputStream(response.getBytes())) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(xmlStream);
        XPathFactory xPathfactory = XPathFactory.newInstance();
        XPath xpath = xPathfactory.newXPath();
        XPathExpression expr = xpath.compile(xPathString);
        Node tokenNode = (Node) expr.evaluate(doc, XPathConstants.NODE);
        if (tokenNode != null) {
            return tokenNode.getTextContent();
        }//from w  ww. ja v a2 s.  c o m
    }
    return null;
}

From source file:gov.nij.bundles.intermediaries.ers.EntityResolutionMessageHandlerTest.java

@Ignore // only use this test to explore performance issues
@Test/*  w w w  . j a  va  2s.  c  om*/
public void testSortLargeRecordSet() throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    Document entityMergeRequestDocument = dbf.newDocumentBuilder()
            .parse(new File("src/test/resources/xml/EntityMergeRequestMessageSortTest.xml"));
    Document attributeParametersDocument = dbf.newDocumentBuilder()
            .parse(new File("src/test/resources/xml/TestAttributeParameters.xml"));
    XPath xp = XPathFactory.newInstance().newXPath();
    xp.setNamespaceContext(new EntityResolutionNamespaceContext());
    Element entityContainerElement = (Element) xp.evaluate(
            "/merge:EntityMergeRequestMessage/merge:MergeParameters/er-ext:EntityContainer",
            entityMergeRequestDocument, XPathConstants.NODE);
    NodeList entityNodes = (NodeList) xp.evaluate("er-ext:Entity", entityContainerElement,
            XPathConstants.NODESET);
    int newEntityGroupCount = 100;
    for (int i = 0; i < newEntityGroupCount; i++) {
        for (int j = 0; j < entityNodes.getLength(); j++) {
            Element newEntityElement = (Element) entityNodes.item(j).cloneNode(true);
            entityContainerElement.appendChild(newEntityElement);
        }
    }
    NodeList newEntityNodes = (NodeList) xp.evaluate("er-ext:Entity", entityContainerElement,
            XPathConstants.NODESET);
    assertEquals((newEntityGroupCount + 1) * entityNodes.getLength(), newEntityNodes.getLength());
    LOG.info("Large Record Set sort test, record count=" + newEntityNodes.getLength());
    // instrument the following line as needed for performance testing
    @SuppressWarnings("unused")
    Document resultDocument = entityResolutionMessageHandler.performEntityResolution(entityContainerElement,
            attributeParametersDocument.getDocumentElement(), makeEntityResolutionConfigurationNode(1 + ""));
    // LOG.info(new XmlConverter().toString(resultDocument));
}

From source file:dk.netarkivet.harvester.harvesting.WARCWriterProcessor.java

/**
 * Return relevant values as header-like fields (here ANVLRecord, but spec-defined "application/warc-fields" type
 * when written). Field names from from DCMI Terms and the WARC/0.17 specification.
 *
 * @see org.archive.crawler.framework.WriterPoolProcessor#getFirstrecordBody(java.io.File)
 */// www  .  j a  v a 2 s .c o  m
@Override
protected String getFirstrecordBody(File orderFile) {
    ANVLRecord record = new ANVLRecord(7);
    record.addLabelValue("software", "Heritrix/" + Heritrix.getVersion() + " http://crawler.archive.org");

    try {
        InetAddress host = InetAddress.getLocalHost();
        record.addLabelValue("ip", host.getHostAddress());
        record.addLabelValue("hostname", host.getCanonicalHostName());
    } catch (UnknownHostException e) {
        logger.log(Level.WARNING, "unable top obtain local crawl engine host", e);
    }

    // conforms to ISO 28500:2009 as of May 2009
    // as described at http://bibnum.bnf.fr/WARC/
    // latest draft as of November 2008
    record.addLabelValue("format", "WARC File Format 1.0");
    record.addLabelValue("conformsTo", "http://bibnum.bnf.fr/WARC/WARC_ISO_28500_version1_latestdraft.pdf");

    // Get other values from order.xml
    try {
        Document doc = XmlUtils.getDocument(orderFile);
        addIfNotBlank(record, "operator", XmlUtils.xpathOrNull(doc, "//meta/operator"));
        addIfNotBlank(record, "publisher", XmlUtils.xpathOrNull(doc, "//meta/organization"));
        addIfNotBlank(record, "audience", XmlUtils.xpathOrNull(doc, "//meta/audience"));
        addIfNotBlank(record, "isPartOf", XmlUtils.xpathOrNull(doc, "//meta/name"));

        // disabling "created" field per HER-1634
        // though it's theoretically useful as a means of distinguishing
        // one crawl from another, the current usage/specification is too
        // vague... in particular a 'created' field in the 'warcinfo' is
        // reasonable to interpret as applying to the WARC-unit, rather
        // than the crawl-job-unit so we remove it and see if anyone
        // complains or makes a case for restoring it in a less-ambiguous
        // manner
        // String rawDate = XmlUtils.xpathOrNull(doc,"//meta/date");
        // if(StringUtils.isNotBlank(rawDate)) {
        // Date date;
        // try {
        // date = ArchiveUtils.parse14DigitDate(rawDate);
        // addIfNotBlank(record,"created",ArchiveUtils.getLog14Date(date));
        // } catch (ParseException e) {
        // logger.log(Level.WARNING,"obtaining warc created date",e);
        // }
        // }

        addIfNotBlank(record, "description", XmlUtils.xpathOrNull(doc, "//meta/description"));
        addIfNotBlank(record, "robots",
                XmlUtils.xpathOrNull(doc, "//newObject[@name='robots-honoring-policy']/string[@name='type']"));
        addIfNotBlank(record, "http-header-user-agent",
                XmlUtils.xpathOrNull(doc, "//map[@name='http-headers']/string[@name='user-agent']"));
        addIfNotBlank(record, "http-header-from",
                XmlUtils.xpathOrNull(doc, "//map[@name='http-headers']/string[@name='from']"));
        if (metadataMap == null) {
            //metadataMap = getMetadataItems();
            XPathFactory factory = XPathFactory.newInstance();
            XPath xpath = factory.newXPath();
            XPathExpression expr = xpath.compile(H1HeritrixTemplate.METADATA_ITEMS_XPATH);
            Node node = (Node) expr.evaluate(doc, XPathConstants.NODE);
            //NodeList nodeList = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
            //Node node = nodeList.item(0);
            if (node != null) {
                NodeList nodeList = node.getChildNodes();
                if (nodeList != null) {
                    metadataMap = new HashMap();
                    for (int i = 0; i < nodeList.getLength(); ++i) {
                        node = nodeList.item(i);
                        if (node.getNodeType() == Node.ELEMENT_NODE) {
                            String typeName = node.getNodeName();
                            if ("string".equals(typeName)) {
                                Node attribute = node.getAttributes().getNamedItem("name");
                                if (attribute != null && attribute.getNodeType() == Node.ATTRIBUTE_NODE) {
                                    String key = attribute.getNodeValue();
                                    if (key != null && key.length() > 0) {
                                        String value = node.getTextContent();
                                        metadataMap.put(key, value);
                                        // debug
                                        //System.out.println(key + "=" + value);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    } catch (IOException e) {
        logger.log(Level.WARNING, "Error obtaining warcinfo", e);
    } catch (XPathExpressionException e) {
        logger.log(Level.WARNING, "Error obtaining metadata items", e);
    }

    // add fields from harvesInfo.xml version 0.4
    /*
     * <harvestInfo> <version>0.4</version> <jobId>1</jobId> <priority>HIGHPRIORITY</priority>
     * <harvestNum>0</harvestNum> <origHarvestDefinitionID>1</origHarvestDefinitionID>
     * <maxBytesPerDomain>500000000</maxBytesPerDomain> <maxObjectsPerDomain>2000</maxObjectsPerDomain>
     * <orderXMLName>default_orderxml</orderXMLName>
     * <origHarvestDefinitionName>netarkivet</origHarvestDefinitionName> <scheduleName>Once_a_week</scheduleName>
     * <harvestFilenamePrefix>1-1</harvestFilenamePrefix> <jobSubmitDate>Some date</jobSubmitDate>
     * <performer>undefined</performer> </harvestInfo>
     */
    String netarchiveSuiteComment = "#added by NetarchiveSuite "
            + dk.netarkivet.common.Constants.getVersionString();
    ANVLRecord recordNAS = new ANVLRecord(7);

    if (metadataMap != null) {
        // Add the data from the metadataMap to the WarcInfoRecord.
        recordNAS.addLabelValue(HARVESTINFO_VERSION, (String) metadataMap.get(HARVESTINFO_VERSION));
        recordNAS.addLabelValue(HARVESTINFO_JOBID, (String) metadataMap.get(HARVESTINFO_JOBID));
        recordNAS.addLabelValue(HARVESTINFO_CHANNEL, (String) metadataMap.get(HARVESTINFO_CHANNEL));
        recordNAS.addLabelValue(HARVESTINFO_HARVESTNUM, (String) metadataMap.get(HARVESTINFO_HARVESTNUM));
        recordNAS.addLabelValue(HARVESTINFO_ORIGHARVESTDEFINITIONID,
                (String) metadataMap.get(HARVESTINFO_ORIGHARVESTDEFINITIONID));
        recordNAS.addLabelValue(HARVESTINFO_MAXBYTESPERDOMAIN,
                (String) metadataMap.get(HARVESTINFO_MAXBYTESPERDOMAIN));

        recordNAS.addLabelValue(HARVESTINFO_MAXOBJECTSPERDOMAIN,
                (String) metadataMap.get(HARVESTINFO_MAXOBJECTSPERDOMAIN));
        recordNAS.addLabelValue(HARVESTINFO_ORDERXMLNAME, (String) metadataMap.get(HARVESTINFO_ORDERXMLNAME));
        recordNAS.addLabelValue(HARVESTINFO_ORIGHARVESTDEFINITIONNAME,
                (String) metadataMap.get(HARVESTINFO_ORIGHARVESTDEFINITIONNAME));

        if (metadataMap.containsKey((HARVESTINFO_SCHEDULENAME))) {
            recordNAS.addLabelValue(HARVESTINFO_SCHEDULENAME,
                    (String) metadataMap.get(HARVESTINFO_SCHEDULENAME));
        }
        recordNAS.addLabelValue(HARVESTINFO_HARVESTFILENAMEPREFIX,
                (String) metadataMap.get(HARVESTINFO_HARVESTFILENAMEPREFIX));

        recordNAS.addLabelValue(HARVESTINFO_JOBSUBMITDATE, (String) metadataMap.get(HARVESTINFO_JOBSUBMITDATE));

        if (metadataMap.containsKey(HARVESTINFO_PERFORMER)) {
            recordNAS.addLabelValue(HARVESTINFO_PERFORMER, (String) metadataMap.get(HARVESTINFO_PERFORMER));
        }

        if (metadataMap.containsKey(HARVESTINFO_AUDIENCE)) {
            recordNAS.addLabelValue(HARVESTINFO_AUDIENCE, (String) metadataMap.get(HARVESTINFO_AUDIENCE));
        }
    } else {
        logger.log(Level.SEVERE, "Error missing metadata");
    }

    // really ugly to return as string, when it may just be merged with
    // a couple other fields at write time, but changing would require
    // larger refactoring
    return record.toString() + netarchiveSuiteComment + "\n" + recordNAS.toString();
}