Example usage for org.w3c.dom Document appendChild

List of usage examples for org.w3c.dom Document appendChild

Introduction

In this page you can find the example usage for org.w3c.dom Document appendChild.

Prototype

public Node appendChild(Node newChild) throws DOMException;

Source Link

Document

Adds the node newChild to the end of the list of children of this node.

Usage

From source file:it.intecs.pisa.toolbox.util.URLReader.java

public static Document getDirectoryStructure(String url) throws Exception {
    Document urlTree = new DOMUtil().newDocument();
    Element rootNode = urlTree.createElement("urlContent");
    urlTree.appendChild(rootNode);
    try {/*from  w  w  w.j  av  a  2 s .  com*/
        getContent(url, urlTree, rootNode);
    } catch (Exception e) {
        e.printStackTrace(System.out);
        return null;
    }
    return urlTree;
}

From source file:Main.java

private static String trimNamespace(String xmlContent, String... except)
        throws ParserConfigurationException, TransformerException, SAXException, IOException {

    Document srcDoc = parse(xmlContent, CHARSET_UTF8);
    Document document = generate();

    List<String> exceptNamespaces = new ArrayList<String>();
    if (except != null) {
        exceptNamespaces = Arrays.asList(except);
    }/*w w  w .  ja va2 s  . co  m*/

    Element rootElement = (Element) copyNodeExceptNamespace(document, srcDoc.getDocumentElement(),
            new HashSet<String>(), exceptNamespaces);
    document.appendChild(rootElement);

    return write(document);
}

From source file:edu.kit.dama.mdm.content.util.DublinCoreHelper.java

/**
 * Create the Dublin Core document.//ww  w  . ja  v a2 s  .  c  om
 *
 * @param theObject The object to create the DC information for.
 * @param pCreator A custom creator stored as author/publisher in Dublin
 * Core. If not provided, the object's uploader is used if available.
 *
 * @return The Dublin Core Document.
 *
 * @throws ParserConfigurationException If creating the Dublin Core document
 * failed.
 */
public static Document createDublinCoreDocument(DigitalObject theObject, UserData pCreator)
        throws ParserConfigurationException {
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.newDocument();

    Element root = doc.createElementNS("http://www.openarchives.org/OAI/2.0/oai_dc/", "oai_dc:dc");
    root.setAttribute("xmlns:dc", "http://purl.org/dc/elements/1.1/");
    root.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
    root.setAttribute("xsi:schemaLocation",
            "http://www.openarchives.org/OAI/2.0/oai_dc/ http://www.openarchives.org/OAI/2.0/oai_dc.xsd");

    doc.appendChild(root);

    Element title = doc.createElementNS("http://purl.org/dc/elements/1.1/", "dc:title");
    title.setTextContent(StringEscapeUtils.escapeXml11(theObject.getLabel()));
    root.appendChild(title);

    if (pCreator != null) {
        Element creator = doc.createElementNS("http://purl.org/dc/elements/1.1/", "dc:creator");
        Element publisher = doc.createElementNS("http://purl.org/dc/elements/1.1/", "dc:publisher");
        creator.setTextContent(StringEscapeUtils.escapeXml11(pCreator.getFullname()));
        publisher.setTextContent(StringEscapeUtils.escapeXml11(pCreator.getFullname()));
        root.appendChild(creator);
        root.appendChild(publisher);
    } else if (theObject.getUploader() != null) {
        Element creator = doc.createElementNS("http://purl.org/dc/elements/1.1/", "dc:creator");
        Element publisher = doc.createElementNS("http://purl.org/dc/elements/1.1/", "dc:publisher");
        creator.setTextContent(StringEscapeUtils.escapeXml11(theObject.getUploader().getFullname()));
        publisher.setTextContent(StringEscapeUtils.escapeXml11(theObject.getUploader().getFullname()));
        root.appendChild(creator);
        root.appendChild(publisher);
    }

    for (UserData experimenter : theObject.getExperimenters()) {
        //don't list uploader a second time here
        if (theObject.getUploader() == null || !experimenter.equals(theObject.getUploader())) {
            Element contributor = doc.createElementNS("http://purl.org/dc/elements/1.1/", "dc:contributor");
            contributor.setTextContent(StringEscapeUtils.escapeXml11(experimenter.getFullname()));
            root.appendChild(contributor);
        }
    }

    if (theObject.getInvestigation() != null) {
        Element subject = doc.createElementNS("http://purl.org/dc/elements/1.1/", "dc:subject");
        subject.setTextContent(StringEscapeUtils.escapeXml11(theObject.getInvestigation().getTopic()));
        root.appendChild(subject);
        if (theObject.getInvestigation().getDescription() != null) {
            Element description = doc.createElementNS("http://purl.org/dc/elements/1.1/", "dc:description");
            description.setTextContent(
                    StringEscapeUtils.escapeXml11(theObject.getInvestigation().getDescription()));
            root.appendChild(description);
        }

        if (theObject.getInvestigation().getStudy() != null) {
            if (theObject.getInvestigation().getStudy().getLegalNote() != null) {
                Element rights = doc.createElementNS("http://purl.org/dc/elements/1.1/", "dc:rights");
                rights.setTextContent(
                        StringEscapeUtils.escapeXml11(theObject.getInvestigation().getStudy().getLegalNote()));
                root.appendChild(rights);
            }
        }
    }

    if (theObject.getStartDate() != null) {
        Element date = doc.createElementNS("http://purl.org/dc/elements/1.1/", "dc:date");
        date.setTextContent(df.format(theObject.getStartDate()));
        root.appendChild(date);
    }
    Element format = doc.createElementNS("http://purl.org/dc/elements/1.1/", "dc:format");
    format.setTextContent("application/octet-stream");
    root.appendChild(format);
    Element type = doc.createElementNS("http://purl.org/dc/elements/1.1/", "dc:type");
    type.setTextContent("Dataset");
    root.appendChild(type);
    Element identifier = doc.createElementNS("http://purl.org/dc/elements/1.1/", "dc:identifier");
    identifier.setTextContent(
            StringEscapeUtils.escapeXml11(theObject.getDigitalObjectId().getStringRepresentation()));
    root.appendChild(identifier);
    return doc;
}

