Java 类javax.xml.xpath.XPathExpressionException 实例源码

项目:VISNode    文件:VersionFinder.java   
/**
 * Returns the version
 * 
 * @return String
 */
public static String getVersion() {
    String jarImplementation = VISNode.class.getPackage().getImplementationVersion();
    if (jarImplementation != null) {
        return jarImplementation;
    }
    String file = VISNode.class.getResource(".").getFile();
    String pack = VISNode.class.getPackage().getName().replace(".", "/") + '/';
    File pomXml = new File(file.replace("target/classes/" + pack, "pom.xml"));
    if (pomXml.exists()) {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(new InputSource(new FileReader(pomXml)));
            XPath xPath = XPathFactory.newInstance().newXPath();
            return (String) xPath.evaluate("/project/version", document, XPathConstants.STRING);
        } catch (IOException | ParserConfigurationException | XPathExpressionException | SAXException e) { }
    }
    return "Unknown version";
}
项目:oscm    文件:PartnerReport.java   
private RDOPartnerReport runPartnerReport(PlatformUser user,
        OrganizationRoleType roleType, int month, int year)
        throws ParserConfigurationException, SAXException, IOException,
        XPathExpressionException, ParseException {
    if (!hasRole(roleType, user)) {
        return new RDOPartnerReport();
    }

    Calendar c = initializeCalendar(month, year);
    long periodStart = c.getTimeInMillis();
    c.add(Calendar.MONTH, 1);
    long periodEnd = c.getTimeInMillis();

    PartnerRevenueDao sqlDao = new PartnerRevenueDao(ds);
    sqlDao.executeSinglePartnerQuery(periodStart, periodEnd, user
            .getOrganization().getKey(), roleType.name().toUpperCase());

    PartnerRevenueBuilder builder;
    builder = new PartnerRevenueBuilder(new Locale(user.getLocale()),
            sqlDao.getReportData());
    RDOPartnerReport result = builder.buildSingleReport();
    return result;
}
项目:verify-hub    文件:SoapMessageManager.java   
public Element unwrapSoapMessage(Element soapElement) {
    XPath xpath = XPathFactory.newInstance().newXPath();
    NamespaceContextImpl context = new NamespaceContextImpl();
    context.startPrefixMapping("soapenv", "http://schemas.xmlsoap.org/soap/envelope/");
    context.startPrefixMapping("samlp", "urn:oasis:names:tc:SAML:2.0:protocol");
    context.startPrefixMapping("saml", "urn:oasis:names:tc:SAML:2.0:assertion");
    context.startPrefixMapping("ds", "http://www.w3.org/2000/09/xmldsig#");
    xpath.setNamespaceContext(context);
    try {
        final String expression = "/soapenv:Envelope/soapenv:Body/samlp:Response";
        Element element = (Element) xpath.evaluate(expression, soapElement, XPathConstants.NODE);

        if (element == null) {
            String errorMessage = format("Document{0}{1}{0}does not have element {2} inside it.", NEW_LINE,
                    writeToString(soapElement), expression);
            LOG.error(errorMessage);
            throw new IllegalArgumentException(errorMessage);
        }

        return element;
    } catch (XPathExpressionException e) {
        throw propagate(e);
    }
}
项目:xpath-to-xml    文件:XmlBuilderTest.java   
@Test
public void shouldNotModifyDocumentWhenAllXPathsTraversable()
        throws XPathExpressionException, ParsingException, IOException {
    Map<String, Object> xmlProperties = fixtureAccessor.getXmlProperties();
    String xml = fixtureAccessor.getPutValueXml();
    Document oldDocument = stringToXml(xml);
    Document builtDocument = new XmlBuilder(namespaceContext)
            .putAll(xmlProperties)
            .build(oldDocument);

    assertThat(xmlToString(builtDocument)).isEqualTo(xml);

    builtDocument = new XmlBuilder(namespaceContext)
            .putAll(xmlProperties.keySet())
            .build(oldDocument);

    assertThat(xmlToString(builtDocument)).isEqualTo(xml);
}
项目:openjdk-jdk10    文件:Internalizer.java   
private NodeList evaluateXPathMultiNode(Node bindings, Node target, String expression, NamespaceContext namespaceContext) {
    NodeList nlst;
    try {
        xpath.setNamespaceContext(namespaceContext);
        nlst = (NodeList) xpath.evaluate(expression, target, XPathConstants.NODESET);
    } catch (XPathExpressionException e) {
        reportError((Element) bindings, WsdlMessages.INTERNALIZER_X_PATH_EVALUATION_ERROR(e.getMessage()), e);
        return null; // abort processing this <jaxb:bindings>
    }

    if (nlst.getLength() == 0) {
        reportError((Element) bindings, WsdlMessages.INTERNALIZER_X_PATH_EVALUATES_TO_NO_TARGET(expression));
        return null; // abort
    }

    return nlst;
}
项目:xpath-to-xml    文件:XmlBuilderTest.java   
@Test
public void shouldBuildDocumentFromSetOfXPathsAndSetValues() throws XPathExpressionException, IOException {
    Map<String, Object> xmlProperties = fixtureAccessor.getXmlProperties();
    Document newDocument = new Document((Element) root.copy());
    Document builtDocument = new XmlBuilder(namespaceContext)
            .putAll(xmlProperties)
            .build(newDocument);

    for (Entry<String, Object> xpathToValuePair : xmlProperties.entrySet()) {
        Nodes nodes = null == namespaceContext
                ? builtDocument.query(xpathToValuePair.getKey())
                : builtDocument.query(xpathToValuePair.getKey(), toXpathContext(namespaceContext));
        assertThat(nodes.get(0).getValue()).isEqualTo(xpathToValuePair.getValue());
    }
    assertThat(xmlToString(builtDocument)).isEqualTo(fixtureAccessor.getPutValueXml());
}
项目:oscm    文件:MigrationBillingResultGatheredEvents.java   
protected String migrateBillingResultXml(String billingXml)
        throws ParserConfigurationException, SAXException, IOException,
        TransformerException, XPathExpressionException {
    Document document = XMLConverter.convertToDocument(billingXml, false);
    NodeList nodeList = XMLConverter.getNodeListByXPath(document,
            XPATH_GATHEREDEVENTS);
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node gatheredEvents = nodeList.item(i);
        if (!istotalEventCostsAlreadyPresent(gatheredEvents)
                && gatheredEvents.getChildNodes().getLength() > 0) {
            Element totalCosts = createNodeTotalEventCosts(gatheredEvents);
            gatheredEvents.appendChild(totalCosts);
        }
    }
    return XMLConverter.convertToString(document, false);
}
项目:openjdk-jdk10    文件:XPathImplUtil.java   
/**
 * Parse the input source and return a Document.
 * @param source The {@code InputSource} of the document
 * @return a DOM Document
 * @throws XPathExpressionException if there is an error parsing the source.
 */
