javax.xml.xpath.XPathExpressionException Java Examples

The following examples show how to use javax.xml.xpath.XPathExpressionException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SupplierRevenueShareBuilder.java    From development with Apache License 2.0 6 votes vote down vote up
private List<RDORevenueShareDetail> buildRevenueShareDetails(
        int parentEntryNr, String currencyId, OfferingType type)
        throws XPathExpressionException, ParseException {

    ArrayList<RDORevenueShareDetail> result = new ArrayList<>();
    for (Node marketplace : marketplaceNodes(currencyId)) {
        String marketplaceId = XMLConverter.getStringAttValue(marketplace,
                BillingShareResultXmlTags.ATTRIBUTE_NAME_ID);
        String marketplaceName = marketplaceNameMap.get(marketplaceId);
        for (Node nodeService : serviceNodes(currencyId, marketplaceId,
                type)) {
            String serviceId = XMLConverter.getStringAttValue(nodeService,
                    BillingShareResultXmlTags.ATTRIBUTE_NAME_ID);
            String serviceKey = XMLConverter.getStringAttValue(nodeService,
                    BillingShareResultXmlTags.ATTRIBUTE_NAME_KEY);
            for (Node details : customerRevenueShareDetailNodes(currencyId,
                    serviceKey, type)) {
                addRevenueShareDetail(parentEntryNr, currencyId, type,
                        result, marketplaceName, nodeService, serviceId,
                        details);
            }
        }
    }
    return result;
}
 
Example #2
Source File: TolerantUpdateProcessorTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Test
public void testInvalidDelete() throws XPathExpressionException, SAXException {
  ignoreException("undefined field invalidfield");
  String response = update("tolerant-chain-max-errors-10", adoc("id", "1", "text", "the quick brown fox"));
  assertNull(BaseTestHarness.validateXPath(response,
                                           "//int[@name='status']=0",
                                           "//arr[@name='errors']",
                                           "count(//arr[@name='errors']/lst)=0"));
  
  response = update("tolerant-chain-max-errors-10", delQ("invalidfield:1"));
  assertNull(BaseTestHarness.validateXPath
             (response,
              "//int[@name='status']=0",
              "count(//arr[@name='errors']/lst)=1",
              "//arr[@name='errors']/lst/str[@name='type']/text()='DELQ'",
              "//arr[@name='errors']/lst/str[@name='id']/text()='invalidfield:1'",
              "//arr[@name='errors']/lst/str[@name='message']/text()='undefined field invalidfield'"));
}
 
Example #3
Source File: NavigationXmlParser.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void setGroupsAndViews(Group parent, Node xmlNode) throws XPathExpressionException {
	NodeList groupList = (NodeList) xpath.evaluate("group", xmlNode, XPathConstants.NODESET);
	int groupCount = groupList.getLength();
	for (int groupIndex = 0; groupIndex < groupCount; groupIndex++) {
		Node groupNode = groupList.item(groupIndex);

		Group group = new Group(xpath.evaluate("@id", groupNode));
		parent.addGroup(group);
		setAttributes(group, groupNode);
		setGroupsAndViews(group, groupNode);
	}

	NodeList viewList = (NodeList) xpath.evaluate("view", xmlNode, XPathConstants.NODESET);
	int viewCount = viewList.getLength();
	for (int viewIndex = 0; viewIndex < viewCount; viewIndex++) {
		Node viewNode = viewList.item(viewIndex);

		View view = new View(xpath.evaluate("@id", viewNode));
		parent.addView(view);
		setAttributes(view, viewNode);
	}
}
 
