Example usage for org.w3c.dom Document createTextNode

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

Introduction

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

Prototype

public Text createTextNode(String data);

Source Link

Document

Creates a Text node given the specified string.

Usage

From source file:com.microsoft.windowsazure.management.storage.StorageAccountOperationsImpl.java

/**
* The Regenerate Keys operation regenerates the primary or secondary access
* key for the specified storage account.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/ee460795.aspx for
* more information)/*from  w  ww .  java 2 s. c om*/
*
* @param parameters Required. Parameters supplied to the Regenerate Keys
* 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 primary and secondary access keys for a storage account.
*/
@Override
public StorageAccountRegenerateKeysResponse regenerateKeys(StorageAccountRegenerateKeysParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException,
        URISyntaxException {
    // Validate
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getKeyType() == null) {
        throw new NullPointerException("parameters.KeyType");
    }
    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("parameters", parameters);
        CloudTracing.enter(invocationId, this, "regenerateKeysAsync", 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/storageservices/";
    url = url + URLEncoder.encode(parameters.getName(), "UTF-8");
    url = url + "/keys";
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("action=regenerate");
    if (queryParameters.size() > 0) {
        url = url + "?" + CollectionStringBuilder.join(queryParameters, "&");
    }
    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-10-01");

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

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

    Element keyTypeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "KeyType");
    keyTypeElement.appendChild(requestDoc.createTextNode(parameters.getKeyType().toString()));
    regenerateKeysElement.appendChild(keyTypeElement);

    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
        StorageAccountRegenerateKeysResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new StorageAccountRegenerateKeysResponse();
            DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance();
            documentBuilderFactory2.setNamespaceAware(true);
            DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder();
            Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent));

            Element storageServiceElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "StorageService");
            if (storageServiceElement != null) {
                Element urlElement = XmlUtility.getElementByTagNameNS(storageServiceElement,
                        "http://schemas.microsoft.com/windowsazure", "Url");
                if (urlElement != null) {
                    URI urlInstance;
                    urlInstance = new URI(urlElement.getTextContent());
                    result.setUri(urlInstance);
                }

                Element storageServiceKeysElement = XmlUtility.getElementByTagNameNS(storageServiceElement,
                        "http://schemas.microsoft.com/windowsazure", "StorageServiceKeys");
                if (storageServiceKeysElement != null) {
                    Element primaryElement = XmlUtility.getElementByTagNameNS(storageServiceKeysElement,
                            "http://schemas.microsoft.com/windowsazure", "Primary");
                    if (primaryElement != null) {
                        String primaryInstance;
                        primaryInstance = primaryElement.getTextContent();
                        result.setPrimaryKey(primaryInstance);
                    }

                    Element secondaryElement = XmlUtility.getElementByTagNameNS(storageServiceKeysElement,
                            "http://schemas.microsoft.com/windowsazure", "Secondary");
                    if (secondaryElement != null) {
                        String secondaryInstance;
                        secondaryInstance = secondaryElement.getTextContent();
                        result.setSecondaryKey(secondaryInstance);
                    }
                }
            }

        }
        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:eu.europa.esig.dss.asic.signature.ASiCService.java

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

    ASiCParameters asicParameters = underlyingParameters.aSiC();

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

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

    DSSDocument currentDetachedDocument = detachedDocument;
    do {//from   w  w  w. jav  a 2 s  .co m

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

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

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

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

    storeXmlDom(outputStream, documentDom);
}

From source file:com.mirth.connect.server.mule.transformers.ResultMapToXML.java

public Object doTransform(Object source) throws TransformerException {
    if (source instanceof Map) {
        Map data = (Map) source;

        try {/* w  ww.ja v  a2 s  .c  o m*/
            Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
            Element root = document.createElement("result");
            document.appendChild(root);

            for (Iterator iter = data.keySet().iterator(); iter.hasNext();) {
                String key = (String) iter.next();
                Element child = document.createElement(key);
                String value = new String();
                Object objectValue = data.get(key);
                if (objectValue != null) {
                    if (objectValue instanceof byte[]) {
                        value = new String((byte[]) objectValue);
                    } else if (objectValue instanceof java.sql.Clob) {
                        // convert it to a string
                        java.sql.Clob clobValue = (java.sql.Clob) objectValue;
                        Reader reader = clobValue.getCharacterStream();
                        if (reader == null) {
                            value = "";
                        }
                        StringBuffer sb = new StringBuffer();
                        try {
                            char[] charbuf = new char[(int) clobValue.length()];
                            for (int i = reader.read(charbuf); i > 0; i = reader.read(charbuf)) {
                                sb.append(charbuf, 0, i);
                            }
                        } catch (IOException e) {
                            logger.error("Error reading clob value.\n" + ExceptionUtils.getStackTrace(e));

                        }
                        value = sb.toString();
                    } else if (objectValue instanceof java.sql.Blob) {
                        try {
                            java.sql.Blob blobValue = (java.sql.Blob) objectValue;
                            value = new String(blobValue.getBytes(1, (int) blobValue.length()));
                        } catch (Exception ex) {
                            logger.error("Error reading blob value.\n" + ExceptionUtils.getStackTrace(ex));
                        }
                    } else {
                        value = objectValue.toString();
                    }

                }
                child.appendChild(document.createTextNode(value));
                root.appendChild(child);
            }

            DocumentSerializer docSerializer = new DocumentSerializer();
            return docSerializer.toXML(document);
        } catch (Exception e) {
            throw new TransformerException(
                    org.mule.config.i18n.Message.createStaticMessage("Failed to parse result map"), this);
        }
    } else if (source instanceof String) {
        return source.toString();
    } else {
        throw new TransformerException(
                org.mule.config.i18n.Message.createStaticMessage("Unregistered result type"), this);
    }
}

