Example usage for org.w3c.dom Document createElementNS

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

Introduction

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

Prototype

public Element createElementNS(String namespaceURI, String qualifiedName) throws DOMException;

Source Link

Document

Creates an element of the given qualified name and namespace URI.

Usage

From source file:org.openmeetings.app.data.record.BatikMethods.java

public void drawText(SVGGraphics2D g2d, int x, int y, int width, int height, String text,
        String default_export_font, int style, int size, Color fontColor, Document document) throws Exception {

    //      g2d.setClip(x, y, width, height);
    //      g2d.setColor(Color.black);
    //      g2d.drawString(text, x, y+20);

    String svgNS = SVGDOMImplementation.SVG_NAMESPACE_URI;

    // Get the root element (the 'svg' element).
    Element svgRoot = document.getDocumentElement();

    log.debug("svgNS DEBUG: " + svgNS);

    //Element textElement = g2d.getDOMFactory().createElementNS(svgNS,"text");
    Element rectangle = document.createElementNS(svgNS, "rect");
    rectangle.setAttributeNS(svgNS, "x", "10");
    rectangle.setAttributeNS(svgNS, "y", "20");
    rectangle.setAttributeNS(svgNS, "width", "100");
    rectangle.setAttributeNS(svgNS, "height", "50");
    rectangle.setAttributeNS(svgNS, "fill", "red");

    // Attach the rectangle to the root 'svg' element.
    svgRoot.appendChild(rectangle);/*  w  w w  .  ja v  a  2s  .  c om*/

}

From source file:com.verisign.epp.codec.gen.EPPUtil.java

/**
 * Encode a <code>List</code> of <code>Integer</code>'s in XML with a given
 * XML namespace and tag name./*from w  w  w  .j av a2  s .  co  m*/
 * 
 * @param aDocument
 *            DOM Document of <code>aRoot</code>. This parameter also acts
 *            as a factory for XML elements.
 * @param aRoot
 *            XML Element to add children nodes to. For example, the root
 *            node could be &ltdomain:update&gt
 * @param aList
 *            <code>List</code> of <code>Integer</code>'s to add.
 * @param aNS
 *            XML namespace of the elements. For example, for domain element
 *            this is "urn:iana:xmlns:domain".
 * @param aTagName
 *            Tag name of the element including an optional namespace
 *            prefix. For example, the tag name for the domain name servers
 *            is "domain:server".
 * 
 * @exception EPPEncodeException
 *                Error encoding the <code>List</code> of
 *                <code>Integer</code>'s.
 */
public static void encodeIntegerList(Document aDocument, Element aRoot, List aList, String aNS, String aTagName)
        throws EPPEncodeException {
    Element currElm;
    Text currVal;

    if (aList != null) {
        Iterator elms = aList.iterator();

        while (elms.hasNext()) {
            currElm = aDocument.createElementNS(aNS, aTagName);
            currVal = aDocument.createTextNode(elms.next().toString());

            currElm.appendChild(currVal);
            aRoot.appendChild(currElm);
        } // end while (elms.hasNext())

    } // end if (aList != null)

}

From source file:com.verisign.epp.codec.gen.EPPUtil.java

/**
 * Encode a <code>List</code> of <code>String</code>'s in XML with a given
 * XML namespace and tag name.//w  ww. ja  v  a2  s  .  c o m
 * 
 * @param aDocument
 *            DOM Document of <code>aRoot</code>. This parameter also acts
 *            as a factory for XML elements.
 * @param aRoot
 *            XML Element to add children nodes to. For example, the root
 *            node could be &ltdomain:update&gt
 * @param aList
 *            <code>List</code> of <code>String's</code> to add.
 * @param aNS
 *            XML namespace of the elements. For example, for domain element
 *            this is "urn:iana:xmlns:domain".
 * @param aTagName
 *            Tag name of the element including an optional namespace
 *            prefix. For example, the tag name for the domain name servers
 *            is "domain:server".
 * @exception EPPEncodeException
 *                Error encoding the <code>List</code> of
 *                <code>String</code>'s.
 */