Example #4
Source File: CreateOrderEndpointMockTest.java    From spring-ws with MIT License 6 votes vote down vote up
@Test
public void testCreateOrder() throws XPathExpressionException {
    Source requestPayload = new StringSource(
            "<ns2:order xmlns:ns2=\"http://codenotfound.com/types/order\">"
                    + "<ns2:customer><ns2:firstName>John</ns2:firstName>"
                    + "<ns2:lastName>Doe</ns2:lastName>"
                    + "</ns2:customer><ns2:lineItems><ns2:lineItem>"
                    + "<ns2:product>" + "<ns2:id>2</ns2:id>"
                    + "<ns2:name>batman action figure</ns2:name>"
                    + "</ns2:product>"
                    + "<ns2:quantity>1</ns2:quantity>"
                    + "</ns2:lineItem>" + "</ns2:lineItems>"
                    + "</ns2:order>");

    Map<String, String> namespaces = Collections.singletonMap("ns1",
            "http://codenotfound.com/types/order");

    mockClient.sendRequest(withPayload(requestPayload))
            .andExpect(ResponseMatchers
                    .xpath("/ns1:orderConfirmation/ns1:confirmationId",
                            namespaces)
                    .exists());
}
 
Example #5
Source File: PartnerReport.java    From development with Apache License 2.0 6 votes vote down vote up
public RDOPartnerReports buildPartnerReport(PlatformUser user, int month,
        int year) throws XPathExpressionException,
        ParserConfigurationException, SAXException, IOException,
        ParseException {
    if (!hasRole(OrganizationRoleType.PLATFORM_OPERATOR, user)) {
        return new RDOPartnerReports();
    }

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

    PartnerRevenueDao sqlDao = new PartnerRevenueDao(ds);
    sqlDao.executePartnerQuery(periodStart, periodEnd);

    PartnerRevenueBuilder builder;
    builder = new PartnerRevenueBuilder(new Locale(user.getLocale()),
            sqlDao.getReportData());
    RDOPartnerReports result = builder.buildReports();
    return result;
}
 
Example #6
Source File: SolrTestCaseHS.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/**
 * Pass "null" for the client to query to the local server.
 * Fetches response in xml format and matches with the given set of xpaths
 */
public static void assertQ(SolrClient client, SolrParams args, String... tests) throws Exception {
  String resp;
  resp = getQueryResponse(client, "xml", args);
  try {
    String results = TestHarness.validateXPath(resp, tests);
    if (null != results) {
      String msg = "REQUEST FAILED: xpath=" + results
          + "\n\txml response was: " + resp
          + "\n\tparams were:" + args.toQueryString();

      log.error(msg);
      throw new RuntimeException(msg);
    }
  } catch (XPathExpressionException e1) {
    throw new RuntimeException("XPath is invalid", e1);
  } catch (Exception e2) {
    SolrException.log(log,"REQUEST FAILED for params: " + args.toQueryString(), e2);
    throw new RuntimeException("Exception during query", e2);
  }
}
 
Example #7
Source File: MultipleTopicTestCase.java    From product-ei with Apache License 2.0 6 votes vote down vote up
/**
 * Gets an AndesClient to subscriber for a given topic
 *
 * @param topicName     Name of the topic which the subscriber subscribes
 * @param expectedCount Expected message count to be received
 * @return AndesClient object to receive messages
 * @throws NamingException
 * @throws JMSException
 * @throws AndesClientConfigurationException
 * @throws XPathExpressionException
 * @throws IOException
 * @throws AndesClientException
 */
private AndesClient getAndesReceiverClient(String topicName, long expectedCount)
        throws NamingException, JMSException, AndesClientConfigurationException,
               XPathExpressionException, IOException, AndesClientException {

    // Creating a initial JMS consumer client configuration
    AndesJMSConsumerClientConfiguration consumerConfig =
            new AndesJMSConsumerClientConfiguration(automationContext.getInstance().getHosts()
                                                            .get("default"),
                                                    Integer.parseInt(automationContext
                                                                             .getInstance()
                                                                             .getPorts()
                                                                             .get("amqp")),
                                                    ExchangeType.TOPIC, topicName);
    // Amount of message to receive
    consumerConfig.setMaximumMessagesToReceived(expectedCount);
    consumerConfig.setPrintsPerMessageCount(expectedCount / 10L);

    return new AndesClient(consumerConfig, true);
}
 
