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:com.igeekinc.indelible.indeliblefs.webaccess.IndelibleWebAccessServlet.java

public void duplicate(HttpServletRequest req, HttpServletResponse resp, String destPathStr, Document buildDoc)
        throws IndelibleWebAccessException, PermissionDeniedException, RemoteException, IOException {
    Element rootElem = buildDoc.createElement("duplicate");
    buildDoc.appendChild(rootElem);
    String path = req.getPathInfo();
    FilePath reqPath = FilePath.getFilePath(path);
    if (reqPath == null || destPathStr == null || reqPath.getNumComponents() < 3)
        throw new IndelibleWebAccessException(IndelibleWebAccessException.kInvalidArgument, null);

    // Should be an absolute path
    reqPath = reqPath.removeLeadingComponent();
    String fsIDStr = reqPath.getComponent(0);
    IndelibleFSVolumeIF volume = getVolume(fsIDStr);
    FilePath sourcePath = reqPath.removeLeadingComponent();

    FilePath destPath = FilePath.getFilePath(destPathStr);
    if (destPath == null)
        throw new IndelibleWebAccessException(IndelibleWebAccessException.kInvalidArgument, null);

    IndelibleFileNodeIF sourceFile = null, checkFile = null;

    // Our semantics on the name of the created file are the same as Unix cp.  If the create path specifies a directory, the
    // name will be the source file name (unless no source file is specified, in which case it's an error).  If the create path
    // specifies a non-existing file, then the create path name will be used (if it specifies an existing file then we copy over the existing file)
    String createName = null;//  www.  ja v  a 2s  .  c  om
    if (sourcePath != null) {
        createName = sourcePath.getName();
    }
    connection.startTransaction();
    try {
        sourceFile = volume.getObjectByPath(sourcePath.makeAbsolute());
    } catch (ObjectNotFoundException e1) {
        connection.rollback();
        throw new IndelibleWebAccessException(IndelibleWebAccessException.kPathNotFound, e1);
    }

    IndelibleFSObjectID createdID;

    try {
        checkFile = volume.getObjectByPath(destPath.makeAbsolute());
        if (checkFile != null && !checkFile.isDirectory()) {
            throw new IndelibleWebAccessException(IndelibleWebAccessException.kDestinationExists, null);
        }
        createName = sourcePath.getName();
    } catch (ObjectNotFoundException e) {
        try {
            checkFile = volume.getObjectByPath(destPath.getParent().makeAbsolute());
            createName = destPath.getName();
        } catch (ObjectNotFoundException e1) {
            throw new IndelibleWebAccessException(IndelibleWebAccessException.kPathNotFound, null);
        }
    }
    if (checkFile.isDirectory()) {
        IndelibleDirectoryNodeIF parentDir = (IndelibleDirectoryNodeIF) checkFile;
        if (sourceFile != null) {

            try {
                CreateFileInfo createFileInfo = parentDir.createChildFile(createName, sourceFile, true);
                XMLUtils.appendSingleValElement(buildDoc, rootElem, "fileID",
                        createFileInfo.getCreatedNode().getObjectID().toString());
            } catch (FileExistsException e) {
                throw new IndelibleWebAccessException(IndelibleWebAccessException.kDestinationExists, e);
            } catch (ObjectNotFoundException e) {
                throw new IndelibleWebAccessException(IndelibleWebAccessException.kPathNotFound, e);
            } catch (NotFileException e) {
                throw new IndelibleWebAccessException(IndelibleWebAccessException.kPathNotFound, e);
            }
        }
    } else {
        throw new IndelibleWebAccessException(IndelibleWebAccessException.kNotDirectory, null);
    }
    connection.commit();
}

From source file:org.kuali.mobility.maps.service.LocationServiceImpl.java

private Document writeLocationsToDocument(List<Location> locations, String groupCode, boolean isOneStart) {
    DocumentBuilderFactory dbf;/*  ww  w . ja v  a2s.  c  om*/
    Document xmlDoc = null;
    try {
        dbf = DocumentBuilderFactory.newInstance();
        xmlDoc = createDocument(dbf);
        if (xmlDoc != null) {
            // Create Root
            Element rootEle = xmlDoc.createElement("markers");
            xmlDoc.appendChild(rootEle);
            for (Location loc : locations) {
                // Create child element, attach to root
                Element marker = xmlDoc.createElement("marker");
                // XML escaping does not appear to be required here
                marker.setAttribute("lat", "" + loc.getLatitude());
                marker.setAttribute("lng", "" + loc.getLongitude());
                marker.setAttribute("cd", loc.getBuildingCode());
                marker.setAttribute("nm", loc.getName());
                marker.setAttribute("snm", loc.getShortName());
                marker.setAttribute("cty", loc.getCity());
                marker.setAttribute("sta", loc.getState());
                marker.setAttribute("str", loc.getStreet());
                marker.setAttribute("zip", loc.getZip());
                marker.setAttribute("miu", loc.getCode());
                if (!isOneStart) {
                    marker.setAttribute("scd", loc.getShortCode());
                    marker.setAttribute("active", "" + loc.isActive());
                    marker.setAttribute("override", "" + loc.isOverride());
                    marker.setAttribute("grp", groupCode);
                }
                rootEle.appendChild(marker);
            }
        }
    } catch (Exception e) {
        //         LOG.error("Failed to create document: ", e);
    }
    return xmlDoc;
}

