Example usage for javax.xml.parsers DocumentBuilder newDocument

List of usage examples for javax.xml.parsers DocumentBuilder newDocument

Introduction

In this page you can find the example usage for javax.xml.parsers DocumentBuilder newDocument.

Prototype


public abstract Document newDocument();

Source Link

Document

Obtain a new instance of a DOM Document object to build a DOM tree with.

Usage

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

/**
* Add an internal load balancer to a an existing deployment. When used by
* an input endpoint, the internal load balancer will provide an additional
* private VIP that can be used for load balancing to the roles in this
* deployment./* w w w .j  a v a  2  s  .  co m*/
*
* @param serviceName Required. The name of the service.
* @param deploymentName Required. The name of the deployment.
* @param parameters Required. Parameters supplied to the Create Load
* Balancer operation.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request and error information regarding the failure.
*/
@Override
public OperationStatusResponse beginCreating(String serviceName, String deploymentName,
        LoadBalancerCreateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serviceName == null) {
        throw new NullPointerException("serviceName");
    }
    if (deploymentName == null) {
        throw new NullPointerException("deploymentName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }

    // Tracing
    boolean shouldTrace = CloudTracing.getIsEnabled();
    String invocationId = null;
    if (shouldTrace) {
        invocationId = Long.toString(CloudTracing.getNextInvocationId());
        HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
        tracingParameters.put("serviceName", serviceName);
        tracingParameters.put("deploymentName", deploymentName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "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/hostedservices/";
    url = url + URLEncoder.encode(serviceName, "UTF-8");
    url = url + "/deployments/";
    url = url + URLEncoder.encode(deploymentName, "UTF-8");
    url = url + "/loadbalancers";
    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 loadBalancerElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "LoadBalancer");
    requestDoc.appendChild(loadBalancerElement);

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

    if (parameters.getFrontendIPConfiguration() != null) {
        Element frontendIpConfigurationElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "FrontendIpConfiguration");
        loadBalancerElement.appendChild(frontendIpConfigurationElement);

        if (parameters.getFrontendIPConfiguration().getType() != null) {
            Element typeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "Type");
            typeElement
                    .appendChild(requestDoc.createTextNode(parameters.getFrontendIPConfiguration().getType()));
            frontendIpConfigurationElement.appendChild(typeElement);
        }

        if (parameters.getFrontendIPConfiguration().getSubnetName() != null) {
            Element subnetNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "SubnetName");
            subnetNameElement.appendChild(
                    requestDoc.createTextNode(parameters.getFrontendIPConfiguration().getSubnetName()));
            frontendIpConfigurationElement.appendChild(subnetNameElement);
        }

        if (parameters.getFrontendIPConfiguration().getStaticVirtualNetworkIPAddress() != null) {
            Element staticVirtualNetworkIPAddressElement = requestDoc.createElementNS(
                    "http://schemas.microsoft.com/windowsazure", "StaticVirtualNetworkIPAddress");
            staticVirtualNetworkIPAddressElement.appendChild(requestDoc.createTextNode(parameters
                    .getFrontendIPConfiguration().getStaticVirtualNetworkIPAddress().getHostAddress()));
            frontendIpConfigurationElement.appendChild(staticVirtualNetworkIPAddressElement);
        }
    }

    DOMSource domSource = new DOMSource(requestDoc);
    StringWriter stringWriter = new StringWriter();
    StreamResult streamResult = new StreamResult(stringWriter);
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.transform(domSource, streamResult);
    requestContent = stringWriter.toString();
    StringEntity entity = new StringEntity(requestContent);
    httpRequest.setEntity(entity);
    httpRequest.setHeader("Content-Type", "application/xml");

    // Send Request
    HttpResponse httpResponse = null;
    try {
        if (shouldTrace) {
            CloudTracing.sendRequest(invocationId, httpRequest);
        }
        httpResponse = this.getClient().getHttpClient().execute(httpRequest);
        if (shouldTrace) {
            CloudTracing.receiveResponse(invocationId, httpResponse);
        }
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_ACCEPTED) {
            ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

        // Create Result
        OperationStatusResponse result = null;
        // Deserialize Response
        result = new OperationStatusResponse();
        result.setStatusCode(statusCode);
        if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
            result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
        }

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

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