From source file:com.appdynamics.connectors.vcd.VappClient.java

public String newvAppFromTemplate(String vAppName, String templateLink, String catalogLink, String vdcLink,
        String network) throws Exception {
    // Step 1//from  w w  w.j  a  va 2  s  . c o  m
    String response = doGet(templateLink);

    // Step 2 - look for NetowrkConnection element in the Vms contained
    Document doc = RestClient.stringToXmlDocument(response);
    Element childrenElement = (Element) doc.getElementsByTagName(Constants.CHILDREN).item(0);
    Element vmElement = (Element) childrenElement.getElementsByTagName(Constants.VM).item(0);
    Element netElement = (Element) vmElement.getElementsByTagName("NetworkConnectionSection").item(0);

    String ovfInfo = doc.getElementsByTagName("ovf:Info").item(0).getTextContent();
    String networkName = netElement.getElementsByTagName("NetworkConnection").item(0).getAttributes()
            .getNamedItem("network").getTextContent().trim();

    String vdcResponse = doGet(vdcLink);
    String parentNetwork;
    if (network.isEmpty()) {
        parentNetwork = findElement(vdcResponse, Constants.NETWORK, Constants.NETWORK_LINK, null);
    } else {
        parentNetwork = findElement(vdcResponse, Constants.NETWORK, Constants.NETWORK_LINK, network);
    }

    // Step 3 - create an InstantiateVAppTemplate Params element
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

    // root elements
    doc = docBuilder.newDocument();
    Element rootElement = doc.createElement("InstantiateVAppTemplateParams");
    doc.appendChild(rootElement);

    rootElement.setAttribute("name", vAppName);
    rootElement.setAttribute("xmlns", Constants.XMLNS);
    rootElement.setAttribute("deploy", "true");
    rootElement.setAttribute("powerOn", "false");
    rootElement.setAttribute("xmlns:xsi", Constants.XMLNS_XSI);
    rootElement.setAttribute("xmlns:ovf", Constants.XMLNS_OVF);

    Element descElement = doc.createElement("Description");
    descElement.appendChild(doc.createTextNode("Created through Appdynamics controller"));
    rootElement.appendChild(descElement);

    Element paramsElement = doc.createElement("InstantiationParams");

    Element configElement = doc.createElement("Configuration");

    Element parentNetElement = doc.createElement("ParentNetwork");
    parentNetElement.setAttribute("href", parentNetwork);
    configElement.appendChild(parentNetElement);

    Element fenceElement = doc.createElement("FenceMode");
    fenceElement.appendChild(doc.createTextNode("bridged"));
    configElement.appendChild(fenceElement);

    Element netconfigSectionElement = doc.createElement("NetworkConfigSection");

    Element ovfInfoElement = doc.createElement("ovf:Info");
    ovfInfoElement.appendChild(doc.createTextNode(ovfInfo));
    netconfigSectionElement.appendChild(ovfInfoElement);

    Element netConfElement = doc.createElement("NetworkConfig");
    netConfElement.setAttribute("networkName", networkName);
    netConfElement.appendChild(configElement);
    netconfigSectionElement.appendChild(netConfElement);

    paramsElement.appendChild(netconfigSectionElement);
    rootElement.appendChild(paramsElement);

    Element sourceElement = doc.createElement("Source");
    sourceElement.setAttribute("href", templateLink);
    rootElement.appendChild(sourceElement);

    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    DOMSource source = new DOMSource(doc);
    StringWriter writer = new StringWriter();
    StreamResult result = new StreamResult(writer);

    transformer.transform(source, result);
    String xmlBody = writer.toString();

    // Step 4 - make a POST 

    String instantiateVAppLink = findElement(vdcResponse, Constants.LINK, Constants.INSTANTIATE_VAPP, null);

    StringEntity entity = new StringEntity(xmlBody);
    entity.setContentType(Constants.INSTANTIATE_VAPP);

    return doPost(instantiateVAppLink, entity);
}

From source file:com.fiorano.openesb.application.aps.ApplicationHeader.java

/**
 *  Returns the xml string equivalent of this object.
 *
 * @param document the input Document object
 * @return element node//from   ww  w.j a  va 2 s.  com
 * @exception FioranoException if an error occurs while creating the element
 *      node.
 * @since Tifosi2.0
 */
