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:com.microsoft.windowsazure.management.sql.DacOperationsImpl.java

/**
* Gets the status of the import or export operation in the specified server
* with the corresponding request ID.  The request ID is provided in the
* responses of the import or export operation.
*
* @param serverName Required. The name of the server in which the import or
* export operation is taking place.// www .j a v a 2 s  . c  o  m
* @param parameters Required. The parameters needed to get the status of an
* import or export 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.
* @throws URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return Represents a list of import or export status values returned from
* GetStatus.
*/
@Override
public DacGetStatusResponse getStatusPost(String serverName, DacGetStatusParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException,
        URISyntaxException {
    // Validate
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getPassword() == null) {
        throw new NullPointerException("parameters.Password");
    }
    if (parameters.getRequestId() == null) {
        throw new NullPointerException("parameters.RequestId");
    }
    if (parameters.getServerName() == null) {
        throw new NullPointerException("parameters.ServerName");
    }
    if (parameters.getUserName() == null) {
        throw new NullPointerException("parameters.UserName");
    }

    // 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("serverName", serverName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "getStatusPostAsync", 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/sqlservers/servers/";
    url = url + URLEncoder.encode(serverName, "UTF-8");
    url = url + "/DacOperations/Status";
    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", "2012-03-01");

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

    Element statusInputElement = requestDoc.createElementNS(
            "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
            "StatusInput");
    requestDoc.appendChild(statusInputElement);

    Element passwordElement = requestDoc.createElementNS(
            "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
            "Password");
    passwordElement.appendChild(requestDoc.createTextNode(parameters.getPassword()));
    statusInputElement.appendChild(passwordElement);

    Element requestIdElement = requestDoc.createElementNS(
            "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
            "RequestId");
    requestIdElement.appendChild(requestDoc.createTextNode(parameters.getRequestId()));
    statusInputElement.appendChild(requestIdElement);

    Element serverNameElement = requestDoc.createElementNS(
            "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
            "ServerName");
    serverNameElement.appendChild(requestDoc.createTextNode(parameters.getServerName()));
    statusInputElement.appendChild(serverNameElement);

    Element userNameElement = requestDoc.createElementNS(
            "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
            "UserName");
    userNameElement.appendChild(requestDoc.createTextNode(parameters.getUserName()));
    statusInputElement.appendChild(userNameElement);

    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_OK) {
            ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

        // Create Result
        DacGetStatusResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new DacGetStatusResponse();
            DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance();
            documentBuilderFactory2.setNamespaceAware(true);
            DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder();
            Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent));

            Element arrayOfStatusInfoElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                    "ArrayOfStatusInfo");
            if (arrayOfStatusInfoElement != null) {
                if (arrayOfStatusInfoElement != null) {
                    for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(arrayOfStatusInfoElement,
                                    "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                                    "StatusInfo")
                            .size(); i1 = i1 + 1) {
                        org.w3c.dom.Element statusInfoElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(arrayOfStatusInfoElement,
                                        "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                                        "StatusInfo")
                                .get(i1));
                        StatusInfo statusInfoInstance = new StatusInfo();
                        result.getStatusInfoList().add(statusInfoInstance);

                        Element blobUriElement = XmlUtility.getElementByTagNameNS(statusInfoElement,
                                "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                                "BlobUri");
                        if (blobUriElement != null) {
                            URI blobUriInstance;
                            blobUriInstance = new URI(blobUriElement.getTextContent());
                            statusInfoInstance.setBlobUri(blobUriInstance);
                        }

                        Element databaseNameElement = XmlUtility.getElementByTagNameNS(statusInfoElement,
                                "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                                "DatabaseName");
                        if (databaseNameElement != null) {
                            String databaseNameInstance;
                            databaseNameInstance = databaseNameElement.getTextContent();
                            statusInfoInstance.setDatabaseName(databaseNameInstance);
                        }

                        Element errorMessageElement = XmlUtility.getElementByTagNameNS(statusInfoElement,
                                "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                                "ErrorMessage");
                        if (errorMessageElement != null) {
                            boolean isNil = false;
                            Attr nilAttribute = errorMessageElement
                                    .getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil");
                            if (nilAttribute != null) {
                                isNil = "true".equals(nilAttribute.getValue());
                            }
                            if (isNil == false) {
                                String errorMessageInstance;
                                errorMessageInstance = errorMessageElement.getTextContent();
                                statusInfoInstance.setErrorMessage(errorMessageInstance);
                            }
                        }

                        Element lastModifiedTimeElement = XmlUtility.getElementByTagNameNS(statusInfoElement,
                                "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                                "LastModifiedTime");
                        if (lastModifiedTimeElement != null) {
                            Calendar lastModifiedTimeInstance;
                            lastModifiedTimeInstance = DatatypeConverter
                                    .parseDateTime(lastModifiedTimeElement.getTextContent());
                            statusInfoInstance.setLastModifiedTime(lastModifiedTimeInstance);
                        }

                        Element queuedTimeElement = XmlUtility.getElementByTagNameNS(statusInfoElement,
                                "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                                "QueuedTime");
                        if (queuedTimeElement != null) {
                            Calendar queuedTimeInstance;
                            queuedTimeInstance = DatatypeConverter
                                    .parseDateTime(queuedTimeElement.getTextContent());
                            statusInfoInstance.setQueuedTime(queuedTimeInstance);
                        }

                        Element requestIdElement2 = XmlUtility.getElementByTagNameNS(statusInfoElement,
                                "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                                "RequestId");
                        if (requestIdElement2 != null) {
                            String requestIdInstance;
                            requestIdInstance = requestIdElement2.getTextContent();
                            statusInfoInstance.setRequestId(requestIdInstance);
                        }

                        Element requestTypeElement = XmlUtility.getElementByTagNameNS(statusInfoElement,
                                "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                                "RequestType");
                        if (requestTypeElement != null) {
                            String requestTypeInstance;
                            requestTypeInstance = requestTypeElement.getTextContent();
                            statusInfoInstance.setRequestType(requestTypeInstance);
                        }

                        Element serverNameElement2 = XmlUtility.getElementByTagNameNS(statusInfoElement,
                                "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                                "ServerName");
                        if (serverNameElement2 != null) {
                            String serverNameInstance;
                            serverNameInstance = serverNameElement2.getTextContent();
                            statusInfoInstance.setServerName(serverNameInstance);
                        }

                        Element statusElement = XmlUtility.getElementByTagNameNS(statusInfoElement,
                                "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                                "Status");
                        if (statusElement != null) {
                            String statusInstance;
                            statusInstance = statusElement.getTextContent();
                            statusInfoInstance.setStatus(statusInstance);
                        }
                    }
                }
            }

        }
        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:dk.statsbiblioteket.doms.central.connectors.fedora.FedoraRest.java

@Override
public void addRelations(String pid, String subject, String predicate, List<String> objects, boolean literal,
        String comment)//from  ww  w . ja  va2 s.  c om
        throws BackendMethodFailedException, BackendInvalidCredsException, BackendInvalidResourceException {
    if (comment == null || comment.isEmpty()) {
        comment = "No message supplied";
    }
    if (literal) {//cant handle literal yet
        for (String object : objects) {
            addRelation(pid, subject, predicate, object, literal, comment);
        }
    }
    if (objects.size() == 1) {//more efficient if only adding one relation
        addRelation(pid, subject, predicate, objects.get(0), literal, comment);
    }

    XPathSelector xpath = DOM.createXPathSelector("rdf", Constants.NAMESPACE_RDF);

    String datastream;
    if (subject == null || subject.isEmpty() || subject.equals(pid) || subject.equals("info:fedora/" + pid)) {
        subject = "info:fedora/" + pid;
        datastream = "RELS-EXT";
    } else {
        datastream = "RELS-INT";
    }

    String rels = getXMLDatastreamContents(pid, datastream, null);
    Document relsDoc = DOM.stringToDOM(rels, true);

    Node rdfDescriptionNode = xpath.selectNode(relsDoc,
            "/rdf:RDF/rdf:Description[@rdf:about='" + subject + "']");

    predicate = getAbsoluteURIAsString(predicate);

    String[] splits = predicate.split("#");

    for (String object : objects) {
        if (!object.startsWith("info:fedora/")) {
            object = "info:fedora/" + object;
        }

        Element relationsShipElement = relsDoc.createElementNS(splits[0] + "#", splits[1]);
        relationsShipElement.setAttributeNS(Constants.NAMESPACE_RDF, "rdf:resource", object);
        rdfDescriptionNode.appendChild(relationsShipElement);
    }

    byte[] bytes;
    try {
        bytes = DOM.domToString(relsDoc).getBytes("UTF-8");
    } catch (UnsupportedEncodingException e) {
        //TODO Not really a backend exception
        throw new BackendMethodFailedException("Failed to transform RELS-EXT", e);
    } catch (TransformerException e) {
        //TODO Not really a backend exception
        throw new BackendMethodFailedException("Failed to transform RELS-EXT", e);
    }
    modifyDatastreamByValue(pid, datastream, ChecksumType.MD5, null, bytes, null, "application/rdf+xml",
            comment, null);
}

From source file:br.org.indt.mobisus.common.ResultWriter.java

public void write() throws ParserConfigurationException, Exception {
    logger.info("creatint result file in " + resultPath);
    Document xmldoc = null;
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    DOMImplementation impl = builder.getDOMImplementation();
    Element answerElement = null;
    Element categoryElement = null;
    Element text = null;//from   w  w  w  . ja  va 2s  .c o m
    Element title = null;
    Element lat = null;
    Element lon = null;
    Element other = null;
    Node titleText = null;
    Node nodeStr = null;

    xmldoc = impl.createDocument(null, "result", null);

    Element root = xmldoc.getDocumentElement();

    root.setAttribute("r_id", result.getResultId());
    root.setAttribute("s_id", result.getSurveyId());
    root.setAttribute("u_id", result.getUserId());
    root.setAttribute("time", result.getTime());

    if (result.getLatitude() != null) {
        lat = xmldoc.createElementNS(null, "latitude");
        titleText = xmldoc.createTextNode(result.getLatitude());
        lat.appendChild(titleText);
        root.appendChild(lat);
    }

    if (result.getLongitude() != null) {
        lon = xmldoc.createElementNS(null, "longitude");
        titleText = xmldoc.createTextNode(result.getLongitude());
        lon.appendChild(titleText);
        root.appendChild(lon);
    }

    title = xmldoc.createElementNS(null, "title");
    titleText = xmldoc.createTextNode("");
    title.appendChild(titleText);
    root.appendChild(title);

    TreeMap<Integer, Category> categories = survey.getCategories();
    Iterator<Category> iteratorCat = categories.values().iterator();
    while (iteratorCat.hasNext()) {
        Category category = iteratorCat.next();
        categoryElement = xmldoc.createElementNS(null, "category");
        categoryElement.setAttribute("name", category.getName());
        categoryElement.setAttribute("id", String.valueOf(category.getId()));
        root.appendChild(categoryElement);
        Integer categoryId = new Integer(category.getId());
        Vector<Field> questions = category.getFields();
        for (Field question : questions) {
            answerElement = xmldoc.createElementNS(null, "answer");
            answerElement.setAttributeNS(null, "type", question.getXmlType());
            answerElement.setAttributeNS(null, "id", String.valueOf(question.getId()));
            answerElement.setAttributeNS(null, "visited", "false");
            Field answer = result.getCategories().get(categoryId).getFieldById(question.getId());

            if (question.getFieldType() == FieldType.CHOICE) {
                ArrayList<Item> items = answer.getChoice().getItems();
                for (Item item : items) {
                    if (item.getOtr() == null || item.getOtr().equals("0")) {
                        nodeStr = xmldoc.createTextNode("" + item.getIndex());
                        text = xmldoc.createElementNS(null, question.getElementName());
                        text.appendChild(nodeStr);
                        answerElement.appendChild(text);
                        categoryElement.appendChild(answerElement);
                    } else {
                        nodeStr = xmldoc.createTextNode(item.getValue());
                        other = xmldoc.createElementNS(null, "other");
                        other.setAttributeNS(null, "index", "" + item.getIndex());
                        other.appendChild(nodeStr);
                        answerElement.appendChild(other);
                        categoryElement.appendChild(answerElement);
                    }
                }
            } else {
                nodeStr = xmldoc.createTextNode((answer.getValue() == null ? "" : answer.getValue()));
                text = xmldoc.createElementNS(null, question.getElementName());
                text.appendChild(nodeStr);
                answerElement.appendChild(text);
                categoryElement.appendChild(answerElement);
            }

            if ((question.getCategoryId() == survey.getDisplayCategory())
                    && (question.getId() == survey.getDisplayQuestion())) {
                (root.getElementsByTagName("title")).item(0).setTextContent(answer.getValue());
            }

        }

    }

    ResultDeploy resultDeploy = new ResultDeploy(xmldoc, getNextResultFile());
    resultDeploy.deploy(resultPath);
}

From source file:de.fuberlin.wiwiss.marbles.MarblesServlet.java

/**
 * Enhances source data with consistently colored icons;
 * adds detailed source list to Fresnel output
 * /*from w  w w .ja v a2s  .  c  o  m*/
 * @param doc   The Fresnel tree 
 */
private void addSources(Document doc, List<org.apache.commons.httpclient.URI> retrievedURLs) {
    int colorIndex = 0;
    HashMap<String, Source> sources = new HashMap<String, Source>();

    NodeList nodeList = doc.getElementsByTagName("source");
    int numNodes = nodeList.getLength();

    for (int i = 0; i < numNodes; i++) {
        Node node = nodeList.item(i);
        String uri = node.getFirstChild().getFirstChild().getNodeValue();

        Source source;

        /* Get source, create it if necessary */
        if (null == (source = sources.get(uri))) {
            source = new Source(uri);
            colorIndex = source.determineIcon(colorIndex);
            sources.put(uri, source);
        }

        /* Enhance source reference with icon */
        Element sourceIcon = doc.createElementNS(Constants.nsFresnelView, "sourceIcon");
        sourceIcon.appendChild(doc.createTextNode(source.getIcon()));
        node.appendChild(sourceIcon);
    }

    /* Supplement source list with retrieved URLs */
    if (retrievedURLs != null)
        for (org.apache.commons.httpclient.URI uri : retrievedURLs) {
            Source source;
            if (null == (source = sources.get(uri.toString()))) {
                source = new Source(uri.toString());
                colorIndex = source.determineIcon(colorIndex);
                sources.put(uri.toString(), source);
            }
        }

    /* Provide list of sources */
    RepositoryConnection metaDataConn = null;
    try {
        metaDataConn = metaDataRepository.getConnection();
        Element sourcesElement = doc.createElementNS(Constants.nsFresnelView, "sources");
        for (String uri : sources.keySet()) {
            Source source = sources.get(uri);
            sourcesElement.appendChild(source.toElement(doc, cacheController, metaDataConn));
        }

        Node results = doc.getFirstChild();
        results.appendChild(sourcesElement);

    } catch (RepositoryException e) {
        e.printStackTrace();
    } finally {
        try {
            if (metaDataConn != null)
                metaDataConn.close();
        } catch (RepositoryException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.microsoft.windowsazure.management.websites.WebHostingPlanOperationsImpl.java

/**
* Updates an existing Web Hosting Plan.  (see
* http://azure.microsoft.com/en-us/documentation/articles/azure-web-sites-web-hosting-plans-in-depth-overview/
* for more information)/*from  ww w.  ja  v  a 2  s .  co m*/
*
* @param webSpaceName Required. The name of the web space.
* @param webHostingPlanName Required. The name of the web hosting plan.
* @param parameters Required. Parameters supplied to the Update Web Hosting
* Plan 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.
* @throws URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return The Create Web Hosting Plan operation response.
*/
@Override
public WebHostingPlanUpdateResponse update(String webSpaceName, String webHostingPlanName,
        WebHostingPlanUpdateParameters parameters) throws ParserConfigurationException, SAXException,
        TransformerException, IOException, ServiceException, URISyntaxException {
    // Validate
    if (webSpaceName == null) {
        throw new NullPointerException("webSpaceName");
    }
    if (webHostingPlanName == null) {
        throw new NullPointerException("webHostingPlanName");
    }
    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("webSpaceName", webSpaceName);
        tracingParameters.put("webHostingPlanName", webHostingPlanName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "updateAsync", 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/WebSpaces/";
    url = url + URLEncoder.encode(webSpaceName, "UTF-8");
    url = url + "/ServerFarms/";
    url = url + URLEncoder.encode(webHostingPlanName, "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", "2014-04-01");

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

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

    if (parameters.getNumberOfWorkers() != null) {
        Element numberOfWorkersElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "NumberOfWorkers");
        numberOfWorkersElement
                .appendChild(requestDoc.createTextNode(Integer.toString(parameters.getNumberOfWorkers())));
        serverFarmElement.appendChild(numberOfWorkersElement);
    }

    if (parameters.getSKU() != null) {
        Element sKUElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "SKU");
        sKUElement.appendChild(requestDoc.createTextNode(parameters.getSKU().toString()));
        serverFarmElement.appendChild(sKUElement);
    }

    if (parameters.getWorkerSize() != null) {
        Element workerSizeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "WorkerSize");
        workerSizeElement.appendChild(requestDoc.createTextNode(parameters.getWorkerSize().toString()));
        serverFarmElement.appendChild(workerSizeElement);
    }

    if (parameters.getAdminSiteName() != null) {
        Element adminSiteNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "AdminSiteName");
        adminSiteNameElement.appendChild(requestDoc.createTextNode(parameters.getAdminSiteName()));
        serverFarmElement.appendChild(adminSiteNameElement);
    }

    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_OK) {
            ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

        // Create Result
        WebHostingPlanUpdateResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new WebHostingPlanUpdateResponse();
            DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance();
            documentBuilderFactory2.setNamespaceAware(true);
            DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder();
            Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent));

            Element serverFarmElement2 = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "ServerFarm");
            if (serverFarmElement2 != null) {
                WebHostingPlan webHostingPlanInstance = new WebHostingPlan();
                result.setWebHostingPlan(webHostingPlanInstance);

                Element nameElement = XmlUtility.getElementByTagNameNS(serverFarmElement2,
                        "http://schemas.microsoft.com/windowsazure", "Name");
                if (nameElement != null) {
                    String nameInstance;
                    nameInstance = nameElement.getTextContent();
                    webHostingPlanInstance.setName(nameInstance);
                }

                Element numberOfWorkersElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2,
                        "http://schemas.microsoft.com/windowsazure", "NumberOfWorkers");
                if (numberOfWorkersElement2 != null && numberOfWorkersElement2.getTextContent() != null
                        && !numberOfWorkersElement2.getTextContent().isEmpty()) {
                    int numberOfWorkersInstance;
                    numberOfWorkersInstance = DatatypeConverter
                            .parseInt(numberOfWorkersElement2.getTextContent());
                    webHostingPlanInstance.setNumberOfWorkers(numberOfWorkersInstance);
                }

                Element sKUElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2,
                        "http://schemas.microsoft.com/windowsazure", "SKU");
                if (sKUElement2 != null && sKUElement2.getTextContent() != null
                        && !sKUElement2.getTextContent().isEmpty()) {
                    SkuOptions sKUInstance;
                    sKUInstance = SkuOptions.valueOf(sKUElement2.getTextContent());
                    webHostingPlanInstance.setSKU(sKUInstance);
                }

                Element workerSizeElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2,
                        "http://schemas.microsoft.com/windowsazure", "WorkerSize");
                if (workerSizeElement2 != null && workerSizeElement2.getTextContent() != null
                        && !workerSizeElement2.getTextContent().isEmpty()) {
                    WorkerSizeOptions workerSizeInstance;
                    workerSizeInstance = WorkerSizeOptions.valueOf(workerSizeElement2.getTextContent());
                    webHostingPlanInstance.setWorkerSize(workerSizeInstance);
                }

                Element adminSiteNameElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2,
                        "http://schemas.microsoft.com/windowsazure", "AdminSiteName");
                if (adminSiteNameElement2 != null) {
                    String adminSiteNameInstance;
                    adminSiteNameInstance = adminSiteNameElement2.getTextContent();
                    webHostingPlanInstance.setAdminSiteName(adminSiteNameInstance);
                }
            }

        }
        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.websites.WebHostingPlanOperationsImpl.java

/**
* Creates a new Web Hosting Plan.  (see//  www .ja  v a 2 s  . c o m
* http://azure.microsoft.com/en-us/documentation/articles/azure-web-sites-web-hosting-plans-in-depth-overview/
* for more information)
*
* @param webSpaceName Required. The name of the web space.
* @param parameters Required. Web Hosting Plan Parameters.
* @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.
* @throws URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return The Create Web Web Hosting Plan operation response.
*/
@Override
public WebHostingPlanCreateResponse create(String webSpaceName, WebHostingPlanCreateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException,
        URISyntaxException {
    // Validate
    if (webSpaceName == null) {
        throw new NullPointerException("webSpaceName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getName() == null) {
        throw new NullPointerException("parameters.Name");
    }

    // 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("webSpaceName", webSpaceName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "createAsync", 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/WebSpaces/";
    url = url + URLEncoder.encode(webSpaceName, "UTF-8");
    url = url + "/ServerFarms";
    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", "2014-04-01");

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

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

    Element nameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name");
    nameElement.appendChild(requestDoc.createTextNode(parameters.getName()));
    serverFarmElement.appendChild(nameElement);

    if (parameters.getNumberOfWorkers() != null) {
        Element numberOfWorkersElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "NumberOfWorkers");
        numberOfWorkersElement
                .appendChild(requestDoc.createTextNode(Integer.toString(parameters.getNumberOfWorkers())));
        serverFarmElement.appendChild(numberOfWorkersElement);
    }

    if (parameters.getSKU() != null) {
        Element sKUElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "SKU");
        sKUElement.appendChild(requestDoc.createTextNode(parameters.getSKU().toString()));
        serverFarmElement.appendChild(sKUElement);
    }

    if (parameters.getWorkerSize() != null) {
        Element workerSizeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "WorkerSize");
        workerSizeElement.appendChild(requestDoc.createTextNode(parameters.getWorkerSize().toString()));
        serverFarmElement.appendChild(workerSizeElement);
    }

    if (parameters.getAdminSiteName() != null) {
        Element adminSiteNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "AdminSiteName");
        adminSiteNameElement.appendChild(requestDoc.createTextNode(parameters.getAdminSiteName()));
        serverFarmElement.appendChild(adminSiteNameElement);
    }

    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_OK) {
            ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

        // Create Result
        WebHostingPlanCreateResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new WebHostingPlanCreateResponse();
            DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance();
            documentBuilderFactory2.setNamespaceAware(true);
            DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder();
            Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent));

            Element serverFarmElement2 = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "ServerFarm");
            if (serverFarmElement2 != null) {
                WebHostingPlan webHostingPlanInstance = new WebHostingPlan();
                result.setWebHostingPlan(webHostingPlanInstance);

                Element nameElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2,
                        "http://schemas.microsoft.com/windowsazure", "Name");
                if (nameElement2 != null) {
                    String nameInstance;
                    nameInstance = nameElement2.getTextContent();
                    webHostingPlanInstance.setName(nameInstance);
                }

                Element numberOfWorkersElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2,
                        "http://schemas.microsoft.com/windowsazure", "NumberOfWorkers");
                if (numberOfWorkersElement2 != null && numberOfWorkersElement2.getTextContent() != null
                        && !numberOfWorkersElement2.getTextContent().isEmpty()) {
                    int numberOfWorkersInstance;
                    numberOfWorkersInstance = DatatypeConverter
                            .parseInt(numberOfWorkersElement2.getTextContent());
                    webHostingPlanInstance.setNumberOfWorkers(numberOfWorkersInstance);
                }

                Element sKUElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2,
                        "http://schemas.microsoft.com/windowsazure", "SKU");
                if (sKUElement2 != null && sKUElement2.getTextContent() != null
                        && !sKUElement2.getTextContent().isEmpty()) {
                    SkuOptions sKUInstance;
                    sKUInstance = SkuOptions.valueOf(sKUElement2.getTextContent());
                    webHostingPlanInstance.setSKU(sKUInstance);
                }

                Element workerSizeElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2,
                        "http://schemas.microsoft.com/windowsazure", "WorkerSize");
                if (workerSizeElement2 != null && workerSizeElement2.getTextContent() != null
                        && !workerSizeElement2.getTextContent().isEmpty()) {
                    WorkerSizeOptions workerSizeInstance;
                    workerSizeInstance = WorkerSizeOptions.valueOf(workerSizeElement2.getTextContent());
                    webHostingPlanInstance.setWorkerSize(workerSizeInstance);
                }

                Element adminSiteNameElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2,
                        "http://schemas.microsoft.com/windowsazure", "AdminSiteName");
                if (adminSiteNameElement2 != null) {
                    String adminSiteNameInstance;
                    adminSiteNameInstance = adminSiteNameElement2.getTextContent();
                    webHostingPlanInstance.setAdminSiteName(adminSiteNameInstance);
                }
            }

        }
        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.connectsdk.service.DLNAService.java