public static void encodeList(Document aDocument, Element aRoot, List aList, String aNS, String aTagName)
        throws EPPEncodeException {
    Element currElm;
    Text currVal;

    if (aList != null) {
        Iterator elms = aList.iterator();

        while (elms.hasNext()) {
            currElm = aDocument.createElementNS(aNS, aTagName);
            currVal = aDocument.createTextNode(elms.next().toString());

            currElm.appendChild(currVal);
            aRoot.appendChild(currElm);
        }

        // end while (elms.hasMoreElements())
    }

    // end if (aList != null)
}

From source file:be.fedict.eid.applet.service.signer.ooxml.OOXMLSignatureFacet.java

private void addSignatureInfo(XMLSignatureFactory signatureFactory, Document document, String signatureId,
        List<Reference> references, List<XMLObject> objects)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
    List<XMLStructure> objectContent = new LinkedList<XMLStructure>();

    Element signatureInfoElement = document.createElementNS(OFFICE_DIGSIG_NS, "SignatureInfoV1");
    signatureInfoElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", OFFICE_DIGSIG_NS);

    Element setupIDElement = document.createElementNS(OFFICE_DIGSIG_NS, "SetupID");

    signatureInfoElement.appendChild(setupIDElement);

    Element signatureTextElement = document.createElementNS(OFFICE_DIGSIG_NS, "SignatureText");

    signatureInfoElement.appendChild(signatureTextElement);

    Element signatureImageElement = document.createElementNS(OFFICE_DIGSIG_NS, "SignatureImage");

    signatureInfoElement.appendChild(signatureImageElement);

    Element signatureCommentsElement = document.createElementNS(OFFICE_DIGSIG_NS, "SignatureComments");

    signatureInfoElement.appendChild(signatureCommentsElement);

    Element windowsVersionElement = document.createElementNS(OFFICE_DIGSIG_NS, "WindowsVersion");
    windowsVersionElement.setTextContent("6.1");
    signatureInfoElement.appendChild(windowsVersionElement);

    Element officeVersionElement = document.createElementNS(OFFICE_DIGSIG_NS, "OfficeVersion");
    officeVersionElement.setTextContent("15.0");
    signatureInfoElement.appendChild(officeVersionElement);

    Element applicationVersionElement = document.createElementNS(OFFICE_DIGSIG_NS, "ApplicationVersion");
    applicationVersionElement.setTextContent("15.0");
    signatureInfoElement.appendChild(applicationVersionElement);

    Element monitorsElement = document.createElementNS(OFFICE_DIGSIG_NS, "Monitors");
    monitorsElement.setTextContent("1");
    signatureInfoElement.appendChild(monitorsElement);

    Element horizontalResolutionElement = document.createElementNS(OFFICE_DIGSIG_NS, "HorizontalResolution");
    horizontalResolutionElement.setTextContent("1366");
    signatureInfoElement.appendChild(horizontalResolutionElement);

    Element verticalResolutionElement = document.createElementNS(OFFICE_DIGSIG_NS, "VerticalResolution");
    verticalResolutionElement.setTextContent("768");
    signatureInfoElement.appendChild(verticalResolutionElement);

    Element colorDepthElement = document.createElementNS(OFFICE_DIGSIG_NS, "ColorDepth");
    colorDepthElement.setTextContent("32");
    signatureInfoElement.appendChild(colorDepthElement);

    Element signatureProviderIdElement = document.createElementNS(OFFICE_DIGSIG_NS, "SignatureProviderId");
    signatureProviderIdElement.setTextContent("{00000000-0000-0000-0000-000000000000}");
    signatureInfoElement.appendChild(signatureProviderIdElement);

    Element signatureProviderUrlElement = document.createElementNS(OFFICE_DIGSIG_NS, "SignatureProviderUrl");
    signatureInfoElement.appendChild(signatureProviderUrlElement);

    Element signatureProviderDetailsElement = document.createElementNS(OFFICE_DIGSIG_NS,
            "SignatureProviderDetails");
    signatureProviderDetailsElement.setTextContent("9");
    signatureInfoElement.appendChild(signatureProviderDetailsElement);

    Element manifestHashAlgorithmElement = document.createElementNS(OFFICE_DIGSIG_NS, "ManifestHashAlgorithm");
    manifestHashAlgorithmElement.setTextContent("http://www.w3.org/2000/09/xmldsig#sha1");
    signatureInfoElement.appendChild(manifestHashAlgorithmElement);

    Element signatureTypeElement = document.createElementNS(OFFICE_DIGSIG_NS, "SignatureType");
    signatureTypeElement.setTextContent("1");
    signatureInfoElement.appendChild(signatureTypeElement);

    List<XMLStructure> signatureInfoContent = new LinkedList<XMLStructure>();
    signatureInfoContent.add(new DOMStructure(signatureInfoElement));
    SignatureProperty signatureInfoSignatureProperty = signatureFactory
            .newSignatureProperty(signatureInfoContent, "#" + signatureId, "idOfficeV1Details");

    List<SignatureProperty> signaturePropertyContent = new LinkedList<SignatureProperty>();
    signaturePropertyContent.add(signatureInfoSignatureProperty);
    SignatureProperties signatureProperties = signatureFactory.newSignatureProperties(signaturePropertyContent,
            null);//from   w  w w.  j av  a2s . c o m
    objectContent.add(signatureProperties);

    String objectId = "idOfficeObject";
    objects.add(signatureFactory.newXMLObject(objectContent, objectId, null, null));

    DigestMethod digestMethod = signatureFactory.newDigestMethod(this.digestAlgo.getXmlAlgoId(), null);
    Reference reference = signatureFactory.newReference("#" + objectId, digestMethod, null,
            "http://www.w3.org/2000/09/xmldsig#Object", null);
    references.add(reference);
}