/**
* Updates an internal load balancer associated with an existing deployment.
*
* @param serviceName Required. The name of the service.
* @param deploymentName Required. The name of the deployment.
* @param loadBalancerName Required. The name of the loadBalancer.
* @param parameters Required. Parameters supplied to the Update Load
* Balancer operation.//from w ww. ja  v  a2  s  .c om
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return The response body contains the status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request and error information regarding the failure.
*/
@Override
public OperationStatusResponse beginUpdating(String serviceName, String deploymentName, String loadBalancerName,
        LoadBalancerUpdateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serviceName == null) {
        throw new NullPointerException("serviceName");
    }
    if (deploymentName == null) {
        throw new NullPointerException("deploymentName");
    }
    if (loadBalancerName == null) {
        throw new NullPointerException("loadBalancerName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }

    // Tracing
    boolean shouldTrace = CloudTracing.getIsEnabled();
    String invocationId = null;
    if (shouldTrace) {
        invocationId = Long.toString(CloudTracing.getNextInvocationId());
        HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
        tracingParameters.put("serviceName", serviceName);
        tracingParameters.put("deploymentName", deploymentName);
        tracingParameters.put("loadBalancerName", loadBalancerName);
        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/hostedservices/";
    url = url + URLEncoder.encode(serviceName, "UTF-8");
    url = url + "/deployments/";
    url = url + URLEncoder.encode(deploymentName, "UTF-8");
    url = url + "/loadbalancers/";
    url = url + URLEncoder.encode(loadBalancerName, "UTF-8");
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

    // Create HTTP transport objects
    HttpPut httpRequest = new HttpPut(url);

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

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

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

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

    if (parameters.getFrontendIPConfiguration() != null) {
        Element frontendIpConfigurationElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "FrontendIpConfiguration");
        loadBalancerElement.appendChild(frontendIpConfigurationElement);

        if (parameters.getFrontendIPConfiguration().getType() != null) {
            Element typeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "Type");
            typeElement
                    .appendChild(requestDoc.createTextNode(parameters.getFrontendIPConfiguration().getType()));
            frontendIpConfigurationElement.appendChild(typeElement);
        }

        if (parameters.getFrontendIPConfiguration().getSubnetName() != null) {
            Element subnetNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "SubnetName");
            subnetNameElement.appendChild(
                    requestDoc.createTextNode(parameters.getFrontendIPConfiguration().getSubnetName()));
            frontendIpConfigurationElement.appendChild(subnetNameElement);
        }

        if (parameters.getFrontendIPConfiguration().getStaticVirtualNetworkIPAddress() != null) {
            Element staticVirtualNetworkIPAddressElement = requestDoc.createElementNS(
                    "http://schemas.microsoft.com/windowsazure", "StaticVirtualNetworkIPAddress");
            staticVirtualNetworkIPAddressElement.appendChild(requestDoc.createTextNode(parameters
                    .getFrontendIPConfiguration().getStaticVirtualNetworkIPAddress().getHostAddress()));
            frontendIpConfigurationElement.appendChild(staticVirtualNetworkIPAddressElement);
        }
    }

    DOMSource domSource = new DOMSource(requestDoc);
    StringWriter stringWriter = new StringWriter();
    StreamResult streamResult = new StreamResult(stringWriter);
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.transform(domSource, streamResult);
    requestContent = stringWriter.toString();
    StringEntity entity = new StringEntity(requestContent);
    httpRequest.setEntity(entity);
    httpRequest.setHeader("Content-Type", "application/xml");

    // Send Request
    HttpResponse httpResponse = null;
    try {
        if (shouldTrace) {
            CloudTracing.sendRequest(invocationId, httpRequest);
        }
        httpResponse = this.getClient().getHttpClient().execute(httpRequest);
        if (shouldTrace) {
            CloudTracing.receiveResponse(invocationId, httpResponse);
        }
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_ACCEPTED) {
            ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

        // Create Result
        OperationStatusResponse result = null;
        // Deserialize Response
        result = new OperationStatusResponse();
        result.setStatusCode(statusCode);
        if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
            result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
        }

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

