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:fi.helsinki.lib.simplerest.CollectionsResource.java

@Get("xml")
public Representation toXml() {
    Context c = null;/*from w  w w .j a  va2  s  .com*/
    Community community = null;
    DomRepresentation representation = null;
    Document d = null;
    try {
        c = new Context();
        community = Community.find(c, this.communityId);
        if (community == null) {
            return errorNotFound(c, "Could not find the community.");
        }

        representation = new DomRepresentation(MediaType.TEXT_HTML);
        d = representation.getDocument();
    } catch (Exception e) {
        return errorInternal(c, e.toString());
    }

    Element html = d.createElement("html");
    d.appendChild(html);

    Element head = d.createElement("head");
    html.appendChild(head);

    Element title = d.createElement("title");
    head.appendChild(title);
    title.appendChild(d.createTextNode("Community " + community.getName()));

    Element body = d.createElement("body");
    html.appendChild(body);

    Collection[] collections;
    try {
        collections = community.getCollections();
    } catch (SQLException e) {
        return errorInternal(c, e.toString());
    }

    String url = getRequest().getResourceRef().getIdentifier();
    url = url.substring(0, url.lastIndexOf('/', url.lastIndexOf('/', url.lastIndexOf('/') - 1) - 1));
    url += "/collection/";

    Element ulCollections = d.createElement("ul");
    setId(ulCollections, "collections");
    body.appendChild(ulCollections);
    for (Collection collection : collections) {
        Element li = d.createElement("li");
        Element a = d.createElement("a");
        String href = url + Integer.toString(collection.getID());
        setAttribute(a, "href", href);
        a.appendChild(d.createTextNode(collection.getName()));
        li.appendChild(a);
        ulCollections.appendChild(li);
    }

    Element form = d.createElement("form");
    form.setAttribute("enctype", "multipart/form-data");
    form.setAttribute("method", "post");
    makeInputRow(d, form, "name", "Name");
    makeInputRow(d, form, "short_description", "Short description");
    makeInputRow(d, form, "introductory_text", "Introductory text");
    makeInputRow(d, form, "copyright_text", "Copyright text");
    makeInputRow(d, form, "side_bar_text", "Side bar text");
    makeInputRow(d, form, "provenance_description", "Provenance Description");
    makeInputRow(d, form, "license", "License");
    makeInputRow(d, form, "logo", "Logo", "file");

    Element submitButton = d.createElement("input");
    submitButton.setAttribute("type", "submit");
    submitButton.setAttribute("value", "Create a new collection");
    form.appendChild(submitButton);

    body.appendChild(form);

    c.abort(); // Same as c.complete() because we didn't modify the db.

    return representation;
}

From source file:gool.generator.xml.XmlCodePrinter.java

@Override
public List<File> print(ClassDef pclass) throws FileNotFoundException {
    Document document = null;
    DocumentBuilderFactory fabrique = null;
    List<File> result = new ArrayList<File>();
    // Debugging info
    // nbNode = 0;

    try {//w ww. ja va 2 s  .c  o m
        // creat document structure
        fabrique = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = fabrique.newDocumentBuilder();
        document = builder.newDocument();
        Element racine = (Element) document.createElement("file");
        Element el = NodeToElement(pclass, document);
        if (el != null)
            racine.appendChild(el);
        document.appendChild(racine);

        // file separator is just a slash in Unix
        // so the second argument to File() is just the directory
        // that corresponds to the package name
        // the first argument is the default output directory of the
        // platform
        // so the directory name ends up being something like
        // GOOLOUPTUTTARGET/pack/age
        File dir = new File(getOutputDir().getAbsolutePath(),
                StringUtils.replace(pclass.getPackageName(), ".", File.separator));
        // Typically the outputdir was created before, but not the package
        // subdirs
        dir.mkdirs();
        // Create the file for the class, fill it in, close it
        File classFile = new File(dir, getFileName(pclass.getName()));
        Log.i(String.format("Writing to file %s", classFile));

        // Create formating output
        OutputFormat format = new OutputFormat(document);
        format.setEncoding("UTF-8");
        format.setLineWidth(80);
        format.setIndenting(true);
        format.setIndent(4);

        // save to output file
        Writer out = new PrintWriter(classFile);
        XMLSerializer serializer = new XMLSerializer(out, format);
        serializer.serialize(document);

        // Remember that you did the generation for this one abstract GOOL
        // class
        printedClasses.add(pclass);
        result.add(classFile);
        classdefok = true;
    } catch (Exception e) {
        Log.e(e);
        System.exit(1);
    }

    return result;
}