Example #8
Source File: Framework.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public Framework(final String name, final File bsFile) {
    super(name, null);
    try {
        final File pathf = bsFile.getCanonicalFile().getParentFile().getParentFile().getParentFile();
        path = pathf.getParentFile().getParentFile().getCanonicalPath();
    } catch (IOException x) {
        throw new RuntimeException(x);
    }
    binaries = findBinaries(path, name);

    pkg = ClassGenerator.JOBJC_PACKAGE + "." + name.toLowerCase();
    try {
        rootNode = (Node)XPATH.evaluate("signatures", new InputSource(bsFile.getAbsolutePath()), XPathConstants.NODE);
    } catch (final XPathExpressionException e) { throw new RuntimeException(e); }
    protocols = new ArrayList<Protocol>();
    categories = new ArrayList<Category>();
}
 
Example #9
Source File: SecureDataServiceTestCase.java    From product-ei with Apache License 2.0 6 votes vote down vote up
private void secureService(int policyId)
        throws SecurityAdminServiceSecurityConfigExceptionException, RemoteException,
               InterruptedException, XPathExpressionException {
    SecurityAdminServiceClient securityAdminServiceClient = new SecurityAdminServiceClient(dssContext.getContextUrls().getBackEndUrl(),sessionCookie);
    if (TestConfigurationProvider.isPlatform()) {
        //todo
        /*securityAdminServiceClient.applySecurity(serviceName, policyId + "", new String[]{"admin"},
                                                 new String[]{userInfo.getDomain().replace('.', '-') + ".jks"},
                                                 userInfo.getDomain().replace('.', '-') + ".jks");*/
    } else {
        securityAdminServiceClient.applySecurity(serviceName, policyId + "", new String[]{"admin"},
                                                 new String[]{"wso2carbon.jks"}, "wso2carbon.jks");
    }
    log.info("Security Scenario " + policyId + " Applied");

    Thread.sleep(1000);

}
 
Example #10
Source File: FaultyDataServiceTestCase.java    From product-ei with Apache License 2.0 6 votes vote down vote up
@Test(groups = "wso2.dss", dependsOnMethods = {"serviceReDeployment"},
      description = "send requests to redeployed service")
@SetEnvironment(executionEnvironments = {ExecutionEnvironment.STANDALONE})
public void serviceInvocation()
        throws RemoteException, ServiceAdminException, XPathExpressionException {
    OMElement response;
    String serviceEndPoint = getServiceUrlHttp(serviceName) +"/";
    AxisServiceClient axisServiceClient = new AxisServiceClient();
    for (int i = 0; i < 5; i++) {
        response = axisServiceClient.sendReceive(getPayload(), serviceEndPoint, "showAllOffices");
        Assert.assertTrue(response.toString().contains("<Office>"), "Expected Result not Found");
        Assert.assertTrue(response.toString().contains("<officeCode>"), "Expected Result not Found");
        Assert.assertTrue(response.toString().contains("<city>"), "Expected Result not Found");
        Assert.assertTrue(response.toString().contains("<phone>"), "Expected Result not Found");
        Assert.assertTrue(response.toString().contains("</Office>"), "Expected Result not Found");
    }
    log.info("service invocation success");
}
 
Example #11
Source File: AssertionsFixer.java    From archie with Apache License 2.0 6 votes vote down vote up
private void fixDvCodedText(Archetype archetype, String pathOfParent) throws XPathExpressionException {
    DvCodedText codedText = ruleEvaluation.getQueryContext().find(pathOfParent.replace("/defining_code", ""));
    Archetyped details = RuleEvaluationUtil.findLastArchetypeDetails(ruleEvaluation, pathOfParent);
    if(details == null) {
        setDefaultTermDefinitionInCodedText(archetype, codedText);
    } else if(archetype instanceof OperationalTemplate) {

        OperationalTemplate template = (OperationalTemplate) archetype;

        String archetypePath = RuleEvaluationUtil.convertRMObjectPathToArchetypePath(pathOfParent);
        setTerminologyFromArchetype(archetype, codedText, archetypePath);

        setValueFromTermDefinition(codedText, details, template);
    } else {
        setDefaultTermDefinitionInCodedText(archetype, codedText);
    }
}
 
