List of usage examples for org.w3c.dom Document createTextNode
public Text createTextNode(String data);
Text
node given the specified string. 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 a v a2 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.hangum.tadpole.engine.sql.util.export.XMLExporter.java
/** * make content// w w w .ja va 2s. c o m * * @param tableName * @param rsDAO * @return */ public static String makeContent(String tableName, QueryExecuteResultDTO rsDAO, int intLimitCnt) throws Exception { final StringWriter stWriter = new StringWriter(); final List<Map<Integer, Object>> dataList = rsDAO.getDataList().getData(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); final Document doc = builder.newDocument(); final Element results = doc.createElement(tableName); doc.appendChild(results); Map<Integer, String> mapLabelName = rsDAO.getColumnLabelName(); for (int i = 0; i < dataList.size(); i++) { Map<Integer, Object> mapColumns = dataList.get(i); Element row = doc.createElement("Row"); results.appendChild(row); for (int j = 1; j < mapColumns.size(); j++) { String columnName = mapLabelName.get(j); String strValue = mapColumns.get(j) == null ? "" : "" + mapColumns.get(j); Element node = doc.createElement(columnName); node.appendChild(doc.createTextNode(strValue)); row.appendChild(node); } if (i == intLimitCnt) break; } DOMSource domSource = new DOMSource(doc); TransformerFactory tf = TransformerFactory.newInstance(); tf.setAttribute("indent-number", 4); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");//"ISO-8859-1"); StreamResult sr = new StreamResult(stWriter); transformer.transform(domSource, sr); return stWriter.toString(); }
From source file:com.hangum.tadpole.engine.sql.util.export.XMLExporter.java
/** * make content file//from www . j a v a 2 s .c om * * @param tableName * @param rsDAO * @return * @throws Exception */ public static String makeContentFile(String tableName, QueryExecuteResultDTO rsDAO) throws Exception { String strTmpDir = PublicTadpoleDefine.TEMP_DIR + tableName + System.currentTimeMillis() + PublicTadpoleDefine.DIR_SEPARATOR; String strFile = tableName + ".xml"; String strFullPath = strTmpDir + strFile; final StringWriter stWriter = new StringWriter(); final List<Map<Integer, Object>> dataList = rsDAO.getDataList().getData(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); final Document doc = builder.newDocument(); final Element results = doc.createElement(tableName); doc.appendChild(results); Map<Integer, String> mapLabelName = rsDAO.getColumnLabelName(); for (int i = 0; i < dataList.size(); i++) { Map<Integer, Object> mapColumns = dataList.get(i); Element row = doc.createElement("Row"); results.appendChild(row); for (int j = 1; j < mapColumns.size(); j++) { String columnName = mapLabelName.get(j); String strValue = mapColumns.get(j) == null ? "" : "" + mapColumns.get(j); Element node = doc.createElement(columnName); node.appendChild(doc.createTextNode(strValue)); row.appendChild(node); } } DOMSource domSource = new DOMSource(doc); TransformerFactory tf = TransformerFactory.newInstance(); tf.setAttribute("indent-number", 4); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");//"ISO-8859-1"); StreamResult sr = new StreamResult(stWriter); transformer.transform(domSource, sr); FileUtils.writeStringToFile(new File(strFullPath), stWriter.toString(), true); return strFullPath; }
From source file:Main.java
public static Element getElement(Document document, String[] path, String value, String translate, String module) {/* ww w . ja v a 2s. c o m*/ Node node = document; NodeList list; for (int i = 0; i < path.length; ++i) { list = node.getChildNodes(); boolean found = false; for (int j = 0; j < list.getLength(); ++j) { Node testNode = list.item(j); if (testNode.getNodeName().equals(path[i])) { found = true; node = testNode; break; } } if (found == false) { Element element = document.createElement(path[i]); node.appendChild(element); node = element; } } if (value != null) { Text text = document.createTextNode(value); list = node.getChildNodes(); boolean found = false; for (int j = 0; j < list.getLength(); ++j) { Node testNode = list.item(j); if (testNode instanceof Text) { node.replaceChild(text, testNode); found = true; break; } } if (!found) node.appendChild(text); } if (node instanceof Element) { Element element = (Element) node; if (translate != null && element.getAttribute("translate").equals("")) { element.setAttribute("translate", translate); } if (module != null && element.getAttribute("module").equals("")) { element.setAttribute("module", module); } } return (Element) node; }
From source file:Main.java
public static void exportXmlFile(ArrayList<?> listObject, String rootElement, String interfaceName, String pathSaveFile) {/*from www . j av a2 s .c o m*/ try { DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = builderFactory.newDocumentBuilder(); // creating a new instance of a DOM to build a DOM tree. Document doc = docBuilder.newDocument(); Element root = doc.createElement(rootElement); // adding a node after the last child node of the specified node. doc.appendChild(root); Element interfaceElement = null; Element child = null; Text text; for (Object obj : listObject) { Class srcClass = obj.getClass(); Field[] field = srcClass.getFields(); interfaceElement = doc.createElement(interfaceName); for (int i = 0; i < field.length; i++) { // System.out.println(field[i].getName() + ":" + // field[i].get(obj)); child = doc.createElement(field[i].getName()); text = doc.createTextNode((field[i].get(obj)).toString()); child.appendChild(text); interfaceElement.appendChild(child); } root.appendChild(interfaceElement); } // TransformerFactory instance is used to create Transformer // objects. TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // create string from xml tree StringWriter sw = new StringWriter(); StreamResult result = new StreamResult(sw); DOMSource source = new DOMSource(doc); transformer.transform(source, result); String xmlString = sw.toString(); File file = new File(pathSaveFile); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file))); bw.write(xmlString); bw.flush(); bw.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:ConfigFiles.java
public static void addTag(String tagname, String tagcontent, Element root, boolean blank, Document document) { Element rootElement = document.createElement(tagname); root.appendChild(rootElement);//ww w. j a va2 s . c o m String temp; if (blank) temp = ""; else temp = tagcontent; rootElement.appendChild(document.createTextNode(temp)); }
From source file:Main.java
private static Element copyNode(Document destDocument, Element dest, Element src) { NamedNodeMap namedNodeMap = src.getAttributes(); for (int i = 0; i < namedNodeMap.getLength(); i++) { Attr attr = (Attr) namedNodeMap.item(i); dest.setAttribute(attr.getName(), attr.getValue()); }/*from www . j ava 2s. c o m*/ NodeList childNodeList = src.getChildNodes(); for (int i = 0; i < childNodeList.getLength(); i++) { Node child = childNodeList.item(i); if (child.getNodeType() == Node.TEXT_NODE) { Text text = destDocument.createTextNode(child.getTextContent()); dest.appendChild(text); } else if (child.getNodeType() == Node.ELEMENT_NODE) { Element element = destDocument.createElement(((Element) child).getTagName()); element = copyNode(destDocument, element, (Element) child); dest.appendChild(element); } } return dest; }
From source file:main.java.vasolsim.common.GenericUtils.java
/** * Creates a text node within a created element and then attaches the date to a parent. * * @param elementName the name for the new element * @param nodeData the data for the new text node * @param parentElement the parent element * @param doc the document (root) *///w w w . j ava 2 s .c o m public static void appendSubNode(String elementName, String nodeData, Element parentElement, Document doc) { Element subElement = doc.createElement(elementName); subElement.appendChild(doc.createTextNode(nodeData)); parentElement.appendChild(subElement); }
From source file:com.viettel.ws.client.JDBCUtil.java
/** * Create document using DOM api/*from www .j a v a 2 s . com*/ * * @param rs a result set * @return A document of a result set * @throws ParserConfigurationException - If error when parse string * @throws SQLException - If error when read data from database */ public static Document toDocument(ResultSet rs) throws ParserConfigurationException, SQLException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setFeature(FEATURE_GENERAL_ENTITIES, false); factory.setFeature(FEATURE_PARAMETER_ENTITIES, false); factory.setXIncludeAware(false); factory.setExpandEntityReferences(false); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.newDocument(); Element results = doc.createElement("Results"); doc.appendChild(results); ResultSetMetaData rsmd = rs.getMetaData(); int colCount = rsmd.getColumnCount(); while (rs.next()) { Element row = doc.createElement("Row"); results.appendChild(row); for (int i = 1; i <= colCount; i++) { String columnName = rsmd.getColumnName(i); Object value = rs.getObject(i); Element node = doc.createElement(columnName); node.appendChild(doc.createTextNode(value.toString())); row.appendChild(node); } } return doc; }
From source file:com.meltmedia.cadmium.core.util.WarUtils.java
/** * Adds the shiro filter to a web.xml file. * @param doc The xml DOM document to create the new xml elements with. * @param root The xml Element node to add the filter to. *//*from ww w . ja v a2 s . c o m*/ public static void addFilter(Document doc, Element root) { Element filter = doc.createElement("filter"); Element filterName = doc.createElement("filter-name"); filterName.appendChild(doc.createTextNode("ShiroFilter")); filter.appendChild(filterName); Element filterClass = doc.createElement("filter-class"); filterClass.appendChild(doc.createTextNode("org.apache.shiro.web.servlet.ShiroFilter")); filter.appendChild(filterClass); addRelativeTo(root, filter, "filter", true); }