Document getDocument(InputSource source)
    throws XPathExpressionException {
    requireNonNull(source, "Source");
    try {
        // we'd really like to cache those DocumentBuilders, but we can't because:
        // 1. thread safety. parsers are not thread-safe, so at least
        //    we need one instance per a thread.
        // 2. parsers are non-reentrant, so now we are looking at having a
        // pool of parsers.
        // 3. then the class loading issue. The look-up procedure of
        //    DocumentBuilderFactory.newInstance() depends on context class loader
        //    and system properties, which may change during the execution of JVM.
        //
        // so we really have to create a fresh DocumentBuilder every time we need one
        // - KK
        DocumentBuilderFactory dbf = FactoryImpl.getDOMFactory(useServiceMechanism);
        dbf.setNamespaceAware(true);
        dbf.setValidating(false);
        return dbf.newDocumentBuilder().parse(source);
    } catch (ParserConfigurationException | SAXException | IOException e) {
        throw new XPathExpressionException (e);
    }
}
项目:xpath-to-xml    文件:XPathParser.java   
private Expr MultiplicativeExpr(Context context) throws XPathExpressionException {
    Expr left = UnaryExpr(context);
    Type type = context.tokenAt(1).getType();
    while (Type.STAR == type) {
        Expr right;
        switch (type) {
            case STAR:
                context.match(Type.STAR);
                right = UnaryExpr(context);
                left = new MultiplicationExpr(left, right);
                break;
            default:
                throw new XPathParserException(context.tokenAt(1), Type.STAR);
        }
        type = context.tokenAt(1).getType();
    }
    return left;
}
项目:oscm    文件:SharesCalculatorBeanCutOffDayIT.java   
private void verify_SupplierResult_Service(Document xml,
        Organization resaleOrg, OfferingType type, String roleString)
        throws XPathExpressionException {

    NodeList services = XMLConverter.getNodeListByXPath(xml, "/"
            + roleString
            + "RevenueShareResult/Currency/Marketplace/Service");

    for (int i = 0; i < services.getLength(); i++) {
        String model = XMLConverter.getStringAttValue(services.item(i),
                "model");

        if (type.name().equals(model)) {

            verify_SupplierResult_RevenueShareDetails(services.item(i));
            if (resaleOrg != null) {
                verify_ResaleOrganization(services.item(i), resaleOrg);
            }

        }
    }
}
项目:oscm    文件:PartnerRevenueBuilder.java   
public RDOPartnerReports buildReports()
        throws ParserConfigurationException, SAXException, IOException,
        XPathExpressionException, ParseException {
    if (sqlData == null || sqlData.isEmpty()) {
        return new RDOPartnerReports();
    }

    RDOPartnerReports result = new RDOPartnerReports();
    result.setEntryNr(idGen.nextValue());
    result.setServerTimeZone(DateConverter.getCurrentTimeZoneAsUTCString());
    for (ReportData data : sqlData) {
        xmlDocument = XMLConverter.convertToDocument(data.getResultXml(),
                false);
        partnerType = Strings.firstCharToUppercase(data.getResulttype());
        result.getReports().add(build(data, result.getEntryNr()));
    }
    return result;
}
项目:openjdk-jdk10    文件:XPathImpl.java   
public Object evaluate(String expression, InputSource source,
        QName returnType) throws XPathExpressionException {
    isSupported(returnType);

    try {
        Document document = getDocument(source);
        XObject resultObject = eval(expression, document);
        return getResultAsType(resultObject, returnType);
    } catch (TransformerException te) {
        Throwable nestedException = te.getException();
        if (nestedException instanceof javax.xml.xpath.XPathFunctionException) {
            throw (javax.xml.xpath.XPathFunctionException)nestedException;
        } else {
            throw new XPathExpressionException (te);
        }
    }
}
项目:xpath-to-xml    文件:XmlBuilderTest.java   
@Test
public void shouldBuildDocumentFromSetOfXPathsAndSetValues() throws XPathExpressionException, IOException {
    Map<String, Object> xmlProperties = fixtureAccessor.getXmlProperties();
    Document builtDocument = new XmlBuilder(namespaceContext)
            .putAll(xmlProperties)
            .build(DocumentHelper.createDocument());

    for (Entry<String, Object> xpathToValuePair : xmlProperties.entrySet()) {
        XPath xpath = builtDocument.createXPath(xpathToValuePair.getKey());
        if (null != namespaceContext) {
            xpath.setNamespaceContext(new SimpleNamespaceContextWrapper(namespaceContext));
        }
        assertThat(xpath.selectSingleNode(builtDocument).getText()).isEqualTo(xpathToValuePair.getValue());
    }
    assertThat(xmlToString(builtDocument)).isEqualTo(fixtureAccessor.getPutValueXml());
}
项目:oscm    文件:SupplierRevenueShareBuilder.java   
public RDOSupplierRevenueShareReports buildReports()
        throws ParserConfigurationException, SAXException, IOException,
        XPathExpressionException, ParseException {
    if (sqlData == null || sqlData.isEmpty()) {
        return new RDOSupplierRevenueShareReports();
    }

    RDOSupplierRevenueShareReports result = new RDOSupplierRevenueShareReports();
    result.setEntryNr(idGen.nextValue());
    result.setServerTimeZone(DateConverter.getCurrentTimeZoneAsUTCString());

    for (ReportData data : sqlData) {
        xmlDocument = XMLConverter.convertToDocument(data.getResultXml(),
                false);
        result.getReports().add(build(data, result.getEntryNr()));
    }
    return result;
}
项目:openjdk-jdk10    文件:XPathExpressionImpl.java   
@Override
public <T>T evaluateExpression(Object item, Class<T> type)
    throws XPathExpressionException {
    isSupportedClassType(type);

    try {
        XObject resultObject = eval(item, xpath);
        if (type.isAssignableFrom(XPathEvaluationResult.class)) {
            return getXPathResult(resultObject, type);
        } else {
            return XPathResultImpl.getValue(resultObject, type);
        }

    } catch (javax.xml.transform.TransformerException te) {
        throw new XPathExpressionException(te);
    }
}
项目:ARCLib    文件:ArclibXmlGeneratorTest.java   
/**
 * Tests that only single element has been created at the destination xPath when specifying the position of the source element
 */