From source file:com.verisign.epp.codec.gen.EPPUtil.java

/**
 * Encode a <code>Vector</code> of <code>String</code>'s in XML with a given
 * XML namespace and tag name.//from w w  w .  j  a v a  2  s .com
 * 
 * @param aDocument
 *            DOM Document of <code>aRoot</code>. This parameter also acts
 *            as a factory for XML elements.
 * @param aRoot
 *            XML Element to add children nodes to. For example, the root
 *            node could be &ltdomain:update&gt
 * @param aVector
 *            <code>Vector</code> of <code>String's</code> to add.
 * @param aNS
 *            XML namespace of the elements. For example, for domain element
 *            this is "urn:iana:xmlns:domain".
 * @param aTagName
 *            Tag name of the element including an optional namespace
 *            prefix. For example, the tag name for the domain name servers
 *            is "domain:server".
 * @exception EPPEncodeException
 *                Error encoding the <code>Vector</code> of
 *                <code>String</code>'s.
 */
public static void encodeVector(Document aDocument, Element aRoot, Vector aVector, String aNS, String aTagName)
        throws EPPEncodeException {
    Element currElm;
    Text currVal;

    if (aVector != null) {
        Enumeration elms = aVector.elements();

        while (elms.hasMoreElements()) {
            currElm = aDocument.createElementNS(aNS, aTagName);
            currVal = aDocument.createTextNode(elms.nextElement().toString());

            currElm.appendChild(currVal);
            aRoot.appendChild(currElm);
        }

        // end while (elms.hasMoreElements())
    }

    // end if (aVector != null)
}

From source file:be.docarch.odt2braille.PEF.java

/**
 * Converts the flat .odt filt to a .pef file according to the braille settings.
 *
 * This function/* w ww  .  ja va2 s  . com*/
 * <ul>
 * <li>uses {@link ODT} to convert the .odt file to multiple DAISY-like xml files,</li>
 * <li>uses {@link LiblouisXML} to translate these files into braille, and</li>
 * <li>recombines these braille files into one single .pef file.</li>
 * </ul>
 *
 * First, the document <i>body</i> is processed and split in volumes, then the <i>page ranges</i> are calculated
 * and finally the <i>preliminary pages</i> of each volume are processed and inserted at the right places.
 * The checker checks the DAISY-like files and the volume lengths.
 *
 */