From source file:com.microsoft.windowsazure.management.scheduler.CloudServiceManagementClientImpl.java

/**
* EntitleResource is used only for 3rd party Store providers. Each
* subscription must be entitled for the resource before creating that
* particular type of resource./* www. j  a  v  a  2  s  .co m*/
*
* @param parameters Required. Parameters provided to the EntitleResource
* method.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return A standard service response including an HTTP status code and
* request ID.
*/
@Override
public OperationResponse entitleResource(EntitleResourceParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getResourceNamespace() == null) {
        throw new NullPointerException("parameters.ResourceNamespace");
    }
    if (parameters.getResourceType() == null) {
        throw new NullPointerException("parameters.ResourceType");
    }

    // Tracing
    boolean shouldTrace = CloudTracing.getIsEnabled();
    String invocationId = null;
    if (shouldTrace) {
        invocationId = Long.toString(CloudTracing.getNextInvocationId());
        HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "entitleResourceAsync", tracingParameters);
    }

    // Construct URL
    String url = "";
    if (this.getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/EntitleResource";
    String baseUrl = this.getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

    // Create HTTP transport objects
    HttpPost httpRequest = new HttpPost(url);

    // Set Headers
    httpRequest.setHeader("Content-Type", "application/xml");
    httpRequest.setHeader("x-ms-version", "2013-03-01");

    // Serialize Request
    String requestContent = null;
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document requestDoc = documentBuilder.newDocument();

    Element entitleResourceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "EntitleResource");
    requestDoc.appendChild(entitleResourceElement);

    Element resourceProviderNameSpaceElement = requestDoc
            .createElementNS("http://schemas.microsoft.com/windowsazure", "ResourceProviderNameSpace");
    resourceProviderNameSpaceElement.appendChild(requestDoc.createTextNode(parameters.getResourceNamespace()));
    entitleResourceElement.appendChild(resourceProviderNameSpaceElement);

    Element typeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Type");
    typeElement.appendChild(requestDoc.createTextNode(parameters.getResourceType()));
    entitleResourceElement.appendChild(typeElement);

    Element registrationDateElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "RegistrationDate");
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
    simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    registrationDateElement.appendChild(
            requestDoc.createTextNode(simpleDateFormat.format(parameters.getRegistrationDate().getTime())));
    entitleResourceElement.appendChild(registrationDateElement);

    DOMSource domSource = new DOMSource(requestDoc);
    StringWriter stringWriter = new StringWriter();
    StreamResult streamResult = new StreamResult(stringWriter);
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.transform(domSource, streamResult);
    requestContent = stringWriter.toString();
    StringEntity entity = new StringEntity(requestContent);
    httpRequest.setEntity(entity);
    httpRequest.setHeader("Content-Type", "application/xml");

    // Send Request
    HttpResponse httpResponse = null;
    try {
        if (shouldTrace) {
            CloudTracing.sendRequest(invocationId, httpRequest);
        }
        httpResponse = this.getHttpClient().execute(httpRequest);
        if (shouldTrace) {
            CloudTracing.receiveResponse(invocationId, httpResponse);
        }
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_ACCEPTED) {
            ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

        // Create Result
        OperationResponse result = null;
        // Deserialize Response
        result = new OperationResponse();
        result.setStatusCode(statusCode);
        if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
            result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
        }

        if (shouldTrace) {
            CloudTracing.exit(invocationId, result);
        }
        return result;
    } finally {
        if (httpResponse != null && httpResponse.getEntity() != null) {
            httpResponse.getEntity().getContent().close();
        }
    }
}

From source file:com.netspective.sparx.form.DialogContext.java

public Document getAsXmlDocument() throws ParserConfigurationException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.newDocument();
    Element root = doc.createElement("sparx");
    doc.appendChild(root);

    exportToXml(doc.getDocumentElement());
    return doc;/*from  w w  w .  j a  v a2  s .c o m*/
}

From source file:com.distrimind.madkit.kernel.MadkitProperties.java

@Override
public Node createOrGetRootNode(Document _document) {
    Node res = getRootNode(_document);
    if (res == null) {
        res = _document.createElement(XMLUtilities.MDK);
        _document.appendChild(res);
    }//from  w w w.  j  a  v  a 2  s .  c  o  m
    return res;
}