Node toJXMLString(Document document) throws FioranoException {
    Node root0 = document.createElement("ApplicationHeader");

    ((Element) root0).setAttribute("isSubgraphable", "" + m_canBeSubGraphed);
    ((Element) root0).setAttribute("Scope", m_scope);

    Node node;

    node = XMLDmiUtil.getNodeObject("Name", m_appName, document);
    if (node != null)
        root0.appendChild(node);

    node = XMLDmiUtil.getNodeObject("ApplicationGUID", m_appGUID, document);
    if (node != null)
        root0.appendChild(node);

    XMLDmiUtil.addVectorValues("Author", m_authorNames, document, root0);

    node = XMLDmiUtil.getNodeObject("CreationDate", m_creationDate, document);
    if (node != null)
        root0.appendChild(node);

    if (!StringUtils.isEmpty(m_iconName)) {
        node = XMLDmiUtil.getNodeObject("Icon", m_iconName, document);
        if (node != null)
            root0.appendChild(node);
    }
    Element child;

    if (m_version != null) {
        child = document.createElement("Version");
        child.setAttribute("isLocked", "" + m_isVersionLocked);

        Node pcData = document.createTextNode(m_version);

        child.appendChild(pcData);
        root0.appendChild(child);
    }

    //adding labels

    //create label object
    node = XMLDmiUtil.getNodeObject("Label", m_strProfile, document);
    if (node != null)
        root0.appendChild(node);

    //        node = XMLDmiUtil.getNodeObject("CompatibleWith", "" + m_compatibleWith, document);
    //        root0.appendChild(node);
    XMLDmiUtil.addVectorValues("CompatibleWith", m_compatibleWith, document, root0);

    node = XMLDmiUtil.getNodeObject("Category", m_category, document);
    if (node != null)
        root0.appendChild(node);

    if (m_maxInstLimit == -1 || m_maxInstLimit > 0) {
        child = document.createElement("MaximumInstances");

        Node pcData = document.createTextNode("" + m_maxInstLimit);

        child.appendChild(pcData);
        root0.appendChild(child);
    }
    if (!StringUtils.isEmpty(m_longDescription)) {
        node = XMLDmiUtil.getNodeObject("LongDescription", m_longDescription, document);
        if (node != null)
            root0.appendChild(node);
    }
    if (!StringUtils.isEmpty(m_shortDescription)) {
        node = XMLDmiUtil.getNodeObject("ShortDescription", m_shortDescription, document);
        if (node != null)
            root0.appendChild(node);
    }
    if (m_params != null && m_params.size() > 0) {
        Enumeration enums = m_params.elements();

        while (enums.hasMoreElements()) {
            Param param = (Param) enums.nextElement();
            if (!StringUtils.isEmpty(param.getParamName()) && !StringUtils.isEmpty(param.getParamValue()))
                root0.appendChild(param.toJXMLString(document));
        }
    }

    //  Add the ApplicationHeader Node to it.
    if (m_appContext != null) {
        Node contextNode = m_appContext.toJXMLString(document);

        root0.appendChild(contextNode);
    }

    return root0;
}

From source file:com.microsoft.windowsazure.management.storage.StorageAccountOperationsImpl.java

/**
* The Begin Creating Storage Account operation creates a new storage
* account in Azure.  (see//  w w  w . j  ava  2s  . c om
* http://msdn.microsoft.com/en-us/library/windowsazure/hh264518.aspx for
* more information)
*
* @param parameters Required. Parameters supplied to the Begin Creating
* Storage Account 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 A standard service response including an HTTP status code and
* request ID.
*/
@Override
public OperationResponse beginCreating(StorageAccountCreateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getDescription() != null && parameters.getDescription().length() > 1024) {
        throw new IllegalArgumentException("parameters.Description");
    }
    if (parameters.getLabel() == null) {
        throw new NullPointerException("parameters.Label");
    }
    if (parameters.getLabel().length() > 100) {
        throw new IllegalArgumentException("parameters.Label");
    }
    if (parameters.getName() == null) {
        throw new NullPointerException("parameters.Name");
    }
    if (parameters.getName().length() < 3) {
        throw new IllegalArgumentException("parameters.Name");
    }
    if (parameters.getName().length() > 24) {
        throw new IllegalArgumentException("parameters.Name");
    }
    for (char nameChar : parameters.getName().toCharArray()) {
        if (Character.isLowerCase(nameChar) == false && Character.isDigit(nameChar) == false) {
            throw new IllegalArgumentException("parameters.Name");
        }
    }
    // TODO: Validate parameters.Name is a valid DNS 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("parameters", parameters);
        CloudTracing.enter(invocationId, this, "beginCreatingAsync", 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/storageservices";
    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-10-01");

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

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

    Element serviceNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "ServiceName");
    serviceNameElement.appendChild(requestDoc.createTextNode(parameters.getName()));
    createStorageServiceInputElement.appendChild(serviceNameElement);

    if (parameters.getDescription() != null) {
        Element descriptionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "Description");
        descriptionElement.appendChild(requestDoc.createTextNode(parameters.getDescription()));
        createStorageServiceInputElement.appendChild(descriptionElement);
    } else {
        Element emptyElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "Description");
        Attr nilAttribute = requestDoc.createAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "nil");
        nilAttribute.setValue("true");
        emptyElement.setAttributeNode(nilAttribute);
        createStorageServiceInputElement.appendChild(emptyElement);
    }

    Element labelElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Label");
    labelElement.appendChild(requestDoc.createTextNode(Base64.encode(parameters.getLabel().getBytes())));
    createStorageServiceInputElement.appendChild(labelElement);

    if (parameters.getAffinityGroup() != null) {
        Element affinityGroupElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "AffinityGroup");
        affinityGroupElement.appendChild(requestDoc.createTextNode(parameters.getAffinityGroup()));
        createStorageServiceInputElement.appendChild(affinityGroupElement);
    }

    if (parameters.getLocation() != null) {
        Element locationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "Location");
        locationElement.appendChild(requestDoc.createTextNode(parameters.getLocation()));
        createStorageServiceInputElement.appendChild(locationElement);
    }

    if (parameters.getExtendedProperties() != null) {
        if (parameters.getExtendedProperties() instanceof LazyCollection == false
                || ((LazyCollection) parameters.getExtendedProperties()).isInitialized()) {
            Element extendedPropertiesDictionaryElement = requestDoc
                    .createElementNS("http://schemas.microsoft.com/windowsazure", "ExtendedProperties");
            for (Map.Entry<String, String> entry : parameters.getExtendedProperties().entrySet()) {
                String extendedPropertiesKey = entry.getKey();
                String extendedPropertiesValue = entry.getValue();
                Element extendedPropertiesElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "ExtendedProperty");
                extendedPropertiesDictionaryElement.appendChild(extendedPropertiesElement);

                Element extendedPropertiesKeyElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "Name");
                extendedPropertiesKeyElement.appendChild(requestDoc.createTextNode(extendedPropertiesKey));
                extendedPropertiesElement.appendChild(extendedPropertiesKeyElement);

                Element extendedPropertiesValueElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "Value");
                extendedPropertiesValueElement.appendChild(requestDoc.createTextNode(extendedPropertiesValue));
                extendedPropertiesElement.appendChild(extendedPropertiesValueElement);
            }
            createStorageServiceInputElement.appendChild(extendedPropertiesDictionaryElement);
        }
    }

    if (parameters.getAccountType() != null) {
        Element accountTypeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "AccountType");
        accountTypeElement.appendChild(requestDoc.createTextNode(parameters.getAccountType()));
        createStorageServiceInputElement.appendChild(accountTypeElement);
    }

    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
        OperationResponse result = null;
        // Deserialize Response
        result = new OperationResponse();
        result.setStatusCode(statusCode);
        if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
            result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
        }

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