protected String getMessageXml(String serviceURN, String method, String instanceId,
        Map<String, String> params) {
    try {/*from  w  w w.  jav  a 2  s .com*/
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.newDocument();
        doc.setXmlStandalone(true);
        doc.setXmlVersion("1.0");

        Element root = doc.createElement("s:Envelope");
        Element bodyElement = doc.createElement("s:Body");
        Element methodElement = doc.createElementNS(serviceURN, "u:" + method);
        Element instanceElement = doc.createElement("InstanceID");

        root.setAttribute("s:encodingStyle", "http://schemas.xmlsoap.org/soap/encoding/");
        root.setAttribute("xmlns:s", "http://schemas.xmlsoap.org/soap/envelope/");

        doc.appendChild(root);
        root.appendChild(bodyElement);
        bodyElement.appendChild(methodElement);
        if (instanceId != null) {
            instanceElement.setTextContent(instanceId);
            methodElement.appendChild(instanceElement);
        }

        if (params != null) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                Element element = doc.createElement(key);
                element.setTextContent(value);
                methodElement.appendChild(element);
            }
        }
        return xmlToString(doc, true);
    } catch (Exception e) {
        return null;
    }
}

From source file:com.collabnet.tracker.core.TrackerWebServicesClient.java

public ClientArtifactListXMLHelper createOrUpdateArtifactList(Document doc, List<ClientArtifact> artifacts,
        Long lastReadOn, boolean provideReason, boolean isFoundReasonForCurrentlyProcessedArtifact,
        String reasonForCurrentlyProcessedArtifact) throws Exception {
    EngineConfiguration config = mClient.getEngineConfiguration();
    DispatcherService service = new DispatcherServiceLocator(config);
    URL portAddress = mClient.constructServiceURL("/ws/Dispatcher");
    Dispatcher theService = service.getDispatcher(portAddress);
    Element root = doc.getDocumentElement();

    Element artifactListNode = doc.createElementNS(DEFAULT_NAMESPACE, "ns1:" + "artifactList");
    root.appendChild(artifactListNode);/*from  w w  w .j ava  2 s . c om*/

    // TODO: Move all the below code to clientArtifact.java?

    HashMap<String, Integer> nameSpaces = new HashMap<String, Integer>();
    // List<String> nameSpaces = new ArrayList<String>();
    int nameSpaceCount = 1;
    nameSpaces.put(DEFAULT_NAMESPACE, nameSpaceCount);

    for (int i = 0; i < artifacts.size(); i++) {
        ClientArtifact ca = artifacts.get(i);
        String nsXNameSpace = ca.getNamespace();
        String artifactType = ca.getTagName();
        // int nsCtr;
        // check if the namespace alrady exists in the xml so far
        if (nameSpaces.get(nsXNameSpace) == null) {
            nameSpaces.put(nsXNameSpace, ++nameSpaceCount);
        }

        String nsNumberString = "ns" + nameSpaces.get(nsXNameSpace) + ":";

        Element artifactNode = doc.createElementNS(nsXNameSpace, nsNumberString + artifactType);
        artifactListNode.appendChild(artifactNode);

        Element modByNode = doc.createElementNS(DEFAULT_NAMESPACE, "ns1:" + MODIFIED_BY_FIELD_NAME);
        modByNode.appendChild(doc.createTextNode(mClient.getUserName()));
        artifactNode.appendChild(modByNode);
        if (lastReadOn != null) {
            Element lastReadNode = doc.createElementNS(DEFAULT_NAMESPACE, "ns1:" + LAST_READ_ON_FIELD_NAME);
            lastReadNode.appendChild(doc.createTextNode(Long.toString(lastReadOn)));
            artifactNode.appendChild(lastReadNode);
        } else {
            Element lastReadNode = doc.createElementNS(DEFAULT_NAMESPACE, "ns1:" + LAST_READ_ON_FIELD_NAME);
            lastReadNode.appendChild(doc.createTextNode(Long.toString(new Date().getTime())));
            artifactNode.appendChild(lastReadNode);
        }

        // Add each attribute
        Map<String, List<String>> textAttributes = ca.getAttributes();

        for (Map.Entry<String, List<String>> attributeEntry : textAttributes.entrySet()) {
            String attribute = attributeEntry.getKey();
            List<String> values = attributeEntry.getValue();

            // strip the namespace from the attribute key
            String[] parts = attribute.substring(1).split("\\}");
            String attributeNamespace = parts[0];
            attribute = parts[1];
            if (nameSpaces.get(attributeNamespace) == null) {
                nameSpaces.put(attributeNamespace, ++nameSpaceCount);
            }
            nsNumberString = "ns" + nameSpaces.get(attributeNamespace) + ":";
            Element attributeNode = doc.createElementNS(attributeNamespace, nsNumberString + attribute);
            if (values.size() > 1 || (attributeNamespace.equals(DEFAULT_NAMESPACE) && attribute.equals("id"))) {
                for (String value : values) {
                    if (!(StringUtils.isEmpty(value))) {

                        Element valueNode = doc.createElementNS(DEFAULT_NAMESPACE, "ns1:value");
                        // valueNode.setNodeValue(value);
                        // we do not need this line any more because the
                        // GenericArtifactXMLHelper will care
                        // about it
                        // value =
                        // TrackerUtil.removeInvalidXmlCharacters(value);
                        valueNode.appendChild(doc.createTextNode(value));
                        attributeNode.appendChild(valueNode);
                    }
                }
            } else {
                // TODO: consider the namespace of the attributes?
                // attributeNode.setNodeValue(values.get(0));
                String value = values.get(0);
                value = TrackerUtil.removeInvalidXmlCharacters(value);
                if (value == null)
                    value = "";
                attributeNode.appendChild(doc.createTextNode(value));
            }
            artifactNode.appendChild(attributeNode);
        }
        List<ClientArtifactComment> comments = ca.getComments();
        for (ClientArtifactComment comment : comments) {
            String commentText = comment.getCommentText();
            Element commentNode = doc.createElementNS("urn:ws.tracker.collabnet.com", "ns1:" + "comment");
            Element textNode = doc.createElementNS(DEFAULT_NAMESPACE, "ns1:" + "text");
            commentText = TrackerUtil.removeInvalidXmlCharacters(commentText);
            textNode.appendChild(doc.createTextNode(commentText));
            commentNode.appendChild(textNode);
            artifactNode.appendChild(commentNode);
        }
        if (provideReason || isFoundReasonForCurrentlyProcessedArtifact) {
            Element reasonNode = doc.createElementNS("urn:ws.tracker.collabnet.com", "ns1:" + "reason");
            reasonNode.appendChild(doc.createTextNode(
                    provideReason ? "Synchronized by Connector" : reasonForCurrentlyProcessedArtifact));
            artifactNode.appendChild(reasonNode);
        }
    } // for every artifact

    Element sendMail = doc.createElementNS(DEFAULT_NAMESPACE, "ns1:" + "sendEmail");
    sendMail.appendChild(doc.createTextNode("true"));
    root.appendChild(sendMail);

    if (log.isDebugEnabled())
        this.printDocument(doc);

    Response r = theService.execute(toRequest(doc));
    Document result = toDocument(r);
    if (log.isDebugEnabled())
        this.printDocument(result);
    ClientArtifactListXMLHelper helper = new ClientArtifactListXMLHelper(result);
    return helper;
}

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