public boolean makePEF() throws IOException, ParserConfigurationException, TransformerException,
        InterruptedException, SAXException, ConversionException, LiblouisXMLException, Exception {

    logger.entering("PEF", "makePEF");

    Configuration settings = odt.getConfiguration();

    Element[] volumeElements;
    Element sectionElement;
    File bodyFile = null;
    File brailleFile = null;
    File preliminaryFile = null;

    List<Volume> volumes = manager.getVolumes();

    String volumeInfo = capitalizeFirstLetter(
            ResourceBundle.getBundle(L10N, settings.mainLocale).getString("in")) + " " + volumes.size() + " "
            + ResourceBundle.getBundle(L10N, settings.mainLocale)
                    .getString((volumes.size() > 1) ? "volumes" : "volume")
            + "\n@title\n@pages";

    volumeElements = new Element[volumes.size()];

    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    docFactory.setValidating(false);
    docFactory.setNamespaceAware(true);
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    DOMImplementation impl = docBuilder.getDOMImplementation();

    Document document = impl.createDocument(pefNS, "pef", null);
    Element root = document.getDocumentElement();
    root.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", pefNS);
    root.setAttributeNS(null, "version", "2008-1");

    Element headElement = document.createElementNS(pefNS, "head");
    Element metaElement = document.createElementNS(pefNS, "meta");
    metaElement.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:dc", "http://purl.org/dc/elements/1.1/");
    Element dcElement = document.createElementNS("http://purl.org/dc/elements/1.1/", "dc:identifier");
    dcElement.appendChild(document.createTextNode(Integer.toHexString((int) (Math.random() * 1000000)) + " "
            + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format((new Date()))));
    metaElement.appendChild(dcElement);
    dcElement = document.createElementNS("http://purl.org/dc/elements/1.1/", "dc:format");
    dcElement.appendChild(document.createTextNode("application/x-pef+xml"));
    metaElement.appendChild(dcElement);
    headElement.appendChild(metaElement);

    root.appendChild(headElement);

    int columns = pefSettings.getColumns();
    int rows = pefSettings.getRows();
    boolean duplex = pefSettings.getDuplex();
    int rowgap = pefSettings.getEightDots() ? 1 : 0;
    int beginPage = settings.getBeginningBraillePageNumber();

    if (statusIndicator != null) {
        statusIndicator.start();
        statusIndicator.setSteps(volumes.size());
        statusIndicator.setStatus(ResourceBundle.getBundle(L10N, statusIndicator.getPreferredLocale())
                .getString("statusIndicatorStep"));
    }

    for (int volumeCount = 0; volumeCount < volumes.size(); volumeCount++) {

        volumeElements[volumeCount] = document.createElementNS(pefNS, "volume");
        volumeElements[volumeCount].setAttributeNS(null, "cols", String.valueOf(columns));
        volumeElements[volumeCount].setAttributeNS(null, "rows",
                String.valueOf(rows + (int) Math.ceil(((rows - 1) * rowgap) / 4d)));
        volumeElements[volumeCount].setAttributeNS(null, "rowgap", String.valueOf(rowgap));
        volumeElements[volumeCount].setAttributeNS(null, "duplex", duplex ? "true" : "false");

        Volume volume = volumes.get(volumeCount);

        // Body section

        logger.info("Processing volume " + (volumeCount + 1) + " : " + volume.getTitle());

        if (!(volume instanceof PreliminaryVolume)) {

            bodyFile = File.createTempFile(TMP_NAME, ".daisy.body." + (volumeCount + 1) + ".xml", TMP_DIR);
            bodyFile.deleteOnExit();
            brailleFile = File.createTempFile(TMP_NAME, ".txt", TMP_DIR);
            brailleFile.deleteOnExit();

            odt.getBodyMatter(bodyFile, volume);
            liblouisXML.configure(bodyFile, brailleFile, false, beginPage);
            liblouisXML.run();

            // Read pages
            sectionElement = document.createElementNS(pefNS, "section");
            int pageCount = addPagesToSection(document, sectionElement, brailleFile, rows, columns, -1);
            volumeElements[volumeCount].appendChild(sectionElement);

            // Checker
            if (checker != null) {
                checker.checkDaisyFile(bodyFile);
            }

            // Braille page range
            volume.setBraillePagesStart(beginPage);
            volume.setNumberOfBraillePages(pageCount);
            beginPage += pageCount;

            // Print page range
            if (volume.getFrontMatter() && settings.getVolumeInfoEnabled()) {
                extractPrintPageRange(bodyFile, volume, settings);
            }
        }

        // Special symbols list
        if (volume.getSpecialSymbolListEnabled()) {
            extractSpecialSymbols(bodyFile, volume, volumeCount, settings);
        }

        // Preliminary section

        if (volume.getFrontMatter() || volume.getTableOfContent() || volume.getTranscribersNotesPageEnabled()
                || volume.getSpecialSymbolListEnabled()) {

            preliminaryFile = File.createTempFile(TMP_NAME, ".daisy.front." + (volumeCount + 1) + ".xml",
                    TMP_DIR);
            preliminaryFile.deleteOnExit();
            brailleFile = File.createTempFile(TMP_NAME, ".txt", TMP_DIR);
            brailleFile.deleteOnExit();

            odt.getFrontMatter(preliminaryFile, volume, volumeInfo);
            liblouisXML.configure(preliminaryFile, brailleFile, true,
                    volume.getTableOfContent() ? volume.getFirstBraillePage() : 1);
            liblouisXML.run();

            // Page range
            int pageCount = countPages(brailleFile, volume);
            volume.setNumberOfPreliminaryPages(pageCount);

            // Translate again with updated volume info and without volume separator marks
            brailleFile = File.createTempFile(TMP_NAME, ".txt", TMP_DIR);
            brailleFile.deleteOnExit();
            odt.getFrontMatter(preliminaryFile, volume, volumeInfo);
            liblouisXML.configure(preliminaryFile, brailleFile, false,
                    volume.getTableOfContent() ? volume.getFirstBraillePage() : 1);
            liblouisXML.run();

            // Read pages
            sectionElement = document.createElementNS(pefNS, "section");
            addPagesToSection(document, sectionElement, brailleFile, rows, columns, pageCount);
            volumeElements[volumeCount].insertBefore(sectionElement,
                    volumeElements[volumeCount].getFirstChild());

            // Checker
            if (checker != null) {
                checker.checkDaisyFile(preliminaryFile);
            }
        }

        if (statusIndicator != null) {
            statusIndicator.increment();
        }
    }

    if (checker != null) {
        checker.checkVolumes(volumes);
    }

    Element bodyElement = document.createElementNS(pefNS, "body");

    for (int volumeCount = 0; volumeCount < volumes.size(); volumeCount++) {
        bodyElement.appendChild(volumeElements[volumeCount]);
    }

    root.appendChild(bodyElement);

    document.insertBefore((ProcessingInstruction) document.createProcessingInstruction("xml-stylesheet",
            "type='text/css' href='pef.css'"), document.getFirstChild());

    OdtUtils.saveDOM(document, pefFile);

    logger.exiting("PEF", "makePEF");

    if (!validatePEF(pefFile)) {
        return false;
    }

    return true;
}