From source file:com.microsoft.windowsazure.management.AffinityGroupOperationsImpl.java

/**
* The Update Affinity Group operation updates the label and/or the
* description for an affinity group for the specified subscription.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/gg715316.aspx for
* more information)/*from  w  ww.  j a  va 2s. c o m*/
*
* @param affinityGroupName Required. The name of the affinity group.
* @param parameters Required. Parameters supplied to the Update Affinity
* Group 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 affinityGroupName, AffinityGroupUpdateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (affinityGroupName == null) {
        throw new NullPointerException("affinityGroupName");
    }
    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");
    }

    // 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("affinityGroupName", affinityGroupName);
        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 + "/affinitygroups/";
    url = url + URLEncoder.encode(affinityGroupName, "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 updateAffinityGroupElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "UpdateAffinityGroup");
    requestDoc.appendChild(updateAffinityGroupElement);

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

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

    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.FirewallRuleOperationsImpl.java

/**
* Adds a new server-level Firewall Rule for an Azure SQL Database Server.
*
* @param serverName Required. The name of the Azure SQL Database Server to
* which this rule will be applied.//  w ww  .j ava 2  s . co  m
* @param parameters Required. The parameters for the Create Firewall Rule
* 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 Contains the response to a Create Firewall Rule operation.
*/
@Override
public FirewallRuleCreateResponse create(String serverName, FirewallRuleCreateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getEndIPAddress() == null) {
        throw new NullPointerException("parameters.EndIPAddress");
    }
    if (parameters.getName() == null) {
        throw new NullPointerException("parameters.Name");
    }
    if (parameters.getStartIPAddress() == null) {
        throw new NullPointerException("parameters.StartIPAddress");
    }

    // 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 + "/firewallrules";
    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);

    Element startIPAddressElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "StartIPAddress");
    startIPAddressElement
            .appendChild(requestDoc.createTextNode(parameters.getStartIPAddress().getHostAddress()));
    serviceResourceElement.appendChild(startIPAddressElement);

    Element endIPAddressElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "EndIPAddress");
    endIPAddressElement.appendChild(requestDoc.createTextNode(parameters.getEndIPAddress().getHostAddress()));
    serviceResourceElement.appendChild(endIPAddressElement);

    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
        FirewallRuleCreateResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_CREATED) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new FirewallRuleCreateResponse();
            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) {
                FirewallRule serviceResourceInstance = new FirewallRule();
                result.setFirewallRule(serviceResourceInstance);

                Element startIPAddressElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "StartIPAddress");
                if (startIPAddressElement2 != null) {
                    InetAddress startIPAddressInstance;
                    startIPAddressInstance = InetAddress.getByName(startIPAddressElement2.getTextContent());
                    serviceResourceInstance.setStartIPAddress(startIPAddressInstance);
                }

                Element endIPAddressElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "EndIPAddress");
                if (endIPAddressElement2 != null) {
                    InetAddress endIPAddressInstance;
                    endIPAddressInstance = InetAddress.getByName(endIPAddressElement2.getTextContent());
                    serviceResourceInstance.setEndIPAddress(endIPAddressInstance);
                }

                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:nl.b3p.kaartenbalie.service.requesthandler.WMSRequestHandler.java

