List of usage examples for javax.xml.parsers DocumentBuilder newDocument
public abstract Document newDocument();
From source file:com.eucalyptus.imaging.manifest.DownloadManifestFactory.java
/** * Generates download manifest based on bundle manifest and puts in into * system owned bucket/*from www .j av a2s . co m*/ * * @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:net.sf.jabref.logic.mods.MODSDatabase.java
public Document getDOMrepresentation() { Document result = null;//from www . j av a 2 s .c o m try { DocumentBuilder dbuild = DocumentBuilderFactory.newInstance().newDocumentBuilder(); result = dbuild.newDocument(); Element modsCollection = result.createElement("modsCollection"); modsCollection.setAttribute("xmlns", "http://www.loc.gov/mods/v3"); modsCollection.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); modsCollection.setAttribute("xsi:schemaLocation", "http://www.loc.gov/mods/v3 http://www.loc.gov/standards/mods/v3/mods-3-0.xsd"); for (MODSEntry entry : entries) { Node node = entry.getDOMrepresentation(result); modsCollection.appendChild(node); } result.appendChild(modsCollection); } catch (Exception e) { LOGGER.info("Could not get DOM representation", e); } return result; }
From source file:BuildXml.java
public BuildXml() { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); try {//from ww w. j a v a2 s . c o m DocumentBuilder builder = factory.newDocumentBuilder(); document = builder.newDocument(); } catch (ParserConfigurationException parserException) { parserException.printStackTrace(); } Element root = document.createElement("root"); document.appendChild(root); // add comment to XML document Comment simpleComment = document.createComment("This is a simple contact list"); root.appendChild(simpleComment); // add child element Node contactNode = createContactNode(document); root.appendChild(contactNode); // add processing instruction ProcessingInstruction pi = document.createProcessingInstruction("myInstruction", "action silent"); root.appendChild(pi); // add CDATA section CDATASection cdata = document.createCDATASection("I can add <, >, and ?"); root.appendChild(cdata); // write the XML document to disk try { // create DOMSource for source XML document Source xmlSource = new DOMSource(document); // create StreamResult for transformation result Result result = new StreamResult(new FileOutputStream("myDocument.xml")); // create TransformerFactory TransformerFactory transformerFactory = TransformerFactory.newInstance(); // create Transformer for transformation Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty("indent", "yes"); // transform and deliver content to client transformer.transform(xmlSource, result); } // handle exception creating TransformerFactory catch (TransformerFactoryConfigurationError factoryError) { System.err.println("Error creating " + "TransformerFactory"); factoryError.printStackTrace(); } catch (TransformerException transformerError) { System.err.println("Error transforming document"); transformerError.printStackTrace(); } catch (IOException ioException) { ioException.printStackTrace(); } }
From source file:bpsperf.modelgen.AbstractGenerator.java
protected void generateSkeleton(String processId) throws ParserConfigurationException { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); doc = docBuilder.newDocument(); Element rootElement = doc.createElementNS(ns, "definitions"); rootElement.setAttribute("targetNamespace", "http://www.activiti.org/test"); doc.appendChild(rootElement);// w w w . j a v a2s. c o m Element process = doc.createElementNS(ns, "process"); process.setAttribute("id", processId); process.setAttribute("name", processId); process.setAttribute("isExecutable", "true"); rootElement.appendChild(process); this.parent = process; }
From source file:it.unibas.spicy.persistence.xml.DAOXmlUtility.java
public org.w3c.dom.Document buildNewDOM() throws DAOException { org.w3c.dom.Document document = null; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(true);/*from w ww. j a v a 2s . co m*/ try { DocumentBuilder builder = factory.newDocumentBuilder(); document = builder.newDocument(); } catch (ParserConfigurationException pce) { logger.error(pce); throw new DAOException(pce.getMessage()); } catch (DOMException doe) { logger.error(doe); throw new DAOException(doe.getMessage()); } return document; }
From source file:net.sf.jabref.logic.msbib.MSBibDatabase.java
public Document getDOM() { Document document = null;/* ww w.j a v a 2s .c o m*/ try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder documentBuilder = factory.newDocumentBuilder(); document = documentBuilder.newDocument(); Element rootNode = document.createElementNS(NAMESPACE, PREFIX + "Sources"); rootNode.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", NAMESPACE); rootNode.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" + PREFIX.substring(0, PREFIX.length() - 1), NAMESPACE); rootNode.setAttribute("SelectedStyle", ""); for (MSBibEntry entry : entries) { Node node = entry.getDOM(document); rootNode.appendChild(node); } document.appendChild(rootNode); } catch (ParserConfigurationException e) { LOGGER.warn("Could not build XML document", e); } return document; }
From source file:com.msopentech.odatajclient.engine.data.json.JSONPropertySerializer.java
/** * {@inheritDoc }//from w ww . j av a 2s . c o m */ @Override public void serialize(final JSONProperty property, final JsonGenerator jgen, final SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeStartObject(); if (property.getMetadata() != null) { jgen.writeStringField(ODataConstants.JSON_METADATA, property.getMetadata().toASCIIString()); } final Element content = property.getContent(); if (XMLUtils.hasOnlyTextChildNodes(content)) { jgen.writeStringField(ODataConstants.JSON_VALUE, content.getTextContent()); } else { try { final DocumentBuilder builder = ODataConstants.DOC_BUILDER_FACTORY.newDocumentBuilder(); final Document document = builder.newDocument(); final Element wrapper = document.createElement(ODataConstants.ELEM_PROPERTY); if (XMLUtils.hasElementsChildNode(content)) { wrapper.appendChild(document.renameNode(document.importNode(content, true), null, ODataConstants.JSON_VALUE)); DOMTreeUtils.writeSubtree(jgen, wrapper); } else if (EdmSimpleType.isGeospatial(content.getAttribute(ODataConstants.ATTR_M_TYPE))) { wrapper.appendChild(document.renameNode(document.importNode(content, true), null, ODataConstants.JSON_VALUE)); DOMTreeUtils.writeSubtree(jgen, wrapper, true); } else { DOMTreeUtils.writeSubtree(jgen, content); } } catch (Exception e) { throw new JsonParseException("Cannot serialize property", JsonLocation.NA, e); } } jgen.writeEndObject(); }
From source file:org.wikipedia.vlsergey.secretary.utils.AbstractDocumentBuilderPool.java
public Document newDocument() throws ParserConfigurationException { DocumentBuilder builder = borrow(); try {// w ww .j a v a2 s . c om return builder.newDocument(); } finally { returnObject(builder); } }
From source file:org.springmodules.validation.bean.conf.loader.xml.SimpleValidationRuleElementHandlerRegistryTests.java
protected Element createElement(String name) throws Exception { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); return builder.newDocument().createElement(name); }
From source file:com.codebutler.farebot.mifare.Card.java
public Element toXML() throws Exception { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = builder.newDocument(); Element element = doc.createElement("card"); element.setAttribute("type", String.valueOf(getCardType().toInteger())); element.setAttribute("id", Utils.getHexString(mTagId)); element.setAttribute("scanned_at", Long.toString(mScannedAt.getTime())); doc.appendChild(element);/*from w ww .j a va2 s . c om*/ return doc.getDocumentElement(); }