From source file:com.eucalyptus.imaging.manifest.DownloadManifestFactory.java

/**
 * Generates download manifest based on bundle manifest and puts in into
 * system owned bucket/*  w w w  .java 2 s . 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:Main.java

/**
 * Append application specific tags into xml signature document
 * @param document//from   ww  w.  j av  a 2s .c  o  m
 * @return
 */
public static Document addUserInfoToSignature(Document document) {

    Element signature = document.getDocumentElement();

    // initially it has no root-element, ... so we create it:
    Element root = document.createElement("digital-signature");

    Element subjInfo = document.createElement("subject-information");
    subjInfo.appendChild(document.createElement("subject"));
    subjInfo.appendChild(document.createElement("date"));
    subjInfo.appendChild(document.createElement("time"));
    subjInfo.appendChild(document.createElement("timestamp"));

    root.appendChild(subjInfo);
    root.appendChild(signature);
    // we can add an element to a document only once,
    // the following calls will raise exceptions:
    document.appendChild(root);
    document.setXmlStandalone(true);

    return document;
}

From source file:com.microfocus.application.automation.tools.octane.executor.TestExecutionJobCreatorService.java

private static String prepareMtbxData(List<TestExecutionInfo> tests) throws IOException {
    /*<Mtbx>/*  w  w w.  j a  va  2  s .co  m*/
    <Test name="test1" path="${WORKSPACE}\${CHECKOUT_SUBDIR}\APITest1">
     <Parameter name="A" value="abc" type="string"/>
     <DataTable path="${WORKSPACE}\aa\bbb.xslx"/>
      .
     </Test>
     <Test name="test2" path="${WORKSPACE}\${CHECKOUT_SUBDIR}\test2">
    <Parameter name="p1" value="123" type="int"/>
    <Parameter name="p4" value="123.4" type="float"/>
     .
     </Test>
    </Mtbx>*/

    try {
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.newDocument();
        Element rootElement = doc.createElement("Mtbx");
        doc.appendChild(rootElement);

        for (TestExecutionInfo test : tests) {
            Element testElement = doc.createElement("Test");
            String packageAndTestName = (StringUtils.isNotEmpty(test.getPackageName())
                    ? test.getPackageName() + "\\"
                    : "") + test.getTestName();
            testElement.setAttribute("name", packageAndTestName);
            String path = "${WORKSPACE}\\${CHECKOUT_SUBDIR}"
                    + (StringUtils.isEmpty(test.getPackageName()) ? ""
                            : SdkConstants.FileSystem.WINDOWS_PATH_SPLITTER + test.getPackageName())
                    + SdkConstants.FileSystem.WINDOWS_PATH_SPLITTER + test.getTestName();
            testElement.setAttribute("path", path);

            if (StringUtils.isNotEmpty(test.getDataTable())) {
                Element dataTableElement = doc.createElement("DataTable");
                dataTableElement.setAttribute("path", "${WORKSPACE}\\${CHECKOUT_SUBDIR}"
                        + SdkConstants.FileSystem.WINDOWS_PATH_SPLITTER + test.getDataTable());
                testElement.appendChild(dataTableElement);
            }

            rootElement.appendChild(testElement);
        }

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

        StringWriter writer = new StringWriter();
        transformer.transform(new DOMSource(doc), new StreamResult(writer));

        return writer.toString();
    } catch (Exception e) {
        throw new IOException("Failed to build MTBX content : " + e.getMessage());
    }

}