From source file:com.verisign.epp.codec.gen.EPPUtil.java

public static void encodeStringList(Document aDocument, Element aRoot, List aList, String aNS,
        String aTagName) {// ww w  . j  a v a  2 s . com
    String aString;
    Element aElement;
    Text aValue;

    if (aList != null) {
        Iterator elms = aList.iterator();

        while (elms.hasNext()) {
            aString = (String) elms.next();
            aElement = aDocument.createElementNS(aNS, aTagName);
            aValue = aDocument.createTextNode(aString);
            aElement.appendChild(aValue);
            aRoot.appendChild(aElement);
        }
    }
}

From source file:at.ac.dbisinformatik.snowprofile.web.svgcreator.SVGCreator.java

/**
 * creates a SVG-Graph for given jsonDocument which includes ExtJS-SVG-Objects. The created SVG-Document will be converted in the given export type. 
 * /*from   ww  w  .  j ava2  s  .co m*/
 * @param jsonDocument
 * @param exportType
 * @param profileID
 * @return
 * @throws TransformerException
 * @throws URISyntaxException
 * @throws TranscoderException
 * @throws IOException
 */
public static ByteArrayOutputStream svgDocument(JsonArray jsonDocument, String exportType, String profileID)
        throws TransformerException, URISyntaxException, TranscoderException, IOException {

    ByteArrayOutputStream ret = null;

    DOMImplementation impl = SVGDOMImplementation.getDOMImplementation();
    String svgNS = SVGDOMImplementation.SVG_NAMESPACE_URI;
    Document doc = impl.createDocument(svgNS, "svg", null);

    // Get the root element (the 'svg' element).
    Element svgRoot = doc.getDocumentElement();

    // Set the width and height attributes on the root 'svg' element.
    svgRoot.setAttributeNS(null, "width", "1500");
    svgRoot.setAttributeNS(null, "height", "1500");
    JsonArray items = jsonDocument;

    for (int i = 0; i < items.size(); ++i) {
        String type = items.get(i).getAsJsonObject().get("type").getAsString();
        Element element = null;
        org.w3c.dom.Text test = null;
        String path = "";
        String width = "";
        String height = "";
        String x = "";
        String y = "";
        String fill = "";
        String text = "";
        String font = "";
        String fontFamily = "";
        String fontSize = "";
        String degrees = "";
        String stroke = "";
        String opacity = "";
        String src = "";
        switch (type) {
        case "rect":
            width = items.get(i).getAsJsonObject().get("width").getAsString();
            height = items.get(i).getAsJsonObject().get("height").getAsString();
            x = items.get(i).getAsJsonObject().get("x").getAsString();
            y = items.get(i).getAsJsonObject().get("y").getAsString();
            fill = items.get(i).getAsJsonObject().get("fill").getAsString();
            stroke = items.get(i).getAsJsonObject().get("stroke").getAsString();
            opacity = items.get(i).getAsJsonObject().get("opacity").getAsString();

            // Create the rectangle.
            element = doc.createElementNS(svgNS, "rect");
            element.setAttributeNS(null, "width", width);
            element.setAttributeNS(null, "height", height);
            element.setAttributeNS(null, "x", x);
            element.setAttributeNS(null, "y", y);
            element.setAttributeNS(null, "fill", fill);
            element.setAttributeNS(null, "stroke", stroke);
            element.setAttributeNS(null, "opacity", opacity);
            break;

        case "path":
            path = items.get(i).getAsJsonObject().get("path").getAsString();
            fill = items.get(i).getAsJsonObject().get("fill").getAsString();
            stroke = items.get(i).getAsJsonObject().get("stroke").getAsString();

            // Create the path.
            element = doc.createElementNS(svgNS, "path");
            element.setAttributeNS(null, "d", path);
            element.setAttributeNS(null, "fill", fill);
            element.setAttributeNS(null, "stroke", stroke);
            break;

        case "image":
            x = items.get(i).getAsJsonObject().get("x").getAsString();
            y = items.get(i).getAsJsonObject().get("y").getAsString();
            width = items.get(i).getAsJsonObject().get("width").getAsString();
            height = items.get(i).getAsJsonObject().get("height").getAsString();
            src = System.class.getResource("/at/ac/dbisinformatik/snowprofile/web/resources/"
                    + items.get(i).getAsJsonObject().get("src").getAsString()).toString();

            // Create the path.
            element = doc.createElementNS(svgNS, "image");
            element.setAttributeNS(null, "x", x);
            element.setAttributeNS(null, "y", y);
            element.setAttributeNS(null, "width", width);
            element.setAttributeNS(null, "height", height);
            element.setAttributeNS(null, "xlink:href", src);
            break;

        case "text":
            text = items.get(i).getAsJsonObject().get("text").getAsString();
            fill = items.get(i).getAsJsonObject().get("fill").getAsString();
            font = items.get(i).getAsJsonObject().get("font").getAsString();
            x = items.get(i).getAsJsonObject().get("x").getAsString();
            y = items.get(i).getAsJsonObject().get("y").getAsString();

            // Transformation
            if (items.get(i).getAsJsonObject().get("rotate") != null) {
                JsonObject temp = items.get(i).getAsJsonObject().get("rotate").getAsJsonObject();
                degrees = temp.get("degrees").getAsString();
            }

            fontSize = font.split(" ")[0];
            fontFamily = font.split(" ")[1];

            // Create the text.
            test = doc.createTextNode(text);
            element = doc.createElementNS(svgNS, "text");
            element.setAttributeNS(null, "text", text);
            element.setAttributeNS(null, "fill", fill);
            element.setAttributeNS(null, "font-family", fontFamily);
            element.setAttributeNS(null, "font-size", fontSize);
            element.setAttributeNS(null, "x", x);
            element.setAttributeNS(null, "y", y);
            if (!degrees.equals("")) {
                // element.setAttributeNS(null, "transform",
                // "rotate(270 "+500+","+80+")");
            }
            element.appendChild(test);
            break;

        default:
            break;
        }

        // Attach the rectangle to the root 'svg' element.
        svgRoot.appendChild(element);
    }

    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer = tFactory.newTransformer();

    DOMSource source = new DOMSource(doc);

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    StreamResult result = new StreamResult(outputStream);
    transformer.transform(source, result);
    InputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());

    switch (exportType) {
    case "png":
        ret = createPNG(inputStream);
        break;

    case "jpg":
        ret = createJPG(inputStream);
        break;

    case "pdf":
        ret = createPDF(inputStream);
        break;

    default:
        break;
    }
    return ret;
}