@Test
public void generateArclibXmlElementAtPositionMapping() throws SAXException, ParserConfigurationException, XPathExpressionException,
        IOException,
        TransformerException {
    SipProfile profile = new SipProfile();
    String sipProfileXml = Resources.toString(this.getClass().getResource(
            "/arclibxmlgeneration/sipProfiles/sipProfileElementAtPositionMapping.xml"), StandardCharsets
            .UTF_8);
    profile.setXml(sipProfileXml);

    store.save(profile);

    String arclibXml = generator.generateArclibXml(SIP_PATH, profile.getId());
    assertThat(arclibXml, is("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<METS:mets xmlns:METS=\"http://www.loc.gov/METS/\"><METS:metsHdr xmlns:METS=\"http://arclib.lib.cas.cz/ARCLIB_XML\"><METS:agent ROLE=\"CREATOR\" TYPE=\"ORGANIZATION\"> \r\n\t\t\t<METS:name>Exon s.r.o.</METS:name>\r\n\t\t</METS:agent>\r\n</METS:metsHdr></METS:mets>"));
}
项目:oscm    文件:BillingResultEvaluator.java   
public void assertPriceModelUserAssignmentCosts(Node priceModel,
        String expectedBasePeriod, String expectedFactor,
        String expectedUserNumber, String price)
        throws XPathExpressionException {

    assertEquals("Wrong base period in user assignment costs",
            expectedBasePeriod, XMLConverter.getNodeTextContentByXPath(
                    priceModel, "UserAssignmentCosts/@basePeriod"));
    assertEquals("Wrong factor in user assignment costs", expectedFactor,
            XMLConverter.getNodeTextContentByXPath(priceModel,
                    "UserAssignmentCosts/@factor"));
    assertEquals("Wrong user number in user assignment costs",
            String.valueOf(expectedUserNumber),
            XMLConverter.getNodeTextContentByXPath(priceModel,
                    "UserAssignmentCosts/@numberOfUsersTotal"));
    assertEquals("Wrong price in user assignment costs", price,
            XMLConverter.getNodeTextContentByXPath(priceModel,
                    "UserAssignmentCosts/@price"));
}
项目:oscm    文件:SharesCalculatorBeanCutOffDayIT.java   
private void verify_ServiceRevenue(Document xml, String roleString)
        throws XPathExpressionException {
    Node serviceRevenue = XMLConverter
            .getNodeByXPath(
                    xml,
                    "/"
                            + roleString
                            + "RevenueShareResult/Currency/Supplier/Service/ServiceRevenue");
    assertEquals(
            REVENUE_SHARE.intValue() + ".00",
            XMLConverter.getStringAttValue(serviceRevenue,
                    roleString.toLowerCase() + "Revenue"));
    assertEquals(
            REVENUE_SHARE_PERCENT.intValue() + ".00",
            XMLConverter.getStringAttValue(serviceRevenue,
                    roleString.toLowerCase() + "RevenueSharePercentage"));
    assertEquals(REVENUE_SHARE.intValue() * NUM_BILLING_RESULTS + ".00",
            XMLConverter.getStringAttValue(serviceRevenue, "totalAmount"));
}
项目:nbreleaseplugin    文件:Pom.java   
private Element findElement(ElementValue pev, String path) {
    XPath xpath = XPathFactory.newInstance().newXPath();
    try {
        return (Element) xpath.evaluate(path, pev.getElement(), XPathConstants.NODE);
    } catch (XPathExpressionException ex) {
        return null;
    }
}
项目:oscm    文件:BillingXMLNodeSearch.java   
public static Node getPriceModelNode(Document billingResult,
        long priceModelKey, String startDate, String endDate)
        throws XPathExpressionException {

    long start = DateTimeHandling.calculateMillis(startDate);
    long end = DateTimeHandling.calculateMillis(endDate);
    Node n = XMLConverter.getNodeByXPath(billingResult,
            "//PriceModel[@id='" + priceModelKey
                    + "']/UsagePeriod[@startDate='" + start
                    + "' and @endDate='" + end + "']");
    return n.getParentNode();
}
项目:openjdk-jdk10    文件:XPathExpressionTest.java   
/**
 * evaluate(InputSource source,QName returnType) throws
 * XPathExpressionException if expression is blank " ".
 *
 * @throws Exception If any errors occur.
 */
