List of usage examples for org.w3c.dom Element setAttribute
public void setAttribute(String name, String value) throws DOMException;
From source file:com.msopentech.odatajclient.engine.data.ODataBinder.java
private static Element toCollectionPropertyElement(final ODataProperty prop, final Document doc, final boolean setType) { if (!prop.hasCollectionValue()) { throw new IllegalArgumentException( "Invalid property value type " + prop.getValue().getClass().getSimpleName()); }//from w w w . ja va 2s. co m final ODataCollectionValue value = prop.getCollectionValue(); final Element element = doc.createElement(ODataConstants.PREFIX_DATASERVICES + prop.getName()); if (value.getTypeName() != null && setType) { element.setAttribute(ODataConstants.ATTR_M_TYPE, value.getTypeName()); } for (ODataValue el : value) { if (el.isPrimitive()) { element.appendChild( toPrimitivePropertyElement(ODataConstants.ELEM_ELEMENT, el.asPrimitive(), doc, setType)); } else { element.appendChild( toComplexPropertyElement(ODataConstants.ELEM_ELEMENT, el.asComplex(), doc, setType)); } } return element; }
From source file:net.sourceforge.dita4publishers.word2dita.Word2DitaValidationHelper.java
/** * @param zipComponents//from w w w . ja v a 2 s . c o m * @param bosOptions * @throws Exception */ public static void addCommentFileContentType(ZipComponents zipComponents, BosConstructionOptions bosOptions) throws Exception { /* * <Override PartName="/word/comments.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml"/> */ ZipComponent comp = zipComponents.getEntry("[Content_Types].xml"); Document doc = zipComponents.getDomForZipComponent(bosOptions, comp); Element docElem = doc.getDocumentElement(); String contentTypesNs = "http://schemas.openxmlformats.org/package/2006/content-types"; NodeList nl = docElem.getElementsByTagNameNS(contentTypesNs, "Override"); boolean foundCommentType = false; for (int i = 0; i < nl.getLength(); i++) { Element elem = (Element) nl.item(i); String partName = elem.getAttribute("PartName"); if (DocxConstants.COMMENTS_PARTNAME.equals(partName)) { foundCommentType = true; break; } } if (!foundCommentType) { Element elem = doc.createElementNS(contentTypesNs, "Override"); elem.setAttribute("PartName", DocxConstants.COMMENTS_PARTNAME); elem.setAttribute("ContentType", DocxConstants.COMMENTS_CONTENT_TYPE); docElem.appendChild(elem); comp.setDom(doc); } }
From source file:eu.semaine.util.XMLTool.java
/** * Create a new document with the given name and namespace for the root element, * and set the 'version' attribute of the root element to the given value. * @param rootTagname//from ww w .j a v a 2 s.c om * @param namespace the namespace URI, e.g. <code>http://www.w3.org/2003/04/emma</code>, * or null if no namespace is to be associated with the new element. * @param version a value to add to the 'version' attribute of the root element * @return */ public static Document newDocument(String rootTagname, String namespace, String version) { Document doc = newDocument(rootTagname, namespace); Element root = doc.getDocumentElement(); root.setAttribute("version", version); return doc; }
From source file:com.centeractive.ws.SchemaUtils.java
/** * Returns a map mapping urls to corresponding XmlSchema XmlObjects for the * specified wsdlUrl// ww w . j a v a 2s. com */ public static void getSchemas(String wsdlUrl, Map<String, XmlObject> existing, SchemaLoader loader, String tns, String xml) { if (existing.containsKey(wsdlUrl)) { return; } log.debug("Getting schema " + wsdlUrl); ArrayList<?> errorList = new ArrayList<Object>(); Map<String, XmlObject> result = new HashMap<String, XmlObject>(); boolean common = false; try { XmlOptions options = new XmlOptions(); options.setCompileNoValidation(); options.setSaveUseOpenFrag(); options.setErrorListener(errorList); options.setSaveSyntheticDocumentElement(new QName(Constants.XSD_NS, "schema")); XmlObject xmlObject = loader.loadXmlObject(xml); if (xmlObject == null) throw new Exception("Failed to load schema from [" + wsdlUrl + "]"); Document dom = (Document) xmlObject.getDomNode(); Node domNode = dom.getDocumentElement(); // is this an xml schema? if (domNode.getLocalName().equals("schema") && Constants.XSD_NS.equals(domNode.getNamespaceURI())) { // set targetNamespace (this happens if we are following an include // statement) if (tns != null) { Element elm = ((Element) domNode); if (!elm.hasAttribute("targetNamespace")) { common = true; elm.setAttribute("targetNamespace", tns); } // check for namespace prefix for targetNamespace NamedNodeMap attributes = elm.getAttributes(); int c = 0; for (; c < attributes.getLength(); c++) { Node item = attributes.item(c); if (item.getNodeName().equals("xmlns")) break; if (item.getNodeValue().equals(tns) && item.getNodeName().startsWith("xmlns")) break; } if (c == attributes.getLength()) elm.setAttribute("xmlns", tns); } if (common && !existing.containsKey(wsdlUrl + "@" + tns)) result.put(wsdlUrl + "@" + tns, xmlObject); else result.put(wsdlUrl, xmlObject); } else { existing.put(wsdlUrl, null); XmlObject[] schemas = xmlObject .selectPath("declare namespace s='" + Constants.XSD_NS + "' .//s:schema"); for (int i = 0; i < schemas.length; i++) { XmlCursor xmlCursor = schemas[i].newCursor(); String xmlText = xmlCursor.getObject().xmlText(options); // schemas[i] = XmlObject.Factory.parse( xmlText, options ); schemas[i] = XmlUtils.createXmlObject(xmlText, options); schemas[i].documentProperties().setSourceName(wsdlUrl); result.put(wsdlUrl + "@" + (i + 1), schemas[i]); } XmlObject[] wsdlImports = xmlObject .selectPath("declare namespace s='" + Constants.WSDL11_NS + "' .//s:import/@location"); for (int i = 0; i < wsdlImports.length; i++) { String location = ((SimpleValue) wsdlImports[i]).getStringValue(); if (location != null) { if (!location.startsWith("file:") && location.indexOf("://") == -1) location = joinRelativeUrl(wsdlUrl, location); getSchemas(location, existing, loader, null, xml); } } XmlObject[] wadl10Imports = xmlObject.selectPath( "declare namespace s='" + Constants.WADL10_NS + "' .//s:grammars/s:include/@href"); for (int i = 0; i < wadl10Imports.length; i++) { String location = ((SimpleValue) wadl10Imports[i]).getStringValue(); if (location != null) { if (!location.startsWith("file:") && location.indexOf("://") == -1) location = joinRelativeUrl(wsdlUrl, location); getSchemas(location, existing, loader, null, xml); } } XmlObject[] wadlImports = xmlObject.selectPath( "declare namespace s='" + Constants.WADL11_NS + "' .//s:grammars/s:include/@href"); for (int i = 0; i < wadlImports.length; i++) { String location = ((SimpleValue) wadlImports[i]).getStringValue(); if (location != null) { if (!location.startsWith("file:") && location.indexOf("://") == -1) location = joinRelativeUrl(wsdlUrl, location); getSchemas(location, existing, loader, null, xml); } } } existing.putAll(result); XmlObject[] schemas = result.values().toArray(new XmlObject[result.size()]); for (int c = 0; c < schemas.length; c++) { xmlObject = schemas[c]; XmlObject[] schemaImports = xmlObject .selectPath("declare namespace s='" + Constants.XSD_NS + "' .//s:import/@schemaLocation"); for (int i = 0; i < schemaImports.length; i++) { String location = ((SimpleValue) schemaImports[i]).getStringValue(); Element elm = ((Attr) schemaImports[i].getDomNode()).getOwnerElement(); if (location != null && !defaultSchemas.containsKey(elm.getAttribute("namespace"))) { if (!location.startsWith("file:") && location.indexOf("://") == -1) location = joinRelativeUrl(wsdlUrl, location); getSchemas(location, existing, loader, null, xml); } } XmlObject[] schemaIncludes = xmlObject .selectPath("declare namespace s='" + Constants.XSD_NS + "' .//s:include/@schemaLocation"); for (int i = 0; i < schemaIncludes.length; i++) { String location = ((SimpleValue) schemaIncludes[i]).getStringValue(); if (location != null) { String targetNS = getTargetNamespace(xmlObject); if (!location.startsWith("file:") && location.indexOf("://") == -1) location = joinRelativeUrl(wsdlUrl, location); getSchemas(location, existing, loader, targetNS, xml); } } } } catch (Exception e) { throw new SoapBuilderException(e); } }
From source file:com.example.soaplegacy.SchemaUtils.java
/** * Returns a map mapping urls to corresponding XmlSchema XmlObjects for the * specified wsdlUrl//from w ww .j av a 2s. co m */ public static void getSchemas(String wsdlUrl, Map<String, XmlObject> existing, SchemaLoader loader, String tns) { if (existing.containsKey(wsdlUrl)) { return; } log.debug("Getting schema " + wsdlUrl); ArrayList<?> errorList = new ArrayList<Object>(); Map<String, XmlObject> result = new HashMap<String, XmlObject>(); boolean common = false; try { XmlOptions options = new XmlOptions(); options.setCompileNoValidation(); options.setSaveUseOpenFrag(); options.setErrorListener(errorList); options.setSaveSyntheticDocumentElement(new QName(Constants.XSD_NS, "schema")); XmlObject xmlObject = loader.loadXmlObject(wsdlUrl, options); if (xmlObject == null) throw new Exception("Failed to load schema from [" + wsdlUrl + "]"); Document dom = (Document) xmlObject.getDomNode(); Node domNode = dom.getDocumentElement(); // is this an xml schema? if (domNode.getLocalName().equals("schema") && Constants.XSD_NS.equals(domNode.getNamespaceURI())) { // set targetNamespace (this happens if we are following an include // statement) if (tns != null) { Element elm = ((Element) domNode); if (!elm.hasAttribute("targetNamespace")) { common = true; elm.setAttribute("targetNamespace", tns); } // check for namespace prefix for targetNamespace NamedNodeMap attributes = elm.getAttributes(); int c = 0; for (; c < attributes.getLength(); c++) { Node item = attributes.item(c); if (item.getNodeName().equals("xmlns")) break; if (item.getNodeValue().equals(tns) && item.getNodeName().startsWith("xmlns")) break; } if (c == attributes.getLength()) elm.setAttribute("xmlns", tns); } if (common && !existing.containsKey(wsdlUrl + "@" + tns)) result.put(wsdlUrl + "@" + tns, xmlObject); else result.put(wsdlUrl, xmlObject); } else { existing.put(wsdlUrl, null); XmlObject[] schemas = xmlObject .selectPath("declare namespace s='" + Constants.XSD_NS + "' .//s:schema"); for (int i = 0; i < schemas.length; i++) { XmlCursor xmlCursor = schemas[i].newCursor(); String xmlText = xmlCursor.getObject().xmlText(options); // schemas[i] = XmlObject.Factory.parse( xmlText, options ); schemas[i] = XmlUtils.createXmlObject(xmlText, options); schemas[i].documentProperties().setSourceName(wsdlUrl); result.put(wsdlUrl + "@" + (i + 1), schemas[i]); } XmlObject[] wsdlImports = xmlObject .selectPath("declare namespace s='" + Constants.WSDL11_NS + "' .//s:import/@location"); for (int i = 0; i < wsdlImports.length; i++) { String location = ((SimpleValue) wsdlImports[i]).getStringValue(); if (location != null) { if (!location.startsWith("file:") && location.indexOf("://") == -1) location = joinRelativeUrl(wsdlUrl, location); getSchemas(location, existing, loader, null); } } XmlObject[] wadl10Imports = xmlObject.selectPath( "declare namespace s='" + Constants.WADL10_NS + "' .//s:grammars/s:include/@href"); for (int i = 0; i < wadl10Imports.length; i++) { String location = ((SimpleValue) wadl10Imports[i]).getStringValue(); if (location != null) { if (!location.startsWith("file:") && location.indexOf("://") == -1) location = joinRelativeUrl(wsdlUrl, location); getSchemas(location, existing, loader, null); } } XmlObject[] wadlImports = xmlObject.selectPath( "declare namespace s='" + Constants.WADL11_NS + "' .//s:grammars/s:include/@href"); for (int i = 0; i < wadlImports.length; i++) { String location = ((SimpleValue) wadlImports[i]).getStringValue(); if (location != null) { if (!location.startsWith("file:") && location.indexOf("://") == -1) location = joinRelativeUrl(wsdlUrl, location); getSchemas(location, existing, loader, null); } } } existing.putAll(result); XmlObject[] schemas = result.values().toArray(new XmlObject[result.size()]); for (int c = 0; c < schemas.length; c++) { xmlObject = schemas[c]; XmlObject[] schemaImports = xmlObject .selectPath("declare namespace s='" + Constants.XSD_NS + "' .//s:import/@schemaLocation"); for (int i = 0; i < schemaImports.length; i++) { String location = ((SimpleValue) schemaImports[i]).getStringValue(); Element elm = ((Attr) schemaImports[i].getDomNode()).getOwnerElement(); if (location != null && !defaultSchemas.containsKey(elm.getAttribute("namespace"))) { if (!location.startsWith("file:") && location.indexOf("://") == -1) location = joinRelativeUrl(wsdlUrl, location); getSchemas(location, existing, loader, null); } } XmlObject[] schemaIncludes = xmlObject .selectPath("declare namespace s='" + Constants.XSD_NS + "' .//s:include/@schemaLocation"); for (int i = 0; i < schemaIncludes.length; i++) { String location = ((SimpleValue) schemaIncludes[i]).getStringValue(); if (location != null) { String targetNS = getTargetNamespace(xmlObject); if (!location.startsWith("file:") && location.indexOf("://") == -1) location = joinRelativeUrl(wsdlUrl, location); getSchemas(location, existing, loader, targetNS); } } } } catch (Exception e) { throw new SoapBuilderException(e); } }
From source file:com.icesoft.faces.renderkit.dom_html_basic.DomBasicRenderer.java
/** * Set the id of the root element of the DOMContext associated with the * UIComponent parameter.// w ww . j ava2 s .co m * * @param facesContext * @param rootElement * @param uiComponent */ public static void setRootElementId(FacesContext facesContext, Element rootElement, UIComponent uiComponent) { if (idNotNull(uiComponent)) { rootElement.setAttribute("id", uiComponent.getClientId(facesContext)); rootElement.setIdAttribute("id", true); } }
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 v a 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:org.openmrs.module.atomfeed.AtomFeedUtil.java
/** * Updates content of atom feed header file by re-creating new xml header block and writing it * into given file. Actually, if given atom feed header file does not exists, it creates it. * Otherwise, it changes values of "updated", "versionId" and "entriesSize" elements within * header xml tree./*from w w w. jav a2 s. c o m*/ * * @param atomfeedheader the file target to be updated * @param entriesSize the size in bytes of entries payload, which is related to given feed * header */ private static void updateFeedFileHeader(File atomfeedheader, long entriesSize) { try { // We need a Document DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); Document doc = docBuilder.newDocument(); // ////////////////////// // Creating the XML tree // create the root element and add it to the document Element root = doc.createElement("feed"); root.setAttribute("xmlns", "http://www.w3.org/2005/Atom"); doc.appendChild(root); // create title element, add its text, and add to root Element title = doc.createElement("title"); Text titleText = doc.createTextNode(AtomFeedConstants.ATOM_FEED_TITLE); title.appendChild(titleText); root.appendChild(title); // create title element, add its attrs, and add to root Element selflink = doc.createElement("link"); selflink.setAttribute("href", AtomFeedUtil.getFeedUrl()); selflink.setAttribute("rel", "self"); root.appendChild(selflink); Element serverlink = doc.createElement("link"); serverlink.setAttribute("href", getWebServiceUrl()); root.appendChild(serverlink); // create title element, add its text, and add to root Element id = doc.createElement("id"); Text idText = doc.createTextNode(AtomFeedConstants.ATOM_FEED_ID); id.appendChild(idText); root.appendChild(id); // create updated element, add its text, and add to root Element updated = doc.createElement("updated"); Date lastModified = new Date(); Text updatedText = doc.createTextNode(dateToRFC3339(lastModified)); updated.appendChild(updatedText); root.appendChild(updated); // create versionId element, add its text, and add to root Element versionId = doc.createElement("versionId"); Text versionIdText = doc.createTextNode(String.valueOf(lastModified.getTime())); versionId.appendChild(versionIdText); root.appendChild(versionId); // create versionId element, add its text, and add to root Element entriesSizeElement = doc.createElement("entriesSize"); Text entriesSizeText = doc.createTextNode(String.valueOf(entriesSize)); entriesSizeElement.appendChild(entriesSizeText); root.appendChild(entriesSizeElement); /* * Print the xml to the file */ // set up a transformer TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans = transfac.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); trans.setOutputProperty(OutputKeys.INDENT, "no"); // create string from xml tree FileWriter fw = new FileWriter(atomfeedheader); StreamResult result = new StreamResult(fw); DOMSource source = new DOMSource(doc); trans.transform(source, result); // print xml for debugging purposes if (log.isTraceEnabled()) { StringWriter sw = new StringWriter(); result = new StreamResult(sw); trans.transform(source, result); log.trace("Here's the initial xml:\n\n" + sw.toString()); } } catch (Exception e) { log.error("unable to initialize feed at: " + atomfeedheader.getAbsolutePath(), e); } }
From source file:org.openmrs.module.atomfeed.AtomFeedUtil.java
/** * Converts the given object to an xml entry * //from ww w . ja va2 s .com * @param action what is happenening * @param object the object being changed * @return atom feed xml entry string * @should return valid entry xml data */ protected static String getEntry(String action, OpenmrsObject object) { try { // We need a Document DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); Document doc = docBuilder.newDocument(); // ////////////////////// // Creating the XML tree // create the root element and add it to the document Element root = doc.createElement("entry"); doc.appendChild(root); // the title element is REQUIRED // create title element, add object class, and add to root Element title = doc.createElement("title"); Text titleText = doc.createTextNode(action + ":" + object.getClass().getName()); title.appendChild(titleText); root.appendChild(title); // create link to view object details Element link = doc.createElement("link"); link.setAttribute("href", AtomFeedUtil.getViewUrl(object)); root.appendChild(link); // the id element is REQUIRED // create id element Element id = doc.createElement("id"); Text idText = doc.createTextNode("urn:uuid:" + object.getUuid()); id.appendChild(idText); root.appendChild(id); // the updated element is REQUIRED // create updated element, set current date Element updated = doc.createElement("updated"); // TODO: try to discover dateChanged/dateCreated from object -- ATOM-2 // instead? Text updatedText = doc.createTextNode(dateToRFC3339(getUpdatedValue(object))); updated.appendChild(updatedText); root.appendChild(updated); // the author element is REQUIRED // add author element, find creator Element author = doc.createElement("author"); Element name = doc.createElement("name"); Text nameText = doc.createTextNode(getAuthor(object)); name.appendChild(nameText); author.appendChild(name); root.appendChild(author); // the summary element is REQUIRED // add a summary Element summary = doc.createElement("summary"); Text summaryText = doc.createTextNode(object.getClass().getSimpleName() + " -- " + action); summary.appendChild(summaryText); root.appendChild(summary); Element classname = doc.createElement("classname"); Text classnameText = doc.createTextNode(object.getClass().getName()); classname.appendChild(classnameText); root.appendChild(classname); Element actionElement = doc.createElement("action"); Text actionText = doc.createTextNode(action); actionElement.appendChild(actionText); root.appendChild(actionElement); /* * Print the xml to the string */ // set up a transformer TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans = transfac.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); trans.setOutputProperty(OutputKeys.INDENT, "no"); StringWriter sw = new StringWriter(); StreamResult result = new StreamResult(sw); DOMSource source = new DOMSource(doc); trans.transform(source, result); return sw.toString(); } catch (Exception e) { log.error("unable to create entry string for: " + object); return ""; } }
From source file:com.ibm.soatf.component.soap.builder.SchemaUtils.java
/** * Returns a map mapping urls to corresponding XmlSchema XmlObjects for the * specified wsdlUrl/*ww w .j ava 2 s. c o m*/ */ public static void getSchemas(final String wsdlUrl, Map<String, XmlObject> existing, SchemaLoader loader, String tns) { if (existing.containsKey(wsdlUrl)) { return; } log.debug("Getting schema " + wsdlUrl); ArrayList<?> errorList = new ArrayList<>(); Map<String, XmlObject> result = new HashMap<>(); boolean common = false; try { XmlOptions options = new XmlOptions(); options.setCompileNoValidation(); options.setSaveUseOpenFrag(); options.setErrorListener(errorList); options.setSaveSyntheticDocumentElement(new QName(Constants.XSD_NS, "schema")); XmlObject xmlObject = loader.loadXmlObject(wsdlUrl, options); if (xmlObject == null) throw new Exception("Failed to load schema from [" + wsdlUrl + "]"); Document dom = (Document) xmlObject.getDomNode(); Node domNode = dom.getDocumentElement(); // is this an xml schema? if (domNode.getLocalName().equals("schema") && Constants.XSD_NS.equals(domNode.getNamespaceURI())) { // set targetNamespace (this happens if we are following an include // statement) if (tns != null) { Element elm = ((Element) domNode); if (!elm.hasAttribute("targetNamespace")) { common = true; elm.setAttribute("targetNamespace", tns); } // check for namespace prefix for targetNamespace NamedNodeMap attributes = elm.getAttributes(); int c = 0; for (; c < attributes.getLength(); c++) { Node item = attributes.item(c); if (item.getNodeName().equals("xmlns")) break; if (item.getNodeValue().equals(tns) && item.getNodeName().startsWith("xmlns")) break; } if (c == attributes.getLength()) elm.setAttribute("xmlns", tns); } if (common && !existing.containsKey(wsdlUrl + "@" + tns)) result.put(wsdlUrl + "@" + tns, xmlObject); else result.put(wsdlUrl, xmlObject); } else { existing.put(wsdlUrl, null); XmlObject[] schemas = xmlObject .selectPath("declare namespace s='" + Constants.XSD_NS + "' .//s:schema"); for (int i = 0; i < schemas.length; i++) { XmlCursor xmlCursor = schemas[i].newCursor(); String xmlText = xmlCursor.getObject().xmlText(options); // schemas[i] = XmlObject.Factory.parse( xmlText, options ); schemas[i] = XmlUtils.createXmlObject(xmlText, options); schemas[i].documentProperties().setSourceName(wsdlUrl); result.put(wsdlUrl + "@" + (i + 1), schemas[i]); } XmlObject[] wsdlImports = xmlObject .selectPath("declare namespace s='" + Constants.WSDL11_NS + "' .//s:import/@location"); for (int i = 0; i < wsdlImports.length; i++) { String location = ((SimpleValue) wsdlImports[i]).getStringValue(); if (location != null) { if (!location.startsWith("file:") && location.indexOf("://") == -1) location = joinRelativeUrl(wsdlUrl, location); getSchemas(location, existing, loader, null); } } XmlObject[] wadl10Imports = xmlObject.selectPath( "declare namespace s='" + Constants.WADL10_NS + "' .//s:grammars/s:include/@href"); for (int i = 0; i < wadl10Imports.length; i++) { String location = ((SimpleValue) wadl10Imports[i]).getStringValue(); if (location != null) { if (!location.startsWith("file:") && location.indexOf("://") == -1) location = joinRelativeUrl(wsdlUrl, location); getSchemas(location, existing, loader, null); } } XmlObject[] wadlImports = xmlObject.selectPath( "declare namespace s='" + Constants.WADL11_NS + "' .//s:grammars/s:include/@href"); for (int i = 0; i < wadlImports.length; i++) { String location = ((SimpleValue) wadlImports[i]).getStringValue(); if (location != null) { if (!location.startsWith("file:") && location.indexOf("://") == -1) location = joinRelativeUrl(wsdlUrl, location); getSchemas(location, existing, loader, null); } } } existing.putAll(result); XmlObject[] schemas = result.values().toArray(new XmlObject[result.size()]); for (int c = 0; c < schemas.length; c++) { xmlObject = schemas[c]; XmlObject[] schemaImports = xmlObject .selectPath("declare namespace s='" + Constants.XSD_NS + "' .//s:import/@schemaLocation"); for (int i = 0; i < schemaImports.length; i++) { String location = ((SimpleValue) schemaImports[i]).getStringValue(); Element elm = ((Attr) schemaImports[i].getDomNode()).getOwnerElement(); if (location != null && !defaultSchemas.containsKey(elm.getAttribute("namespace"))) { if (!location.startsWith("file:") && location.indexOf("://") == -1) location = joinRelativeUrl(wsdlUrl, location); getSchemas(location, existing, loader, null); } } XmlObject[] schemaIncludes = xmlObject .selectPath("declare namespace s='" + Constants.XSD_NS + "' .//s:include/@schemaLocation"); for (int i = 0; i < schemaIncludes.length; i++) { String location = ((SimpleValue) schemaIncludes[i]).getStringValue(); if (location != null) { String targetNS = getTargetNamespace(xmlObject); if (!location.startsWith("file:") && location.indexOf("://") == -1) location = joinRelativeUrl(wsdlUrl, location); getSchemas(location, existing, loader, targetNS); } } } } catch (Exception e) { throw new SoapBuilderException(e); } }