/**
 * Gets the data from a specific set of URL's and converts the information
 * to the format usefull to the REQUEST_TYPE. Once the information is
 * collected and converted the method calls for a write in the DataWrapper,
 * which will sent the data to the client requested for this information.
 *
 * @param dw DataWrapper object containing the clients request information
 * @param urls StringBuffer with the urls where kaartenbalie should connect
 * to to recieve the requested data.//from   w  w w. jav  a  2  s.  c o m
 * @param overlay A boolean setting the overlay to true or false. If false
 * is chosen the images are placed under eachother.
 *
 * @return byte[]
 *
 * @throws Exception
 */
protected void getOnlineData(DataWrapper dw, ArrayList urlWrapper, boolean overlay, String REQUEST_TYPE)
        throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    BufferedImage[] bi = null;

    //The list is given in the opposit ranking. Therefore we first need to swap the list.
    int size = urlWrapper.size();
    ArrayList swaplist = new ArrayList(size);
    for (int i = size - 1; i >= 0; i--) {
        swaplist.add(urlWrapper.get(i));
        log.debug("Outgoing url: " + ((ServiceProviderRequest) urlWrapper.get(i)).getProviderRequestURI());
    }
    urlWrapper = swaplist;

    /* To save time, this method checks first if the ArrayList contains more then one url
     * If it contains only one url then the method doesn't have to load the image into the G2D
     * environment, which saves a lot of time and capacity because it doesn't have to decode
     * and recode the image.
     */
    long startprocestime = System.currentTimeMillis();

    DataMonitoring rr = dw.getRequestReporting();
    if (urlWrapper.size() > 1) {
        if (REQUEST_TYPE.equalsIgnoreCase(OGCConstants.WMS_REQUEST_GetMap)) {
            /*
             * Log the time in ms from the start of the clientrequest.. (Reporting)
             */
            Operation o = new Operation();
            o.setType(Operation.SERVER_TRANSFER);
            o.setMsSinceRequestStart(new Long(rr.getMSSinceStart()));

            ImageManager imagemanager = new ImageManager(urlWrapper, dw);
            imagemanager.process();
            long endprocestime = System.currentTimeMillis();
            Long time = new Long(endprocestime - startprocestime);
            dw.setHeader("X-Kaartenbalie-ImageServerResponseTime", time.toString());

            o.setDuration(time);
            rr.addRequestOperation(o);

            imagemanager.sendCombinedImages(dw);
        } else if (REQUEST_TYPE.equalsIgnoreCase(OGCConstants.WMS_REQUEST_GetFeatureInfo)) {

            /*
             * Create a DOM document and copy all the information of the several GetFeatureInfo
             * responses into one document. This document has the same layout as the received
             * documents and will hold all the information of the specified objects.
             * After combining these documents, the new document will be sent onto the request.
             */
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setValidating(false);
            dbf.setNamespaceAware(true);
            dbf.setIgnoringElementContentWhitespace(true);

            DocumentBuilder builder = dbf.newDocumentBuilder();
            Document destination = builder.newDocument();
            Element rootElement = destination.createElement("msGMLOutput");
            destination.appendChild(rootElement);
            rootElement.setAttribute("xmlns:gml", "http://www.opengis.net/gml");
            rootElement.setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink");
            rootElement.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
            Document source = null;
            for (int i = 0; i < urlWrapper.size(); i++) {
                ServiceProviderRequest wmsRequest = (ServiceProviderRequest) urlWrapper.get(i);
                String url = wmsRequest.getProviderRequestURI();
                // code below could be used to get bytes received
                //InputStream is = new URL(url).openStream();
                //CountingInputStream cis = new CountingInputStream(is);
                //source = builder.parse(cis);
                source = builder.parse(url); //what if url points to non MapServer service?
                copyElements(source, destination);

                wmsRequest.setBytesSent(new Long(url.getBytes().length));
                wmsRequest.setProviderRequestURI(url);
                wmsRequest.setMsSinceRequestStart(new Long(rr.getMSSinceStart()));
                wmsRequest.setBytesReceived(new Long(-1));
                //wmsRequest.setBytesReceived(new Long(cis.getByteCount()));
                wmsRequest.setResponseStatus(new Integer(-1));
                rr.addServiceProviderRequest(wmsRequest);
            }

            OutputFormat format = new OutputFormat(destination);
            format.setIndenting(true);
            XMLSerializer serializer = new XMLSerializer(baos, format);
            serializer.serialize(destination);
            dw.write(baos);
        } else if (REQUEST_TYPE.equalsIgnoreCase(OGCConstants.WMS_REQUEST_DescribeLayer)) {

            //TODO: implement and refactor so there is less code duplication with getFeatureInfo
            /*
              DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
              dbf.setValidating(false);
              dbf.setNamespaceAware(true);
              dbf.setIgnoringElementContentWhitespace(true);
                    
              DocumentBuilder builder = dbf.newDocumentBuilder();
              Document destination = builder.newDocument();
                     
              //root element is different
              Element rootElement = destination.createElement("WMS_DescribeLayerResponse");
              destination.appendChild(rootElement);
              //set version attribute
              Document source = null;
              for (int i = 0; i < urlWrapper.size(); i++) {
              ServiceProviderRequest dlRequest = (ServiceProviderRequest) urlWrapper.get(i);
              String url = dlRequest.getProviderRequestURI();
              source = builder.parse(url);
              copyElements(source,destination);
              }*/

            throw new Exception(REQUEST_TYPE + " request with more then one service url is not supported yet!");
        }

    } else {
        //urlWrapper not > 1, so only 1 url or zero urls
        if (!urlWrapper.isEmpty()) {
            getOnlineData(dw, (ServiceProviderRequest) urlWrapper.get(0), REQUEST_TYPE);
        } else {
            if (REQUEST_TYPE.equalsIgnoreCase(OGCConstants.WMS_REQUEST_GetFeatureInfo)) {
                log.error(KBConfiguration.FEATUREINFO_EXCEPTION);
                throw new Exception(KBConfiguration.FEATUREINFO_EXCEPTION);
            } else if (REQUEST_TYPE.equalsIgnoreCase(OGCConstants.WMS_REQUEST_GetLegendGraphic)) {
                log.error(KBConfiguration.LEGENDGRAPHIC_EXCEPTION);
                throw new Exception(KBConfiguration.LEGENDGRAPHIC_EXCEPTION);
            }
        }
    }
}

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