From source file:com.microsoft.windowsazure.management.compute.DNSServerOperationsImpl.java

/**
* Add a definition for a DNS server to an existing deployment. VM's in this
* deployment will be programmed to use this DNS server for all DNS
* resolutions/*w w w  . ja  va2s.c om*/
*
* @param serviceName Required. The name of the service.
* @param deploymentName Required. The name of the deployment.
* @param parameters Required. Parameters supplied to the Add DNS Server
* operation.
* @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 The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request and error information regarding the failure.
*/
@Override
public OperationStatusResponse beginAddingDNSServer(String serviceName, String deploymentName,
        DNSAddParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serviceName == null) {
        throw new NullPointerException("serviceName");
    }
    if (deploymentName == null) {
        throw new NullPointerException("deploymentName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }

    // 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("serviceName", serviceName);
        tracingParameters.put("deploymentName", deploymentName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "beginAddingDNSServerAsync", tracingParameters);
    }

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/services/hostedservices/";
    url = url + URLEncoder.encode(serviceName, "UTF-8");
    url = url + "/deployments/";
    url = url + URLEncoder.encode(deploymentName, "UTF-8");
    url = url + "/dnsservers";
    String baseUrl = this.getClient().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", "2015-04-01");

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

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

    if (parameters.getName() != null) {
        Element nameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name");
        nameElement.appendChild(requestDoc.createTextNode(parameters.getName()));
        dnsServerElement.appendChild(nameElement);
    }

    if (parameters.getAddress() != null) {
        Element addressElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "Address");
        addressElement.appendChild(requestDoc.createTextNode(parameters.getAddress().getHostAddress()));
        dnsServerElement.appendChild(addressElement);
    }

    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.getClient().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
        OperationStatusResponse result = null;
        // Deserialize Response
        result = new OperationStatusResponse();
        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.microsoft.windowsazure.management.compute.DNSServerOperationsImpl.java