@Test(expectedExceptions = XPathExpressionException.class)
public void testCheckXPathExpression25() throws Exception {
    try (InputStream is = Files.newInputStream(XML_PATH)) {
        xpath.compile(" ").evaluate(new InputSource(is), STRING);
    }
}
项目:ARCLib    文件:ValidationServiceTest.java   
@Test
public void validateSipMixedChecksSuccess() throws ParserConfigurationException, SAXException, XPathExpressionException, IOException {
    InputStream inputStream = getClass().getResourceAsStream("/validation/validationProfileMixedChecks.xml");
    String xml = readFromInputStream(inputStream);

    ValidationProfile validationProfile = new ValidationProfile();
    validationProfile.setXml(xml);

    store.save(validationProfile);
    flushCache();

    service.validateSip(SIP_ID, SIP_PATH, validationProfile.getId());
}
项目:oscm    文件:XmlSearch.java   
public Set<Long> findPriceModelKeys() {
    try {
        Set<Long> result = new HashSet<Long>();
        NodeList nodeList = XMLConverter.getNodeListByXPath(billingResult,
                "//PriceModel/@id");
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node n = nodeList.item(i);
            String idValue = n.getTextContent();
            result.add(Long.valueOf(idValue));
        }
        return result;
    } catch (XPathExpressionException e) {
        throw new BillingRunFailed(e);
    }
}
项目:xrd4j    文件:JSONToXMLConverterTest.java   
/**
 * Test converting nested elements.
 */