/**
* Updates an existing server-level Firewall Rule for an Azure SQL Database
* Server./*  ww  w . j a  va  2 s. c o  m*/
*
* @param serverName Required. The name of the Azure SQL Database Server
* that has the Firewall Rule to be updated.
* @param ruleName Required. The name of the Firewall Rule to be updated.
* @param parameters Required. The parameters for the Update Firewall Rule
* 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 firewall rule update response.
*/
@Override
public FirewallRuleUpdateResponse update(String serverName, String ruleName,
        FirewallRuleUpdateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }
    if (ruleName == null) {
        throw new NullPointerException("ruleName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getEndIPAddress() == null) {
        throw new NullPointerException("parameters.EndIPAddress");
    }
    if (parameters.getName() == null) {
        throw new NullPointerException("parameters.Name");
    }
    if (parameters.getStartIPAddress() == null) {
        throw new NullPointerException("parameters.StartIPAddress");
    }

    // 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("ruleName", ruleName);
        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/sqlservers/servers/";
    url = url + URLEncoder.encode(serverName, "UTF-8");
    url = url + "/firewallrules/";
    url = url + URLEncoder.encode(ruleName, "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", "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);

    Element startIPAddressElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "StartIPAddress");
    startIPAddressElement
            .appendChild(requestDoc.createTextNode(parameters.getStartIPAddress().getHostAddress()));
    serviceResourceElement.appendChild(startIPAddressElement);

    Element endIPAddressElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "EndIPAddress");
    endIPAddressElement.appendChild(requestDoc.createTextNode(parameters.getEndIPAddress().getHostAddress()));
    serviceResourceElement.appendChild(endIPAddressElement);

    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
        FirewallRuleUpdateResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new FirewallRuleUpdateResponse();
            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) {
                FirewallRule serviceResourceInstance = new FirewallRule();
                result.setFirewallRule(serviceResourceInstance);

                Element startIPAddressElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "StartIPAddress");
                if (startIPAddressElement2 != null) {
                    InetAddress startIPAddressInstance;
                    startIPAddressInstance = InetAddress.getByName(startIPAddressElement2.getTextContent());
                    serviceResourceInstance.setStartIPAddress(startIPAddressInstance);
                }

                Element endIPAddressElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "EndIPAddress");
                if (endIPAddressElement2 != null) {
                    InetAddress endIPAddressInstance;
                    endIPAddressInstance = InetAddress.getByName(endIPAddressElement2.getTextContent());
                    serviceResourceInstance.setEndIPAddress(endIPAddressInstance);
                }

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