From source file:com.microsoft.windowsazure.management.storage.StorageAccountOperationsImpl.java

/**
* The Update Storage Account operation updates the label and the
* description, and enables or disables the geo-replication status for a
* storage account in Azure.  (see//www  . j a va 2 s  .  c o  m
* http://msdn.microsoft.com/en-us/library/windowsazure/hh264516.aspx for
* more information)
*
* @param accountName Required. Name of the storage account to update.
* @param parameters Required. Parameters supplied to the Update Storage
* Account 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 A standard service response including an HTTP status code and
* request ID.
*/
@Override
public OperationResponse update(String accountName, StorageAccountUpdateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (accountName == null) {
        throw new NullPointerException("accountName");
    }
    if (accountName.length() < 3) {
        throw new IllegalArgumentException("accountName");
    }
    if (accountName.length() > 24) {
        throw new IllegalArgumentException("accountName");
    }
    for (char accountNameChar : accountName.toCharArray()) {
        if (Character.isLowerCase(accountNameChar) == false && Character.isDigit(accountNameChar) == false) {
            throw new IllegalArgumentException("accountName");
        }
    }
    // TODO: Validate accountName is a valid DNS name.
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getDescription() != null && parameters.getDescription().length() > 1024) {
        throw new IllegalArgumentException("parameters.Description");
    }

    // 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("accountName", accountName);
        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/storageservices/";
    url = url + URLEncoder.encode(accountName, "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-10-01");

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

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

    if (parameters.getDescription() != null) {
        Element descriptionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "Description");
        descriptionElement.appendChild(requestDoc.createTextNode(parameters.getDescription()));
        updateStorageServiceInputElement.appendChild(descriptionElement);
    } else {
        Element emptyElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "Description");
        Attr nilAttribute = requestDoc.createAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "nil");
        nilAttribute.setValue("true");
        emptyElement.setAttributeNode(nilAttribute);
        updateStorageServiceInputElement.appendChild(emptyElement);
    }

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

    if (parameters.getExtendedProperties() != null) {
        if (parameters.getExtendedProperties() instanceof LazyCollection == false
                || ((LazyCollection) parameters.getExtendedProperties()).isInitialized()) {
            Element extendedPropertiesDictionaryElement = requestDoc
                    .createElementNS("http://schemas.microsoft.com/windowsazure", "ExtendedProperties");
            for (Map.Entry<String, String> entry : parameters.getExtendedProperties().entrySet()) {
                String extendedPropertiesKey = entry.getKey();
                String extendedPropertiesValue = entry.getValue();
                Element extendedPropertiesElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "ExtendedProperty");
                extendedPropertiesDictionaryElement.appendChild(extendedPropertiesElement);

                Element extendedPropertiesKeyElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "Name");
                extendedPropertiesKeyElement.appendChild(requestDoc.createTextNode(extendedPropertiesKey));
                extendedPropertiesElement.appendChild(extendedPropertiesKeyElement);

                Element extendedPropertiesValueElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "Value");
                extendedPropertiesValueElement.appendChild(requestDoc.createTextNode(extendedPropertiesValue));
                extendedPropertiesElement.appendChild(extendedPropertiesValueElement);
            }
            updateStorageServiceInputElement.appendChild(extendedPropertiesDictionaryElement);
        }
    }

    if (parameters.getAccountType() != null) {
        Element accountTypeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "AccountType");
        accountTypeElement.appendChild(requestDoc.createTextNode(parameters.getAccountType()));
        updateStorageServiceInputElement.appendChild(accountTypeElement);
    }

    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
        OperationResponse result = null;
        // Deserialize Response
        result = new OperationResponse();
        result.setStatusCode(statusCode);
        if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
            result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
        }

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

From source file:com.microsoft.windowsazure.management.sql.DacOperationsImpl.java

