@Override public SdkServiceException unmarshall(Node in) throws Exception { XPath xpath = xpath(); String error = asString("Error/Code", in, xpath); String requestId = asString("Error/RequestId", in, xpath); String message = asString("Error/Message", in, xpath); if (!StringUtils.equals(error, this.errorCode)) { return null; } SdkServiceException exception = newException(message); exception.errorCode(errorCode); exception.requestId(requestId); return exception; }
public void testAddRoots() throws Exception { NbModuleProject prj = TestBase.generateStandaloneModule(getWorkDir(), "module"); FileObject src = prj.getSourceDirectory(); FileObject jar = TestFileUtils.writeZipFile(FileUtil.toFileObject(getWorkDir()), "a.jar", "entry:contents"); URL root = FileUtil.getArchiveRoot(jar.toURL()); assertTrue(ProjectClassPathModifier.addRoots(new URL[] {root}, src, ClassPath.COMPILE)); assertFalse(ProjectClassPathModifier.addRoots(new URL[] {root}, src, ClassPath.COMPILE)); FileObject releaseModulesExt = prj.getProjectDirectory().getFileObject("release/modules/ext"); assertNotNull(releaseModulesExt); assertNotNull(releaseModulesExt.getFileObject("a.jar")); jar = TestFileUtils.writeZipFile(releaseModulesExt, "b.jar", "entry2:contents"); root = FileUtil.getArchiveRoot(jar.toURL()); assertTrue(ProjectClassPathModifier.addRoots(new URL[] {root}, src, ClassPath.COMPILE)); assertFalse(ProjectClassPathModifier.addRoots(new URL[] {root}, src, ClassPath.COMPILE)); assertEquals(2, releaseModulesExt.getChildren().length); String projectXml = prj.getProjectDirectory().getFileObject("nbproject/project.xml").toURL().toString(); InputSource input = new InputSource(projectXml); XPath xpath = XPathFactory.newInstance().newXPath(); xpath.setNamespaceContext(nbmNamespaceContext()); assertEquals(projectXml, "ext/a.jar", xpath.evaluate("//nbm:class-path-extension[1]/nbm:runtime-relative-path", input)); assertEquals(projectXml, "release/modules/ext/a.jar", xpath.evaluate("//nbm:class-path-extension[1]/nbm:binary-origin", input)); assertEquals(projectXml, "ext/b.jar", xpath.evaluate("//nbm:class-path-extension[2]/nbm:runtime-relative-path", input)); assertEquals(projectXml, "release/modules/ext/b.jar", xpath.evaluate("//nbm:class-path-extension[2]/nbm:binary-origin", input)); }
@Override public SdkServiceException unmarshall(Node in) throws Exception { XPath xpath = XpathUtils.xpath(); String errorCode = parseErrorCode(in, xpath); String message = XpathUtils.asString("Response/Errors/Error/Message", in, xpath); String requestId = XpathUtils.asString("Response/RequestID", in, xpath); String errorType = XpathUtils.asString("Response/Errors/Error/Type", in, xpath); SdkServiceException exception = newException(message); exception.errorCode(errorCode); exception.requestId(requestId); if ("Client".equalsIgnoreCase(errorType)) { exception.errorType(ErrorType.CLIENT); } else if ("Server".equalsIgnoreCase(errorType)) { exception.errorType(ErrorType.SERVICE); } else { exception.errorType(ErrorType.fromValue(errorType)); } return exception; }
@Override public final void vulStuurgegevens(final T verzoek, final Node node, final XPath xPath) throws ParseException { verzoek.getStuurgegevens().setCommunicatieId( getNodeTextContent(getPrefix() + "/brp:stuurgegevens/@brp:communicatieID", xPath, node)); verzoek.getStuurgegevens() .setZendendePartijCode(getNodeTextContent(getPrefix() + "/brp:stuurgegevens/brp:zendendePartij", xPath, node)); verzoek.getStuurgegevens().setZendendSysteem( getNodeTextContent(getPrefix() + "/brp:stuurgegevens/brp:zendendeSysteem", xPath, node)); verzoek.getStuurgegevens() .setReferentieNummer(getNodeTextContent(getPrefix() + "/brp:stuurgegevens/brp:referentienummer", xPath, node)); final String tijdstipVerzendingString = getNodeTextContent(getPrefix() + "/brp:stuurgegevens/brp:tijdstipVerzending", xPath, node); if (tijdstipVerzendingString != null) { final ZonedDateTime tijdstipVerzending = DatumUtil.vanXsdDatumTijdNaarZonedDateTime(tijdstipVerzendingString); verzoek.getStuurgegevens().setTijdstipVerzending(tijdstipVerzending); } }
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); } }
/** * Find the element reference for the selected element. The selected element * is an XPATH expression relation to the element reference given as a * parameter. * * @param pev the element reference from which the XPATH expression is * evaluated. * @param path the XPATH expression * @return the resulting element reference */ public final ElementValue findElementValue(ElementValue pev, String path) { XPath xpath = XPathFactory.newInstance().newXPath(); try { Element el = (Element) xpath.evaluate(path, pev.getElement(), XPathConstants.NODE); return pev.isInHerited() ? (el == null ? new ElementValue(Type.INHERITED_MISSING) : new ElementValue(el, Type.INHERITED)) : (el == null ? new ElementValue(pev, path) : new ElementValue(el, Type.OK)); } catch (XPathExpressionException ex) { return new ElementValue(pev, path); } }
protected static void countColumns(XPath xPath, Table table, Node tableHead) throws XPathExpressionException, DOMException, NumberFormatException { if (tableHead != null) { Node firstRow = (Node) xPath.compile("*[1]").evaluate(tableHead, XPathConstants.NODE); NodeList childFirstRows = firstRow.getChildNodes(); int columnNumber = 0; for (int w = 0; w < childFirstRows.getLength(); w++) { Node childFirstRow = childFirstRows.item(w); if (childFirstRow.getNodeValue() == null && (childFirstRow.getNodeName() == "th" || childFirstRow.getNodeName() == "td")) { int number = 1; if (childFirstRow.getAttributes().getNamedItem("colspan") != null) { number = Integer.parseInt(childFirstRow.getAttributes().getNamedItem("colspan").getNodeValue()); } columnNumber = columnNumber + number; } } table.setColumnNumber(columnNumber); } }
public boolean eval() throws BuildException { if (nullOrEmpty(fileName)) { throw new BuildException("No file set"); } File file = new File(fileName); if (!file.exists() || file.isDirectory()) { throw new BuildException( "The specified file does not exist or is a directory"); } if (nullOrEmpty(path)) { throw new BuildException("No XPath expression set"); } XPath xpath = XPathFactory.newInstance().newXPath(); InputSource inputSource = new InputSource(fileName); Boolean result = Boolean.FALSE; try { result = (Boolean) xpath.evaluate(path, inputSource, XPathConstants.BOOLEAN); } catch (XPathExpressionException e) { throw new BuildException("XPath expression fails", e); } return result.booleanValue(); }
public static Iterator<Node> getNodeList(String exp, Element dom) throws XPathExpressionException { XPath xpath = XPathFactory.newInstance().newXPath(); XPathExpression expUserTask = xpath.compile(exp); final NodeList nodeList = (NodeList) expUserTask.evaluate(dom, XPathConstants.NODESET); return new Iterator<Node>() { private int index = 0; @Override public Node next() { return nodeList.item(index++); } @Override public boolean hasNext() { return (nodeList.getLength() - index) > 0; } }; }
/** * Performs all file existence checks contained in the validation profile. If the validation has failed (some of the files specified * in the validation profile do not exist), {@link MissingFile} exception is thrown. * * @param sipPath path to the SIP * @param validationProfileDoc document with the validation profile * @param validationProfileId id of the validation profile * @throws XPathExpressionException if there is an error in the XPath expression */ private void performFileExistenceChecks(String sipPath, Document validationProfileDoc, String validationProfileId) throws XPathExpressionException { XPath xPath = XPathFactory.newInstance().newXPath(); NodeList nodes = (NodeList) xPath.compile("/profile/rule/fileExistenceCheck") .evaluate(validationProfileDoc, XPathConstants.NODESET); for (int i = 0; i< nodes.getLength(); i++) { Element element = (Element) nodes.item(i); String relativePath = element.getElementsByTagName("filePath").item(0).getTextContent(); String absolutePath = sipPath + relativePath; if (!ValidationChecker.fileExists(absolutePath)) { log.info("Validation of SIP with profile " + validationProfileId + " failed. File at \"" + relativePath + "\" is missing."); throw new MissingFile(relativePath, validationProfileId); } } }
/** * Performs all validation schema checks contained in the validation profile. If the validation has failed (some of the XMLs * specified in the validation profile do not match their respective validation schemas) {@link SchemaValidationError} is thrown. * * @param sipPath path to the SIP * @param validationProfileDoc document with the validation profile * @param validationProfileId id of the validation profile * @throws IOException if some of the XMLs address from the validation profile does not exist * @throws XPathExpressionException if there is an error in the XPath expression * @throws SAXException if the XSD schema is invalid */ private void performValidationSchemaChecks(String sipPath, Document validationProfileDoc, String validationProfileId) throws XPathExpressionException, IOException, SAXException { XPath xPath = XPathFactory.newInstance().newXPath(); NodeList nodes = (NodeList) xPath.compile("/profile/rule/validationSchemaCheck") .evaluate(validationProfileDoc, XPathConstants.NODESET); for (int i = 0; i< nodes.getLength(); i++) { Element element = (Element) nodes.item(i); String filePath = element.getElementsByTagName("filePath").item(0).getTextContent(); String schema = element.getElementsByTagName("schema").item(0).getTextContent(); String absoluteFilePath = sipPath + filePath; try { ValidationChecker.validateWithXMLSchema(new FileInputStream(absoluteFilePath), new InputStream[] { new ByteArrayInputStream(schema.getBytes(StandardCharsets.UTF_8.name()))}); } catch (GeneralException e) { log.info("Validation of SIP with profile " + validationProfileId + " failed. File at \"" + filePath + "\" is not " + "valid against its corresponding schema."); throw new SchemaValidationError(filePath, schema, e.getMessage()); } } }
/** * Get value from status XML doc. * * @param doc Doc to get value from * @param elementName Element name to search * @param attribute Attribute to search * @return The value found * @throws XPathExpressionException Error in XPath expression */ public static String getValueFromStatus(final Document doc, final String elementName, final String attribute) throws XPathExpressionException { // Create XPath XPathFactory xPathFactory = XPathFactory.newInstance(); XPath xPath = xPathFactory.newXPath(); StringBuilder expression = new StringBuilder(); // Build XPath from element name and attribute value (if exists) expression.append("//").append(elementName); if (attribute != null) { expression.append("[@name=\'").append(attribute).append("\']"); } expression.append("/text()"); XPathExpression xPathExpression = xPath.compile(expression.toString()); // Return result from XPath expression return xPathExpression.evaluate(doc); }
/** * Searches XML element with XPath and returns list of nodes found * * @param xml input stream with the XML in which the element is being searched * @param expression XPath expression used in search * @return {@link NodeList} of elements matching the XPath in the XML * @throws XPathExpressionException if there is an error in the XPath expression * @throws IOException if the XML at the specified path is missing * @throws SAXException if the XML cannot be parsed * @throws ParserConfigurationException */ public static NodeList findWithXPath(InputStream xml, String expression) throws IOException, SAXException, ParserConfigurationException { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder; dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(xml); doc.getDocumentElement().normalize(); XPath xPath = XPathFactory.newInstance().newXPath(); try { return (NodeList) xPath.compile(expression).evaluate(doc, XPathConstants.NODESET); } catch (XPathExpressionException e) { throw new InvalidXPathException(expression, e); } }
private static String getStringValue(@NonNull IAbstractFile file, @NonNull String xPath) throws StreamException, XPathExpressionException { XPath xpath = AndroidXPathFactory.newXPath(); InputStream is = null; try { is = file.getContents(); return xpath.evaluate(xPath, new InputSource(is)); } finally { try { Closeables.close(is, true /* swallowIOException */); } catch (IOException e) { // cannot happen } } }
private Afnemerindicatie getAfnemerIndicatie(final XPath xPath, final Node node) { final Afnemerindicatie afnemerindicatie = new Afnemerindicatie(); afnemerindicatie .setBsn(getNodeTextContent(getActieSpecifiekePrefix() + "/brp:persoon/brp:identificatienummers/brp:burgerservicenummer", xPath, node)); afnemerindicatie.setPartijCode( getNodeTextContent(getActieSpecifiekePrefix() + "/brp:persoon/brp:afnemerindicaties/brp:afnemerindicatie/brp:partijCode", xPath, node)); final String datumAanvangMaterielePeriode = getNodeTextContent( getActieSpecifiekePrefix() + "/brp:persoon/brp:afnemerindicaties/brp:afnemerindicatie/brp:datumAanvangMaterielePeriode", xPath, node); if (datumAanvangMaterielePeriode != null) { afnemerindicatie .setDatumAanvangMaterielePeriode(datumAanvangMaterielePeriode); } final String datumEindeVolgen = getNodeTextContent( getActieSpecifiekePrefix() + "/brp:persoon/brp:afnemerindicaties/brp:afnemerindicatie/brp:datumEindeVolgen", xPath, node); if (datumEindeVolgen != null) { afnemerindicatie.setDatumEindeVolgen(datumEindeVolgen); } return afnemerindicatie; }
/** * Hulpmethode om een xml fragment uit een node te halen middels xpath. * @param locatie de locatie van de node als xpath. * @param xPath een XPath instantie * @param node de basis node * @return de text */ protected static String getXmlFragment(final String locatie, final XPath xPath, final Node node) { try { final Node xPathNode = (Node) xPath.evaluate(locatie, node, XPathConstants.NODE); if (xPathNode != null) { final StringWriter buf = new StringWriter(); final Transformer xform = TransformerFactory.newInstance().newTransformer(); xform.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); xform.transform(new DOMSource(xPathNode), new StreamResult(buf)); return buf.toString(); } } catch (final XPathExpressionException | TransformerException e) { LOGGER.error("XPath voor text content kon niet worden geëvalueerd voor locatie {}.", locatie); throw new UnsupportedOperationException(e); } return null; }
private void handleRequireModules(AddOnVersion addOnVersion, XPath xpath, Document config) throws XPathExpressionException { NodeList nodeList = (NodeList) xpath.evaluate("/module/require_modules/require_module", config, XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength(); ++i) { Node item = nodeList.item(i); Node version = item.getAttributes().getNamedItem("version"); String requiredModule = item.getTextContent().trim(); String requiredVersion = version == null ? null : version.getTextContent().trim(); // sometimes modules are inadvertently uploaded without substituting maven variables in config.xml and we end // up with a required module version like ${reportingVersion} if (requiredVersion != null && requiredVersion.startsWith("${")) { requiredVersion = null; } addOnVersion.addRequiredModule(requiredModule, requiredVersion); } }
public static String parseSOAPResponse(SOAPMessage soapResponse, String expression) { String retStr = null; try { final StringWriter writer = new StringWriter(); TransformerFactory.newInstance().newTransformer().transform(new DOMSource(soapResponse.getSOAPPart()), new StreamResult(writer)); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); ByteArrayInputStream stream = new ByteArrayInputStream(writer.toString().getBytes("UTF-8")); Document doc = builder.parse(stream); XPath xPath = XPathFactory.newInstance().newXPath(); //String expression = "//return"; NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(doc, XPathConstants.NODESET); for (int index = 0; index < nodeList.getLength(); index++) { org.w3c.dom.Node node = nodeList.item(index); retStr = node.getTextContent(); } } catch (TransformerConfigurationException ex) { Logger.getLogger(SoapZephyrUtil.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception e) { Logger.getLogger(SoapZephyrUtil.class.getName()).log(Level.SEVERE, null, e); } return retStr; }
/** * Evaluates the specified expression on the specified node and returns the * result as a String. * * @param expression * The Xpath expression to evaluate. * @param node * The node on which to evaluate the expression. * * @return The result of evaluating the specified expression, or null if the * evaluation didn't return any result. * * @throws XPathExpressionException * If there are any problems evaluating the Xpath expression. */ private static String evaluateAsString(String expression, Node node, XPath xpath) throws XPathExpressionException { if (isEmpty(node)) return null; if (!expression.equals(".")) { /* * If the expression being evaluated doesn't select a node, we want * to return null to distinguish between cases where a node isn't * present (which should be represented as null) and when a node is * present, but empty (which should be represented as the empty * string). * * We skip this test if the expression is "." since we've already * checked that the node exists. */ if (asNode(expression, node, xpath) == null) return null; } String s = xpath.evaluate(expression, node); return s.trim(); }
/**@param{Object} Address- The physical address of a location * This method returns Geocode coordinates of the Address object.Geocoding is the process of converting addresses (like "1600 Amphitheatre Parkway, * Mountain View, CA") into geographic coordinates (like latitude 37.423021 and longitude -122.083739).Please give all the physical Address values * for a precise coordinate. setting none of the values will give a null value for the Latitude and Longitude. */ public static GeoCode getCoordinates(Address address) throws Exception { GeoCode geo= new GeoCode(); String physicalAddress = (address.getAddress1() == null ? "" : address.getAddress1() + ",") + (address.getAddress2() == null ? "" : address.getAddress2() + ",") + (address.getCityName() == null ? "" : address.getCityName() + ",") + (address.getState() == null ? "" : address.getState() + "-") + (address.getZip() == null ? "" : address.getZip() + ",") + (address.getCountry() == null ? "" : address.getCountry()); String api = GMAPADDRESS + URLEncoder.encode(physicalAddress, "UTF-8") + SENSOR; URL url = new URL(api); HttpURLConnection httpConnection = (HttpURLConnection)url.openConnection(); httpConnection.connect(); int responseCode = httpConnection.getResponseCode(); if(responseCode == 200) { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document document = builder.parse(httpConnection.getInputStream()); XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); XPathExpression expr = xpath.compile(STATUS); String status = (String)expr.evaluate(document, XPathConstants.STRING); if(status.equals("OK")) { expr = xpath.compile(LATITUDE); String latitude = (String)expr.evaluate(document, XPathConstants.STRING); expr = xpath.compile(LONGITUDE); String longitude = (String)expr.evaluate(document, XPathConstants.STRING); geo.setLatitude(latitude); geo.setLongitude(longitude); } } else { throw new Exception("Fail to Convert to Geocode"); } return geo; }
/** * Hulpmethode om de nodes uit een node te halen middels xpath. * @param locatie de locatie van de node als xpath. * @param xPath een XPath instantie * @param node de basis node * @return de text */ protected static NodeList getNodeList(final String locatie, final XPath xPath, final Node node) { try { return (NodeList) xPath.evaluate(locatie, node, XPathConstants.NODESET); } catch (final XPathExpressionException e) { LOGGER.error("XPath voor node list kon niet worden geëvalueerd voor locatie {}.", locatie); throw new UnsupportedOperationException(e); } }
@Test public void testIsEmpty() throws Exception { Document document = XpathUtils.documentFrom(DOCUMENT); XPath xpath = xpath(); Node emptyNode = asNode("Foo/Fake", document, xpath); Node realNode = asNode("Foo/Count", document, xpath); assertTrue(isEmpty(emptyNode)); assertFalse(isEmpty(realNode)); }
@Test public void testXmlDocumentWithNamespace() throws Exception { Document document = documentFrom(DOCUMENT_WITH_NAMESPACE); XPath xpath = xpath(); Node root = asNode("/", document, xpath); assertNotNull(root); Node node = asNode("//AllocateAddressResponse", document, xpath); assertNotNull(node); }
/** * Tests that we can correctly pull a Byte out of an XML document. */ @Test public void testAsByte() throws Exception { Document document = XpathUtils.documentFrom(DOCUMENT); XPath xpath = xpath(); assertEquals(new Byte((byte) 123), asByte("Foo/PositiveByte", document, xpath)); assertEquals(new Byte((byte) -99), asByte("Foo/NegativeByte", document, xpath)); assertEquals(null, XpathUtils.asByte("Foo/Empty", document)); }
private void doPopulateUnapproved(Map<String, ModuleInfo> moduleRATInfo, Element rootElement, XPath path) throws XPathExpressionException { NodeList evaluate = (NodeList) path.evaluate("descendant::resource[license-approval/@name=\"false\"]", rootElement, XPathConstants.NODESET); for (int i = 0; i < evaluate.getLength(); i++) { String resources = relativize(evaluate.item(i).getAttributes().getNamedItem("name").getTextContent()); String moduleName = getModuleName(resources); if (!moduleRATInfo.containsKey(moduleName)) { moduleRATInfo.get(NOT_CLUSTER).addUnapproved(resources); } else { moduleRATInfo.get(moduleName).addUnapproved(resources); } } }
public static List<String> runXPathQuery(File parsedFile, String xpathExpr) throws Exception{ List<String> result = new ArrayList<String>(); XPath xpath = XPathFactory.newInstance().newXPath(); xpath.setNamespaceContext(getNamespaceContext()); InputSource inputSource = new InputSource(new FileInputStream(parsedFile)); NodeList nodes = (NodeList) xpath.evaluate(xpathExpr, inputSource, XPathConstants.NODESET); if((nodes != null) && (nodes.getLength() > 0)){ for(int i=0; i<nodes.getLength();i++){ Node node = nodes.item(i); result.add(node.getNodeValue()); } } return result; }
public static List runXPathQuery(File parsedFile, String xpathExpr) throws Exception{ List result = new ArrayList(); XPath xpath = XPathFactory.newInstance().newXPath(); xpath.setNamespaceContext(getNamespaceContext()); InputSource inputSource = new InputSource(new FileInputStream(parsedFile)); NodeList nodes = (NodeList) xpath.evaluate(xpathExpr, inputSource, XPathConstants.NODESET); if((nodes != null) && (nodes.getLength() > 0)){ for(int i=0; i<nodes.getLength();i++){ org.w3c.dom.Node node = nodes.item(i); result.add(node.getNodeValue()); } } return result; }
@Test public void testXPath10() throws Exception { try { XPath xpath = xpathFactory.newXPath(); Assert.assertNotNull(xpath); xpath.evaluate(".", d, XPathConstants.STRING); Assert.fail("XPathExpressionException not thrown"); } catch (XPathExpressionException e) { // Expected exception as context node is null } }
/**Query the API and returns the list of expansions. Update the cache. * @param abbrev lowercase abbreviation. * @throws Exception */ private synchronized String[] queryApi(String abbrev, int retryLeft) throws Exception { if (retryLeft < MAX_RETRY) Thread.sleep(1000); URL url = new URL(String.format("%s?uid=%s&tokenid=%s&term=%s", API_URL, uid, tokenId, URLEncoder.encode(abbrev, "utf8"))); boolean cached = abbrToExpansion.containsKey(abbrev); LOG.info("{} {}", cached ? "<cached>" : "Querying", url); if (cached) return abbrToExpansion.get(abbrev); HttpURLConnection connection = (HttpURLConnection) url .openConnection(); connection.setConnectTimeout(0); connection.setRequestProperty("Accept", "*/*"); connection .setRequestProperty("Content-Type", "multipart/form-data"); connection.setUseCaches(false); if (connection.getResponseCode() != 200) { Scanner s = new Scanner(connection.getErrorStream()) .useDelimiter("\\A"); LOG.error("Got HTTP error {}. Message is: {}", connection.getResponseCode(), s.next()); s.close(); throw new RuntimeException("Got response code:" + connection.getResponseCode()); } DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc; try { doc = builder.parse(connection.getInputStream()); } catch (IOException e) { LOG.error("Got error while querying: {}", url); throw e; } XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); XPathExpression resourceExpr = xpath.compile("//definition/text()"); NodeList resources = (NodeList) resourceExpr.evaluate(doc, XPathConstants.NODESET); Vector<String> resVect = new Vector<>(); for (int i=0; i<resources.getLength(); i++){ String expansion = resources.item(i).getTextContent().replace(String.valueOf((char) 160), " ").trim(); if (!resVect.contains(expansion)) resVect.add(expansion); } String[] res = resVect.toArray(new String[]{}); abbrToExpansion.put(abbrev, res); increaseFlushCounter(); return res; }
/** * @param bevragingVerzoek bevragingVerzoek * @param node node * @param xPath xPath */ final void parseZoekCriteria(final T bevragingVerzoek, final Node node, final XPath xPath) { final String zoekcriteriumXpath = getPrefix() + "/brp:zoekcriteria/brp:zoekcriterium"; final NodeList zoekcriteriaNodes = getNodeList(zoekcriteriumXpath, xPath, node); final int nodesCount = zoekcriteriaNodes.getLength(); for (int i = 0; i < nodesCount; i++) { final Node zoekCriteriumNode = zoekcriteriaNodes.item(i); final ZoekPersoonVerzoek.ZoekCriteria zoekCriterium = new AbstractZoekPersoonVerzoek.ZoekCriteria(); zoekCriterium.setElementNaam(getNodeTextContent("brp:elementNaam", xPath, zoekCriteriumNode)); zoekCriterium.setWaarde(getNodeTextContent("brp:waarde", xPath, zoekCriteriumNode)); zoekCriterium.setZoekOptie(Zoekoptie.getByNaam(getNodeTextContent("brp:optie", xPath, zoekCriteriumNode))); zoekCriterium.setCommunicatieId(getNodeTextContent("@brp:communicatieID", xPath, zoekCriteriumNode)); bevragingVerzoek.getZoekCriteriaPersoon().add(zoekCriterium); } }
private Element getAttributeQuery(Document document) throws XPathExpressionException { 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"); xpath.setNamespaceContext(context); return (Element) xpath.evaluate("//samlp:Response", document, XPathConstants.NODE); }
@Test public void testXPathVariableResolver() throws Exception { XPath xpath = getXPath(); xpath.setXPathVariableResolver(new MyXPathVariableResolver()); assertEquals(xpath.evaluate("//astro:stardb/astro:star[astro:hr=$id]/astro:constellation", doc.getDocumentElement()), "Peg"); }
@Test public void testAsInteger() throws Exception { Document document = documentFrom(DOCUMENT); XPath xpath = xpath(); assertEquals((Integer)1, (Integer)asInteger("Foo/Count", document, xpath)); assertEquals(null, asInteger("Foo/Empty", document, xpath)); }
public MetaDataMerger ( final String label, final boolean compressed ) throws Exception { this.doc = createDocument (); final XPathFactory xpf = XPathFactory.newInstance (); final XPath xp = xpf.newXPath (); this.isCategoryPathExpression = xp.compile ( "properties/property[@name='org.eclipse.equinox.p2.type.category']/@value" ); final ProcessingInstruction pi = this.doc.createProcessingInstruction ( "metadataRepository", "" ); pi.setData ( "version=\"1.1.0\"" ); this.doc.appendChild ( pi ); this.r = this.doc.createElement ( "repository" ); this.doc.appendChild ( this.r ); this.r.setAttribute ( "name", label ); this.r.setAttribute ( "type", "org.eclipse.equinox.internal.p2.metadata.repository.LocalMetadataRepository" ); this.r.setAttribute ( "version", "1" ); this.p = this.doc.createElement ( "properties" ); this.r.appendChild ( this.p ); addProperty ( this.p, "p2.compressed", "" + compressed ); addProperty ( this.p, "p2.timestamp", "" + System.currentTimeMillis () ); this.u = this.doc.createElement ( "units" ); this.r.appendChild ( this.u ); }
/** * Any @string reference in a <provider> value in AndroidManifest.xml will break on * build, thus preventing the application from installing. This is from a bug/error * in AOSP where public resources cannot be part of an authorities attribute within * a <provider> tag. * * This finds any reference and replaces it with the literal value found in the * res/values/strings.xml file. * * @param file File for AndroidManifest.xml * @throws AndrolibException */ public static void fixingPublicAttrsInProviderAttributes(File file) throws AndrolibException { if (file.exists()) { try { Document doc = loadDocument(file); XPath xPath = XPathFactory.newInstance().newXPath(); XPathExpression expression = xPath.compile("/manifest/application/provider"); Object result = expression.evaluate(doc, XPathConstants.NODESET); NodeList nodes = (NodeList) result; for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); NamedNodeMap attrs = node.getAttributes(); if (attrs != null) { Node provider = attrs.getNamedItem("android:authorities"); if (provider != null) { String reference = provider.getNodeValue(); String replacement = pullValueFromStrings(file.getParentFile(), reference); if (replacement != null) { provider.setNodeValue(replacement); saveDocument(file, doc); } } } } } catch (SAXException | ParserConfigurationException | IOException | XPathExpressionException | TransformerException ignored) { } } }
/** * Finds key in strings.xml file and returns text value * * @param directory Root directory of apk * @param key String reference (ie @string/foo) * @return String|null * @throws AndrolibException */ public static String pullValueFromStrings(File directory, String key) throws AndrolibException { if (! key.contains("@")) { return null; } File file = new File(directory, "/res/values/strings.xml"); key = key.replace("@string/", ""); if (file.exists()) { try { Document doc = loadDocument(file); XPath xPath = XPathFactory.newInstance().newXPath(); XPathExpression expression = xPath.compile("/resources/string[@name=" + '"' + key + "\"]/text()"); Object result = expression.evaluate(doc, XPathConstants.STRING); if (result != null) { return (String) result; } } catch (SAXException | ParserConfigurationException | IOException | XPathExpressionException ignored) { } } return null; }
@Override public void vulDienstSpecifiekeGegevens(StufBerichtVerzoek verzoek, Node node, XPath xPath) { final String inhoud = getXmlFragment(getPrefix() + "/brp:berichtVertaling/brp:teVertalenBericht/brp:lvg_synVerwerkPersoon", xPath, node); final String soortSynchronisatie = getNodeTextContent(getPrefix() + "/brp:berichtVertaling/brp:teVertalenBericht/brp:lvg_synVerwerkPersoon/brp:parameters/brp:soortSynchronisatie", xPath, node); verzoek.setStufBericht(new StufBericht(inhoud, soortSynchronisatie)); verzoek.setSoortDienst(SoortDienst.GEEF_STUF_BG_BERICHT); }
/** * Evaluates the specified expression on the specified node and returns the * result as a String. * * @param expression * The Xpath expression to evaluate. * @param node * The node on which to evaluate the expression. * * @return The result of evaluating the specified expression, or null if the * evaluation didn't return any result. * * @throws XPathExpressionException * If there are any problems evaluating the Xpath expression. */ private static String evaluateAsString(String expression, Node node, XPath xpath) throws XPathExpressionException { if (isEmpty(node)) { return null; } if (!expression.equals(".")) { /* * If the expression being evaluated doesn't select a node, we want * to return null to distinguish between cases where a node isn't * present (which should be represented as null) and when a node is * present, but empty (which should be represented as the empty * string). * * We skip this test if the expression is "." since we've already * checked that the node exists. */ if (asNode(expression, node, xpath) == null) { return null; } } String s = xpath.evaluate(expression, node); return s.trim(); }
public static Node getChildNode(Document doc, String parentTag, String childnode) { try { XPath xpath = XPathFactory.newInstance().newXPath(); XPathExpression expr = xpath.compile("//" + parentTag + "/" + childnode); Object obj = expr.evaluate(doc, XPathConstants.NODE); return obj != null ? (Node) obj : null; } catch (Exception ex) { ex.printStackTrace(); } return null; }