From source file:com.igeekinc.indelible.indeliblefs.webaccess.IndelibleWebAccessServlet.java

public void createFilePut(HttpServletRequest req, HttpServletResponse resp, Document buildDoc)
        throws RemoteException, IndelibleWebAccessException {
    boolean completedOK = false;
    try {/*from   w ww . j av a 2  s.co m*/
        connection.startTransaction();
        Element rootElem = buildDoc.createElement("createFile");
        buildDoc.appendChild(rootElem);
        String path = req.getPathInfo();

        FilePath reqPath = FilePath.getFilePath(path);
        if (reqPath == null || reqPath.getNumComponents() < 2)
            throw new IndelibleWebAccessException(IndelibleWebAccessException.kInvalidArgument, null);

        // Should be an absolute path
        reqPath = reqPath.removeLeadingComponent();
        String fsIDStr = reqPath.getComponent(0);
        IndelibleFSVolumeIF volume = getVolume(fsIDStr);
        if (volume == null)
            throw new IndelibleWebAccessException(IndelibleWebAccessException.kVolumeNotFoundError, null);
        FilePath createPath = reqPath.removeLeadingComponent();
        FilePath parentPath = createPath.getParent();
        FilePath childPath = createPath.getPathRelativeTo(parentPath);
        if (childPath.getNumComponents() != 1)
            throw new IndelibleWebAccessException(IndelibleWebAccessException.kInvalidArgument, null);
        IndelibleFileNodeIF parentNode = volume.getObjectByPath(parentPath.makeAbsolute());
        if (!parentNode.isDirectory())
            throw new IndelibleWebAccessException(IndelibleWebAccessException.kNotDirectory, null);
        IndelibleDirectoryNodeIF parentDirectory = (IndelibleDirectoryNodeIF) parentNode;
        IndelibleFileNodeIF childNode = null;
        childNode = parentDirectory.getChildNode(childPath.getName());
        if (childNode == null) {
            try {
                CreateFileInfo childInfo = parentDirectory.createChildFile(childPath.getName(), true);
                childNode = childInfo.getCreatedNode();
            } catch (FileExistsException e) {
                // Probably someone else beat us to it...
                childNode = parentDirectory.getChildNode(childPath.getName());
            }
        } else {

        }
        if (childNode.isDirectory())
            throw new IndelibleWebAccessException(IndelibleWebAccessException.kNotFile, null);

        IndelibleFSForkIF dataFork = childNode.getFork("data", true);
        dataFork.truncate(0);
        InputStream readStream = req.getInputStream();
        byte[] writeBuffer = new byte[1024 * 1024];
        int readLength;
        long bytesCopied = 0;
        int bufOffset = 0;
        while ((readLength = readStream.read(writeBuffer, bufOffset, writeBuffer.length - bufOffset)) > 0) {
            if (bufOffset + readLength == writeBuffer.length) {
                dataFork.appendDataDescriptor(
                        new CASIDMemoryDataDescriptor(writeBuffer, 0, writeBuffer.length));
                bufOffset = 0;
            } else
                bufOffset += readLength;
            bytesCopied += readLength;
        }
        if (bufOffset != 0) {
            // Flush out the final stuff
            dataFork.appendDataDescriptor(new CASIDMemoryDataDescriptor(writeBuffer, 0, bufOffset));
        }
        connection.commit();
        completedOK = true;
        XMLUtils.appendSingleValElement(buildDoc, rootElem, "fileID", childNode.getObjectID().toString());
        XMLUtils.appendSingleValElement(buildDoc, rootElem, "copied", Long.toString(bytesCopied));
    } catch (PermissionDeniedException e) {
        throw new IndelibleWebAccessException(IndelibleWebAccessException.kPermissionDenied, e);
    } catch (IOException e) {
        throw new IndelibleWebAccessException(IndelibleWebAccessException.kInternalError, e);
    } catch (ObjectNotFoundException e) {
        throw new IndelibleWebAccessException(IndelibleWebAccessException.kPathNotFound, e);
    } catch (ForkNotFoundException e) {
        throw new IndelibleWebAccessException(IndelibleWebAccessException.kForkNotFound, e);
    } finally {
        if (!completedOK)
            try {
                connection.rollback();
            } catch (IOException e) {
                throw new IndelibleWebAccessException(IndelibleWebAccessException.kInternalError, e);
            }
    }
}