/**
* Create a job collection./*from  w w  w . j a  v a 2  s.  co  m*/
*
* @param cloudServiceName Required. The name of the cloud service
* containing the job collection.
* @param jobCollectionName Required. The name of the job collection to
* create.
* @param parameters Required. Parameters supplied to the Create Job
* Collection 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 Create Job Collection operation response.
*/
@Override
public JobCollectionCreateResponse beginCreating(String cloudServiceName, String jobCollectionName,
        JobCollectionCreateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (cloudServiceName == null) {
        throw new NullPointerException("cloudServiceName");
    }
    if (jobCollectionName == null) {
        throw new NullPointerException("jobCollectionName");
    }
    if (jobCollectionName.length() > 100) {
        throw new IllegalArgumentException("jobCollectionName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getIntrinsicSettings() != null) {
        if (parameters.getIntrinsicSettings().getQuota() != null) {
            if (parameters.getIntrinsicSettings().getQuota().getMaxRecurrence() != null) {
                if (parameters.getIntrinsicSettings().getQuota().getMaxRecurrence().getFrequency() == null) {
                    throw new NullPointerException(
                            "parameters.IntrinsicSettings.Quota.MaxRecurrence.Frequency");
                }
            }
        }
    }

    // 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("cloudServiceName", cloudServiceName);
        tracingParameters.put("jobCollectionName", jobCollectionName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "beginCreatingAsync", tracingParameters);
    }

    // Construct URL
    String url = "";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/cloudservices/";
    url = url + URLEncoder.encode(cloudServiceName, "UTF-8");
    url = url + "/resources/";
    url = url + "scheduler";
    url = url + "/";
    url = url + "JobCollections";
    url = url + "/";
    url = url + URLEncoder.encode(jobCollectionName, "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", "2013-03-01");

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

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

    if (parameters.getSchemaVersion() != null) {
        Element schemaVersionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "SchemaVersion");
        schemaVersionElement.appendChild(requestDoc.createTextNode(parameters.getSchemaVersion()));
        resourceElement.appendChild(schemaVersionElement);
    }

    if (parameters.getIntrinsicSettings() != null) {
        Element intrinsicSettingsElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "IntrinsicSettings");
        resourceElement.appendChild(intrinsicSettingsElement);

        if (parameters.getIntrinsicSettings().getPlan() != null) {
            Element planElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "Plan");
            planElement.appendChild(
                    requestDoc.createTextNode(parameters.getIntrinsicSettings().getPlan().toString()));
            intrinsicSettingsElement.appendChild(planElement);
        }

        if (parameters.getIntrinsicSettings().getQuota() != null) {
            Element quotaElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "Quota");
            intrinsicSettingsElement.appendChild(quotaElement);

            if (parameters.getIntrinsicSettings().getQuota().getMaxJobCount() != null) {
                Element maxJobCountElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "MaxJobCount");
                maxJobCountElement.appendChild(requestDoc.createTextNode(
                        Integer.toString(parameters.getIntrinsicSettings().getQuota().getMaxJobCount())));
                quotaElement.appendChild(maxJobCountElement);
            }

            if (parameters.getIntrinsicSettings().getQuota().getMaxJobOccurrence() != null) {
                Element maxJobOccurrenceElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "MaxJobOccurrence");
                maxJobOccurrenceElement.appendChild(requestDoc.createTextNode(
                        Integer.toString(parameters.getIntrinsicSettings().getQuota().getMaxJobOccurrence())));
                quotaElement.appendChild(maxJobOccurrenceElement);
            }

            if (parameters.getIntrinsicSettings().getQuota().getMaxRecurrence() != null) {
                Element maxRecurrenceElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "MaxRecurrence");
                quotaElement.appendChild(maxRecurrenceElement);

                Element frequencyElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "Frequency");
                frequencyElement.appendChild(requestDoc.createTextNode(parameters.getIntrinsicSettings()
                        .getQuota().getMaxRecurrence().getFrequency().toString()));
                maxRecurrenceElement.appendChild(frequencyElement);

                Element intervalElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "Interval");
                intervalElement.appendChild(requestDoc.createTextNode(Integer.toString(
                        parameters.getIntrinsicSettings().getQuota().getMaxRecurrence().getInterval())));
                maxRecurrenceElement.appendChild(intervalElement);
            }
        }
    }

    if (parameters.getLabel() != null) {
        Element labelElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Label");
        labelElement.appendChild(requestDoc.createTextNode(Base64.encode(parameters.getLabel().getBytes())));
        resourceElement.appendChild(labelElement);
    }

    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
        JobCollectionCreateResponse result = null;
        // Deserialize Response
        result = new JobCollectionCreateResponse();
        result.setStatusCode(statusCode);
        if (httpResponse.getHeaders("ETag").length > 0) {
            result.setETag(httpResponse.getFirstHeader("ETag").getValue());
        }
        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();
        }
    }
}