public void testArray() throws XPathExpressionException {
    List<String> elements = new ArrayList<>();
    elements.add("<id>49</id>");
    elements.add("<name_en>City of Espoo</name_en>");
    elements.add("<name_sv>Esbo stad</name_sv>");
    elements.add("<data_source_url>www.espoo.fi</data_source_url>");
    elements.add("<name_fi>Espoon kaupunki</name_fi>");
    elements.add("<id>91</id>");
    elements.add("<name_en>City of Helsinki</name_en>");
    elements.add("<name_sv>Helsingfors stad</name_sv>");
    elements.add("<data_source_url>www.hel.fi</data_source_url>");
    elements.add("<name_fi>Helsingin kaupunki</name_fi>");
    // Correct XML (length: 345):
    // "<array><id>49</id><name_en>City of Espoo</name_en><name_sv>Esbo stad</name_sv><data_source_url>www.espoo.fi</data_source_url><name_fi>Espoon kaupunki</name_fi></array><array><id>91</id><name_en>City of Helsinki</name_en><name_sv>Helsingfors stad</name_sv><data_source_url>www.hel.fi</data_source_url><name_fi>Helsingin kaupunki</name_fi></array>";
    String json = "[{\"id\":49,\"name_fi\":\"Espoon kaupunki\",\"name_sv\":\"Esbo stad\",\"name_en\":\"City of Espoo\",\"data_source_url\":\"www.espoo.fi\"},{\"id\":91,\"name_fi\":\"Helsingin kaupunki\",\"name_sv\":\"Helsingfors stad\",\"name_en\":\"City of Helsinki\",\"data_source_url\":\"www.hel.fi\"}]";
    String xml = this.converter.convert(json);

    if (xml.length() != 345) {
        fail();
    }
    if (!xml.matches("^<array>.+</array>$")) {
        fail();
    }
    for (String element : elements) {
        if (!xml.contains(element)) {
            fail();
        }
    }
}
项目:monarch    文件:CacheElement.java   
/**
 * Build element map adding to existing <code>elementMap</code>.
 * 
 * @param elementMap to add elements to.
 * @param inputSource to parse elements from.
 * @throws SAXException
 * @throws IOException
 * @throws ParserConfigurationException
 * @throws XPathExpressionException
 * @since GemFire 8.1
 */