From source file:de.mpg.escidoc.services.syndication.Utils.java

public static Document createDocument(Node sourceNode) throws Exception {
    Document doc = createDocumentBuilder().newDocument();
    Node source;/*from   ww w  . ja  v a2 s .c o  m*/
    if (sourceNode.getNodeType() == Node.DOCUMENT_NODE) {
        source = ((Document) sourceNode).getDocumentElement();
    } else {
        source = sourceNode;
    }

    Node node = doc.importNode(source, true);
    doc.appendChild(node);

    return doc;
}

From source file:com.zimbra.cs.service.AutoDiscoverServlet.java

private static String createResponseDoc(String displayName, String email, String serviceUrl) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);/*from w w  w  .  j a v  a 2s .  c o m*/
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document xmlDoc = builder.newDocument();

    Element root = xmlDoc.createElementNS(NS, "Autodiscover");
    root.setAttribute("xmlns", NS);
    root.setAttribute("xmlns:xsi", XSI_NS);
    root.setAttribute("xmlns:xsd", XSD_NS);
    xmlDoc.appendChild(root);

    //Add the response element.
    Element response = xmlDoc.createElementNS(NS_MOBILE, "Response");
    root.appendChild(response);

    //Add culture to to response
    Element culture = xmlDoc.createElement("Culture");
    culture.appendChild(xmlDoc.createTextNode("en:en"));
    response.appendChild(culture);

    //User
    Element user = xmlDoc.createElement("User");
    Element displayNameElm = xmlDoc.createElement("DisplayName");
    displayNameElm.appendChild(xmlDoc.createTextNode(displayName));
    user.appendChild(displayNameElm);
    Element emailAddr = xmlDoc.createElement("EMailAddress");
    emailAddr.appendChild(xmlDoc.createTextNode(email));
    user.appendChild(emailAddr);
    response.appendChild(user);

    //Action
    Element action = xmlDoc.createElement("Action");
    Element settings = xmlDoc.createElement("Settings");
    Element server = xmlDoc.createElement("Server");

    Element type = xmlDoc.createElement("Type");
    type.appendChild(xmlDoc.createTextNode("MobileSync"));
    server.appendChild(type);

    Element url = xmlDoc.createElement("Url");
    url.appendChild(xmlDoc.createTextNode(serviceUrl));
    server.appendChild(url);

    Element name = xmlDoc.createElement("Name");
    name.appendChild(xmlDoc.createTextNode(serviceUrl));
    server.appendChild(name);

    settings.appendChild(server);
    action.appendChild(settings);
    response.appendChild(action);

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    DOMSource source = new DOMSource(xmlDoc);
    StringWriter writer = new StringWriter();
    StreamResult result = new StreamResult(writer);
    transformer.transform(source, result);
    writer.flush();
    String xml = writer.toString();
    writer.close();

    //manually generate xmlns for Autodiscover and Response element, this works
    //for testexchangeconnectivity.com, but iOS and Android don't like Response's xmlns
    //        StringBuilder str = new StringBuilder();
    //        str.append("<?xml version=\"1.0\"?>\n");
    //        str.append("<Autodiscover xmlns:xsd=\"").append(XSD_NS).append("\"");
    //        str.append(" xmlns:xsi=\"").append(XSI_NS).append("\"");
    //        str.append(" xmlns=\"").append(NS).append("\">\n");
    //        int respIndex = xml.indexOf("<Response>");
    //        str.append("<Response xmlns=\"").append(NS_MOBILE).append("\">");
    //        str.append(xml.substring(respIndex + "<Response>".length(), xml.length()));
    //        return str.toString();
    return "<?xml version=\"1.0\"?>\n" + xml;
}

From source file:com.zimbra.cs.service.AutoDiscoverServlet.java