Example #12
Source File: XPathAssert.java    From JVoiceXML with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Checks if the evaluation of <code>expression</code> on
 * <code>document</code> node's node value
 * is equal to <code>expected</code>. 
 * @param document the current XML document
 * @param expression the XPath expression to evaluate
 * @param expected the expected result
 * @exception XPathExpressionException
 *            error evaluating the XPath expression
 */
public static void assertEquals(final Document document,
        final String expression, final String expected)
                throws XPathExpressionException {
    final XPathFactory xpathFactory = XPathFactory.newInstance();
    final XPath xpath = xpathFactory.newXPath();
    final Document doc;
    if (document instanceof XmlDocument) {
        final XmlDocument xmldocument = (XmlDocument) document;
        doc = xmldocument.getDocument();
    } else {
        doc = document;
    }
    final String actual = (String) xpath.evaluate(expression,
            doc, XPathConstants.STRING);
    Assert.assertEquals(expected, actual);
}
 
Example #13
Source File: KmehrHelper.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
private boolean verifyXpath(String[] xpathConfigs, Document doc) throws XPathExpressionException, NumberFormatException, IntegrationModuleException {
    if (xpathConfigs == null) {
        return false;
    }
    String xpathStr = xpathConfigs[0];
    int min = Integer.parseInt(xpathConfigs[1].trim());
    int max = xpathConfigs.length > 2 ? Integer.parseInt(xpathConfigs[2].trim()) : Integer.MAX_VALUE;

    XPath xpath = XPathFactory.newInstance().newXPath();
    NamespaceContext nsCtx = new MapNamespaceContext();
    xpath.setNamespaceContext(nsCtx);
    NodeList nodes = (NodeList) xpath.evaluate(xpathStr, doc, XPathConstants.NODESET);

    if (nodes.getLength() < min || nodes.getLength() > max) {
        LOG.error("FAILED Xpath query : " + xpathStr);
        return false;
        //throw new IntegrationModuleException(I18nHelper.getLabel("error.xml.invalid"));
    }
    return true;
}
 
Example #14
Source File: XmlSearch.java    From development with Apache License 2.0 6 votes vote down vote up
public List<BigDecimal> retrieveNetAmounts(Long pmKey) {
    try {
        List<BigDecimal> result = new ArrayList<BigDecimal>();
        String xpath = String.format(
                "//PriceModel[@id='%d']/PriceModelCosts/@amount", pmKey);
        NodeList nodeList = XMLConverter.getNodeListByXPath(billingResult,
                xpath);

        for (int i = 0; i < nodeList.getLength(); i++) {
            Node n = nodeList.item(i);
            String amountValue = n.getTextContent();
            result.add(new BigDecimal(amountValue));
        }
        return result;
    } catch (XPathExpressionException e) {
        throw new BillingRunFailed(e);
    }

}
 
Example #15
Source File: ESBIntegrationTest.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
protected OMElement setEndpoints(OMElement synapseConfig) throws XMLStreamException, XPathExpressionException {
    if (isBuilderEnabled()) {
        return synapseConfig;
    }
    String config = replaceEndpoints(synapseConfig.toString());
    return AXIOMUtil.stringToOM(config);
}
 
Example #16
Source File: CallMediatorBlockingSecurityTestCase.java    From product-ei with Apache License 2.0 5 votes vote down vote up
@Test(groups = { "wso2.esb" },
      description = "Call the security endpoint with blocking external calls")
public void callMediatorBlockingSecurityTest() throws AxisFault, XPathExpressionException {
    OMElement response = axis2Client
            .sendSimpleStockQuoteRequest(getProxyServiceURLHttp("callMediatorBlockingEndpointSecurityProxy"), "",
                    "WSO2");
    boolean responseContainsWSO2 = response.toString().contains("WSO2");
    assertTrue(responseContainsWSO2);
}
 