/**
* Exports an Azure SQL Database into a DACPAC file in Azure Blob Storage.
*
* @param serverName Required. The name of the Azure SQL Database Server in
* which the database to export resides./*from  ww  w  .jav  a  2s .c  o m*/
* @param parameters Optional. The parameters needed to initiate the export
* request.
* @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 Represents the response that the service returns once an import
* or export operation has been initiated.
*/
@Override
public DacImportExportResponse export(String serverName, DacExportParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }
    if (parameters != null) {
        if (parameters.getBlobCredentials() != null) {
            if (parameters.getBlobCredentials().getStorageAccessKey() == null) {
                throw new NullPointerException("parameters.BlobCredentials.StorageAccessKey");
            }
            if (parameters.getBlobCredentials().getUri() == null) {
                throw new NullPointerException("parameters.BlobCredentials.Uri");
            }
        }
        if (parameters.getConnectionInfo() != null) {
            if (parameters.getConnectionInfo().getDatabaseName() == null) {
                throw new NullPointerException("parameters.ConnectionInfo.DatabaseName");
            }
            if (parameters.getConnectionInfo().getPassword() == null) {
                throw new NullPointerException("parameters.ConnectionInfo.Password");
            }
            if (parameters.getConnectionInfo().getServerName() == null) {
                throw new NullPointerException("parameters.ConnectionInfo.ServerName");
            }
            if (parameters.getConnectionInfo().getUserName() == null) {
                throw new NullPointerException("parameters.ConnectionInfo.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, "exportAsync", 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/Export";
    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();

    if (parameters != null) {
        Element exportInputElement = requestDoc.createElementNS(
                "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                "ExportInput");
        requestDoc.appendChild(exportInputElement);

        if (parameters.getBlobCredentials() != null) {
            Element blobCredentialsElement = requestDoc.createElementNS(
                    "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                    "BlobCredentials");
            exportInputElement.appendChild(blobCredentialsElement);

            Attr typeAttribute = requestDoc.createAttributeNS("http://www.w3.org/2001/XMLSchema-instance",
                    "type");
            typeAttribute.setValue("BlobStorageAccessKeyCredentials");
            blobCredentialsElement.setAttributeNode(typeAttribute);

            Element uriElement = requestDoc.createElementNS(
                    "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                    "Uri");
            uriElement.appendChild(
                    requestDoc.createTextNode(parameters.getBlobCredentials().getUri().toString()));
            blobCredentialsElement.appendChild(uriElement);

            Element storageAccessKeyElement = requestDoc.createElementNS(
                    "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                    "StorageAccessKey");
            storageAccessKeyElement.appendChild(
                    requestDoc.createTextNode(parameters.getBlobCredentials().getStorageAccessKey()));
            blobCredentialsElement.appendChild(storageAccessKeyElement);
        }

        if (parameters.getConnectionInfo() != null) {
            Element connectionInfoElement = requestDoc.createElementNS(
                    "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                    "ConnectionInfo");
            exportInputElement.appendChild(connectionInfoElement);

            Element databaseNameElement = requestDoc.createElementNS(
                    "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                    "DatabaseName");
            databaseNameElement
                    .appendChild(requestDoc.createTextNode(parameters.getConnectionInfo().getDatabaseName()));
            connectionInfoElement.appendChild(databaseNameElement);

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

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

            Element userNameElement = requestDoc.createElementNS(
                    "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                    "UserName");
            userNameElement
                    .appendChild(requestDoc.createTextNode(parameters.getConnectionInfo().getUserName()));
            connectionInfoElement.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
        DacImportExportResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new DacImportExportResponse();
            DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance();
            documentBuilderFactory2.setNamespaceAware(true);
            DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder();
            Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent));

            Element guidElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/2003/10/Serialization/", "guid");
            if (guidElement != null) {
                result.setGuid(guidElement.getTextContent());
            }

        }
        result.setStatusCode(statusCode);
        if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
            result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
        }

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

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

/**
* Register a new extension. An extension is identified by the combination
* of its ProviderNamespace and Type (case-sensitive string). It is not
* allowed to register an extension with the same identity (i.e.
* combination of ProviderNamespace and Type) of an already-registered
* extension. To register new version of an existing extension, the Update
* Extension API should be used.// w  ww  .j  av a2  s .co  m
*
* @param parameters Required. Parameters supplied to the Register Virtual
* Machine Extension Image 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 A standard service response including an HTTP status code and
* request ID.
*/
@Override
public OperationResponse beginRegistering(ExtensionImageRegisterParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getCertificate() != null) {
        if (parameters.getCertificate().getStoreLocation() == null) {
            throw new NullPointerException("parameters.Certificate.StoreLocation");
        }
    }
    if (parameters.getExtensionEndpoints() != null) {
        if (parameters.getExtensionEndpoints().getInputEndpoints() != null) {
            for (ExtensionEndpointConfiguration.InputEndpoint inputEndpointsParameterItem : parameters
                    .getExtensionEndpoints().getInputEndpoints()) {
                if (inputEndpointsParameterItem.getLocalPort() == null) {
                    throw new NullPointerException("parameters.ExtensionEndpoints.InputEndpoints.LocalPort");
                }
                if (inputEndpointsParameterItem.getName() == null) {
                    throw new NullPointerException("parameters.ExtensionEndpoints.InputEndpoints.Name");
                }
                if (inputEndpointsParameterItem.getProtocol() == null) {
                    throw new NullPointerException("parameters.ExtensionEndpoints.InputEndpoints.Protocol");
                }
            }
        }
        if (parameters.getExtensionEndpoints().getInstanceInputEndpoints() != null) {
            for (ExtensionEndpointConfiguration.InstanceInputEndpoint instanceInputEndpointsParameterItem : parameters
                    .getExtensionEndpoints().getInstanceInputEndpoints()) {
                if (instanceInputEndpointsParameterItem.getLocalPort() == null) {
                    throw new NullPointerException(
                            "parameters.ExtensionEndpoints.InstanceInputEndpoints.LocalPort");
                }
                if (instanceInputEndpointsParameterItem.getName() == null) {
                    throw new NullPointerException("parameters.ExtensionEndpoints.InstanceInputEndpoints.Name");
                }
                if (instanceInputEndpointsParameterItem.getProtocol() == null) {
                    throw new NullPointerException(
                            "parameters.ExtensionEndpoints.InstanceInputEndpoints.Protocol");
                }
            }
        }
        if (parameters.getExtensionEndpoints().getInternalEndpoints() != null) {
            for (ExtensionEndpointConfiguration.InternalEndpoint internalEndpointsParameterItem : parameters
                    .getExtensionEndpoints().getInternalEndpoints()) {
                if (internalEndpointsParameterItem.getName() == null) {
                    throw new NullPointerException("parameters.ExtensionEndpoints.InternalEndpoints.Name");
                }
                if (internalEndpointsParameterItem.getProtocol() == null) {
                    throw new NullPointerException("parameters.ExtensionEndpoints.InternalEndpoints.Protocol");
                }
            }
        }
    }
    if (parameters.getLocalResources() != null) {
        for (ExtensionLocalResourceConfiguration localResourcesParameterItem : parameters.getLocalResources()) {
            if (localResourcesParameterItem.getName() == null) {
                throw new NullPointerException("parameters.LocalResources.Name");
            }
        }
    }
    if (parameters.getProviderNameSpace() == null) {
        throw new NullPointerException("parameters.ProviderNameSpace");
    }
    if (parameters.getType() == null) {
        throw new NullPointerException("parameters.Type");
    }
    if (parameters.getVersion() == null) {
        throw new NullPointerException("parameters.Version");
    }

    // Tracing
    boolean shouldTrace = CloudTracing.getIsEnabled();
    String invocationId = null;
    if (shouldTrace) {
        invocationId = Long.toString(CloudTracing.getNextInvocationId());
        HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "beginRegisteringAsync", 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/extensions";
    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 extensionImageElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "ExtensionImage");
    requestDoc.appendChild(extensionImageElement);

    Element providerNameSpaceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "ProviderNameSpace");
    providerNameSpaceElement.appendChild(requestDoc.createTextNode(parameters.getProviderNameSpace()));
    extensionImageElement.appendChild(providerNameSpaceElement);

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

    Element versionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Version");
    versionElement.appendChild(requestDoc.createTextNode(parameters.getVersion()));
    extensionImageElement.appendChild(versionElement);

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

    if (parameters.getHostingResources() != null) {
        Element hostingResourcesElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "HostingResources");
        hostingResourcesElement.appendChild(requestDoc.createTextNode(parameters.getHostingResources()));
        extensionImageElement.appendChild(hostingResourcesElement);
    }

    if (parameters.getMediaLink() != null) {
        Element mediaLinkElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "MediaLink");
        mediaLinkElement.appendChild(requestDoc.createTextNode(parameters.getMediaLink().toString()));
        extensionImageElement.appendChild(mediaLinkElement);
    }

    if (parameters.getCertificate() != null) {
        Element certificateElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "Certificate");
        extensionImageElement.appendChild(certificateElement);

        Element storeLocationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "StoreLocation");
        storeLocationElement
                .appendChild(requestDoc.createTextNode(parameters.getCertificate().getStoreLocation()));
        certificateElement.appendChild(storeLocationElement);

        if (parameters.getCertificate().getStoreName() != null) {
            Element storeNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "StoreName");
            storeNameElement.appendChild(requestDoc.createTextNode(parameters.getCertificate().getStoreName()));
            certificateElement.appendChild(storeNameElement);
        }

        if (parameters.getCertificate().isThumbprintRequired() != null) {
            Element thumbprintRequiredElement = requestDoc
                    .createElementNS("http://schemas.microsoft.com/windowsazure", "ThumbprintRequired");
            thumbprintRequiredElement.appendChild(requestDoc.createTextNode(
                    Boolean.toString(parameters.getCertificate().isThumbprintRequired()).toLowerCase()));
            certificateElement.appendChild(thumbprintRequiredElement);
        }

        if (parameters.getCertificate().getThumbprintAlgorithm() != null) {
            Element thumbprintAlgorithmElement = requestDoc
                    .createElementNS("http://schemas.microsoft.com/windowsazure", "ThumbprintAlgorithm");
            thumbprintAlgorithmElement.appendChild(
                    requestDoc.createTextNode(parameters.getCertificate().getThumbprintAlgorithm()));
            certificateElement.appendChild(thumbprintAlgorithmElement);
        }
    }

    if (parameters.getExtensionEndpoints() != null) {
        Element endpointsElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "Endpoints");
        extensionImageElement.appendChild(endpointsElement);

        if (parameters.getExtensionEndpoints().getInputEndpoints() != null) {
            if (parameters.getExtensionEndpoints().getInputEndpoints() instanceof LazyCollection == false
                    || ((LazyCollection) parameters.getExtensionEndpoints().getInputEndpoints())
                            .isInitialized()) {
                Element inputEndpointsSequenceElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "InputEndpoints");
                for (ExtensionEndpointConfiguration.InputEndpoint inputEndpointsItem : parameters
                        .getExtensionEndpoints().getInputEndpoints()) {
                    Element inputEndpointElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "InputEndpoint");
                    inputEndpointsSequenceElement.appendChild(inputEndpointElement);

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

                    Element protocolElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Protocol");
                    protocolElement.appendChild(requestDoc.createTextNode(inputEndpointsItem.getProtocol()));
                    inputEndpointElement.appendChild(protocolElement);

                    Element portElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Port");
                    portElement.appendChild(
                            requestDoc.createTextNode(Integer.toString(inputEndpointsItem.getPort())));
                    inputEndpointElement.appendChild(portElement);

                    Element localPortElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "LocalPort");
                    localPortElement.appendChild(requestDoc.createTextNode(inputEndpointsItem.getLocalPort()));
                    inputEndpointElement.appendChild(localPortElement);
                }
                endpointsElement.appendChild(inputEndpointsSequenceElement);
            }
        }

        if (parameters.getExtensionEndpoints().getInternalEndpoints() != null) {
            if (parameters.getExtensionEndpoints().getInternalEndpoints() instanceof LazyCollection == false
                    || ((LazyCollection) parameters.getExtensionEndpoints().getInternalEndpoints())
                            .isInitialized()) {
                Element internalEndpointsSequenceElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "InternalEndpoints");
                for (ExtensionEndpointConfiguration.InternalEndpoint internalEndpointsItem : parameters
                        .getExtensionEndpoints().getInternalEndpoints()) {
                    Element internalEndpointElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "InternalEndpoint");
                    internalEndpointsSequenceElement.appendChild(internalEndpointElement);

                    Element nameElement2 = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Name");
                    nameElement2.appendChild(requestDoc.createTextNode(internalEndpointsItem.getName()));
                    internalEndpointElement.appendChild(nameElement2);

                    Element protocolElement2 = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Protocol");
                    protocolElement2
                            .appendChild(requestDoc.createTextNode(internalEndpointsItem.getProtocol()));
                    internalEndpointElement.appendChild(protocolElement2);

                    Element portElement2 = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Port");
                    portElement2.appendChild(
                            requestDoc.createTextNode(Integer.toString(internalEndpointsItem.getPort())));
                    internalEndpointElement.appendChild(portElement2);
                }
                endpointsElement.appendChild(internalEndpointsSequenceElement);
            }
        }

        if (parameters.getExtensionEndpoints().getInstanceInputEndpoints() != null) {
            if (parameters.getExtensionEndpoints()
                    .getInstanceInputEndpoints() instanceof LazyCollection == false
                    || ((LazyCollection) parameters.getExtensionEndpoints().getInstanceInputEndpoints())
                            .isInitialized()) {
                Element instanceInputEndpointsSequenceElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "InstanceInputEndpoints");
                for (ExtensionEndpointConfiguration.InstanceInputEndpoint instanceInputEndpointsItem : parameters
                        .getExtensionEndpoints().getInstanceInputEndpoints()) {
                    Element instanceInputEndpointElement = requestDoc.createElementNS(
                            "http://schemas.microsoft.com/windowsazure", "InstanceInputEndpoint");
                    instanceInputEndpointsSequenceElement.appendChild(instanceInputEndpointElement);

                    Element nameElement3 = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Name");
                    nameElement3.appendChild(requestDoc.createTextNode(instanceInputEndpointsItem.getName()));
                    instanceInputEndpointElement.appendChild(nameElement3);

                    Element protocolElement3 = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Protocol");
                    protocolElement3
                            .appendChild(requestDoc.createTextNode(instanceInputEndpointsItem.getProtocol()));
                    instanceInputEndpointElement.appendChild(protocolElement3);

                    Element localPortElement2 = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "LocalPort");
                    localPortElement2
                            .appendChild(requestDoc.createTextNode(instanceInputEndpointsItem.getLocalPort()));
                    instanceInputEndpointElement.appendChild(localPortElement2);

                    Element fixedPortMinElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "FixedPortMin");
                    fixedPortMinElement.appendChild(requestDoc
                            .createTextNode(Integer.toString(instanceInputEndpointsItem.getFixedPortMin())));
                    instanceInputEndpointElement.appendChild(fixedPortMinElement);

                    Element fixedPortMaxElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "FixedPortMax");
                    fixedPortMaxElement.appendChild(requestDoc
                            .createTextNode(Integer.toString(instanceInputEndpointsItem.getFixedPortMax())));
                    instanceInputEndpointElement.appendChild(fixedPortMaxElement);
                }
                endpointsElement.appendChild(instanceInputEndpointsSequenceElement);
            }
        }
    }

    if (parameters.getPublicConfigurationSchema() != null) {
        Element publicConfigurationSchemaElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "PublicConfigurationSchema");
        publicConfigurationSchemaElement.appendChild(
                requestDoc.createTextNode(Base64.encode(parameters.getPublicConfigurationSchema().getBytes())));
        extensionImageElement.appendChild(publicConfigurationSchemaElement);
    }

    if (parameters.getPrivateConfigurationSchema() != null) {
        Element privateConfigurationSchemaElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "PrivateConfigurationSchema");
        privateConfigurationSchemaElement.appendChild(requestDoc
                .createTextNode(Base64.encode(parameters.getPrivateConfigurationSchema().getBytes())));
        extensionImageElement.appendChild(privateConfigurationSchemaElement);
    }

    if (parameters.getDescription() != null) {
        Element descriptionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "Description");
        descriptionElement.appendChild(requestDoc.createTextNode(parameters.getDescription()));
        extensionImageElement.appendChild(descriptionElement);
    }

    if (parameters.getPublisherName() != null) {
        Element publisherNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "PublisherName");
        publisherNameElement.appendChild(requestDoc.createTextNode(parameters.getPublisherName()));
        extensionImageElement.appendChild(publisherNameElement);
    }

    if (parameters.getPublishedDate() != null) {
        Element publishedDateElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "PublishedDate");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
        simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        publishedDateElement.appendChild(
                requestDoc.createTextNode(simpleDateFormat.format(parameters.getPublishedDate().getTime())));
        extensionImageElement.appendChild(publishedDateElement);
    }

    if (parameters.getLocalResources() != null) {
        Element localResourcesSequenceElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "LocalResources");
        for (ExtensionLocalResourceConfiguration localResourcesItem : parameters.getLocalResources()) {
            Element localResourceElement = requestDoc
                    .createElementNS("http://schemas.microsoft.com/windowsazure", "LocalResource");
            localResourcesSequenceElement.appendChild(localResourceElement);

            Element nameElement4 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "Name");
            nameElement4.appendChild(requestDoc.createTextNode(localResourcesItem.getName()));
            localResourceElement.appendChild(nameElement4);

            if (localResourcesItem.getSizeInMB() != null) {
                Element sizeInMBElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "SizeInMB");
                sizeInMBElement.appendChild(
                        requestDoc.createTextNode(Integer.toString(localResourcesItem.getSizeInMB())));
                localResourceElement.appendChild(sizeInMBElement);
            }
        }
        extensionImageElement.appendChild(localResourcesSequenceElement);
    }

    if (parameters.isBlockRoleUponFailure() != null) {
        Element blockRoleUponFailureElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "BlockRoleUponFailure");
        blockRoleUponFailureElement.appendChild(
                requestDoc.createTextNode(Boolean.toString(parameters.isBlockRoleUponFailure()).toLowerCase()));
        extensionImageElement.appendChild(blockRoleUponFailureElement);
    }

    if (parameters.isInternalExtension() != null) {
        Element isInternalExtensionElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "IsInternalExtension");
        isInternalExtensionElement.appendChild(
                requestDoc.createTextNode(Boolean.toString(parameters.isInternalExtension()).toLowerCase()));
        extensionImageElement.appendChild(isInternalExtensionElement);
    }

    if (parameters.getSampleConfig() != null) {
        Element sampleConfigElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "SampleConfig");
        sampleConfigElement
                .appendChild(requestDoc.createTextNode(Base64.encode(parameters.getSampleConfig().getBytes())));
        extensionImageElement.appendChild(sampleConfigElement);
    }

    if (parameters.isReplicationCompleted() != null) {
        Element replicationCompletedElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "ReplicationCompleted");
        replicationCompletedElement.appendChild(
                requestDoc.createTextNode(Boolean.toString(parameters.isReplicationCompleted()).toLowerCase()));
        extensionImageElement.appendChild(replicationCompletedElement);
    }

    if (parameters.getEula() != null) {
        Element eulaElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Eula");
        eulaElement.appendChild(requestDoc.createTextNode(parameters.getEula().toString()));
        extensionImageElement.appendChild(eulaElement);
    }

    if (parameters.getPrivacyUri() != null) {
        Element privacyUriElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "PrivacyUri");
        privacyUriElement.appendChild(requestDoc.createTextNode(parameters.getPrivacyUri().toString()));
        extensionImageElement.appendChild(privacyUriElement);
    }

    if (parameters.getHomepageUri() != null) {
        Element homepageUriElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "HomepageUri");
        homepageUriElement.appendChild(requestDoc.createTextNode(parameters.getHomepageUri().toString()));
        extensionImageElement.appendChild(homepageUriElement);
    }

    if (parameters.isJsonExtension() != null) {
        Element isJsonExtensionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "IsJsonExtension");
        isJsonExtensionElement.appendChild(
                requestDoc.createTextNode(Boolean.toString(parameters.isJsonExtension()).toLowerCase()));
        extensionImageElement.appendChild(isJsonExtensionElement);
    }

    if (parameters.isDisallowMajorVersionUpgrade() != null) {
        Element disallowMajorVersionUpgradeElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "DisallowMajorVersionUpgrade");
        disallowMajorVersionUpgradeElement.appendChild(requestDoc
                .createTextNode(Boolean.toString(parameters.isDisallowMajorVersionUpgrade()).toLowerCase()));
        extensionImageElement.appendChild(disallowMajorVersionUpgradeElement);
    }

    if (parameters.getSupportedOS() != null) {
        Element supportedOSElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "SupportedOS");
        supportedOSElement.appendChild(requestDoc.createTextNode(parameters.getSupportedOS()));
        extensionImageElement.appendChild(supportedOSElement);
    }

    if (parameters.getCompanyName() != null) {
        Element companyNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "CompanyName");
        companyNameElement.appendChild(requestDoc.createTextNode(parameters.getCompanyName()));
        extensionImageElement.appendChild(companyNameElement);
    }

    if (parameters.getRegions() != null) {
        Element regionsElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "Regions");
        regionsElement.appendChild(requestDoc.createTextNode(parameters.getRegions()));
        extensionImageElement.appendChild(regionsElement);
    }

    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
        OperationResponse result = null;
        // Deserialize Response
        result = new OperationResponse();
        result.setStatusCode(statusCode);
        if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
            result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
        }

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

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

public ClientArtifactListXMLHelper createOrUpdateArtifactList(Document doc, List<ClientArtifact> artifacts,
        Long lastReadOn) 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);// w  w w .j  a v a 2s  . com

    // 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);
                        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);
        }

        //            Element reasonNode = doc.createElementNS("urn:ws.tracker.collabnet.com", "ns1:"+"reason");
        //            reasonNode.appendChild(doc.createTextNode("Synchronized by Connector"));
        //            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;
}