From source file:no.dusken.barweb.view.InvoiceView.java

private Document generateXml(Map<BarPerson, Integer> persons, Gjeng gjeng, Invoice invoice) {
    Document dom = null;
    //get an instance of factory
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    try {//ww  w  .  ja va  2 s  .co  m
        //get an instance of builder
        DocumentBuilder db = dbf.newDocumentBuilder();

        //create an instance of DOM
        dom = db.newDocument();

    } catch (ParserConfigurationException pce) {
        log.error("Error when generating invoice");
    }
    Element root = createInvoiceElement(invoice, gjeng, dom);
    SimpleDateFormat dateformat = new SimpleDateFormat("dd. MMMMMMMMM yyyy - HH:mm", new Locale("no"));
    root.setAttribute("generated", dateformat.format((new GregorianCalendar()).getTime()));
    root.setAttribute("magicNumber", String.valueOf(((new Random()).nextDouble() * 1000)));
    dom.appendChild(root);
    Element personsEle = dom.createElement("persons");

    for (Map.Entry<BarPerson, Integer> p : persons.entrySet()) {
        Element personEle = createPersonElement(p.getKey(), p.getValue(), dom);
        personsEle.appendChild(personEle);
    }

    root.appendChild(personsEle);

    return dom;
}

From source file:com.datatorrent.stram.client.DTConfiguration.java

public void writeToFile(File file, Scope scope, String comment) throws IOException {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    Date date = new Date();
    Document doc;
    try {//from   ww  w. j  av  a  2 s  .  co m
        doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    } catch (ParserConfigurationException ex) {
        throw new RuntimeException(ex);
    }
    Element rootElement = doc.createElement("configuration");
    rootElement.appendChild(
            doc.createComment(" WARNING: Do not edit this file. Your changes will be overwritten. "));
    rootElement.appendChild(doc.createComment(" Written by dtgateway on " + sdf.format(date)));
    rootElement.appendChild(doc.createComment(" " + comment + " "));
    doc.appendChild(rootElement);
    for (Map.Entry<String, ValueEntry> entry : map.entrySet()) {
        ValueEntry valueEntry = entry.getValue();
        if (scope == null || valueEntry.scope == scope) {
            Element property = doc.createElement("property");
            rootElement.appendChild(property);
            Element name = doc.createElement("name");
            name.appendChild(doc.createTextNode(entry.getKey()));
            property.appendChild(name);
            Element value = doc.createElement("value");
            value.appendChild(doc.createTextNode(valueEntry.value));
            property.appendChild(value);
            if (valueEntry.description != null) {
                Element description = doc.createElement("description");
                description.appendChild(doc.createTextNode(valueEntry.description));
                property.appendChild(description);
            }
            if (valueEntry.isFinal) {
                Element isFinal = doc.createElement("final");
                isFinal.appendChild(doc.createTextNode("true"));
                property.appendChild(isFinal);
            }
        }
    }
    rootElement.appendChild(
            doc.createComment(" WARNING: Do not edit this file. Your changes will be overwritten. "));

    // write the content into xml file
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(file);
    try {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        transformer.transform(source, result);
    } catch (TransformerConfigurationException ex) {
        throw new RuntimeException(ex);
    } catch (TransformerException ex) {
        throw new IOException(ex);
    }
}

From source file:eu.europa.esig.dss.asic.signature.ASiCService.java