Example #17
Source File: ReferenceReplacer.java    From android-string-extractor-plugin with MIT License 5 votes vote down vote up
void replaceHardCodedValues(Document document, List<StringOccurrence> stringOccurrences)
    throws XPathExpressionException {
  for (StringOccurrence stringOccurrence : stringOccurrences) {
    Element n = findElementByAndroidId(document, stringOccurrence.getId());
    if (n == null) continue;
    n.setAttribute("android:" + stringOccurrence.getAttribute(), stringOccurrence.getValue());
  }
}
 
Example #18
Source File: Sample420TestCase.java    From product-ei with Apache License 2.0 5 votes vote down vote up
@SetEnvironment(executionEnvironments = {ExecutionEnvironment.STANDALONE})
@Test(groups = {"wso2.esb"}, description = "Creating simple cache sample 420 Test Case")
public void testSimpleCachingExists() throws AxisFault, XPathExpressionException, InterruptedException {
    OMElement response;

    response = axis2Client.sendSimpleStockQuoteRequest(getMainSequenceURL(), "", "IBM");
    String firstResponse = response.getFirstElement().toString();

    response = axis2Client.sendSimpleStockQuoteRequest(getMainSequenceURL(), "", "IBM");

    assertEquals(firstResponse, response.getFirstElement().toString());
}
 
Example #19
Source File: BillingResultEvaluator.java    From development with Apache License 2.0 5 votes vote down vote up
public void assertOrganizationDetails(String orgId, String orgName,
        String address, String email, String paymenttype)
        throws XPathExpressionException {
    final Node orgDetails = XMLConverter.getNodeByXPath(billingResult,
            "/BillingDetails/OrganizationDetails");
    assertTextContent(orgDetails, "Id", orgId);
    assertTextContent(orgDetails, "Name", orgName);
    assertTextContent(orgDetails, "Address", address);
    assertTextContent(orgDetails, "Email", email);
    assertTextContent(orgDetails, "Paymenttype", paymenttype);
}
 
Example #20
Source File: NavigationXmlParser.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void parseInto(NavigationModel result, URL navigationXml) {
	try {
		Document document = DocumentUtil.getDocument(navigationXml);
		Node rootNode = (Node) xpath.evaluate("/navigation", document, XPathConstants.NODE);
		fillModel(result, rootNode);
	} catch (IOException | XPathExpressionException e) {
		e.printStackTrace();
	}
}
 
Example #21
Source File: SimplePostTool.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the string content of the matching an XPath
 * @param n the node (or doc)
 * @param xpath the xpath string
 * @param concatAll if true, text from all matching nodes will be concatenated, else only the first returned
 */
public static String getXP(Node n, String xpath, boolean concatAll)
    throws XPathExpressionException {
  NodeList nodes = getNodesFromXP(n, xpath);
  StringBuilder sb = new StringBuilder();
  if (nodes.getLength() > 0) {
    for(int i = 0; i < nodes.getLength() ; i++) {
      sb.append(nodes.item(i).getNodeValue()).append(' ');
      if(!concatAll) break;
    }
    return sb.toString().trim();
  } else
    return "";
}
 
Example #22
Source File: EpubBook.java    From BookyMcBookface with GNU General Public License v3.0 5 votes vote down vote up
private static Map<String,?> processToc(BufferedReader tocReader) {
    Map<String,Object> bookdat = new LinkedHashMap<>();

    DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
    XPathFactory factory = XPathFactory.newInstance();
    DocumentBuilder builder = null;
    try {
        builder = dfactory.newDocumentBuilder();

        tocReader.mark(4);
        if ('\ufeff' != tocReader.read()) tocReader.reset(); // not the BOM marker

        Document doc = builder.parse(new InputSource(tocReader));

        XPath tocPath = factory.newXPath();
        tocPath.setNamespaceContext(tocnsc);

        Node nav = (Node)tocPath.evaluate("/ncx/navMap", doc, XPathConstants.NODE);

        int total = readNavPoint(nav, tocPath, bookdat, 0);
        bookdat.put(TOCCOUNT, total);

    } catch (ParserConfigurationException | IOException | SAXException | XPathExpressionException e) {
        Log.e("BMBF", "Error parsing xml " + e.getMessage(), e);
    }
    return bookdat;
}
 