/**
* The Create Affinity Group operation creates a new affinity group for the
* specified subscription.  (see/*from w w w .jav  a 2  s  .  com*/
* http://msdn.microsoft.com/en-us/library/windowsazure/gg715317.aspx for
* more information)
*
* @param parameters Required. Parameters supplied to the Create Affinity
* Group 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 create(AffinityGroupCreateParameters 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.getLocation() == null) {
        throw new NullPointerException("parameters.Location");
    }
    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, "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 + "/affinitygroups";
    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 createAffinityGroupElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "CreateAffinityGroup");
    requestDoc.appendChild(createAffinityGroupElement);

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

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

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

    Element locationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "Location");
    locationElement.appendChild(requestDoc.createTextNode(parameters.getLocation()));
    createAffinityGroupElement.appendChild(locationElement);

    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
        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:eu.eidas.auth.engine.AbstractSAMLEngine.java

/**
 * Method that transform the received SAML object into a byte array
 * representation./*from   w w  w . j a  v a  2  s  . c o m*/
 *
 * @param samlToken the SAML token.
 * @return the byte[] of the SAML token.
 * @throws SAMLEngineException the SAML engine exception
 */
private byte[] marshall(final XMLObject samlToken) throws SAMLEngineException {

    try {
        final MarshallerFactory marshallerFactory = Configuration.getMarshallerFactory();

        final Marshaller marshaller = marshallerFactory.getMarshaller(samlToken);

        // See http://stackoverflow.com/questions/9828254/is-documentbuilderfactory-thread-safe-in-java-5
        DocumentBuilder documentBuilder = DOCUMENT_BUILDER_POOL.poll();
        if (documentBuilder == null) {
            DocumentBuilderFactory documentBuilderFactory = DOCUMENT_BUILDER_FACTORY_POOL.poll();
            if (documentBuilderFactory == null) {
                documentBuilderFactory = newDocumentBuilderFactory();
            }
            documentBuilder = documentBuilderFactory.newDocumentBuilder();
            DOCUMENT_BUILDER_FACTORY_POOL.offer(documentBuilderFactory);
        }
        final Document doc = documentBuilder.newDocument();

        marshaller.marshall(samlToken, doc);

        // Obtain a byte array representation of the marshalled SAML object
        final DOMSource domSource = new DOMSource(doc);
        final StringWriter writer = new StringWriter();
        final StreamResult result = new StreamResult(writer);

        // See http://stackoverflow.com/questions/9828254/is-documentbuilderfactory-thread-safe-in-java-5
        Transformer transformer = TRANSFORMER_POOL.poll();
        if (transformer == null) {
            TransformerFactory transformerFactory = TRANSFORMER_FACTORY_POOL.poll();
            if (transformerFactory == null) {
                transformerFactory = TransformerFactory.newInstance();
            }
            transformer = transformerFactory.newTransformer();
            TRANSFORMER_FACTORY_POOL.offer(transformerFactory);
        }

        transformer.transform(domSource, result);
        LOG.debug("SAML request \n" + writer.toString());
        return writer.toString().getBytes(CHARACTER_ENCODING);

    } catch (ParserConfigurationException e) {
        LOG.error("ParserConfigurationException.", e.getMessage());
        throw new SAMLEngineException(e);
    } catch (MarshallingException e) {
        LOG.info("ERROR : MarshallingException.", e.getMessage());
        throw new SAMLEngineException(e);
    } catch (TransformerConfigurationException e) {
        LOG.info("ERROR : TransformerConfigurationException.", e.getMessage());
        throw new SAMLEngineException(e);
    } catch (TransformerException e) {
        LOG.info("ERROR : TransformerException.", e.getMessage());
        throw new SAMLEngineException(e);
    } catch (UnsupportedEncodingException e) {
        LOG.error("ERROR : UnsupportedEncodingException: " + CHARACTER_ENCODING, e.getMessage());
        throw new SAMLEngineException(e);
    }
}