private void buildAsicManifest(final ASiCSignatureParameters underlyingParameters,
        final DSSDocument detachedDocument, final OutputStream outputStream) {

    ASiCParameters asicParameters = underlyingParameters.aSiC();

    final Document documentDom = DSSXMLUtils.buildDOM();
    final Element asicManifestDom = documentDom.createElementNS(ASiCNamespaces.ASiC, "asic:ASiCManifest");
    documentDom.appendChild(asicManifestDom);

    final Element sigReferenceDom = DSSXMLUtils.addElement(documentDom, asicManifestDom, ASiCNamespaces.ASiC,
            "asic:SigReference");
    final String signatureName = getSignatureFileName(asicParameters);
    sigReferenceDom.setAttribute("URI", signatureName);
    sigReferenceDom.setAttribute("MimeType", MimeType.PKCS7.getMimeTypeString()); // only CAdES form

    DSSDocument currentDetachedDocument = detachedDocument;
    do {//  w  w  w. j  av  a  2 s  .c  om

        final String detachedDocumentName = currentDetachedDocument.getName();
        final Element dataObjectReferenceDom = DSSXMLUtils.addElement(documentDom, sigReferenceDom,
                ASiCNamespaces.ASiC, "asic:DataObjectReference");
        dataObjectReferenceDom.setAttribute("URI", detachedDocumentName);

        final Element digestMethodDom = DSSXMLUtils.addElement(documentDom, dataObjectReferenceDom,
                XMLSignature.XMLNS, "DigestMethod");
        final DigestAlgorithm digestAlgorithm = underlyingParameters.getDigestAlgorithm();
        digestMethodDom.setAttribute("Algorithm", digestAlgorithm.getXmlId());

        final Element digestValueDom = DSSXMLUtils.addElement(documentDom, dataObjectReferenceDom,
                XMLSignature.XMLNS, "DigestValue");
        final byte[] digest = DSSUtils.digest(digestAlgorithm, currentDetachedDocument.getBytes());
        final String base64Encoded = Base64.encodeBase64String(digest);
        final Text textNode = documentDom.createTextNode(base64Encoded);
        digestValueDom.appendChild(textNode);

        currentDetachedDocument = currentDetachedDocument.getNextDocument();
    } while (currentDetachedDocument != null);

    storeXmlDom(outputStream, documentDom);
}

From source file:org.apache.cxf.cwiki.SiteExporter.java

private static synchronized void doLogin() throws Exception {
    if (loginToken == null) {
        Document doc = DOMUtils.createDocument();
        Element el = doc.createElementNS(SOAPNS, "ns1:login");
        Element el2 = doc.createElement("in0");

        if (userName == null) {
            System.out.println("Enter username: ");
            el2.setTextContent(System.console().readLine());
        } else {// w  ww.  ja  v a  2  s  . c om
            el2.setTextContent(userName);
        }
        el.appendChild(el2);
        el2 = doc.createElement("in1");
        el.appendChild(el2);
        if (password == null) {
            System.out.println("Enter password: ");
            el2.setTextContent(new String(System.console().readPassword()));
        } else {
            el2.setTextContent(password);
        }
        doc.appendChild(el);
        doc = getDispatch().invoke(doc);
        loginToken = doc.getDocumentElement().getFirstChild().getTextContent();
    }
}

From source file:ar.edu.uns.cs.vyglab.arq.rockar.gui.JFrameControlPanel.java

public void saveTable() {
    File currentDir = new File(System.getProperty("user.dir"));
    JFileChooser saveDialog = new JFileChooser(currentDir);
    FileNameExtensionFilter filter = new FileNameExtensionFilter("MTF File", "mtf", "mtf");
    saveDialog.setFileFilter(filter);// w  w  w . jav  a  2  s  .  c o m
    int response = saveDialog.showSaveDialog(this);
    if (response == saveDialog.APPROVE_OPTION) {
        File file = saveDialog.getSelectedFile();
        if (file.getName().lastIndexOf(".") == -1) {
            file = new File(file.getName() + ".mtf");
        }
        DataCenter.fileMineralList = file;
        try {
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            // root elements
            Document doc = docBuilder.newDocument();
            Element rootElement = doc.createElement("table");
            doc.appendChild(rootElement);

            // para cada mineral en la tabla de minerales, agrego un Element
            for (int i = 0; i < this.jTableMineralsModel.getRowCount(); i++) {
                Element mineral = doc.createElement("mineral");

                // set attribute id to mineral element
                Attr attr = doc.createAttribute("key");
                //attr.setValue(this.jTableMinerales.getModel().getValueAt(i, 0).toString());
                attr.setValue(this.jTableMineralsModel.getValueAt(i, 0).toString());
                mineral.setAttributeNode(attr);

                // set attribute name to mineral element
                attr = doc.createAttribute("name");
                attr.setValue(this.jTableMineralsModel.getValueAt(i, 1).toString());
                mineral.setAttributeNode(attr);

                // set attribute color to mineral element
                attr = doc.createAttribute("color");
                attr.setValue(String.valueOf(((Color) this.jTableMineralsModel.getValueAt(i, 2)).getRGB()));
                mineral.setAttributeNode(attr);

                // agrego el mineral a los minerales
                rootElement.appendChild(mineral);
            }

            // write the content into xml file
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(DataCenter.fileMineralList);

            transformer.transform(source, result);

        } catch (Exception e) {
        }
    }
}