private static String createResponseDocForEws(String displayName, String email, String serviceUrl, Account acct)
        throws Exception {

    Provisioning prov = Provisioning.getInstance();
    Server server = prov.getServer(acct);

    String cn = server.getCn();//from  w  w w.  jav  a 2 s  .com
    String name = server.getName();
    String acctId = acct.getId();

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document xmlDoc = builder.newDocument();

    Element root = xmlDoc.createElementNS(NS, "Autodiscover");
    root.setAttribute("xmlns", NS);
    root.setAttribute("xmlns:xsi", XSI_NS);
    root.setAttribute("xmlns:xsd", XSD_NS);
    xmlDoc.appendChild(root);

    //Add the response element.
    Element response = xmlDoc.createElementNS(NS_OUTLOOK, "Response");
    root.appendChild(response);

    //User
    Element user = xmlDoc.createElement("User");
    Element displayNameElm = xmlDoc.createElement("DisplayName");
    displayNameElm.appendChild(xmlDoc.createTextNode(displayName));
    user.appendChild(displayNameElm);
    Element emailAddr = xmlDoc.createElement("EmailAddress");
    emailAddr.appendChild(xmlDoc.createTextNode(email));
    user.appendChild(emailAddr);

    Element depId = xmlDoc.createElement("DeploymentId");
    depId.appendChild(xmlDoc.createTextNode(acctId));
    user.appendChild(depId);

    response.appendChild(user);

    //Action
    Element account = xmlDoc.createElement("Account");
    Element acctType = xmlDoc.createElement("AccountType");
    acctType.appendChild(xmlDoc.createTextNode("email"));
    account.appendChild(acctType);
    response.appendChild(account);

    Element action = xmlDoc.createElement("Action");
    action.appendChild(xmlDoc.createTextNode("settings"));
    account.appendChild(action);

    Element protocol = xmlDoc.createElement("Protocol");
    account.appendChild(protocol);

    Element type = xmlDoc.createElement("Type");
    type.appendChild(xmlDoc.createTextNode("EXCH"));
    protocol.appendChild(type);

    Element ews = xmlDoc.createElement("EwsUrl");
    protocol.appendChild(ews);
    ews.appendChild(xmlDoc.createTextNode(serviceUrl));

    Element as = xmlDoc.createElement("ASUrl");
    protocol.appendChild(as);
    as.appendChild(xmlDoc.createTextNode(serviceUrl));

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    DOMSource source = new DOMSource(xmlDoc);
    StringWriter writer = new StringWriter();
    StreamResult result = new StreamResult(writer);
    transformer.transform(source, result);
    writer.flush();
    String xml = writer.toString();
    writer.close();
    return "<?xml version=\"1.0\"?>\n" + xml;
}

From source file:com.moviejukebox.writer.MovieJukeboxHTMLWriter.java

/**
 * Use an XSL file to generate the jukebox index file
 *
 * @param jukebox/*from w w  w . ja va 2s .c  om*/
 * @param library
 */
private static void generateTransformedIndexHTML(Jukebox jukebox, Library library) {
    LOG.debug("Generating Index file from jukebox-index.xsl");

    String homePage = PropertiesUtil.getProperty("mjb.homePage", "");
    if (StringUtils.isBlank(homePage)) {
        String defCat = library.getDefaultCategory();
        if (defCat != null) {
            homePage = FileTools.createPrefix("Other", HTMLTools.encodeUrl(FileTools.makeSafeFilename(defCat)))
                    + "1";
        } else {
            // figure out something better to do here
            LOG.info("No categories were found, so you should specify mjb.homePage in the config file.");
        }
    }

    try {
        // Create the index.xml file with some properties in it.
        File indexXmlFile = new File(jukebox.getJukeboxTempLocation(), "index.xml");
        FileTools.makeDirsForFile(indexXmlFile);

        Document docIndex = DOMHelper.createDocument();
        Element eRoot = docIndex.createElement("index");
        docIndex.appendChild(eRoot);

        DOMHelper.appendChild(docIndex, eRoot, "detailsDirName", jukebox.getDetailsDirName());
        DOMHelper.appendChild(docIndex, eRoot, "homePage", homePage);

        DOMHelper.writeDocumentToFile(docIndex, indexXmlFile);

        // Now generate the HTML from the XLST
        File htmlFile = new File(jukebox.getJukeboxTempLocation(),
                PropertiesUtil.getProperty("mjb.indexFile", "index.htm"));
        FileTools.addJukeboxFile(indexXmlFile.getName());
        FileTools.addJukeboxFile(htmlFile.getName());

        Transformer transformer = getTransformer(new File(SKIN_HOME, "jukebox-index.xsl"),
                jukebox.getJukeboxTempLocation());

        Source xmlSource = new StreamSource(indexXmlFile);
        Result xmlResult = new StreamResult(htmlFile);

        doTransform(transformer, xmlSource, xmlResult, "Jukebox index");
    } catch (ParserConfigurationException | RuntimeException ex) {
        LOG.error("Failed generating jukebox index: {}", ex.getMessage());
        LOG.error(SystemTools.getStackTrace(ex));
    }
}