private static final void buildElementMapCacheType(
    final LinkedHashMap<String, CacheElement> elementMap, final InputSource inputSource)
    throws SAXException, IOException, ParserConfigurationException, XPathExpressionException {
  final Document doc = XmlUtils.getDocumentBuilder().parse(inputSource);

  int rank = 0;

  final XPathContext xPathContext =
      new XPathContext(XSD_PREFIX, XMLConstants.W3C_XML_SCHEMA_NS_URI);
  final Node cacheType = XmlUtils.querySingleElement(doc, CACHE_TYPE_EMBEDDED, xPathContext);

  rank = buildElementMapXPath(elementMap, doc, cacheType, rank, XSD_COMPLEX_TYPE_CHILDREN,
      xPathContext);
}
项目:PTEAssistant    文件:XPaths.java   
public static Object eval(String expr, Document doc, QName returnType) {
    try {
        return path.evaluate(expr, doc, returnType);
    } catch (XPathExpressionException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}
项目:parsel    文件:Utils.java   
public static Object fromXpath(Node node, String xpath, QName type) {
    try {
        return XPATH.evaluate(xpath, node, type);
    } catch(XPathExpressionException e) {
        LOG.severe(e.getMessage());
    }
    return null;
}
项目:cornerstone    文件:TextUtils.java   
public static String getTagInnerText(final String tagName,final String xml) throws XPathExpressionException {
    Pattern pattern = Pattern.compile("<\\s*("+tagName+")\\s*>([^</\\s*\1\\s*>]*)",Pattern.MULTILINE);//;

    Matcher mather = pattern.matcher(xml);
    if(mather.find()) {
        return String.valueOf(mather.group(2));
    }else{
        return "";
    }

}
项目:oscm    文件:PartnerRevenueBuilder.java   
private String readServicesPerCustomerAmount(String currencyId,
        String supplierId, String serviceKey, String customerId)
        throws XPathExpressionException {
    return priceToDisplay(XMLConverter
            .getNodeTextContentByXPath(
                    xmlDocument,
                    "//Currency[@id='"
                            + currencyId
                            + "']/Supplier[OrganizationData[@id='"
                            + supplierId
                            + "']]/Service[@key='"
                            + serviceKey
                            + "']/ServiceRevenue/ServiceCustomerRevenue[@customerId='"
                            + customerId + "']/@totalAmount"));
}
项目:SofaTime    文件:VlcRequest.java   
/**
 * Handle the given response from the given command.
 *
 * @param response Response to handle
 */
private void handleResponse(final Response response) {
    try {
        ResponseBody body = response.body();
        if (body != null) {
            handleStatus(body.string());
        }
    } catch (IOException | XPathExpressionException | SAXException
            | ParserConfigurationException e) {
        // Ignore the status
        Log.e(TAG, e.getMessage(), e);
    }
}
项目:Equella    文件:AddNotificationSchemaXML.java   
@SuppressWarnings("nls")
public AddNotificationSchemaXML()
{
    XPathFactory factory = XPathFactory.newInstance();
    xpath = factory.newXPath();
    try
    {
        allNodes = xpath.compile("nodes/com.tle.common.workflow.node.WorkflowItem");
    }
    catch( XPathExpressionException e )
    {
        throw new RuntimeException(e);
    }
}
项目:fluentxml4j    文件:FromNodeImplTest.java   
@Test
public void selectNodeGivesEmptyOptionalWhenNoResultFound() throws XPathExpressionException
{
    givenResultNodeSetIsEmpty();

    boolean present = this.fromNode.selectNode("aQuery").isPresent();

    assertThat(present, is(false));
}
项目:fluentxml4j    文件:FromNodeImplTest.java   
@Test
public void selectElementGivesEmptyOptionalWhenNoResultFound() throws XPathExpressionException
{
    givenResultNodeSetIsEmpty();

    boolean present = this.fromNode.selectElement("aQuery").isPresent();

    assertThat(present, is(false));
}
项目:fluentxml4j    文件:FromNodeImplTest.java   
@Test
public void singleStringWhenSingleNodeFound() throws XPathExpressionException
{
    givenResultNodeSetContains("string1");

    String result = this.fromNode.selectString("aQuery").get();

    assertThat(result, is("string1"));
}
项目:oscm    文件:PaymentServiceProviderBeanTest.java   
private void validateDeregistrationXMLResponse(PaymentInfo pi,
        NameValuePair[] requestBodyDetails, String pspPaymentTypeId)
        throws ParserConfigurationException, SAXException, IOException,
        XPathExpressionException {
    NameValuePair nameValuePair = requestBodyDetails[0];
    String value = nameValuePair.getValue();
    System.out.println(value);
    Document doc = XMLConverter.convertToDocument(value, true);
    Assert.assertEquals("1.0", XMLConverter.getNodeTextContentByXPath(doc,
            "/Request/@version"));
    Assert.assertEquals("securitySender", XMLConverter
            .getNodeTextContentByXPath(doc,
                    "/Request/Header/Security/@sender"));
    Assert.assertEquals("INTEGRATOR_TEST", XMLConverter
            .getNodeTextContentByXPath(doc, "/Request/Transaction/@mode"));
    Assert.assertEquals("txnChannel",
            XMLConverter.getNodeTextContentByXPath(doc,
                    "/Request/Transaction/@channel"));
    Assert.assertEquals("SYNC", XMLConverter.getNodeTextContentByXPath(doc,
            "/Request/Transaction/@response"));
    Assert.assertEquals("userLogin", XMLConverter
            .getNodeTextContentByXPath(doc,
                    "/Request/Transaction/User/@login"));
    Assert.assertEquals("userPwd", XMLConverter.getNodeTextContentByXPath(
            doc, "/Request/Transaction/User/@pwd"));
    Assert.assertEquals(
            String.valueOf(pi.getKey()),
            XMLConverter
                    .getNodeTextContentByXPath(doc,
                            "/Request/Transaction/Identification/TransactionID/text()"));
    Assert.assertEquals(
            "externalId",
            XMLConverter
                    .getNodeTextContentByXPath(doc,
                            "/Request/Transaction/Identification/ReferenceID/text()"));
    Assert.assertEquals(pspPaymentTypeId + ".DR", XMLConverter
            .getNodeTextContentByXPath(doc,
                    "/Request/Transaction/Payment/@code"));
}
项目:oscm    文件:ProviderSupplierReport.java   
/**
 * Creates the technology provider supplier report listing all registered
 * suppliers and their created products based on which technical product.
 */
public void buildReport(String organizationId, VOReportResult result)
        throws XPathExpressionException, ParserConfigurationException {
    result.setServerTimeZone(DateConverter.getCurrentTimeZoneAsUTCString());

    List<ReportResultData> reportData = dao
            .retrieveProviderSupplierReportData(organizationId);
    ReportDataConverter converter = new ReportDataConverter(subscriptionDao);
    converter.convertToXml(reportData, result.getData(),
            Collections.<String, String> emptyMap());
}
项目:jaffa-framework    文件:AopXmlLoader.java   
/**
 * Attempts to load a given stream into the repositories.  Will perform light validation against the document to
 * see if it appears to be a JBoss AOP xml file.
 *
 * @param aopFileStream An inputStream for the resource that contains the aop content
 * @param reportedPath  A friendly name for the resource for reporting purposes
 */
private void loadStream(InputStream aopFileStream, String reportedPath) {
    try {

        // attempt to load the stream as a document
        Document aopDocument = builder.parse(aopFileStream);

        boolean foundAtLeastOne = false;
        // loop through the repomaps and assign each element

        if (logger.isDebugEnabled()) {
            logger.debug("Processing AOP XML resourcepath " + reportedPath);
        }

        for (XPathExpression xPathStatement : repoMap.keySet()) {
            AbstractLoader repo = repoMap.get(xPathStatement);

            // pull out the elements that we are looking for based upon
            // the xpath to repo map
            NodeList nodes = (NodeList) xPathStatement.evaluate(aopDocument, XPathConstants.NODESET);

            if (logger.isDebugEnabled()) {
                logger.debug("Found (" + nodes.getLength() + ") elements for repo " + repo.getClass().getName());
            }

            // add each element to the appropriate repo
            for (int i = 0; i < nodes.getLength(); i++) {
                Node current = nodes.item(i);
                repo.load((Element) current, reportedPath);
                foundAtLeastOne = true;
            }
        }

        if (!foundAtLeastOne && logger.isDebugEnabled()) {
            logger.debug("Could not find any valid elements in file " + reportedPath);
        }
    } catch (XPathExpressionException | JaffaRulesFrameworkException | IOException | SAXException e) {
        logger.error("An Error occurred while attempting to load an AOP resource from:" + reportedPath);
    }
}
项目:lams    文件:SimpleContentPackageConverter.java   
private String getText(String xPathString, Object context) throws IOException {
try {
    return xPath.evaluate(xPathString, context);
} catch (XPathExpressionException e) {
    throw new IOException("Error when parsing XPath expression: " + xPathString, e);
}
   }
项目:oscm    文件:BillingResultEvaluator.java   
public void assertSubscriptionId(String subscriptionId)
        throws XPathExpressionException {
    final Node n = XMLConverter.getNodeByXPath(billingResult,
            "/BillingDetails/Subscriptions/Subscription");
    assertEquals("Wrong subscription id", subscriptionId,
            XMLConverter.getStringAttValue(n,
                    BillingResultXMLTags.ID_ATTRIBUTE_NAME));
}
项目:bibliome-java-utils    文件:YateaHandler.java   
@Override
protected void handleCandidate() throws XPathExpressionException {
    String id = getCurrentCandidateId();
    if (termCandidates.containsKey(id)) {
        throw new RuntimeException("duplicate term id: " + id);
    }
    TermCandidate cand = new TermCandidate();
    termCandidates.put(id, cand);
    cand.setId(id);
    cand.setMnp(isMNP());
    cand.setForm(getForm());
    cand.setLemma(getLemma());
    cand.setSyntacticCategory(getPOS());
    cand.setHead(getHeadID());
    cand.setnOccurrences(getNumberOfOccurrences());
    cand.setConfidence(getConfidence());
    String saHeadId = getSuperHeadID();
    if (!saHeadId.isEmpty()) {
        cand.setSaHead(saHeadId);
    }
    List<Pair<String,ModifierPosition>> modifiers = getModifiersID();
    if (!modifiers.isEmpty()) {
        Pair<String,ModifierPosition> p = modifiers.get(0);
        cand.setSaModifier(p.first);
        cand.setSaPosition(p.second);
    }
    String prep = getPreposition();
    if (!prep.isEmpty()) {
        cand.setSaPrep(prep);
    }
}