List of usage examples for javax.xml.xpath XPathConstants NODE
QName NODE
To view the source code for javax.xml.xpath XPathConstants NODE.
Click Source Link
The XPath 1.0 NodeSet data type.
From source file:com.baracuda.piepet.nexusrelease.nexus.StageClient.java
/** * Check if we have the required permissions for nexus staging. * /*from w w w . j a v a2 s . c o m*/ * @return * @throws StageException if an exception occurred whilst checking the authorisation. */ public void checkAuthentication() throws StageException { try { URL url = new URL(nexusURL, "service/local/status?perms=1"); Document doc = getDocument(url); /* * check for the following permissions: */ String[] requiredPerms = new String[] { "nexus:stagingprofiles", "nexus:stagingfinish", "nexus:stagingprofilerepos", "nexus:stagingpromote", "nexus:stagingdrop" }; for (String perm : requiredPerms) { String expression = "//clientPermissions/permissions/permission[id=\"" + perm + "\"]/value"; Node node = (Node) evaluateXPath(expression, doc, XPathConstants.NODE); if (node == null) { throw new StageException( "Invalid reponse from server - is the URL a Nexus Professional server?"); } int val = Integer.parseInt(node.getTextContent()); if (val == 0) { throw new StageException( "User has insufficient privileges to perform staging actions (" + perm + ")"); } } } catch (MalformedURLException ex) { throw createStageExceptionForIOException(nexusURL, ex); } }
From source file:de.ingrid.iplug.opensearch.converter.IngridRSSConverter.java
/** * Get the link of the entry.//from w w w. jav a2 s.c o m * * @param item * @return * @throws XPathExpressionException */ private Object getLink(Node item) throws XPathExpressionException { XPath xpath = XPathFactory.newInstance().newXPath(); Node node = (Node) xpath.evaluate("link", item, XPathConstants.NODE); if (node != null) { return node.getTextContent(); } else { return ""; } }
From source file:org.eclipse.lyo.testsuite.server.oslcv1tests.ServiceDescriptionTests.java
@Test public void changeManagementServiceDescriptionHasValidSimpleQuery() throws XPathException { //If ServiceDescription is oslc_cm, make sure it has a valid simple query child element Node cmRequest = (Node) OSLCUtils.getXPath().evaluate("//oslc_cm:changeRequests", doc, XPathConstants.NODE); if (cmRequest != null) { NodeList sQ = (NodeList) OSLCUtils.getXPath().evaluate("//oslc_cm:changeRequests/oslc_cm:simpleQuery", doc, XPathConstants.NODESET); assertTrue(sQ.getLength() == 1); Node url = (Node) OSLCUtils.getXPath() .evaluate("//oslc_cm:changeRequests/oslc_cm:simpleQuery/oslc_cm:url", doc, XPathConstants.NODE); assertNotNull(url);// w ww. j av a 2 s . c o m Node title = (Node) OSLCUtils.getXPath() .evaluate("//oslc_cm:changeRequests/oslc_cm:simpleQuery/dc:title", doc, XPathConstants.NODE); assertNotNull(title); assertFalse(title.getTextContent().isEmpty()); } }
From source file:org.opencastproject.remotetest.server.ComposerRestEndpointTest.java
protected String getJobId(String xml) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true);//from w ww . jav a 2 s .co m DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(IOUtils.toInputStream(xml, "UTF-8")); return ((Element) XPathFactory.newInstance().newXPath().compile("/*").evaluate(doc, XPathConstants.NODE)) .getAttribute("id"); }
From source file:org.eclipse.lyo.testsuite.server.oslcv1tests.ServiceProviderCatalogTests.java
@Test public void serviceProvidersHaveValidTitles() throws XPathException { //Get all entries, parse out which have embedded ServiceProviders and check the titles NodeList entries = (NodeList) OSLCUtils.getXPath().evaluate("//oslc_disc:entry/*", doc, XPathConstants.NODESET); for (int i = 0; i < entries.getLength(); i++) { Node provider = (Node) OSLCUtils.getXPath().evaluate( "//oslc_disc:entry[" + (i + 1) + "]/oslc_disc:ServiceProvider", doc, XPathConstants.NODE); //This entry has a catalog, check that it has a title if (provider != null) { Node pTitle = (Node) OSLCUtils.getXPath().evaluate( "//oslc_disc:entry[" + (i + 1) + "]/oslc_disc:ServiceProvider/dc:title", doc, XPathConstants.NODE); assertNotNull(pTitle);/* w w w . j a v a 2 s. com*/ //Make sure the title isn't empty assertFalse(pTitle.getTextContent().isEmpty()); Node child = (Node) OSLCUtils.getXPath().evaluate( "//oslc_disc:entry[" + (i + 1) + "]/oslc_disc:ServiceProvider/dc:title/*", doc, XPathConstants.NODE); //Make sure the title has no child elements assertTrue(child == null); } } }
From source file:edu.cornell.mannlib.semservices.util.XMLUtils.java
/** * @param doc (either a Document or a Node) * @param expression/*w w w . j av a 2s . c o m*/ * @return string contents */ public static Node getNodeWithXpath(Object obj, String expression) { Object root = null; if (obj instanceof Document) { Document doc = (Document) obj; root = doc.getDocumentElement(); } else { root = (Node) obj; } XPath xpath = XPathFactory.newInstance().newXPath(); xpath.setNamespaceContext(new MetadataNamespaceContext()); Node result = null; try { result = ((Node) xpath.evaluate(expression, root, XPathConstants.NODE)); return result; } catch (XPathExpressionException e) { logger.error("XPathExpressionException ", e); return null; } }
From source file:org.callimachusproject.rdfa.test.RDFaGenerationTest.java
boolean isViewable(Document doc) throws Exception { XPath xpath = xPathFactory.newXPath(); // there are no namespaces in this xpath so a prefix resolver is not required String exp = "//*[@about='?this']"; XPathExpression compiled = xpath.compile(exp); Object result = compiled.evaluate(doc, XPathConstants.NODE); return result != null; }
From source file:com.eucalyptus.imaging.manifest.DownloadManifestFactory.java
/** * Generates download manifest based on bundle manifest and puts in into * system owned bucket//from w w w .j a va 2 s. c om * * @param baseManifest * the base manifest * @param keyToUse * public key that used for encryption * @param manifestName * name for generated manifest file * @param expirationHours * expiration policy in hours for pre-signed URLs * @param urlForNc * indicates if urs are constructed for NC use * @return pre-signed URL that can be used to download generated manifest * @throws DownloadManifestException */ public static String generateDownloadManifest(final ImageManifestFile baseManifest, final PublicKey keyToUse, final String manifestName, int expirationHours, boolean urlForNc) throws DownloadManifestException { EucaS3Client s3Client = null; try { try { s3Client = s3ClientsPool.borrowObject(); } catch (Exception ex) { throw new DownloadManifestException("Can't borrow s3Client from the pool"); } // prepare to do pre-signed urls if (!urlForNc) s3Client.refreshEndpoint(true); else s3Client.refreshEndpoint(); Date expiration = new Date(); long msec = expiration.getTime() + 1000 * 60 * 60 * expirationHours; expiration.setTime(msec); // check if download-manifest already exists if (objectExist(s3Client, DOWNLOAD_MANIFEST_BUCKET_NAME, DOWNLOAD_MANIFEST_PREFIX + manifestName)) { LOG.debug("Manifest '" + (DOWNLOAD_MANIFEST_PREFIX + manifestName) + "' is already created and has not expired. Skipping creation"); URL s = s3Client.generatePresignedUrl(DOWNLOAD_MANIFEST_BUCKET_NAME, DOWNLOAD_MANIFEST_PREFIX + manifestName, expiration, HttpMethod.GET); return String.format("%s://imaging@%s%s?%s", s.getProtocol(), s.getAuthority(), s.getPath(), s.getQuery()); } else { LOG.debug("Manifest '" + (DOWNLOAD_MANIFEST_PREFIX + manifestName) + "' does not exist"); } UrlValidator urlValidator = new UrlValidator(); final String manifest = baseManifest.getManifest(); if (manifest == null) { throw new DownloadManifestException("Can't generate download manifest from null base manifest"); } final Document inputSource; final XPath xpath; Function<String, String> xpathHelper; DocumentBuilder builder = XMLParser.getDocBuilder(); inputSource = builder.parse(new ByteArrayInputStream(manifest.getBytes())); if (!"manifest".equals(inputSource.getDocumentElement().getNodeName())) { LOG.error("Expected image manifest. Got " + nodeToString(inputSource, false)); throw new InvalidBaseManifestException("Base manifest does not have manifest element"); } StringBuilder signatureSrc = new StringBuilder(); Document manifestDoc = builder.newDocument(); Element root = (Element) manifestDoc.createElement("manifest"); manifestDoc.appendChild(root); Element el = manifestDoc.createElement("version"); el.appendChild(manifestDoc.createTextNode("2014-01-14")); signatureSrc.append(nodeToString(el, false)); root.appendChild(el); el = manifestDoc.createElement("file-format"); el.appendChild(manifestDoc.createTextNode(baseManifest.getManifestType().getFileType().toString())); root.appendChild(el); signatureSrc.append(nodeToString(el, false)); xpath = XPathFactory.newInstance().newXPath(); xpathHelper = new Function<String, String>() { @Override public String apply(String input) { try { return (String) xpath.evaluate(input, inputSource, XPathConstants.STRING); } catch (XPathExpressionException ex) { return null; } } }; // extract keys // TODO: move this? if (baseManifest.getManifestType().getFileType() == FileType.BUNDLE) { String encryptedKey = xpathHelper.apply("/manifest/image/ec2_encrypted_key"); String encryptedIV = xpathHelper.apply("/manifest/image/ec2_encrypted_iv"); String size = xpathHelper.apply("/manifest/image/size"); EncryptedKey encryptKey = reEncryptKey(new EncryptedKey(encryptedKey, encryptedIV), keyToUse); el = manifestDoc.createElement("bundle"); Element key = manifestDoc.createElement("encrypted-key"); key.appendChild(manifestDoc.createTextNode(encryptKey.getKey())); Element iv = manifestDoc.createElement("encrypted-iv"); iv.appendChild(manifestDoc.createTextNode(encryptKey.getIV())); el.appendChild(key); el.appendChild(iv); Element sizeEl = manifestDoc.createElement("unbundled-size"); sizeEl.appendChild(manifestDoc.createTextNode(size)); el.appendChild(sizeEl); root.appendChild(el); signatureSrc.append(nodeToString(el, false)); } el = manifestDoc.createElement("image"); String bundleSize = xpathHelper.apply(baseManifest.getManifestType().getSizePath()); if (bundleSize == null) { throw new InvalidBaseManifestException("Base manifest does not have size element"); } Element size = manifestDoc.createElement("size"); size.appendChild(manifestDoc.createTextNode(bundleSize)); el.appendChild(size); Element partsEl = manifestDoc.createElement("parts"); el.appendChild(partsEl); // parts NodeList parts = (NodeList) xpath.evaluate(baseManifest.getManifestType().getPartsPath(), inputSource, XPathConstants.NODESET); if (parts == null) { throw new InvalidBaseManifestException("Base manifest does not have parts"); } for (int i = 0; i < parts.getLength(); i++) { Node part = parts.item(i); String partIndex = part.getAttributes().getNamedItem("index").getNodeValue(); String partKey = ((Node) xpath.evaluate(baseManifest.getManifestType().getPartUrlElement(), part, XPathConstants.NODE)).getTextContent(); String partDownloadUrl = partKey; if (baseManifest.getManifestType().signPartUrl()) { GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest( baseManifest.getBaseBucket(), partKey, HttpMethod.GET); generatePresignedUrlRequest.setExpiration(expiration); URL s = s3Client.generatePresignedUrl(generatePresignedUrlRequest); partDownloadUrl = s.toString(); } else { // validate url per EUCA-9144 if (!urlValidator.isEucalyptusUrl(partDownloadUrl)) throw new DownloadManifestException( "Some parts in the manifest are not stored in the OS. Its location is outside Eucalyptus:" + partDownloadUrl); } Node digestNode = null; if (baseManifest.getManifestType().getDigestElement() != null) digestNode = ((Node) xpath.evaluate(baseManifest.getManifestType().getDigestElement(), part, XPathConstants.NODE)); Element aPart = manifestDoc.createElement("part"); Element getUrl = manifestDoc.createElement("get-url"); getUrl.appendChild(manifestDoc.createTextNode(partDownloadUrl)); aPart.setAttribute("index", partIndex); aPart.appendChild(getUrl); if (digestNode != null) { NamedNodeMap nm = digestNode.getAttributes(); if (nm == null) throw new DownloadManifestException( "Some parts in manifest don't have digest's verification algorithm"); Element digest = manifestDoc.createElement("digest"); digest.setAttribute("algorithm", nm.getNamedItem("algorithm").getTextContent()); digest.appendChild(manifestDoc.createTextNode(digestNode.getTextContent())); aPart.appendChild(digest); } partsEl.appendChild(aPart); } root.appendChild(el); signatureSrc.append(nodeToString(el, false)); String signatureData = signatureSrc.toString(); Element signature = manifestDoc.createElement("signature"); signature.setAttribute("algorithm", "RSA-SHA256"); signature.appendChild(manifestDoc .createTextNode(Signatures.SHA256withRSA.trySign(Eucalyptus.class, signatureData.getBytes()))); root.appendChild(signature); String downloadManifest = nodeToString(manifestDoc, true); // TODO: move this ? createManifestsBucketIfNeeded(s3Client); putManifestData(s3Client, DOWNLOAD_MANIFEST_BUCKET_NAME, DOWNLOAD_MANIFEST_PREFIX + manifestName, downloadManifest, expiration); // generate pre-sign url for download manifest URL s = s3Client.generatePresignedUrl(DOWNLOAD_MANIFEST_BUCKET_NAME, DOWNLOAD_MANIFEST_PREFIX + manifestName, expiration, HttpMethod.GET); return String.format("%s://imaging@%s%s?%s", s.getProtocol(), s.getAuthority(), s.getPath(), s.getQuery()); } catch (Exception ex) { LOG.error("Got an error", ex); throw new DownloadManifestException("Can't generate download manifest"); } finally { if (s3Client != null) try { s3ClientsPool.returnObject(s3Client); } catch (Exception e) { // sad, but let's not break instances run LOG.warn("Could not return s3Client to the pool"); } } }
From source file:com.photon.phresco.impl.ConfigManagerImpl.java
private Node getNode(String xpath) throws ConfigurationException { XPathFactory xPathFactory = XPathFactory.newInstance(); XPath newXPath = xPathFactory.newXPath(); XPathExpression xPathExpression; Node xpathNode = null;/* w w w. ja v a2s. c om*/ try { xPathExpression = newXPath.compile(xpath); xpathNode = (Node) xPathExpression.evaluate(document, XPathConstants.NODE); } catch (XPathExpressionException e) { throw new ConfigurationException(e); } return xpathNode; }
From source file:de.ingrid.iplug.opensearch.converter.IngridRSSConverter.java
/** * Get the title of the entry./*from w ww. j a va 2 s .c o m*/ * * @param item * @return * @throws XPathExpressionException */ private Object getTitle(Node item) throws XPathExpressionException { XPath xpath = XPathFactory.newInstance().newXPath(); Node node = (Node) xpath.evaluate("title", item, XPathConstants.NODE); if (node != null) { return node.getTextContent(); } else { return ""; } }