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.compute.ExtensionImageOperationsImpl.java

/**
* Update a new extension. It is allowed to update an extension which had
* already been registered with the same identity (i.e. combination of
* ProviderNamespace and Type) but with different version. It will fail if
* the extension to update has an identity that has not been registered
* before, or there is already an extension with the same identity and same
* version./*from   ww  w .  ja va 2  s .c om*/
*
* @param parameters Required. Parameters supplied to the Update 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 beginUpdating(ExtensionImageUpdateParameters 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, "beginUpdatingAsync", 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";
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("action=update");
    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
    HttpPut httpRequest = new HttpPut(url);

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

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

    Element 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:net.sourceforge.eclipsetrader.core.internal.XMLRepository.java

private void saveSecurityGroup(SecurityGroup group, Document document, Element root) {
    Element element = document.createElement("group"); //$NON-NLS-1$
    element.setAttribute("id", String.valueOf(group.getId())); //$NON-NLS-1$
    root.appendChild(element);//ww w  .j  av  a2s .  co m

    Element node = document.createElement("code"); //$NON-NLS-1$
    node.appendChild(document.createTextNode(group.getCode()));
    element.appendChild(node);
    node = document.createElement("description"); //$NON-NLS-1$
    node.appendChild(document.createTextNode(group.getDescription()));
    element.appendChild(node);
    if (group.getCurrency() != null) {
        node = document.createElement("currency"); //$NON-NLS-1$
        node.appendChild(document.createTextNode(group.getCurrency().getCurrencyCode()));
        element.appendChild(node);
    }

    for (PersistentObject child : group.getChildrens()) {
        if (child instanceof Security)
            saveSecurity((Security) child, document, element);
        if (child instanceof SecurityGroup)
            saveSecurityGroup((SecurityGroup) child, document, element);
    }
}

From source file:net.sourceforge.eclipsetrader.core.internal.XMLRepository.java

private void saveGroup(AccountGroup group, Document document, Element root) {
    Element element = document.createElement("group"); //$NON-NLS-1$
    element.setAttribute("id", String.valueOf(group.getId())); //$NON-NLS-1$
    root.appendChild(element);//  w w w.  j  a  va 2  s.  c om

    Element node = document.createElement("description"); //$NON-NLS-1$
    node.appendChild(document.createTextNode(group.getDescription()));
    element.appendChild(node);

    for (Iterator iter = group.getGroups().iterator(); iter.hasNext();) {
        AccountGroup grp = (AccountGroup) iter.next();
        saveGroup(grp, document, element);
    }

    for (Iterator iter = group.getAccounts().iterator(); iter.hasNext();) {
        Account account = (Account) iter.next();
        saveAccount(account, document, element);
    }
}

From source file:net.sourceforge.eclipsetrader.core.internal.XMLRepository.java

private void saveTransaction(Transaction transaction, Document document, Element root) {
    Element element = document.createElement("transaction"); //$NON-NLS-1$
    element.setAttribute("id", String.valueOf(transaction.getId())); //$NON-NLS-1$
    root.appendChild(element);/*from w  w  w.j  a  va  2s .com*/

    Element node = document.createElement("date"); //$NON-NLS-1$
    node.appendChild(document.createTextNode(dateTimeFormat.format(transaction.getDate())));
    element.appendChild(node);
    node = document.createElement("security"); //$NON-NLS-1$
    node.appendChild(document.createTextNode(String.valueOf(transaction.getSecurity().getId())));
    element.appendChild(node);
    node = document.createElement("price"); //$NON-NLS-1$
    node.appendChild(document.createTextNode(String.valueOf(transaction.getPrice())));
    element.appendChild(node);
    node = document.createElement("quantity"); //$NON-NLS-1$
    node.appendChild(document.createTextNode(String.valueOf(transaction.getQuantity())));
    element.appendChild(node);
    node = document.createElement("expenses"); //$NON-NLS-1$
    node.appendChild(document.createTextNode(String.valueOf(transaction.getExpenses())));
    element.appendChild(node);

    for (Iterator paramIter = transaction.getParams().keySet().iterator(); paramIter.hasNext();) {
        String key = (String) paramIter.next();
        node = document.createElement("param"); //$NON-NLS-1$
        node.setAttribute("key", key); //$NON-NLS-1$
        node.setAttribute("value", (String) transaction.getParams().get(key)); //$NON-NLS-1$
        element.appendChild(node);
    }
}

From source file:net.sourceforge.eclipsetrader.core.internal.XMLRepository.java

private void encodeBarData(List list, Element root, Document document) {
    for (Iterator iter = list.iterator(); iter.hasNext();) {
        Bar bar = (Bar) iter.next();/*ww w.j  ava2  s . c o m*/

        Element element = document.createElement("data"); //$NON-NLS-1$
        root.appendChild(element);

        Element node = document.createElement("open"); //$NON-NLS-1$
        node.appendChild(document.createTextNode(String.valueOf(bar.getOpen())));
        element.appendChild(node);
        node = document.createElement("high"); //$NON-NLS-1$
        node.appendChild(document.createTextNode(String.valueOf(bar.getHigh())));
        element.appendChild(node);
        node = document.createElement("low"); //$NON-NLS-1$
        node.appendChild(document.createTextNode(String.valueOf(bar.getLow())));
        element.appendChild(node);
        node = document.createElement("close"); //$NON-NLS-1$
        node.appendChild(document.createTextNode(String.valueOf(bar.getClose())));
        element.appendChild(node);
        node = document.createElement("volume"); //$NON-NLS-1$
        node.appendChild(document.createTextNode(String.valueOf(bar.getVolume())));
        element.appendChild(node);
        if (bar.getDate() != null) {
            node = document.createElement("date"); //$NON-NLS-1$
            node.appendChild(document.createTextNode(dateTimeFormat.format(bar.getDate())));
            element.appendChild(node);
        }
    }
}

From source file:net.sourceforge.eclipsetrader.core.internal.XMLRepository.java

private void saveChart(Chart chart, Element root, Document document) {
    Element element = document.createElement("chart"); //$NON-NLS-1$
    element.setAttribute("id", String.valueOf(chart.getId())); //$NON-NLS-1$
    root.appendChild(element);/*from  w w w  .ja v  a  2 s. c o  m*/

    Element node = document.createElement("title"); //$NON-NLS-1$
    node.appendChild(document.createTextNode(chart.getTitle()));
    element.appendChild(node);
    node = document.createElement("security"); //$NON-NLS-1$
    node.appendChild(document.createTextNode(String.valueOf(chart.getSecurity().getId())));
    element.appendChild(node);
    node = document.createElement("compression"); //$NON-NLS-1$
    node.appendChild(document.createTextNode(String.valueOf(chart.getCompression())));
    element.appendChild(node);
    node = document.createElement("period"); //$NON-NLS-1$
    node.appendChild(document.createTextNode(String.valueOf(chart.getPeriod())));
    element.appendChild(node);
    node = document.createElement("autoScale"); //$NON-NLS-1$
    node.appendChild(document.createTextNode(String.valueOf(chart.isAutoScale())));
    element.appendChild(node);
    if (chart.getBeginDate() != null) {
        node = document.createElement("begin"); //$NON-NLS-1$
        node.appendChild(document.createTextNode(dateTimeFormat.format(chart.getBeginDate())));
        element.appendChild(node);
    }
    if (chart.getEndDate() != null) {
        node = document.createElement("end"); //$NON-NLS-1$
        node.appendChild(document.createTextNode(dateTimeFormat.format(chart.getEndDate())));
        element.appendChild(node);
    }
    for (int r = 0; r < chart.getRows().size(); r++) {
        ChartRow row = (ChartRow) chart.getRows().get(r);
        row.setId(new Integer(r));
        row.setParent(chart);
        row.setRepository(this);

        Element rowNode = document.createElement("row"); //$NON-NLS-1$
        element.appendChild(rowNode);

        for (int t = 0; t < row.getTabs().size(); t++) {
            ChartTab tab = (ChartTab) row.getTabs().get(t);
            tab.setId(new Integer(t));
            tab.setParent(row);
            tab.setRepository(this);

            Element tabNode = document.createElement("tab"); //$NON-NLS-1$
            tabNode.setAttribute("label", tab.getLabel()); //$NON-NLS-1$
            rowNode.appendChild(tabNode);

            for (int i = 0; i < tab.getIndicators().size(); i++) {
                ChartIndicator indicator = (ChartIndicator) tab.getIndicators().get(i);
                indicator.setId(new Integer(i));
                indicator.setParent(tab);
                indicator.setRepository(this);

                Element indicatorNode = document.createElement("indicator"); //$NON-NLS-1$
                indicatorNode.setAttribute("pluginId", indicator.getPluginId()); //$NON-NLS-1$
                tabNode.appendChild(indicatorNode);

                for (Iterator iter = indicator.getParameters().keySet().iterator(); iter.hasNext();) {
                    String key = (String) iter.next();

                    node = document.createElement("param"); //$NON-NLS-1$
                    node.setAttribute("key", key); //$NON-NLS-1$
                    node.setAttribute("value", (String) indicator.getParameters().get(key)); //$NON-NLS-1$
                    indicatorNode.appendChild(node);
                }
            }

            for (int i = 0; i < tab.getObjects().size(); i++) {
                ChartObject object = (ChartObject) tab.getObjects().get(i);
                object.setId(new Integer(i));
                object.setParent(tab);
                object.setRepository(this);

                Element indicatorNode = document.createElement("object"); //$NON-NLS-1$
                indicatorNode.setAttribute("pluginId", object.getPluginId()); //$NON-NLS-1$
                tabNode.appendChild(indicatorNode);

                for (Iterator iter = object.getParameters().keySet().iterator(); iter.hasNext();) {
                    String key = (String) iter.next();

                    node = document.createElement("param"); //$NON-NLS-1$
                    node.setAttribute("key", key); //$NON-NLS-1$
                    node.setAttribute("value", (String) object.getParameters().get(key)); //$NON-NLS-1$
                    indicatorNode.appendChild(node);
                }
            }
        }
    }
}

From source file:lcmc.data.VMSXML.java

/** Creates XML for new domain. */
public Node createDomainXML(final String uuid, final String domainName, final Map<String, String> parametersMap,
        final boolean needConsole) {
    //<domain type='kvm'>
    //  <memory>524288</memory>
    //  <name>fff</name>
    //  <os>
    //    <type arch='i686' machine='pc-0.12'>hvm</type>
    //  </os>
    //</domain>

    /* domain type: kvm/xen */
    final String type = parametersMap.get(VM_PARAM_DOMAIN_TYPE);
    final String configName = getConfigName(type, domainName);
    namesConfigsMap.put(domainName, configName);
    /* build xml */
    final String encoding = "UTF-8";
    final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = null;/* w w  w .  j av  a 2s . c om*/

    try {
        db = dbf.newDocumentBuilder();
    } catch (ParserConfigurationException pce) {
        assert false;
    }
    final Document doc = db.newDocument();
    final Element root = (Element) doc.appendChild(doc.createElement("domain"));
    /* type */
    root.setAttribute("type", type); /* kvm/xen */
    /* uuid */
    final Node uuidNode = (Element) root.appendChild(doc.createElement("uuid"));
    uuidNode.appendChild(doc.createTextNode(uuid));
    /* name */
    final Node nameNode = (Element) root.appendChild(doc.createElement("name"));
    nameNode.appendChild(doc.createTextNode(domainName));
    /* memory */
    final Node memoryNode = (Element) root.appendChild(doc.createElement("memory"));
    final long mem = Tools.convertToKilobytes(parametersMap.get(VM_PARAM_MEMORY));
    memoryNode.appendChild(doc.createTextNode(Long.toString(mem)));
    /* current memory */
    final Node curMemoryNode = (Element) root.appendChild(doc.createElement("currentMemory"));
    final long curMem = Tools.convertToKilobytes(parametersMap.get(VM_PARAM_CURRENTMEMORY));
    curMemoryNode.appendChild(doc.createTextNode(Long.toString(curMem)));
    /* vcpu */
    final String vcpu = parametersMap.get(VM_PARAM_VCPU);
    if (vcpu != null) {
        final Node vcpuNode = (Element) root.appendChild(doc.createElement("vcpu"));
        vcpuNode.appendChild(doc.createTextNode(vcpu));
    }

    /* bootloader */
    final String bootloader = parametersMap.get(VM_PARAM_BOOTLOADER);
    if (bootloader != null) {
        final Node bootloaderNode = (Element) root.appendChild(doc.createElement("bootloader"));
        bootloaderNode.appendChild(doc.createTextNode(bootloader));
    }

    /* os */
    final Element osNode = (Element) root.appendChild(doc.createElement("os"));
    final Element typeNode = (Element) osNode.appendChild(doc.createElement("type"));
    typeNode.appendChild(doc.createTextNode(parametersMap.get(VM_PARAM_TYPE)));
    typeNode.setAttribute("arch", parametersMap.get(VM_PARAM_TYPE_ARCH));
    typeNode.setAttribute("machine", parametersMap.get(VM_PARAM_TYPE_MACHINE));
    final String init = parametersMap.get(VM_PARAM_INIT);
    if (init != null && !"".equals(init)) {
        final Element initNode = (Element) osNode.appendChild(doc.createElement("init"));
        initNode.appendChild(doc.createTextNode(init));
    }
    final Element bootNode = (Element) osNode.appendChild(doc.createElement(OS_BOOT_NODE));
    bootNode.setAttribute(OS_BOOT_NODE_DEV, parametersMap.get(VM_PARAM_BOOT));
    final String bootDev2 = parametersMap.get(VM_PARAM_BOOT_2);
    if (bootDev2 != null && !"".equals(bootDev2)) {
        final Element bootNode2 = (Element) osNode.appendChild(doc.createElement(OS_BOOT_NODE));
        bootNode2.setAttribute(OS_BOOT_NODE_DEV, parametersMap.get(VM_PARAM_BOOT_2));
    }

    final Node loaderNode = (Element) osNode.appendChild(doc.createElement("loader"));
    loaderNode.appendChild(doc.createTextNode(parametersMap.get(VM_PARAM_LOADER)));

    /* features */
    addFeatures(doc, root, parametersMap);

    /* cpu match */
    addCPUMatchNode(doc, root, parametersMap);

    /* on_ */
    final String onPoweroff = parametersMap.get(VM_PARAM_ON_POWEROFF);
    if (onPoweroff != null) {
        final Element onPoweroffNode = (Element) root.appendChild(doc.createElement("on_poweroff"));
        onPoweroffNode.appendChild(doc.createTextNode(onPoweroff));

    }
    final String onReboot = parametersMap.get(VM_PARAM_ON_REBOOT);
    if (onReboot != null) {
        final Element onRebootNode = (Element) root.appendChild(doc.createElement("on_reboot"));
        onRebootNode.appendChild(doc.createTextNode(onReboot));

    }
    final String onCrash = parametersMap.get(VM_PARAM_ON_CRASH);
    if (onCrash != null) {
        final Element onCrashNode = (Element) root.appendChild(doc.createElement("on_crash"));
        onCrashNode.appendChild(doc.createTextNode(onCrash));

    }
    /* devices / emulator */
    final String emulator = parametersMap.get(VM_PARAM_EMULATOR);
    if (emulator != null || needConsole) {
        final Element devicesNode = (Element) root.appendChild(doc.createElement("devices"));
        if (needConsole) {
            final Element consoleNode = (Element) devicesNode.appendChild(doc.createElement("console"));
            consoleNode.setAttribute("type", "pty");
        }
        final Element emulatorNode = (Element) devicesNode.appendChild(doc.createElement("emulator"));
        emulatorNode.appendChild(doc.createTextNode(emulator));
    }
    return root;
}

From source file:net.sourceforge.eclipsetrader.core.internal.XMLRepository.java

private void saveAccount(Account account, Document document, Element root) {
    Element element = document.createElement("account"); //$NON-NLS-1$
    element.setAttribute("id", String.valueOf(account.getId())); //$NON-NLS-1$
    element.setAttribute("pluginId", String.valueOf(account.getPluginId())); //$NON-NLS-1$
    root.appendChild(element);/*from  w  w w.j  a  v  a2 s  . c om*/

    Element node = document.createElement("description"); //$NON-NLS-1$
    node.appendChild(document.createTextNode(account.getDescription()));
    element.appendChild(node);
    if (account.getCurrency() != null) {
        node = document.createElement("currency"); //$NON-NLS-1$
        node.appendChild(document.createTextNode(account.getCurrency().getCurrencyCode()));
        element.appendChild(node);
    }
    node = document.createElement("initialBalance"); //$NON-NLS-1$
    node.appendChild(document.createTextNode(String.valueOf(account.getInitialBalance())));
    element.appendChild(node);

    String[] names = account.getPreferenceStore().preferenceNames();
    for (int i = 0; i < names.length; i++) {
        node = document.createElement(names[i]);
        node.appendChild(document.createTextNode(account.getPreferenceStore().getString(names[i])));
        element.appendChild(node);
    }

    int transactionId = 0;
    for (Iterator iter = account.getTransactions().iterator(); iter.hasNext();) {
        Transaction transaction = (Transaction) iter.next();
        if (transaction.getId() != null)
            transactionId = Math.max(transactionId, transaction.getId().intValue());
    }
    for (Iterator iter = account.getTransactions().iterator(); iter.hasNext();) {
        Transaction transaction = (Transaction) iter.next();
        if (transaction.getId() == null)
            transaction.setId(new Integer(++transactionId));
        saveTransaction(transaction, document, element);
    }
}

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

/**
* Creates a database in an Azure SQL Database Server.
*
* @param serverName Required. The name of the Azure SQL Database Server
* where the database will be created.//from w w w .j  av  a2s. c o m
* @param parameters Required. The parameters for the create database
* 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 Represents the response to a create database request from the
* service.
*/
@Override
public DatabaseCreateResponse create(String serverName, DatabaseCreateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }
    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("serverName", serverName);
        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/sqlservers/servers/";
    url = url + URLEncoder.encode(serverName, "UTF-8");
    url = url + "/databases";
    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 serviceResourceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "ServiceResource");
    requestDoc.appendChild(serviceResourceElement);

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

    if (parameters.getEdition() != null) {
        Element editionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "Edition");
        editionElement.appendChild(requestDoc.createTextNode(parameters.getEdition()));
        serviceResourceElement.appendChild(editionElement);
    }

    if (parameters.getMaximumDatabaseSizeInGB() != null) {
        Element maxSizeGBElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "MaxSizeGB");
        maxSizeGBElement.appendChild(
                requestDoc.createTextNode(Integer.toString(parameters.getMaximumDatabaseSizeInGB())));
        serviceResourceElement.appendChild(maxSizeGBElement);
    }

    if (parameters.getCollationName() != null) {
        Element collationNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "CollationName");
        collationNameElement.appendChild(requestDoc.createTextNode(parameters.getCollationName()));
        serviceResourceElement.appendChild(collationNameElement);
    }

    if (parameters.getMaximumDatabaseSizeInBytes() != null) {
        Element maxSizeBytesElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "MaxSizeBytes");
        maxSizeBytesElement.appendChild(
                requestDoc.createTextNode(Long.toString(parameters.getMaximumDatabaseSizeInBytes())));
        serviceResourceElement.appendChild(maxSizeBytesElement);
    }

    if (parameters.getServiceObjectiveId() != null) {
        Element serviceObjectiveIdElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "ServiceObjectiveId");
        serviceObjectiveIdElement.appendChild(requestDoc.createTextNode(parameters.getServiceObjectiveId()));
        serviceResourceElement.appendChild(serviceObjectiveIdElement);
    }

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

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

            Element serviceResourceElement2 = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "ServiceResource");
            if (serviceResourceElement2 != null) {
                Database serviceResourceInstance = new Database();
                result.setDatabase(serviceResourceInstance);

                Element idElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "Id");
                if (idElement != null) {
                    int idInstance;
                    idInstance = DatatypeConverter.parseInt(idElement.getTextContent());
                    serviceResourceInstance.setId(idInstance);
                }

                Element editionElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "Edition");
                if (editionElement2 != null) {
                    String editionInstance;
                    editionInstance = editionElement2.getTextContent();
                    serviceResourceInstance.setEdition(editionInstance);
                }

                Element maxSizeGBElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "MaxSizeGB");
                if (maxSizeGBElement2 != null) {
                    int maxSizeGBInstance;
                    maxSizeGBInstance = DatatypeConverter.parseInt(maxSizeGBElement2.getTextContent());
                    serviceResourceInstance.setMaximumDatabaseSizeInGB(maxSizeGBInstance);
                }

                Element maxSizeBytesElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "MaxSizeBytes");
                if (maxSizeBytesElement2 != null) {
                    long maxSizeBytesInstance;
                    maxSizeBytesInstance = DatatypeConverter.parseLong(maxSizeBytesElement2.getTextContent());
                    serviceResourceInstance.setMaximumDatabaseSizeInBytes(maxSizeBytesInstance);
                }

                Element collationNameElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "CollationName");
                if (collationNameElement2 != null) {
                    String collationNameInstance;
                    collationNameInstance = collationNameElement2.getTextContent();
                    serviceResourceInstance.setCollationName(collationNameInstance);
                }

                Element creationDateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "CreationDate");
                if (creationDateElement != null) {
                    Calendar creationDateInstance;
                    creationDateInstance = DatatypeConverter
                            .parseDateTime(creationDateElement.getTextContent());
                    serviceResourceInstance.setCreationDate(creationDateInstance);
                }

                Element isFederationRootElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "IsFederationRoot");
                if (isFederationRootElement != null) {
                    boolean isFederationRootInstance;
                    isFederationRootInstance = DatatypeConverter
                            .parseBoolean(isFederationRootElement.getTextContent().toLowerCase());
                    serviceResourceInstance.setIsFederationRoot(isFederationRootInstance);
                }

                Element isSystemObjectElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "IsSystemObject");
                if (isSystemObjectElement != null) {
                    boolean isSystemObjectInstance;
                    isSystemObjectInstance = DatatypeConverter
                            .parseBoolean(isSystemObjectElement.getTextContent().toLowerCase());
                    serviceResourceInstance.setIsSystemObject(isSystemObjectInstance);
                }

                Element sizeMBElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "SizeMB");
                if (sizeMBElement != null) {
                    String sizeMBInstance;
                    sizeMBInstance = sizeMBElement.getTextContent();
                    serviceResourceInstance.setSizeMB(sizeMBInstance);
                }

                Element serviceObjectiveAssignmentErrorCodeElement = XmlUtility.getElementByTagNameNS(
                        serviceResourceElement2, "http://schemas.microsoft.com/windowsazure",
                        "ServiceObjectiveAssignmentErrorCode");
                if (serviceObjectiveAssignmentErrorCodeElement != null) {
                    String serviceObjectiveAssignmentErrorCodeInstance;
                    serviceObjectiveAssignmentErrorCodeInstance = serviceObjectiveAssignmentErrorCodeElement
                            .getTextContent();
                    serviceResourceInstance.setServiceObjectiveAssignmentErrorCode(
                            serviceObjectiveAssignmentErrorCodeInstance);
                }

                Element serviceObjectiveAssignmentErrorDescriptionElement = XmlUtility.getElementByTagNameNS(
                        serviceResourceElement2, "http://schemas.microsoft.com/windowsazure",
                        "ServiceObjectiveAssignmentErrorDescription");
                if (serviceObjectiveAssignmentErrorDescriptionElement != null) {
                    String serviceObjectiveAssignmentErrorDescriptionInstance;
                    serviceObjectiveAssignmentErrorDescriptionInstance = serviceObjectiveAssignmentErrorDescriptionElement
                            .getTextContent();
                    serviceResourceInstance.setServiceObjectiveAssignmentErrorDescription(
                            serviceObjectiveAssignmentErrorDescriptionInstance);
                }

                Element serviceObjectiveAssignmentStateElement = XmlUtility.getElementByTagNameNS(
                        serviceResourceElement2, "http://schemas.microsoft.com/windowsazure",
                        "ServiceObjectiveAssignmentState");
                if (serviceObjectiveAssignmentStateElement != null) {
                    String serviceObjectiveAssignmentStateInstance;
                    serviceObjectiveAssignmentStateInstance = serviceObjectiveAssignmentStateElement
                            .getTextContent();
                    serviceResourceInstance
                            .setServiceObjectiveAssignmentState(serviceObjectiveAssignmentStateInstance);
                }

                Element serviceObjectiveAssignmentStateDescriptionElement = XmlUtility.getElementByTagNameNS(
                        serviceResourceElement2, "http://schemas.microsoft.com/windowsazure",
                        "ServiceObjectiveAssignmentStateDescription");
                if (serviceObjectiveAssignmentStateDescriptionElement != null) {
                    String serviceObjectiveAssignmentStateDescriptionInstance;
                    serviceObjectiveAssignmentStateDescriptionInstance = serviceObjectiveAssignmentStateDescriptionElement
                            .getTextContent();
                    serviceResourceInstance.setServiceObjectiveAssignmentStateDescription(
                            serviceObjectiveAssignmentStateDescriptionInstance);
                }

                Element serviceObjectiveAssignmentSuccessDateElement = XmlUtility.getElementByTagNameNS(
                        serviceResourceElement2, "http://schemas.microsoft.com/windowsazure",
                        "ServiceObjectiveAssignmentSuccessDate");
                if (serviceObjectiveAssignmentSuccessDateElement != null) {
                    String serviceObjectiveAssignmentSuccessDateInstance;
                    serviceObjectiveAssignmentSuccessDateInstance = serviceObjectiveAssignmentSuccessDateElement
                            .getTextContent();
                    serviceResourceInstance.setServiceObjectiveAssignmentSuccessDate(
                            serviceObjectiveAssignmentSuccessDateInstance);
                }

                Element serviceObjectiveIdElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "ServiceObjectiveId");
                if (serviceObjectiveIdElement2 != null) {
                    String serviceObjectiveIdInstance;
                    serviceObjectiveIdInstance = serviceObjectiveIdElement2.getTextContent();
                    serviceResourceInstance.setServiceObjectiveId(serviceObjectiveIdInstance);
                }

                Element assignedServiceObjectiveIdElement = XmlUtility.getElementByTagNameNS(
                        serviceResourceElement2, "http://schemas.microsoft.com/windowsazure",
                        "AssignedServiceObjectiveId");
                if (assignedServiceObjectiveIdElement != null) {
                    String assignedServiceObjectiveIdInstance;
                    assignedServiceObjectiveIdInstance = assignedServiceObjectiveIdElement.getTextContent();
                    serviceResourceInstance.setAssignedServiceObjectiveId(assignedServiceObjectiveIdInstance);
                }

                Element recoveryPeriodStartDateElement = XmlUtility.getElementByTagNameNS(
                        serviceResourceElement2, "http://schemas.microsoft.com/windowsazure",
                        "RecoveryPeriodStartDate");
                if (recoveryPeriodStartDateElement != null
                        && recoveryPeriodStartDateElement.getTextContent() != null
                        && !recoveryPeriodStartDateElement.getTextContent().isEmpty()) {
                    Calendar recoveryPeriodStartDateInstance;
                    recoveryPeriodStartDateInstance = DatatypeConverter
                            .parseDateTime(recoveryPeriodStartDateElement.getTextContent());
                    serviceResourceInstance.setRecoveryPeriodStartDate(recoveryPeriodStartDateInstance);
                }

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

                Element typeElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "Type");
                if (typeElement != null) {
                    String typeInstance;
                    typeInstance = typeElement.getTextContent();
                    serviceResourceInstance.setType(typeInstance);
                }

                Element stateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "State");
                if (stateElement != null) {
                    String stateInstance;
                    stateInstance = stateElement.getTextContent();
                    serviceResourceInstance.setState(stateInstance);
                }
            }

        }
        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:net.sourceforge.eclipsetrader.core.internal.XMLRepository.java