Example #23
Source File: BillingResultParser.java    From development with Apache License 2.0 5 votes vote down vote up
int readTimeZoneFromBillingDetails(Node nodePriceModel)
        throws XPathExpressionException {
    String timezoneId = XMLConverter
            .getNodeTextContentByXPath(nodePriceModel.getOwnerDocument(),
                    "//BillingDetails/@timezone");
    return rawOffsetFromTimzoneId(timezoneId);
}
 
Example #24
Source File: BaseIndicatorBox.java    From TAcharting with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void loadSmoothedRSIIndicator(String key) throws XPathExpressionException {
    int timeFrame = Integer.parseInt(parameter.getParameter(key, "Time Frame"));
    IndicatorCategory category = parameter.getCategory(key);
    ChartType chartType = parameter.getChartType(key);
    XYLineAndShapeRenderer renderer = createRenderer(key, "Color", "Shape", "Stroke");

    addChartIndicator(key,
            new RSIIndicator(closePriceIndicator.get(), timeFrame),
            String.format("%s [%s] (%s)",getIdentifier(key), getID(key),timeFrame),
            renderer,
            chartType.toBoolean(),
            category);
}
 
Example #25
Source File: EI1222JSONSecuredServiceWithXMLCharacterTestCase.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * This method add the Security policy which will be used with the service.
 *
 * @throws RemoteException
 * @throws MalformedURLException
 * @throws ResourceAdminServiceExceptionException
 * @throws XPathExpressionException
 */
private void addResource() throws RemoteException, MalformedURLException, ResourceAdminServiceExceptionException,
        XPathExpressionException {
    ResourceAdminServiceClient resourceAdmin = new ResourceAdminServiceClient(
            dssContext.getContextUrls().getBackEndUrl(), sessionCookie);
    deleteResource();
    resourceAdmin.addResource("/_system/config/automation/resources/policies/SecPolicy-withRoles.xml",
            "text/comma-separated-values", "", new DataHandler(
                    new URL("file:///" + getResourceLocation() + File.separator + "resources" + File.separator
                            + "SecPolicy-withRoles.xml")));
}
 
Example #26
Source File: TenantDeadLetterChannelTestCase.java    From product-ei with Apache License 2.0 5 votes vote down vote up
/**
 * Initializes the test case.
 *
 * @throws XPathExpressionException
 * @throws java.rmi.RemoteException
 * @throws org.wso2.carbon.user.mgt.stub.UserAdminUserAdminException
 */
@BeforeClass(alwaysRun = true)
public void init() throws XPathExpressionException, RemoteException,
                          UserAdminUserAdminException {
    super.init(TestUserMode.SUPER_TENANT_USER);

    // Get current "AndesAckWaitTimeOut" system property.
    defaultAndesAckWaitTimeOut = System.getProperty(AndesClientConstants.
                                                            ANDES_ACK_WAIT_TIMEOUT_PROPERTY);


    // Setting system property "AndesAckWaitTimeOut" for andes
    System.setProperty(AndesClientConstants.ANDES_ACK_WAIT_TIMEOUT_PROPERTY, "0");

}
 
Example #27
Source File: DS1186JsonRenderTestCase.java    From product-ei with Apache License 2.0 5 votes vote down vote up
/**
 * Delete the security policy from the registry.
 * @throws RemoteException
 * @throws MalformedURLException
 * @throws ResourceAdminServiceExceptionException
 * @throws XPathExpressionException
 */
private void deleteResource()
        throws RemoteException, MalformedURLException, ResourceAdminServiceExceptionException,
        XPathExpressionException {
    ResourceAdminServiceClient resourceAdmin = new ResourceAdminServiceClient(dssContext.getContextUrls().getBackEndUrl()
            , sessionCookie);
    resourceAdmin.deleteResource("/_system/config/automation/resources/policies/");
}
 