From source file:de.interactive_instruments.ShapeChange.Target.ReplicationSchema.ReplicationXmlSchema.java

@Override
public void initialise(PackageInfo p, Model m, Options o, ShapeChangeResult r, boolean diagOnly)
        throws ShapeChangeAbortException {

    schemaPi = p;/*from   w ww .ja va 2  s .  c  o m*/
    model = m;
    options = o;
    result = r;
    diagnosticsOnly = diagOnly;

    result.addDebug(this, 1, schemaPi.name());

    outputDirectory = options.parameter(this.getClass().getName(), "outputDirectory");
    if (outputDirectory == null)
        outputDirectory = options.parameter("outputDirectory");
    if (outputDirectory == null)
        outputDirectory = options.parameter(".");

    outputFilename = schemaPi.name().replace("/", "_").replace(" ", "_") + ".xsd";

    // Check if we can use the output directory; create it if it
    // does not exist
    outputDirectoryFile = new File(outputDirectory);
    boolean exi = outputDirectoryFile.exists();
    if (!exi) {
        try {
            FileUtils.forceMkdir(outputDirectoryFile);
        } catch (IOException e) {
            result.addError(null, 600, e.getMessage());
            e.printStackTrace(System.err);
        }
        exi = outputDirectoryFile.exists();
    }
    boolean dir = outputDirectoryFile.isDirectory();
    boolean wrt = outputDirectoryFile.canWrite();
    boolean rea = outputDirectoryFile.canRead();
    if (!exi || !dir || !wrt || !rea) {
        result.addFatalError(null, 601, outputDirectory);
        throw new ShapeChangeAbortException();
    }

    File outputFile = new File(outputDirectoryFile, outputFilename);

    // check if output file already exists - if so, attempt to delete it
    exi = outputFile.exists();
    if (exi) {

        result.addInfo(this, 3, outputFilename, outputDirectory);

        try {
            FileUtils.forceDelete(outputFile);
            result.addInfo(this, 4);
        } catch (IOException e) {
            result.addInfo(null, 600, e.getMessage());
            e.printStackTrace(System.err);
        }
    }

    // identify map entries defined in the target configuration
    List<ProcessMapEntry> mapEntries = options.getCurrentProcessConfig().getMapEntries();

    if (mapEntries == null || mapEntries.isEmpty()) {

        result.addFatalError(this, 9);
        throw new ShapeChangeAbortException();

    } else {

        for (ProcessMapEntry pme : mapEntries) {
            this.mapEntryByType.put(pme.getType(), pme);
        }
    }

    // reset processed flags on all classes in the schema
    for (Iterator<ClassInfo> k = model.classes(schemaPi).iterator(); k.hasNext();) {
        ClassInfo ci = k.next();
        ci.processed(getTargetID(), false);
    }

    // ======================================
    // Parse configuration parameters
    // ======================================

    objectIdentifierFieldName = options.parameter(this.getClass().getName(),
            PARAM_OBJECT_IDENTIFIER_FIELD_NAME);
    if (objectIdentifierFieldName == null || objectIdentifierFieldName.trim().length() == 0) {
        objectIdentifierFieldName = DEFAULT_OBJECT_IDENTIFIER_FIELD_NAME;
    }

    suffixForPropWithFeatureValueType = options.parameter(this.getClass().getName(),
            PARAM_SUFFIX_FOR_PROPERTIES_WITH_FEATURE_VALUE_TYPE);
    if (suffixForPropWithFeatureValueType == null || suffixForPropWithFeatureValueType.trim().length() == 0) {
        suffixForPropWithFeatureValueType = "";
    }

    suffixForPropWithObjectValueType = options.parameter(this.getClass().getName(),
            PARAM_SUFFIX_FOR_PROPERTIES_WITH_OBJECT_VALUE_TYPE);
    if (suffixForPropWithObjectValueType == null || suffixForPropWithObjectValueType.trim().length() == 0) {
        suffixForPropWithObjectValueType = "";
    }

    targetNamespaceSuffix = options.parameter(this.getClass().getName(), PARAM_TARGET_NAMESPACE_SUFFIX);
    if (targetNamespaceSuffix == null || objectIdentifierFieldName.trim().length() == 0) {
        targetNamespaceSuffix = "";
    }

    String defaultSizeByConfig = options.parameter(this.getClass().getName(), PARAM_SIZE);
    if (defaultSizeByConfig != null) {
        try {
            defaultSize = Integer.parseInt(defaultSizeByConfig);
        } catch (NumberFormatException e) {
            MessageContext mc = result.addWarning(this, 8, PARAM_SIZE, e.getMessage());
            mc.addDetail(this, 0);
        }
    }

    // ======================================
    // Set up the document and create root
    // ======================================

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(true);
    dbf.setAttribute(Options.JAXP_SCHEMA_LANGUAGE, Options.W3C_XML_SCHEMA);
    DocumentBuilder db;
    try {
        db = dbf.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        result.addFatalError(null, 2);
        throw new ShapeChangeAbortException();
    }
    document = db.newDocument();

    root = document.createElementNS(Options.W3C_XML_SCHEMA, "schema");
    document.appendChild(root);

    addAttribute(root, "xmlns", Options.W3C_XML_SCHEMA);
    addAttribute(root, "elementFormDefault", "qualified");

    addAttribute(root, "version", schemaPi.version());
    targetNamespace = schemaPi.targetNamespace() + targetNamespaceSuffix;
    addAttribute(root, "targetNamespace", targetNamespace);
    addAttribute(root, "xmlns:" + schemaPi.xmlns(), targetNamespace);

    hook = document.createComment("XML Schema document created by ShapeChange - http://shapechange.net/");
    root.appendChild(hook);
}

From source file:DOMProcessor.java

/** Reads the XML from the given input stream and converts it into a DOM. 
  * @param inStream Input stream containing XML to convert.
  * @return True if converted successfully.
  *//*from   www  .  j a va 2 s .  c om*/
public boolean readXML(InputStream inStream) {
    // Create a DocumentBuilder using the DocumentBuilderFactory.
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = null;
    indent = 0;

    try {
        db = dbf.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        System.err.println("Problem finding an XML parser:\n" + e);
        return false;
    }

    // Try to parse the given file and store XML nodes in the DOM. 
    try {
        dom = db.parse(inStream);
    } catch (SAXException e) {
        System.err.println("Problem parsing document: " + e.getMessage());
        dom = db.newDocument();
        return false;
    } catch (IOException e) {
        System.err.println("Problem reading from " + inStream);
        return false;
    }
    return true;
}