/**
* Updates a definition for an existing DNS server. Updates to address is
* the only change allowed. DNS server name cannot be changed
*
* @param serviceName Required. The name of the service.
* @param deploymentName Required. The name of the deployment.
* @param dnsServerName Required. The name of the dns server.
* @param parameters Required. Parameters supplied to the Update DNS Server
* operation./* www.  ja v a 2 s .c om*/
* @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 The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request and error information regarding the failure.
*/
@Override
public OperationStatusResponse beginUpdatingDNSServer(String serviceName, String deploymentName,
        String dnsServerName, DNSUpdateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serviceName == null) {
        throw new NullPointerException("serviceName");
    }
    if (deploymentName == null) {
        throw new NullPointerException("deploymentName");
    }
    if (dnsServerName == null) {
        throw new NullPointerException("dnsServerName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }

    // 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("serviceName", serviceName);
        tracingParameters.put("deploymentName", deploymentName);
        tracingParameters.put("dnsServerName", dnsServerName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "beginUpdatingDNSServerAsync", tracingParameters);
    }

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/services/hostedservices/";
    url = url + URLEncoder.encode(serviceName, "UTF-8");
    url = url + "/deployments/";
    url = url + URLEncoder.encode(deploymentName, "UTF-8");
    url = url + "/dnsservers/";
    url = url + URLEncoder.encode(dnsServerName, "UTF-8");
    String baseUrl = this.getClient().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
    HttpPut httpRequest = new HttpPut(url);

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

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

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

    if (parameters.getName() != null) {
        Element nameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name");
        nameElement.appendChild(requestDoc.createTextNode(parameters.getName()));
        dnsServerElement.appendChild(nameElement);
    }

    if (parameters.getAddress() != null) {
        Element addressElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "Address");
        addressElement.appendChild(requestDoc.createTextNode(parameters.getAddress().getHostAddress()));
        dnsServerElement.appendChild(addressElement);
    }

    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.getClient().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
        OperationStatusResponse result = null;
        // Deserialize Response
        result = new OperationStatusResponse();
        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();
        }
    }
}