private void saveSecurity(Security security, Document document, Element root) {
    Element element = document.createElement("security"); //$NON-NLS-1$
    element.setAttribute("id", String.valueOf(security.getId())); //$NON-NLS-1$
    root.appendChild(element);//from w w w. jav  a  2  s. c  o  m

    Element node = document.createElement("code"); //$NON-NLS-1$
    node.appendChild(document.createTextNode(security.getCode()));
    element.appendChild(node);
    node = document.createElement("description"); //$NON-NLS-1$
    node.appendChild(document.createTextNode(security.getDescription()));
    element.appendChild(node);
    if (security.getCurrency() != null) {
        node = document.createElement("currency"); //$NON-NLS-1$
        node.appendChild(document.createTextNode(security.getCurrency().getCurrencyCode()));
        element.appendChild(node);
    }

    NumberFormat nf = NumberFormat.getInstance();
    nf.setGroupingUsed(false);
    nf.setMinimumIntegerDigits(2);
    nf.setMinimumFractionDigits(0);
    nf.setMaximumFractionDigits(0);

    Element collectorNode = document.createElement("dataCollector"); //$NON-NLS-1$
    collectorNode.setAttribute("enable", String.valueOf(security.isEnableDataCollector())); //$NON-NLS-1$
    element.appendChild(collectorNode);
    node = document.createElement("begin"); //$NON-NLS-1$
    node.appendChild(document.createTextNode(
            nf.format(security.getBeginTime() / 60) + ":" + nf.format(security.getBeginTime() % 60))); //$NON-NLS-1$
    collectorNode.appendChild(node);
    node = document.createElement("end"); //$NON-NLS-1$
    node.appendChild(document.createTextNode(
            nf.format(security.getEndTime() / 60) + ":" + nf.format(security.getEndTime() % 60))); //$NON-NLS-1$
    collectorNode.appendChild(node);
    node = document.createElement("weekdays"); //$NON-NLS-1$
    node.appendChild(document.createTextNode(String.valueOf(security.getWeekDays())));
    collectorNode.appendChild(node);
    node = document.createElement("keepdays"); //$NON-NLS-1$
    node.appendChild(document.createTextNode(String.valueOf(security.getKeepDays())));
    collectorNode.appendChild(node);

    if (security.getQuoteFeed() != null || security.getLevel2Feed() != null
            || security.getHistoryFeed() != null) {
        Node feedsNode = document.createElement("feeds"); //$NON-NLS-1$
        element.appendChild(feedsNode);
        if (security.getQuoteFeed() != null) {
            node = document.createElement("quote"); //$NON-NLS-1$
            node.setAttribute("id", security.getQuoteFeed().getId()); //$NON-NLS-1$
            if (security.getQuoteFeed().getExchange() != null)
                node.setAttribute("exchange", security.getQuoteFeed().getExchange()); //$NON-NLS-1$
            node.appendChild(document.createTextNode(security.getQuoteFeed().getSymbol()));
            feedsNode.appendChild(node);
        }
        if (security.getLevel2Feed() != null) {
            node = document.createElement("level2"); //$NON-NLS-1$
            node.setAttribute("id", security.getLevel2Feed().getId()); //$NON-NLS-1$
            if (security.getLevel2Feed().getExchange() != null)
                node.setAttribute("exchange", security.getLevel2Feed().getExchange()); //$NON-NLS-1$
            node.appendChild(document.createTextNode(security.getLevel2Feed().getSymbol()));
            feedsNode.appendChild(node);
        }
        if (security.getHistoryFeed() != null) {
            node = document.createElement("history"); //$NON-NLS-1$
            node.setAttribute("id", security.getHistoryFeed().getId()); //$NON-NLS-1$
            if (security.getHistoryFeed().getExchange() != null)
                node.setAttribute("exchange", security.getHistoryFeed().getExchange()); //$NON-NLS-1$
            node.appendChild(document.createTextNode(security.getHistoryFeed().getSymbol()));
            feedsNode.appendChild(node);
        }
    }

    if (security.getTradeSource() != null) {
        TradeSource source = security.getTradeSource();

        Element feedsNode = document.createElement("tradeSource"); //$NON-NLS-1$
        feedsNode.setAttribute("id", source.getTradingProviderId()); //$NON-NLS-1$
        if (source.getExchange() != null)
            feedsNode.setAttribute("exchange", source.getExchange()); //$NON-NLS-1$
        element.appendChild(feedsNode);

        if (!source.getSymbol().equals("")) //$NON-NLS-1$
        {
            node = document.createElement("symbol"); //$NON-NLS-1$
            node.appendChild(document.createTextNode(source.getSymbol()));
            feedsNode.appendChild(node);
        }
        if (source.getAccountId() != null) {
            node = document.createElement("account"); //$NON-NLS-1$
            node.appendChild(document.createTextNode(String.valueOf(source.getAccountId())));
            feedsNode.appendChild(node);
        }
        node = document.createElement("quantity"); //$NON-NLS-1$
        node.appendChild(document.createTextNode(String.valueOf(source.getQuantity())));
        feedsNode.appendChild(node);
    }

    if (security.getQuote() != null) {
        Quote quote = security.getQuote();
        Node quoteNode = document.createElement("quote"); //$NON-NLS-1$

        if (quote.getDate() != null) {
            node = document.createElement("date"); //$NON-NLS-1$
            node.appendChild(document.createTextNode(dateTimeFormat.format(quote.getDate())));
            quoteNode.appendChild(node);
        }
        node = document.createElement("last"); //$NON-NLS-1$
        node.appendChild(document.createTextNode(String.valueOf(quote.getLast())));
        quoteNode.appendChild(node);
        node = document.createElement("bid"); //$NON-NLS-1$
        node.appendChild(document.createTextNode(String.valueOf(quote.getBid())));
        quoteNode.appendChild(node);
        node = document.createElement("ask"); //$NON-NLS-1$
        node.appendChild(document.createTextNode(String.valueOf(quote.getAsk())));
        quoteNode.appendChild(node);
        node = document.createElement("bidSize"); //$NON-NLS-1$
        node.appendChild(document.createTextNode(String.valueOf(quote.getBidSize())));
        quoteNode.appendChild(node);
        node = document.createElement("askSize"); //$NON-NLS-1$
        node.appendChild(document.createTextNode(String.valueOf(quote.getAskSize())));
        quoteNode.appendChild(node);
        node = document.createElement("volume"); //$NON-NLS-1$
        node.appendChild(document.createTextNode(String.valueOf(quote.getVolume())));
        quoteNode.appendChild(node);

        element.appendChild(quoteNode);
    }

    Node dataNode = document.createElement("data"); //$NON-NLS-1$
    element.appendChild(dataNode);

    if (security.getOpen() != null) {
        node = document.createElement("open"); //$NON-NLS-1$
        node.appendChild(document.createTextNode(String.valueOf(security.getOpen())));
        dataNode.appendChild(node);
    }
    if (security.getHigh() != null) {
        node = document.createElement("high"); //$NON-NLS-1$
        node.appendChild(document.createTextNode(String.valueOf(security.getHigh())));
        dataNode.appendChild(node);
    }
    if (security.getLow() != null) {
        node = document.createElement("low"); //$NON-NLS-1$
        node.appendChild(document.createTextNode(String.valueOf(security.getLow())));
        dataNode.appendChild(node);
    }
    if (security.getClose() != null) {
        node = document.createElement("close"); //$NON-NLS-1$
        node.appendChild(document.createTextNode(String.valueOf(security.getClose())));
        dataNode.appendChild(node);
    }

    node = document.createElement("comment"); //$NON-NLS-1$
    node.appendChild(document.createTextNode(security.getComment()));
    element.appendChild(node);

    for (Iterator iter = security.getSplits().iterator(); iter.hasNext();) {
        Split split = (Split) iter.next();
        node = document.createElement("split"); //$NON-NLS-1$
        node.setAttribute("date", dateTimeFormat.format(split.getDate())); //$NON-NLS-1$
        node.setAttribute("fromQuantity", String.valueOf(split.getFromQuantity())); //$NON-NLS-1$
        node.setAttribute("toQuantity", String.valueOf(split.getToQuantity())); //$NON-NLS-1$
        element.appendChild(node);
    }

    for (Iterator iter = security.getDividends().iterator(); iter.hasNext();) {
        Dividend dividend = (Dividend) iter.next();
        node = document.createElement("dividend"); //$NON-NLS-1$
        node.setAttribute("date", dateTimeFormat.format(dividend.getDate())); //$NON-NLS-1$
        node.setAttribute("value", String.valueOf(dividend.getValue())); //$NON-NLS-1$
        element.appendChild(node);
    }
}