From source file:com.igeekinc.indelible.indeliblefs.webaccess.IndelibleWebAccessServlet.java

public void createVolume(HttpServletRequest req, HttpServletResponse resp, Document buildDoc)
        throws RemoteException, IndelibleWebAccessException {
    try {//from www . j a v  a2 s  .  c  o  m
        connection.startTransaction();
        IndelibleFSVolumeIF createVolume = connection.createVolume(null);
        connection.commit();
        Element rootElem = buildDoc.createElement("createVolume");
        buildDoc.appendChild(rootElem);
        XMLUtils.appendSingleValElement(buildDoc, rootElem, "fsid", createVolume.getObjectID().toString());
    } catch (PermissionDeniedException e) {
        throw new IndelibleWebAccessException(IndelibleWebAccessException.kPermissionDenied, e);
    } catch (IOException e) {
        throw new IndelibleWebAccessException(IndelibleWebAccessException.kInternalError, e);
    }
}

From source file:edu.isi.pfindr.servlets.QueryServlet.java

/**
 * get the XML string of the results of an SQL Query 
 * /*from   w w  w. j  av a 2 s  .c  o m*/
 * @param request
 *            the servlet request
 * @param conn
 *            the DB connection
 * @return the XML string to be saved in a file
 */
@SuppressWarnings("unused")
private String saveXML(HttpServletRequest request, Connection conn) {
    String sql = request.getParameter("sql");
    JSONObject json;
    String phenotypes = "";
    try {
        // get the query results
        json = new JSONObject(sql);
        String sqlQuery = Utils.getPhenotypesSQL(json);
        logger.info(sqlQuery);
        PreparedStatement stmt = conn.prepareStatement(sqlQuery);
        Utils.loadValues(stmt, json, "", false);
        JSONArray group = new JSONArray(request.getParameter("template"));
        JSONArray rows = Utils.executeSQL(stmt);
        stmt.close();

        // create the document builder
        DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
        Document doc = docBuilder.newDocument();
        Element root = doc.createElement("Phenotypes");
        doc.appendChild(root);

        // append the query results to the document
        JSONObject res = Utils.toJSONObject(group, rows);
        Utils.toXML(doc, root, res);

        // transform the document to an XML string
        TransformerFactory transfac = TransformerFactory.newInstance();
        Transformer trans = transfac.newTransformer();
        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        trans.setOutputProperty(OutputKeys.INDENT, "yes");
        StringWriter sw = new StringWriter();
        StreamResult result = new StreamResult(sw);
        DOMSource source = new DOMSource(doc);
        trans.transform(source, result);
        phenotypes = sw.toString();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (TransformerConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (TransformerException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return phenotypes;
}

From source file:net.solarnetwork.node.support.XmlServiceSupport.java

/**
 * Turn an object into a simple XML Document.
 * /*  ww w.  j  a v  a2  s. c  o m*/
 * <p>
 * The returned XML will be a single element with all JavaBean properties
 * turned into attributes. For example:
 * <p>
 * 
 * <pre>
 * &lt;powerDatum
 *   id="123"
 *   pvVolts="123.123"
 *   ... /&gt;
 * </pre>
 * 
 * @param o
 *        the object to turn into XML
 * @param elementName
 *        the name of the XML element
 * @return the element, as an XML DOM Document
 */
protected Document getSimpleDocument(Object o, String elementName) {
    Document dom = null;
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
    try {
        dom = getDocBuilderFactory().newDocumentBuilder().newDocument();
        Element root = dom.createElement(elementName);
        dom.appendChild(root);
        Map<String, Object> props = ClassUtils.getBeanProperties(o, null);
        for (Map.Entry<String, Object> me : props.entrySet()) {
            Object val = me.getValue();
            if (val instanceof Date) {
                val = sdf.format((Date) val);
            }
            root.setAttribute(me.getKey(), val.toString());

            if (log.isTraceEnabled()) {
                log.trace("attribute name: " + me.getKey() + " attribute value: " + val.toString());
            }

        }
    } catch (ParserConfigurationException e) {
        throw new RuntimeException(e);
    }
    return dom;
}

From source file:org.shareok.data.sagedata.SageJournalDataProcessorAbstract.java

@Override
/** // ww  w .ja  va 2 s .c o m
 * Convert the article data to dublin core xml metadata and save the the file
 * 
 * @param String fileName : the root folder contains all the uploading article data
 */
public void exportXmlByJournalData(String fileName) {

    try {
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        Document doc = docBuilder.newDocument();
        Element rootElement = doc.createElement("dublin_core");
        doc.appendChild(rootElement);

        // Add the type node:
        Element element = doc.createElement("dcvalue");
        element.appendChild(doc.createTextNode("Research Article"));
        rootElement.appendChild(element);

        Attr attr = doc.createAttribute("element");
        attr.setValue("type");
        element.setAttributeNode(attr);

        attr = doc.createAttribute("language");
        attr.setValue("en_US");
        element.setAttributeNode(attr);

        attr = doc.createAttribute("qualifier");
        attr.setValue("none");
        element.setAttributeNode(attr);

        // Add the abstract node:
        String abs = journalData.getAbstractText();
        if (null != abs) {
            Element elementAbs = doc.createElement("dcvalue");
            elementAbs.appendChild(doc.createTextNode(abs));
            rootElement.appendChild(elementAbs);

            attr = doc.createAttribute("element");
            attr.setValue("description");
            elementAbs.setAttributeNode(attr);

            attr = doc.createAttribute("language");
            attr.setValue("en_US");
            elementAbs.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("abstract");
            elementAbs.setAttributeNode(attr);
        }

        // Add the language node:
        String lang = journalData.getLanguage();
        if (null != lang) {
            Element elementLang = doc.createElement("dcvalue");
            elementLang.appendChild(doc.createTextNode(lang));
            rootElement.appendChild(elementLang);

            attr = doc.createAttribute("element");
            attr.setValue("language");
            elementLang.setAttributeNode(attr);

            attr = doc.createAttribute("language");
            attr.setValue("en_US");
            elementLang.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("iso");
            elementLang.setAttributeNode(attr);
        }

        // Add the title node:
        String tit = journalData.getTitle();
        if (null != tit) {
            Element elementTitle = doc.createElement("dcvalue");
            elementTitle.appendChild(doc.createTextNode(tit));
            rootElement.appendChild(elementTitle);

            attr = doc.createAttribute("element");
            attr.setValue("title");
            elementTitle.setAttributeNode(attr);

            attr = doc.createAttribute("language");
            attr.setValue("en_US");
            elementTitle.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("none");
            elementTitle.setAttributeNode(attr);
        }

        // Add the available date node:
        //            Element elementAvailable = doc.createElement("dcvalue");
        //            elementAvailable.appendChild(doc.createTextNode(getDateAvailable().toString()));
        //            rootElement.appendChild(elementAvailable);
        //            
        //            attr = doc.createAttribute("element");
        //            attr.setValue("date");
        //            elementAvailable.setAttributeNode(attr);
        //            
        //            attr = doc.createAttribute("qualifier");
        //            attr.setValue("available");
        //            elementAvailable.setAttributeNode(attr);

        // Add the issued date node:
        Date issueDate = journalData.getDateIssued();
        if (null != issueDate) {
            SimpleDateFormat format_issuedDate = new SimpleDateFormat("yyyy-MM-dd");
            Element elementIssued = doc.createElement("dcvalue");
            elementIssued.appendChild(doc.createTextNode(format_issuedDate.format(issueDate)));
            rootElement.appendChild(elementIssued);

            attr = doc.createAttribute("element");
            attr.setValue("date");
            elementIssued.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("issued");
            elementIssued.setAttributeNode(attr);
        }

        // Add the author nodes:
        String[] authorSet = journalData.getAuthors();
        if (null != authorSet && authorSet.length > 0) {
            for (String author : authorSet) {
                Element elementAuthor = doc.createElement("dcvalue");
                elementAuthor.appendChild(doc.createTextNode(author));
                rootElement.appendChild(elementAuthor);

                attr = doc.createAttribute("element");
                attr.setValue("contributor");
                elementAuthor.setAttributeNode(attr);

                attr = doc.createAttribute("qualifier");
                attr.setValue("author");
                elementAuthor.setAttributeNode(attr);
            }
        }

        // Add the acknowledgements node:
        String ack = journalData.getAcknowledgements();
        if (null != ack) {
            Element elementAck = doc.createElement("dcvalue");
            elementAck.appendChild(doc.createTextNode(ack));
            rootElement.appendChild(elementAck);

            attr = doc.createAttribute("element");
            attr.setValue("description");
            elementAck.setAttributeNode(attr);

            attr = doc.createAttribute("language");
            attr.setValue("en_US");
            elementAck.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("none");
            elementAck.setAttributeNode(attr);
        }

        // Add the author contributions node:
        String contrib = journalData.getAuthorContributions();
        if (null != contrib) {
            Element elementContribution = doc.createElement("dcvalue");
            elementContribution.appendChild(doc.createTextNode(contrib));
            rootElement.appendChild(elementContribution);

            attr = doc.createAttribute("element");
            attr.setValue("description");
            elementContribution.setAttributeNode(attr);

            attr = doc.createAttribute("language");
            attr.setValue("en_US");
            elementContribution.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("none");
            elementContribution.setAttributeNode(attr);
        }

        // Add the publisher node:
        String puber = journalData.getPublisher();
        if (null != puber) {
            Element elementPublisher = doc.createElement("dcvalue");
            elementPublisher.appendChild(doc.createTextNode(puber));
            rootElement.appendChild(elementPublisher);

            attr = doc.createAttribute("element");
            attr.setValue("publisher");
            elementPublisher.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("none");
            elementPublisher.setAttributeNode(attr);
        }

        // Add the citation node:
        String cit = journalData.getCitation();
        if (null != cit) {
            Element elementCitation = doc.createElement("dcvalue");
            elementCitation.appendChild(doc.createTextNode(cit));
            rootElement.appendChild(elementCitation);

            attr = doc.createAttribute("element");
            attr.setValue("identifier");
            elementCitation.setAttributeNode(attr);

            attr = doc.createAttribute("language");
            attr.setValue("en_US");
            elementCitation.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("citation");
            elementCitation.setAttributeNode(attr);
        }

        // Add the rights node:
        String rit = journalData.getRights();
        if (null != rit) {
            Element elementRights = doc.createElement("dcvalue");
            elementRights.appendChild(doc.createTextNode(rit));
            rootElement.appendChild(elementRights);

            attr = doc.createAttribute("element");
            attr.setValue("rights");
            elementRights.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("none");
            elementRights.setAttributeNode(attr);
        }

        // Add the rights URI node:
        String ritUri = journalData.getRightsUri();
        if (null != ritUri) {
            Element elementRightsUri = doc.createElement("dcvalue");
            elementRightsUri.appendChild(doc.createTextNode(ritUri));
            rootElement.appendChild(elementRightsUri);

            attr = doc.createAttribute("element");
            attr.setValue("rights");
            elementRightsUri.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("uri");
            elementRightsUri.setAttributeNode(attr);
        }

        // Add the rights requestable node:
        Element elementRightsRequestable = doc.createElement("dcvalue");
        elementRightsRequestable
                .appendChild(doc.createTextNode(Boolean.toString(journalData.isRightsRequestable())));
        rootElement.appendChild(elementRightsRequestable);

        attr = doc.createAttribute("element");
        attr.setValue("rights");
        elementRightsRequestable.setAttributeNode(attr);

        attr = doc.createAttribute("language");
        attr.setValue("en_US");
        elementRightsRequestable.setAttributeNode(attr);

        attr = doc.createAttribute("qualifier");
        attr.setValue("requestable");
        elementRightsRequestable.setAttributeNode(attr);

        // Add the is part of node:
        String partOf = journalData.getIsPartOfSeries();
        if (null != partOf) {
            Element elementIsPartOf = doc.createElement("dcvalue");
            elementIsPartOf.appendChild(doc.createTextNode(partOf));
            rootElement.appendChild(elementIsPartOf);

            attr = doc.createAttribute("element");
            attr.setValue("relation");
            elementIsPartOf.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("ispartofseries");
            elementIsPartOf.setAttributeNode(attr);
        }

        // Add the relation uri node:
        String reUri = journalData.getRelationUri();
        if (null != reUri) {
            Element elementRelationUri = doc.createElement("dcvalue");
            elementRelationUri.appendChild(doc.createTextNode(reUri));
            rootElement.appendChild(elementRelationUri);

            attr = doc.createAttribute("element");
            attr.setValue("relation");
            elementRelationUri.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("uri");
            elementRelationUri.setAttributeNode(attr);
        }

        // Add the subject nodes:
        String[] subjectSet = journalData.getSubjects();
        if (null != subjectSet && subjectSet.length > 0) {
            for (String subject : subjectSet) {
                Element elementSubject = doc.createElement("dcvalue");
                elementSubject.appendChild(doc.createTextNode(subject));
                rootElement.appendChild(elementSubject);

                attr = doc.createAttribute("element");
                attr.setValue("subject");
                elementSubject.setAttributeNode(attr);

                attr = doc.createAttribute("language");
                attr.setValue("en_US");
                elementSubject.setAttributeNode(attr);

                attr = doc.createAttribute("qualifier");
                attr.setValue("none");
                elementSubject.setAttributeNode(attr);
            }
        }

        // Add the peerReview node:
        String review = journalData.getPeerReview();
        if (null != review) {
            Element elementPeerReview = doc.createElement("dcvalue");
            elementPeerReview.appendChild(doc.createTextNode(review));
            rootElement.appendChild(elementPeerReview);

            attr = doc.createAttribute("element");
            attr.setValue("description");
            elementPeerReview.setAttributeNode(attr);

            attr = doc.createAttribute("language");
            attr.setValue("en_US");
            elementPeerReview.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("peerreview");
            elementPeerReview.setAttributeNode(attr);
        }

        // Add the peer review notes node:
        String peer = journalData.getPeerReviewNotes();
        if (null != peer) {
            Element elementPeerReviewNotes = doc.createElement("dcvalue");
            elementPeerReviewNotes.appendChild(doc.createTextNode(peer));
            rootElement.appendChild(elementPeerReviewNotes);

            attr = doc.createAttribute("element");
            attr.setValue("description");
            elementPeerReviewNotes.setAttributeNode(attr);

            attr = doc.createAttribute("language");
            attr.setValue("en_US");
            elementPeerReviewNotes.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("peerreviewnotes");
            elementPeerReviewNotes.setAttributeNode(attr);
        }

        // Add the doi node:
        String doi = journalData.getDoi();
        if (null != doi) {
            Element elementDoi = doc.createElement("dcvalue");
            elementDoi.appendChild(doc.createTextNode(doi));
            rootElement.appendChild(elementDoi);

            attr = doc.createAttribute("element");
            attr.setValue("identifier");
            elementDoi.setAttributeNode(attr);

            attr = doc.createAttribute("language");
            attr.setValue("en_US");
            elementDoi.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("doi");
            elementDoi.setAttributeNode(attr);
        }

        String folderPath = setOutputPath(fileName);
        String filePath = folderPath + "/dublin_core.xml";
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File(filePath));

        transformer.transform(source, result);

    } catch (ParserConfigurationException | TransformerException pce) {
        pce.printStackTrace();
    } catch (DOMException | BeansException e) {
        e.printStackTrace();
    }
}

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/*from   ww  w. jav a  2 s.  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:org.shareok.data.plosdata.PlosData.java

/**
 * Generate the metadata xml file/* ww  w.ja v  a 2  s  .c o m*/
 * @param fileName 
 */
public void exportXmlByDoiData(String fileName) {

    try {
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        Document doc = docBuilder.newDocument();
        Element rootElement = doc.createElement("dublin_core");
        doc.appendChild(rootElement);

        // Add the type node:
        Element element = doc.createElement("dcvalue");
        element.appendChild(doc.createTextNode("Research Article"));
        rootElement.appendChild(element);

        Attr attr = doc.createAttribute("element");
        attr.setValue("type");
        element.setAttributeNode(attr);

        attr = doc.createAttribute("language");
        attr.setValue("en_US");
        element.setAttributeNode(attr);

        attr = doc.createAttribute("qualifier");
        attr.setValue("none");
        element.setAttributeNode(attr);

        // Add the abstract node:
        String abs = getAbstractText();
        if (null != abs) {
            Element elementAbs = doc.createElement("dcvalue");
            elementAbs.appendChild(doc.createTextNode(abs));
            rootElement.appendChild(elementAbs);

            attr = doc.createAttribute("element");
            attr.setValue("description");
            elementAbs.setAttributeNode(attr);

            attr = doc.createAttribute("language");
            attr.setValue("en_US");
            elementAbs.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("abstract");
            elementAbs.setAttributeNode(attr);
        }

        // Add the language node:
        String lang = getLanguage();
        if (null != lang) {
            Element elementLang = doc.createElement("dcvalue");
            elementLang.appendChild(doc.createTextNode(lang));
            rootElement.appendChild(elementLang);

            attr = doc.createAttribute("element");
            attr.setValue("language");
            elementLang.setAttributeNode(attr);

            attr = doc.createAttribute("language");
            attr.setValue("en_US");
            elementLang.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("iso");
            elementLang.setAttributeNode(attr);
        }

        // Add the title node:
        String tit = getTitle();
        if (null != tit) {
            Element elementTitle = doc.createElement("dcvalue");
            elementTitle.appendChild(doc.createTextNode(tit));
            rootElement.appendChild(elementTitle);

            attr = doc.createAttribute("element");
            attr.setValue("title");
            elementTitle.setAttributeNode(attr);

            attr = doc.createAttribute("language");
            attr.setValue("en_US");
            elementTitle.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("none");
            elementTitle.setAttributeNode(attr);
        }

        // Add the available date node:
        //            Element elementAvailable = doc.createElement("dcvalue");
        //            elementAvailable.appendChild(doc.createTextNode(getDateAvailable().toString()));
        //            rootElement.appendChild(elementAvailable);
        //            
        //            attr = doc.createAttribute("element");
        //            attr.setValue("date");
        //            elementAvailable.setAttributeNode(attr);
        //            
        //            attr = doc.createAttribute("qualifier");
        //            attr.setValue("available");
        //            elementAvailable.setAttributeNode(attr);

        // Add the issued date node:
        Date issueDate = getDateIssued();
        if (null != issueDate) {
            SimpleDateFormat format_issuedDate = new SimpleDateFormat("yyyy-MM-dd");
            Element elementIssued = doc.createElement("dcvalue");
            elementIssued.appendChild(doc.createTextNode(format_issuedDate.format(issueDate)));
            rootElement.appendChild(elementIssued);

            attr = doc.createAttribute("element");
            attr.setValue("date");
            elementIssued.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("issued");
            elementIssued.setAttributeNode(attr);
        }

        // Add the author nodes:
        String[] authorSet = getAuthors();
        if (null != authorSet && authorSet.length > 0) {
            for (String author : authorSet) {
                Element elementAuthor = doc.createElement("dcvalue");
                elementAuthor.appendChild(doc.createTextNode(author));
                rootElement.appendChild(elementAuthor);

                attr = doc.createAttribute("element");
                attr.setValue("contributor");
                elementAuthor.setAttributeNode(attr);

                attr = doc.createAttribute("qualifier");
                attr.setValue("author");
                elementAuthor.setAttributeNode(attr);
            }
        }

        // Add the acknowledgements node:
        String ack = getAcknowledgements();
        if (null != ack) {
            Element elementAck = doc.createElement("dcvalue");
            elementAck.appendChild(doc.createTextNode(ack));
            rootElement.appendChild(elementAck);

            attr = doc.createAttribute("element");
            attr.setValue("description");
            elementAck.setAttributeNode(attr);

            attr = doc.createAttribute("language");
            attr.setValue("en_US");
            elementAck.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("none");
            elementAck.setAttributeNode(attr);
        }

        // Add the author contributions node:
        String contrib = getAuthorContributions();
        if (null != contrib) {
            Element elementContribution = doc.createElement("dcvalue");
            elementContribution.appendChild(doc.createTextNode(contrib));
            rootElement.appendChild(elementContribution);

            attr = doc.createAttribute("element");
            attr.setValue("description");
            elementContribution.setAttributeNode(attr);

            attr = doc.createAttribute("language");
            attr.setValue("en_US");
            elementContribution.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("none");
            elementContribution.setAttributeNode(attr);
        }

        // Add the publisher node:
        String puber = getPublisher();
        if (null != puber) {
            Element elementPublisher = doc.createElement("dcvalue");
            elementPublisher.appendChild(doc.createTextNode(puber));
            rootElement.appendChild(elementPublisher);

            attr = doc.createAttribute("element");
            attr.setValue("publisher");
            elementPublisher.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("none");
            elementPublisher.setAttributeNode(attr);
        }

        // Add the citation node:
        String cit = getCitation();
        if (null != cit) {
            Element elementCitation = doc.createElement("dcvalue");
            elementCitation.appendChild(doc.createTextNode(cit));
            rootElement.appendChild(elementCitation);

            attr = doc.createAttribute("element");
            attr.setValue("identifier");
            elementCitation.setAttributeNode(attr);

            attr = doc.createAttribute("language");
            attr.setValue("en_US");
            elementCitation.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("citation");
            elementCitation.setAttributeNode(attr);
        }

        // Add the rights node:
        String rit = getRights();
        if (null != rit) {
            Element elementRights = doc.createElement("dcvalue");
            elementRights.appendChild(doc.createTextNode(rit));
            rootElement.appendChild(elementRights);

            attr = doc.createAttribute("element");
            attr.setValue("rights");
            elementRights.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("none");
            elementRights.setAttributeNode(attr);
        }

        // Add the rights URI node:
        String ritUri = getRightsUri();
        if (null != ritUri) {
            Element elementRightsUri = doc.createElement("dcvalue");
            elementRightsUri.appendChild(doc.createTextNode(ritUri));
            rootElement.appendChild(elementRightsUri);

            attr = doc.createAttribute("element");
            attr.setValue("rights");
            elementRightsUri.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("uri");
            elementRightsUri.setAttributeNode(attr);
        }

        // Add the rights requestable node:
        Element elementRightsRequestable = doc.createElement("dcvalue");
        elementRightsRequestable.appendChild(doc.createTextNode(Boolean.toString(isRightsRequestable())));
        rootElement.appendChild(elementRightsRequestable);

        attr = doc.createAttribute("element");
        attr.setValue("rights");
        elementRightsRequestable.setAttributeNode(attr);

        attr = doc.createAttribute("language");
        attr.setValue("en_US");
        elementRightsRequestable.setAttributeNode(attr);

        attr = doc.createAttribute("qualifier");
        attr.setValue("requestable");
        elementRightsRequestable.setAttributeNode(attr);

        // Add the is part of node:
        String partOf = getIsPartOfSeries();
        if (null != partOf) {
            Element elementIsPartOf = doc.createElement("dcvalue");
            elementIsPartOf.appendChild(doc.createTextNode(partOf));
            rootElement.appendChild(elementIsPartOf);

            attr = doc.createAttribute("element");
            attr.setValue("relation");
            elementIsPartOf.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("ispartofseries");
            elementIsPartOf.setAttributeNode(attr);
        }

        // Add the relation uri node:
        String reUri = getRelationUri();
        if (null != reUri) {
            Element elementRelationUri = doc.createElement("dcvalue");
            elementRelationUri.appendChild(doc.createTextNode(reUri));
            rootElement.appendChild(elementRelationUri);

            attr = doc.createAttribute("element");
            attr.setValue("relation");
            elementRelationUri.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("uri");
            elementRelationUri.setAttributeNode(attr);
        }

        // Add the subject nodes:
        String[] subjectSet = getSubjects();
        if (null != subjectSet && subjectSet.length > 0) {
            for (String subject : subjectSet) {
                Element elementSubject = doc.createElement("dcvalue");
                elementSubject.appendChild(doc.createTextNode(subject));
                rootElement.appendChild(elementSubject);

                attr = doc.createAttribute("element");
                attr.setValue("subject");
                elementSubject.setAttributeNode(attr);

                attr = doc.createAttribute("language");
                attr.setValue("en_US");
                elementSubject.setAttributeNode(attr);

                attr = doc.createAttribute("qualifier");
                attr.setValue("none");
                elementSubject.setAttributeNode(attr);
            }
        }

        // Add the peerReview node:
        String review = getPeerReview();
        if (null != review) {
            Element elementPeerReview = doc.createElement("dcvalue");
            elementPeerReview.appendChild(doc.createTextNode(review));
            rootElement.appendChild(elementPeerReview);

            attr = doc.createAttribute("element");
            attr.setValue("description");
            elementPeerReview.setAttributeNode(attr);

            attr = doc.createAttribute("language");
            attr.setValue("en_US");
            elementPeerReview.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("peerreview");
            elementPeerReview.setAttributeNode(attr);
        }

        // Add the peer review notes node:
        String peer = getPeerReviewNotes();
        if (null != peer) {
            Element elementPeerReviewNotes = doc.createElement("dcvalue");
            elementPeerReviewNotes.appendChild(doc.createTextNode(peer));
            rootElement.appendChild(elementPeerReviewNotes);

            attr = doc.createAttribute("element");
            attr.setValue("description");
            elementPeerReviewNotes.setAttributeNode(attr);

            attr = doc.createAttribute("language");
            attr.setValue("en_US");
            elementPeerReviewNotes.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("peerreviewnotes");
            elementPeerReviewNotes.setAttributeNode(attr);
        }

        // Add the doi node:
        String doi = getDoi();
        if (null != doi) {
            Element elementDoi = doc.createElement("dcvalue");
            elementDoi.appendChild(doc.createTextNode(doi));
            rootElement.appendChild(elementDoi);

            attr = doc.createAttribute("element");
            attr.setValue("identifier");
            elementDoi.setAttributeNode(attr);

            attr = doc.createAttribute("language");
            attr.setValue("en_US");
            elementDoi.setAttributeNode(attr);

            attr = doc.createAttribute("qualifier");
            attr.setValue("doi");
            elementDoi.setAttributeNode(attr);
        }

        // Generate the xml file:
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File(fileName));

        transformer.transform(source, result);
    } catch (ParserConfigurationException | TransformerException pce) {
        pce.printStackTrace();
        System.exit(0);
    } catch (DOMException | BeansException e) {
        e.printStackTrace();
        System.exit(0);
    }
}

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./* w w w . j av a2  s  . com*/
* @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();
        }
    }
}