Example #28
Source File: DOMDocumentTest.java    From lemminx with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void findTextWithXPath() throws XPathExpressionException {
	DOMDocument document = DOMParser.getInstance().parse("<a><b><c>XXXX</c></b></a>", "test", null);

	XPath xPath = XPathFactory.newInstance().newXPath();
	Object result = xPath.evaluate("/a/b/c/text()", document, XPathConstants.NODE);
	assertNotNull(result);
	assertTrue(result instanceof DOMText);
	DOMText text = (DOMText) result;
	assertEquals("XXXX", text.getData());

	result = xPath.evaluate("/a/b/c/text()", document, XPathConstants.STRING);
	assertNotNull(result);
	assertEquals("XXXX", result.toString());
}
 
Example #29
Source File: CarbonServerManager.java    From product-ei with Apache License 2.0 5 votes vote down vote up
/**
 * Unzip carbon zip file and return the carbon home. Based on the coverage configuration in automation.xml
 * This method will inject jacoco agent to the carbon server startup scripts.
 *
 * @param carbonServerZipFile - Carbon zip file, which should be specified in test module pom
 * @return - carbonHome - carbon home
 * @throws IOException - If pack extraction fails
 */
public synchronized String setUpCarbonHome(String carbonServerZipFile)
        throws IOException, AutomationFrameworkException {
    if (process != null) { // An instance of the server is running
        return carbonHome;
    }
    int indexOfZip = carbonServerZipFile.lastIndexOf(".zip");
    if (indexOfZip == -1) {
        throw new IllegalArgumentException(carbonServerZipFile + " is not a zip file");
    }
    String fileSeparator = (File.separator.equals("\\")) ? "\\" : "/";
    if (fileSeparator.equals("\\")) {
        carbonServerZipFile = carbonServerZipFile.replace("/", "\\");
    }
    String extractedCarbonDir =
            carbonServerZipFile.substring(carbonServerZipFile.lastIndexOf(fileSeparator) + 1,
                                          indexOfZip);
    FileManipulator.deleteDir(extractedCarbonDir);
    String extractDir = "carbontmp" + System.currentTimeMillis();
    String baseDir = (System.getProperty("basedir", ".")) + File.separator + "target";
    log.info("Extracting carbon zip file.. ");

    new ArchiveExtractor().extractFile(carbonServerZipFile, baseDir + File.separator + extractDir);
    carbonHome = new File(baseDir).getAbsolutePath() + File.separator + extractDir + File.separator +
                 extractedCarbonDir;
    try {
        //read coverage status from automation.xml
        isCoverageEnable = Boolean.parseBoolean(automationContext.getConfigurationValue("//coverage"));
    } catch (XPathExpressionException e) {
        throw new AutomationFrameworkException("Coverage configuration not found in automation.xml", e);
    }

    //insert Jacoco agent configuration to carbon server startup script. This configuration
    //cannot be directly pass as server startup command due to script limitation.
    if (isCoverageEnable) {
        instrumentForCoverage();
    }

    return carbonHome;
}
 
Example #30
Source File: EI1222JSONSecuredServiceWithXMLCharacterTestCase.java    From product-ei with Apache License 2.0 5 votes vote down vote up
/**
 * This method add the Security policy which will be used with the service.
 * @throws RemoteException
 * @throws MalformedURLException
 * @throws ResourceAdminServiceExceptionException
 * @throws XPathExpressionException
 */
private void addResource()
        throws RemoteException, MalformedURLException, ResourceAdminServiceExceptionException,
        XPathExpressionException {
    ResourceAdminServiceClient resourceAdmin = new ResourceAdminServiceClient(dssContext.getContextUrls().getBackEndUrl()
            , sessionCookie);
    deleteResource();
    resourceAdmin.addResource("/_system/config/automation/resources/policies/SecPolicy-withRoles.xml",
            "text/comma-separated-values", "",
            new DataHandler(new URL("file:///" + getResourceLocation()
                    + File.separator + "resources" + File.separator
                    + "SecPolicy-withRoles.xml")));
}