Example usage for javax.xml.bind DatatypeConverter parseInt

List of usage examples for javax.xml.bind DatatypeConverter parseInt

Introduction

In this page you can find the example usage for javax.xml.bind DatatypeConverter parseInt.

Prototype

public static int parseInt(String lexicalXSDInt) 

Source Link

Document

Convert the string argument into an int value.

Usage

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

/**
* Creates a new Web Hosting Plan.  (see//from   w  w  w . j av a  2 s  . c o m
* http://azure.microsoft.com/en-us/documentation/articles/azure-web-sites-web-hosting-plans-in-depth-overview/
* for more information)
*
* @param webSpaceName Required. The name of the web space.
* @param parameters Required. Web Hosting Plan Parameters.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @throws URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return The Create Web Web Hosting Plan operation response.
*/
@Override
public WebHostingPlanCreateResponse create(String webSpaceName, WebHostingPlanCreateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException,
        URISyntaxException {
    // Validate
    if (webSpaceName == null) {
        throw new NullPointerException("webSpaceName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getName() == null) {
        throw new NullPointerException("parameters.Name");
    }

    // Tracing
    boolean shouldTrace = CloudTracing.getIsEnabled();
    String invocationId = null;
    if (shouldTrace) {
        invocationId = Long.toString(CloudTracing.getNextInvocationId());
        HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
        tracingParameters.put("webSpaceName", webSpaceName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "createAsync", tracingParameters);
    }

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/services/WebSpaces/";
    url = url + URLEncoder.encode(webSpaceName, "UTF-8");
    url = url + "/ServerFarms";
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

From source file:com.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  ww  .  j a  va 2s . 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:com.microsoft.azure.management.sql.ReplicationLinkOperationsImpl.java

/**
* Begins a forced failover of the Azure SQL Database Replication Link with
* the given id which may result in data loss.
*
* @param resourceGroupName Required. The name of the Resource Group to
* which the Azure SQL Server belongs./* w  w  w .  j a  v  a 2 s . com*/
* @param serverName Required. The name of the Azure SQL Server on which the
* Azure SQL Database is hosted.
* @param databaseName Required. The name of the Azure SQL Database that has
* the replication link to be failed over.
* @param linkId Required. The id of the replication link to be failed over.
* @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 Response for long running Azure Sql Database replication failover
* operations.
*/
@Override
public ReplicationLinkFailoverResponse beginFailoverAllowDataLoss(String resourceGroupName, String serverName,
        String databaseName, String linkId) throws IOException, ServiceException {
    // Validate
    if (resourceGroupName == null) {
        throw new NullPointerException("resourceGroupName");
    }
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }
    if (databaseName == null) {
        throw new NullPointerException("databaseName");
    }
    if (linkId == null) {
        throw new NullPointerException("linkId");
    }

    // 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("resourceGroupName", resourceGroupName);
        tracingParameters.put("serverName", serverName);
        tracingParameters.put("databaseName", databaseName);
        tracingParameters.put("linkId", linkId);
        CloudTracing.enter(invocationId, this, "beginFailoverAllowDataLossAsync", tracingParameters);
    }

    // Construct URL
    String url = "";
    url = url + "/subscriptions/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/resourceGroups/";
    url = url + URLEncoder.encode(resourceGroupName, "UTF-8");
    url = url + "/providers/";
    url = url + "Microsoft.Sql";
    url = url + "/servers/";
    url = url + URLEncoder.encode(serverName, "UTF-8");
    url = url + "/databases/";
    url = url + URLEncoder.encode(databaseName, "UTF-8");
    url = url + "/replicationLinks/";
    url = url + URLEncoder.encode(linkId, "UTF-8");
    url = url + "/forceFailoverAllowDataLoss";
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("api-version=" + "2014-04-01");
    if (queryParameters.size() > 0) {
        url = url + "?" + CollectionStringBuilder.join(queryParameters, "&");
    }
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

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

    // Set Headers

    // 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 && statusCode != HttpStatus.SC_NO_CONTENT) {
            ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

        // Create Result
        ReplicationLinkFailoverResponse result = null;
        // Deserialize Response
        result = new ReplicationLinkFailoverResponse();
        result.setStatusCode(statusCode);
        if (httpResponse.getHeaders("Location").length > 0) {
            result.setOperationStatusLink(httpResponse.getFirstHeader("Location").getValue());
        }
        if (httpResponse.getHeaders("Retry-After").length > 0) {
            result.setRetryAfter(
                    DatatypeConverter.parseInt(httpResponse.getFirstHeader("Retry-After").getValue()));
        }
        if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
            result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
        }
        if (statusCode == HttpStatus.SC_NO_CONTENT) {
            result.setStatus(OperationStatus.Succeeded);
        }

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

/**
* Starts a SQL Server database copy.//  ww  w . j  a  v  a2s  . c o  m
*
* @param serverName Required. The name of the SQL Server where the source
* database resides.
* @param databaseName Required. The name of the source database.
* @param parameters Required. The additional parameters for the create
* database copy 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 a response to the create request.
*/
@Override
public DatabaseCopyCreateResponse create(String serverName, String databaseName,
        DatabaseCopyCreateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }
    if (databaseName == null) {
        throw new NullPointerException("databaseName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getPartnerDatabase() == null) {
        throw new NullPointerException("parameters.PartnerDatabase");
    }
    if (parameters.getPartnerServer() == null) {
        throw new NullPointerException("parameters.PartnerServer");
    }

    // 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("databaseName", databaseName);
        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/";
    url = url + URLEncoder.encode(databaseName, "UTF-8");
    url = url + "/databasecopies";
    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 partnerServerElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "PartnerServer");
    partnerServerElement.appendChild(requestDoc.createTextNode(parameters.getPartnerServer()));
    serviceResourceElement.appendChild(partnerServerElement);

    Element partnerDatabaseElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "PartnerDatabase");
    partnerDatabaseElement.appendChild(requestDoc.createTextNode(parameters.getPartnerDatabase()));
    serviceResourceElement.appendChild(partnerDatabaseElement);

    Element isContinuousElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "IsContinuous");
    isContinuousElement
            .appendChild(requestDoc.createTextNode(Boolean.toString(parameters.isContinuous()).toLowerCase()));
    serviceResourceElement.appendChild(isContinuousElement);

    Element isOfflineSecondaryElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "IsOfflineSecondary");
    isOfflineSecondaryElement.appendChild(
            requestDoc.createTextNode(Boolean.toString(parameters.isOfflineSecondary()).toLowerCase()));
    serviceResourceElement.appendChild(isOfflineSecondaryElement);

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

                Element sourceServerNameElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "SourceServerName");
                if (sourceServerNameElement != null) {
                    String sourceServerNameInstance;
                    sourceServerNameInstance = sourceServerNameElement.getTextContent();
                    serviceResourceInstance.setSourceServerName(sourceServerNameInstance);
                }

                Element sourceDatabaseNameElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "SourceDatabaseName");
                if (sourceDatabaseNameElement != null) {
                    String sourceDatabaseNameInstance;
                    sourceDatabaseNameInstance = sourceDatabaseNameElement.getTextContent();
                    serviceResourceInstance.setSourceDatabaseName(sourceDatabaseNameInstance);
                }

                Element destinationServerNameElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "DestinationServerName");
                if (destinationServerNameElement != null) {
                    String destinationServerNameInstance;
                    destinationServerNameInstance = destinationServerNameElement.getTextContent();
                    serviceResourceInstance.setDestinationServerName(destinationServerNameInstance);
                }

                Element destinationDatabaseNameElement = XmlUtility.getElementByTagNameNS(
                        serviceResourceElement2, "http://schemas.microsoft.com/windowsazure",
                        "DestinationDatabaseName");
                if (destinationDatabaseNameElement != null) {
                    String destinationDatabaseNameInstance;
                    destinationDatabaseNameInstance = destinationDatabaseNameElement.getTextContent();
                    serviceResourceInstance.setDestinationDatabaseName(destinationDatabaseNameInstance);
                }

                Element isContinuousElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "IsContinuous");
                if (isContinuousElement2 != null) {
                    boolean isContinuousInstance;
                    isContinuousInstance = DatatypeConverter
                            .parseBoolean(isContinuousElement2.getTextContent().toLowerCase());
                    serviceResourceInstance.setIsContinuous(isContinuousInstance);
                }

                Element replicationStateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "ReplicationState");
                if (replicationStateElement != null) {
                    byte replicationStateInstance;
                    replicationStateInstance = DatatypeConverter
                            .parseByte(replicationStateElement.getTextContent());
                    serviceResourceInstance.setReplicationState(replicationStateInstance);
                }

                Element replicationStateDescriptionElement = XmlUtility.getElementByTagNameNS(
                        serviceResourceElement2, "http://schemas.microsoft.com/windowsazure",
                        "ReplicationStateDescription");
                if (replicationStateDescriptionElement != null) {
                    String replicationStateDescriptionInstance;
                    replicationStateDescriptionInstance = replicationStateDescriptionElement.getTextContent();
                    serviceResourceInstance.setReplicationStateDescription(replicationStateDescriptionInstance);
                }

                Element localDatabaseIdElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "LocalDatabaseId");
                if (localDatabaseIdElement != null) {
                    int localDatabaseIdInstance;
                    localDatabaseIdInstance = DatatypeConverter
                            .parseInt(localDatabaseIdElement.getTextContent());
                    serviceResourceInstance.setLocalDatabaseId(localDatabaseIdInstance);
                }

                Element isLocalDatabaseReplicationTargetElement = XmlUtility.getElementByTagNameNS(
                        serviceResourceElement2, "http://schemas.microsoft.com/windowsazure",
                        "IsLocalDatabaseReplicationTarget");
                if (isLocalDatabaseReplicationTargetElement != null) {
                    boolean isLocalDatabaseReplicationTargetInstance;
                    isLocalDatabaseReplicationTargetInstance = DatatypeConverter.parseBoolean(
                            isLocalDatabaseReplicationTargetElement.getTextContent().toLowerCase());
                    serviceResourceInstance
                            .setIsLocalDatabaseReplicationTarget(isLocalDatabaseReplicationTargetInstance);
                }

                Element isInterlinkConnectedElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "IsInterlinkConnected");
                if (isInterlinkConnectedElement != null) {
                    boolean isInterlinkConnectedInstance;
                    isInterlinkConnectedInstance = DatatypeConverter
                            .parseBoolean(isInterlinkConnectedElement.getTextContent().toLowerCase());
                    serviceResourceInstance.setIsInterlinkConnected(isInterlinkConnectedInstance);
                }

                Element startDateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "StartDate");
                if (startDateElement != null) {
                    String startDateInstance;
                    startDateInstance = startDateElement.getTextContent();
                    serviceResourceInstance.setStartDate(startDateInstance);
                }

                Element modifyDateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "ModifyDate");
                if (modifyDateElement != null) {
                    String modifyDateInstance;
                    modifyDateInstance = modifyDateElement.getTextContent();
                    serviceResourceInstance.setModifyDate(modifyDateInstance);
                }

                Element percentCompleteElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "PercentComplete");
                if (percentCompleteElement != null) {
                    float percentCompleteInstance;
                    percentCompleteInstance = DatatypeConverter
                            .parseFloat(percentCompleteElement.getTextContent());
                    serviceResourceInstance.setPercentComplete(percentCompleteInstance);
                }

                Element isOfflineSecondaryElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "IsOfflineSecondary");
                if (isOfflineSecondaryElement2 != null) {
                    boolean isOfflineSecondaryInstance;
                    isOfflineSecondaryInstance = DatatypeConverter
                            .parseBoolean(isOfflineSecondaryElement2.getTextContent().toLowerCase());
                    serviceResourceInstance.setIsOfflineSecondary(isOfflineSecondaryInstance);
                }

                Element isTerminationAllowedElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "IsTerminationAllowed");
                if (isTerminationAllowedElement != null) {
                    boolean isTerminationAllowedInstance;
                    isTerminationAllowedInstance = DatatypeConverter
                            .parseBoolean(isTerminationAllowedElement.getTextContent().toLowerCase());
                    serviceResourceInstance.setIsTerminationAllowed(isTerminationAllowedInstance);
                }

                Element nameElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "Name");
                if (nameElement != null) {
                    String nameInstance;
                    nameInstance = nameElement.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:br.com.upic.camel.openedge.OpenEdgeEndpoint.java

@Override
protected void onExchange(final Exchange exchange) throws Exception {

    try {//from   w ww . ja  v  a2  s  .  c  om
        LOG.info("Unmarshalling the request");

        final Request req = (Request) unmarshaller.unmarshal(exchange.getIn().getBody(Document.class));

        LOG.info("Setting the input params");

        final List<JAXBElement<? extends Serializable>> reqParamElementList = req.getParamElementList();

        final ParamArray proParams = new ParamArray(reqParamElementList.size());

        for (final JAXBElement<? extends Serializable> reqParamElement : reqParamElementList) {
            final Serializable reqParam = reqParamElement.getValue();

            if (reqParam instanceof CharArrayParam) {
                final CharArrayParam charArrayParam = (CharArrayParam) reqParam;

                final ParamMode mode = charArrayParam.getMode();

                final int id = charArrayParam.getId();

                if (((ParamMode.INPUT == mode) || (ParamMode.INPUT_OUTPUT == mode))
                        && (!reqParamElement.isNil())) {
                    final List<String> value = new ArrayList<String>();

                    for (final JAXBElement<String> valueElement : charArrayParam.getValueElementList()) {

                        if (!valueElement.isNil())
                            value.add(DatatypeConverter.parseString(valueElement.getValue()));
                        else
                            value.add(null);

                    }

                    proParams.addCharacterArray(id, value.toArray(new String[] {}), mode.value(), value.size());
                } else {
                    proParams.addCharacterArray(id, null, mode.value(), 0);
                }

            } else if (reqParam instanceof CharParam) {
                final CharParam charParam = (CharParam) reqParam;

                final ParamMode mode = charParam.getMode();

                final int id = charParam.getId();

                if (((ParamMode.INPUT == mode) || (ParamMode.INPUT_OUTPUT == mode))
                        && (!reqParamElement.isNil()))
                    proParams.addCharacter(id, DatatypeConverter.parseString(charParam.getContent()),
                            mode.value());
                else
                    proParams.addCharacter(id, null, mode.value());

            } else if (reqParam instanceof DateArrayParam) {
                final DateArrayParam dateArrayParam = (DateArrayParam) reqParam;

                final ParamMode mode = dateArrayParam.getMode();

                final int id = dateArrayParam.getId();

                if (((ParamMode.INPUT == mode) || (ParamMode.INPUT_OUTPUT == mode))
                        && (!reqParamElement.isNil())) {
                    final List<GregorianCalendar> value = new ArrayList<GregorianCalendar>();

                    for (final JAXBElement<String> valueElement : dateArrayParam.getValueElementList()) {

                        if (!valueElement.isNil()) {
                            final GregorianCalendar cal = new GregorianCalendar();

                            cal.setTime(DatatypeConverter.parseDate(valueElement.getValue()).getTime());

                            value.add(cal);
                        } else {
                            value.add(null);
                        }

                    }

                    proParams.addDateArray(id, value.toArray(new GregorianCalendar[] {}), mode.value(),
                            value.size());
                } else {
                    proParams.addDateArray(id, null, mode.value(), 0);
                }

            } else if (reqParam instanceof DateParam) {
                final DateParam dateParam = (DateParam) reqParam;

                final ParamMode mode = dateParam.getMode();

                final int id = dateParam.getId();

                if (((ParamMode.INPUT == mode) || (ParamMode.INPUT_OUTPUT == mode))
                        && (!reqParamElement.isNil())) {
                    final GregorianCalendar cal = new GregorianCalendar();

                    cal.setTime(DatatypeConverter.parseDate(dateParam.getContent()).getTime());

                    proParams.addDate(id, cal, mode.value());
                } else {
                    proParams.addDate(id, null, mode.value());
                }

            } else if (reqParam instanceof DateTimeArrayParam) {
                final DateTimeArrayParam dateTimeArrayParam = (DateTimeArrayParam) reqParam;

                final ParamMode mode = dateTimeArrayParam.getMode();

                final int id = dateTimeArrayParam.getId();

                if (((ParamMode.INPUT == mode) || (ParamMode.INPUT_OUTPUT == mode))
                        && (!reqParamElement.isNil())) {
                    final List<GregorianCalendar> value = new ArrayList<GregorianCalendar>();

                    for (final JAXBElement<String> valueElement : dateTimeArrayParam.getValueElementList()) {

                        if (!valueElement.isNil()) {
                            final GregorianCalendar cal = new GregorianCalendar();

                            cal.setTime(DatatypeConverter.parseDateTime(valueElement.getValue()).getTime());

                            value.add(cal);
                        } else {
                            value.add(null);
                        }

                    }

                    proParams.addDatetimeArray(id, value.toArray(new GregorianCalendar[] {}), mode.value(),
                            value.size());
                } else {
                    proParams.addDatetimeArray(id, null, mode.value(), 0);
                }

            } else if (reqParam instanceof DateTimeParam) {
                final DateTimeParam dateTimeParam = (DateTimeParam) reqParam;

                final ParamMode mode = dateTimeParam.getMode();

                final int id = dateTimeParam.getId();

                if (((ParamMode.INPUT == mode) || (ParamMode.INPUT_OUTPUT == mode))
                        && (!reqParamElement.isNil())) {
                    final GregorianCalendar cal = new GregorianCalendar();

                    cal.setTime(DatatypeConverter.parseDateTime(dateTimeParam.getContent()).getTime());

                    proParams.addDatetime(id, cal, mode.value());
                } else {
                    proParams.addDatetime(id, null, mode.value());
                }

            } else if (reqParam instanceof DateTimeTZArrayParam) {
                final DateTimeTZArrayParam dateTimeTZArrayParam = (DateTimeTZArrayParam) reqParam;

                final ParamMode mode = dateTimeTZArrayParam.getMode();

                final int id = dateTimeTZArrayParam.getId();

                if (((ParamMode.INPUT == mode) || (ParamMode.INPUT_OUTPUT == mode))
                        && (!reqParamElement.isNil())) {
                    final List<GregorianCalendar> value = new ArrayList<GregorianCalendar>();

                    for (final JAXBElement<String> valueElement : dateTimeTZArrayParam.getValueElementList()) {

                        if (!valueElement.isNil()) {
                            final GregorianCalendar cal = new GregorianCalendar();

                            cal.setTime(DatatypeConverter.parseDateTime(valueElement.getValue()).getTime());

                            value.add(cal);
                        } else {
                            value.add(null);
                        }

                    }

                    proParams.addDatetimeTZArray(id, value.toArray(new GregorianCalendar[] {}), mode.value(),
                            value.size());
                } else {
                    proParams.addDatetimeTZArray(id, null, mode.value(), 0);
                }

            } else if (reqParam instanceof DateTimeTZParam) {
                final DateTimeTZParam dateTimeTZParam = (DateTimeTZParam) reqParam;

                final ParamMode mode = dateTimeTZParam.getMode();

                final int id = dateTimeTZParam.getId();

                if (((ParamMode.INPUT == mode) || (ParamMode.INPUT_OUTPUT == mode))
                        && (!reqParamElement.isNil())) {
                    final GregorianCalendar cal = new GregorianCalendar();

                    cal.setTime(DatatypeConverter.parseDateTime(dateTimeTZParam.getContent()).getTime());

                    proParams.addDatetimeTZ(id, cal, mode.value());
                } else {
                    proParams.addDatetimeTZ(id, null, mode.value());
                }

            } else if (reqParam instanceof DecArrayParam) {
                final DecArrayParam decArrayParam = (DecArrayParam) reqParam;

                final ParamMode mode = decArrayParam.getMode();

                final int id = decArrayParam.getId();

                if (((ParamMode.INPUT == mode) || (ParamMode.INPUT_OUTPUT == mode))
                        && (!reqParamElement.isNil())) {
                    final List<BigDecimal> value = new ArrayList<BigDecimal>();

                    for (final JAXBElement<String> valueElement : decArrayParam.getValueElementList()) {

                        if (!valueElement.isNil())
                            value.add(DatatypeConverter.parseDecimal(valueElement.getValue()));
                        else
                            value.add(null);

                    }

                    proParams.addDecimalArray(id, value.toArray(new BigDecimal[] {}), mode.value(),
                            value.size());
                } else {
                    proParams.addDecimalArray(id, null, mode.value(), 0);
                }

            } else if (reqParam instanceof DecParam) {
                final DecParam decParam = (DecParam) reqParam;

                final ParamMode mode = decParam.getMode();

                final int id = decParam.getId();

                if (((ParamMode.INPUT == mode) || (ParamMode.INPUT_OUTPUT == mode))
                        && (!reqParamElement.isNil()))
                    proParams.addDecimal(id, DatatypeConverter.parseDecimal(decParam.getContent()),
                            mode.value());
                else
                    proParams.addDecimal(id, null, mode.value());

            } else if (reqParam instanceof IntArrayParam) {
                final IntArrayParam intArrayParam = (IntArrayParam) reqParam;

                final ParamMode mode = intArrayParam.getMode();

                final int id = intArrayParam.getId();

                if (((ParamMode.INPUT == mode) || (ParamMode.INPUT_OUTPUT == mode))
                        && (!reqParamElement.isNil())) {
                    final List<Integer> value = new ArrayList<Integer>();

                    for (final JAXBElement<String> valueElement : intArrayParam.getValueElementList()) {

                        if (!valueElement.isNil())
                            value.add(DatatypeConverter.parseInt(valueElement.getValue()));
                        else
                            value.add(null);

                    }

                    proParams.addIntegerArray(id, value.toArray(new Integer[] {}), mode.value(), value.size());
                } else {
                    proParams.addIntegerArray(id, (Integer[]) null, mode.value(), 0);
                }

            } else if (reqParam instanceof IntParam) {
                final IntParam intParam = (IntParam) reqParam;

                final ParamMode mode = intParam.getMode();

                final int id = intParam.getId();

                if (((ParamMode.INPUT == mode) || (ParamMode.INPUT_OUTPUT == mode))
                        && (!reqParamElement.isNil()))
                    proParams.addInteger(id, new Integer(DatatypeConverter.parseInt(intParam.getContent())),
                            mode.value());
                else
                    proParams.addInteger(id, null, mode.value());

            } else if (reqParam instanceof LogArrayParam) {
                final LogArrayParam logArrayParam = (LogArrayParam) reqParam;

                final ParamMode mode = logArrayParam.getMode();

                final int id = logArrayParam.getId();

                if (((ParamMode.INPUT == mode) || (ParamMode.INPUT_OUTPUT == mode))
                        && (!reqParamElement.isNil())) {
                    final List<Boolean> value = new ArrayList<Boolean>();

                    for (final JAXBElement<String> valueElement : logArrayParam.getValueElementList()) {

                        if (!valueElement.isNil())
                            value.add(DatatypeConverter.parseBoolean(valueElement.getValue()));
                        else
                            value.add(null);

                    }

                    proParams.addLogicalArray(id, value.toArray(new Boolean[] {}), mode.value(), value.size());
                } else {
                    proParams.addLogicalArray(id, (Boolean[]) null, mode.value(), 0);
                }

            } else if (reqParam instanceof LogParam) {
                final LogParam logParam = (LogParam) reqParam;

                final ParamMode mode = logParam.getMode();

                final int id = logParam.getId();

                if (((ParamMode.INPUT == mode) || (ParamMode.INPUT_OUTPUT == mode))
                        && (!reqParamElement.isNil()))
                    proParams.addLogical(id, new Boolean(DatatypeConverter.parseBoolean(logParam.getContent())),
                            mode.value());
                else
                    proParams.addLogical(id, null, mode.value());

            } else if (reqParam instanceof ResultSetParam) {
                final ResultSetParam rsParam = (ResultSetParam) reqParam;

                final ParamMode mode = rsParam.getMode();

                final int id = rsParam.getId();

                final ResultSetMetaData rsMetaData = rsParam.getResultSetMetaData();

                final List<Serializable> fieldMetaDataList = rsMetaData.getFieldMetaDataList();

                final ProResultSetMetaDataImpl proRsMetaData = new ProResultSetMetaDataImpl(
                        fieldMetaDataList.size());

                for (final Serializable fieldMetaData : fieldMetaDataList) {

                    if (fieldMetaData instanceof CharFieldMetaData) {
                        final CharFieldMetaData charFieldMetaData = (CharFieldMetaData) fieldMetaData;

                        proRsMetaData.setFieldMetaData(charFieldMetaData.getId(), charFieldMetaData.getName(),
                                charFieldMetaData.getExtent(), Parameter.PRO_CHARACTER);
                    } else if (fieldMetaData instanceof DateFieldMetaData) {
                        final DateFieldMetaData dateFieldMetaData = (DateFieldMetaData) fieldMetaData;

                        proRsMetaData.setFieldMetaData(dateFieldMetaData.getId(), dateFieldMetaData.getName(),
                                dateFieldMetaData.getExtent(), Parameter.PRO_DATE);
                    } else if (fieldMetaData instanceof DateTimeFieldMetaData) {
                        final DateTimeFieldMetaData dateTimeFieldMetaData = (DateTimeFieldMetaData) fieldMetaData;

                        proRsMetaData.setFieldMetaData(dateTimeFieldMetaData.getId(),
                                dateTimeFieldMetaData.getName(), dateTimeFieldMetaData.getExtent(),
                                Parameter.PRO_DATETIME);
                    } else if (fieldMetaData instanceof DateTimeTZFieldMetaData) {
                        final DateTimeTZFieldMetaData dateTimeTZFieldMetaData = (DateTimeTZFieldMetaData) fieldMetaData;

                        proRsMetaData.setFieldMetaData(dateTimeTZFieldMetaData.getId(),
                                dateTimeTZFieldMetaData.getName(), dateTimeTZFieldMetaData.getExtent(),
                                Parameter.PRO_DATETIMETZ);
                    } else if (fieldMetaData instanceof DecFieldMetaData) {
                        final DecFieldMetaData decFieldMetaData = (DecFieldMetaData) fieldMetaData;

                        proRsMetaData.setFieldMetaData(decFieldMetaData.getId(), decFieldMetaData.getName(),
                                decFieldMetaData.getExtent(), Parameter.PRO_DECIMAL);
                    } else if (fieldMetaData instanceof IntFieldMetaData) {
                        final IntFieldMetaData intFieldMetaData = (IntFieldMetaData) fieldMetaData;

                        proRsMetaData.setFieldMetaData(intFieldMetaData.getId(), intFieldMetaData.getName(),
                                intFieldMetaData.getExtent(), Parameter.PRO_INTEGER);
                    } else if (fieldMetaData instanceof LogFieldMetaData) {
                        final LogFieldMetaData logFieldMetaData = (LogFieldMetaData) fieldMetaData;

                        proRsMetaData.setFieldMetaData(logFieldMetaData.getId(), logFieldMetaData.getName(),
                                logFieldMetaData.getExtent(), Parameter.PRO_LOGICAL);
                    }

                }

                if (((ParamMode.INPUT == mode) || (ParamMode.INPUT_OUTPUT == mode))
                        && (!reqParamElement.isNil()))
                    proParams.addTable(id, new OpenEdgeResultSet(rsParam.getRowList().iterator()), mode.value(),
                            proRsMetaData);
                else
                    proParams.addTable(id, null, mode.value(), proRsMetaData);

            }

        }

        LOG.info("Connecting to the AppServer");

        if (SESSION_MODEL_MANAGED == sessionModel)
            RunTimeProperties.setSessionModel(0);
        else if (SESSION_MODEL_FREE == sessionModel)
            RunTimeProperties.setSessionModel(1);

        final OpenAppObject proAppObject = new OpenAppObject(url, user, password, null, null);

        proAppObject.runProc(req.getProgram(), proParams);

        LOG.info("Marshalling the response");

        final Response res = OBJECT_FACTORY.createResponse();

        res.setResult(proParams.getProcReturnString());

        LOG.info("Setting the output params");

        for (final JAXBElement<? extends Serializable> reqParamElement : reqParamElementList) {
            final Serializable reqParam = reqParamElement.getValue();

            if (reqParam instanceof CharArrayParam) {
                final CharArrayParam reqCharArrayParam = (CharArrayParam) reqParam;

                if (ParamMode.INPUT != reqCharArrayParam.getMode()) {
                    final JAXBElement<CharArrayParam> resParamElement = new JAXBElement<CharArrayParam>(
                            new QName(NS, "CharArray"), CharArrayParam.class, null);

                    final CharArrayParam resParam = OBJECT_FACTORY.createCharArrayParam();

                    resParam.setId(reqCharArrayParam.getId());

                    resParam.setName(reqCharArrayParam.getName());

                    final String[] proParam = (String[]) proParams.getOutputParameter(resParam.getId());

                    if (proParam != null) {

                        for (int i = 0; i < proParam.length; i++) {
                            final JAXBElement<String> valueElement = new JAXBElement<String>(
                                    new QName(NS, "Value"), String.class, null);

                            if (proParam[i] != null)
                                valueElement.setValue(DatatypeConverter.printString(proParam[i]));
                            else
                                valueElement.setNil(true);

                            resParam.getValueElementList().add(valueElement);
                        }

                        resParamElement.setValue(resParam);
                    } else {
                        resParamElement.setNil(true);
                    }

                    res.getParamElementList().add(resParamElement);
                }

            } else if (reqParam instanceof CharParam) {
                final CharParam reqCharParam = (CharParam) reqParam;

                if (ParamMode.INPUT != reqCharParam.getMode()) {
                    final JAXBElement<CharParam> resParamElement = new JAXBElement<CharParam>(
                            new QName(NS, "Char"), CharParam.class, null);

                    final CharParam resParam = OBJECT_FACTORY.createCharParam();

                    resParam.setId(reqCharParam.getId());

                    resParam.setName(reqCharParam.getName());

                    final String proParam = (String) proParams.getOutputParameter(resParam.getId());

                    if (proParam != null) {
                        resParam.setContent(DatatypeConverter.printString(proParam));

                        resParamElement.setValue(resParam);
                    } else {
                        resParamElement.setNil(true);
                    }

                    res.getParamElementList().add(resParamElement);
                }

            } else if (reqParam instanceof DateArrayParam) {
                final DateArrayParam reqDateArrayParam = (DateArrayParam) reqParam;

                if (ParamMode.INPUT != reqDateArrayParam.getMode()) {
                    final JAXBElement<DateArrayParam> resParamElement = new JAXBElement<DateArrayParam>(
                            new QName(NS, "DateArray"), DateArrayParam.class, null);

                    final DateArrayParam resParam = OBJECT_FACTORY.createDateArrayParam();

                    resParam.setId(reqDateArrayParam.getId());

                    resParam.setName(reqDateArrayParam.getName());

                    final Date[] proParam = (Date[]) proParams.getOutputParameter(resParam.getId());

                    if (proParam != null) {

                        for (int i = 0; i < proParam.length; i++) {
                            final JAXBElement<String> valueElement = new JAXBElement<String>(
                                    new QName(NS, "Value"), String.class, null);

                            if (proParam[i] != null) {
                                final Calendar cal = Calendar.getInstance();

                                cal.setTime(proParam[i]);

                                valueElement.setValue(DatatypeConverter.printDate(cal));
                            } else {
                                valueElement.setNil(true);
                            }

                            resParam.getValueElementList().add(valueElement);
                        }

                        resParamElement.setValue(resParam);
                    } else {
                        resParamElement.setNil(true);
                    }

                    res.getParamElementList().add(resParamElement);
                }

            } else if (reqParam instanceof DateParam) {
                final DateParam reqDateParam = (DateParam) reqParam;

                if (ParamMode.INPUT != reqDateParam.getMode()) {
                    final JAXBElement<DateParam> resParamElement = new JAXBElement<DateParam>(
                            new QName(NS, "Date"), DateParam.class, null);

                    final DateParam resParam = OBJECT_FACTORY.createDateParam();

                    resParam.setId(reqDateParam.getId());

                    resParam.setName(reqDateParam.getName());

                    final Date proParam = (Date) proParams.getOutputParameter(resParam.getId());

                    if (proParam != null) {
                        final Calendar cal = Calendar.getInstance();

                        cal.setTime(proParam);

                        resParam.setContent(DatatypeConverter.printDate(cal));

                        resParamElement.setValue(resParam);
                    } else {
                        resParamElement.setNil(true);
                    }

                    res.getParamElementList().add(resParamElement);
                }

            } else if (reqParam instanceof DateTimeArrayParam) {
                final DateTimeArrayParam reqDateTimeArrayParam = (DateTimeArrayParam) reqParam;

                if (ParamMode.INPUT != reqDateTimeArrayParam.getMode()) {
                    final JAXBElement<DateTimeArrayParam> resParamElement = new JAXBElement<DateTimeArrayParam>(
                            new QName(NS, "DateTimeArray"), DateTimeArrayParam.class, null);

                    final DateTimeArrayParam resParam = OBJECT_FACTORY.createDateTimeArrayParam();

                    resParam.setId(reqDateTimeArrayParam.getId());

                    resParam.setName(reqDateTimeArrayParam.getName());

                    final GregorianCalendar[] proParam = (GregorianCalendar[]) proParams
                            .getOutputParameter(resParam.getId());

                    if (proParam != null) {

                        for (int i = 0; i < proParam.length; i++) {
                            final JAXBElement<String> valueElement = new JAXBElement<String>(
                                    new QName(NS, "Value"), String.class, null);

                            if (proParam[i] != null)
                                valueElement.setValue(DatatypeConverter.printDateTime(proParam[i]));
                            else
                                valueElement.setNil(true);

                            resParam.getValueElementList().add(valueElement);
                        }

                        resParamElement.setValue(resParam);
                    } else {
                        resParamElement.setNil(true);
                    }

                    res.getParamElementList().add(resParamElement);
                }

            } else if (reqParam instanceof DateTimeParam) {
                final DateTimeParam reqDateTimeParam = (DateTimeParam) reqParam;

                if (ParamMode.INPUT != reqDateTimeParam.getMode()) {
                    final JAXBElement<DateTimeParam> resParamElement = new JAXBElement<DateTimeParam>(
                            new QName(NS, "DateTime"), DateTimeParam.class, null);

                    final DateTimeParam resParam = OBJECT_FACTORY.createDateTimeParam();

                    resParam.setId(reqDateTimeParam.getId());

                    resParam.setName(reqDateTimeParam.getName());

                    final GregorianCalendar proParam = (GregorianCalendar) proParams
                            .getOutputParameter(resParam.getId());

                    if (proParam != null) {
                        resParam.setContent(DatatypeConverter.printDateTime(proParam));

                        resParamElement.setValue(resParam);
                    } else {
                        resParamElement.setNil(true);
                    }

                    res.getParamElementList().add(resParamElement);
                }

            } else if (reqParam instanceof DateTimeTZArrayParam) {
                final DateTimeTZArrayParam reqDateTimeTZArrayParam = (DateTimeTZArrayParam) reqParam;

                if (ParamMode.INPUT != reqDateTimeTZArrayParam.getMode()) {
                    final JAXBElement<DateTimeTZArrayParam> resParamElement = new JAXBElement<DateTimeTZArrayParam>(
                            new QName(NS, "DateTimeTZArray"), DateTimeTZArrayParam.class, null);

                    final DateTimeTZArrayParam resParam = OBJECT_FACTORY.createDateTimeTZArrayParam();

                    resParam.setId(reqDateTimeTZArrayParam.getId());

                    resParam.setName(reqDateTimeTZArrayParam.getName());

                    final GregorianCalendar[] proParam = (GregorianCalendar[]) proParams
                            .getOutputParameter(resParam.getId());

                    if (proParam != null) {

                        for (int i = 0; i < proParam.length; i++) {
                            final JAXBElement<String> valueElement = new JAXBElement<String>(
                                    new QName(NS, "Value"), String.class, null);

                            if (proParam[i] != null)
                                valueElement.setValue(DatatypeConverter.printDateTime(proParam[i]));
                            else
                                valueElement.setNil(true);

                            resParam.getValueElementList().add(valueElement);
                        }

                        resParamElement.setValue(resParam);
                    } else {
                        resParamElement.setNil(true);
                    }

                    res.getParamElementList().add(resParamElement);
                }

            } else if (reqParam instanceof DateTimeTZParam) {
                final DateTimeTZParam reqDateTimeTZParam = (DateTimeTZParam) reqParam;

                if (ParamMode.INPUT != reqDateTimeTZParam.getMode()) {
                    final JAXBElement<DateTimeTZParam> resParamElement = new JAXBElement<DateTimeTZParam>(
                            new QName(NS, "DateTimeTZ"), DateTimeTZParam.class, null);

                    final DateTimeTZParam resParam = OBJECT_FACTORY.createDateTimeTZParam();

                    resParam.setId(reqDateTimeTZParam.getId());

                    resParam.setName(reqDateTimeTZParam.getName());

                    final GregorianCalendar proParam = (GregorianCalendar) proParams
                            .getOutputParameter(resParam.getId());

                    if (proParam != null) {
                        resParam.setContent(DatatypeConverter.printDateTime(proParam));

                        resParamElement.setValue(resParam);
                    } else {
                        resParamElement.setNil(true);
                    }

                    res.getParamElementList().add(resParamElement);
                }

            } else if (reqParam instanceof DecArrayParam) {
                final DecArrayParam reqDecArrayParam = (DecArrayParam) reqParam;

                if (ParamMode.INPUT != reqDecArrayParam.getMode()) {
                    final JAXBElement<DecArrayParam> resParamElement = new JAXBElement<DecArrayParam>(
                            new QName(NS, "DecArray"), DecArrayParam.class, null);

                    final DecArrayParam resParam = OBJECT_FACTORY.createDecArrayParam();

                    resParam.setId(reqDecArrayParam.getId());

                    resParam.setName(reqDecArrayParam.getName());

                    final BigDecimal[] proParam = (BigDecimal[]) proParams.getOutputParameter(resParam.getId());

                    if (proParam != null) {

                        for (int i = 0; i < proParam.length; i++) {
                            final JAXBElement<String> valueElement = new JAXBElement<String>(
                                    new QName(NS, "Value"), String.class, null);

                            if (proParam[i] != null)
                                valueElement.setValue(DatatypeConverter.printDecimal(proParam[i]));
                            else
                                valueElement.setNil(true);

                            resParam.getValueElementList().add(valueElement);
                        }

                        resParamElement.setValue(resParam);
                    } else {
                        resParamElement.setNil(true);
                    }

                    res.getParamElementList().add(resParamElement);
                }

            } else if (reqParam instanceof DecParam) {
                final DecParam reqDecParam = (DecParam) reqParam;

                if (ParamMode.INPUT != reqDecParam.getMode()) {
                    final JAXBElement<DecParam> resParamElement = new JAXBElement<DecParam>(
                            new QName(NS, "Dec"), DecParam.class, null);

                    final DecParam resParam = OBJECT_FACTORY.createDecParam();

                    resParam.setId(reqDecParam.getId());

                    resParam.setName(reqDecParam.getName());

                    final BigDecimal proParam = (BigDecimal) proParams.getOutputParameter(resParam.getId());

                    if (proParam != null) {
                        resParam.setContent(DatatypeConverter.printDecimal(proParam));

                        resParamElement.setValue(resParam);
                    } else {
                        resParamElement.setNil(true);
                    }

                    res.getParamElementList().add(resParamElement);
                }

            } else if (reqParam instanceof IntArrayParam) {
                final IntArrayParam reqIntArrayParam = (IntArrayParam) reqParam;

                if (ParamMode.INPUT != reqIntArrayParam.getMode()) {
                    final JAXBElement<IntArrayParam> resParamElement = new JAXBElement<IntArrayParam>(
                            new QName(NS, "IntArray"), IntArrayParam.class, null);

                    final IntArrayParam resParam = OBJECT_FACTORY.createIntArrayParam();

                    resParam.setId(reqIntArrayParam.getId());

                    resParam.setName(reqIntArrayParam.getName());

                    final Integer[] proParam = (Integer[]) proParams.getOutputParameter(resParam.getId());

                    if (proParam != null) {

                        for (int i = 0; i < proParam.length; i++) {
                            final JAXBElement<String> valueElement = new JAXBElement<String>(
                                    new QName(NS, "Value"), String.class, null);

                            if (proParam[i] != null)
                                valueElement.setValue(DatatypeConverter.printInt(proParam[i]));
                            else
                                valueElement.setNil(true);

                            resParam.getValueElementList().add(valueElement);
                        }

                        resParamElement.setValue(resParam);
                    } else {
                        resParamElement.setNil(true);
                    }

                    res.getParamElementList().add(resParamElement);
                }

            } else if (reqParam instanceof IntParam) {
                final IntParam reqIntParam = (IntParam) reqParam;

                if (ParamMode.INPUT != reqIntParam.getMode()) {
                    final JAXBElement<IntParam> resParamElement = new JAXBElement<IntParam>(
                            new QName(NS, "Int"), IntParam.class, null);

                    final IntParam resParam = OBJECT_FACTORY.createIntParam();

                    resParam.setId(reqIntParam.getId());

                    resParam.setName(reqIntParam.getName());

                    final Integer proParam = (Integer) proParams.getOutputParameter(resParam.getId());

                    if (proParam != null) {
                        resParam.setContent(DatatypeConverter.printInt(proParam));

                        resParamElement.setValue(resParam);
                    } else {
                        resParamElement.setNil(true);
                    }

                    res.getParamElementList().add(resParamElement);
                }

            } else if (reqParam instanceof LogArrayParam) {
                final LogArrayParam reqLogArrayParam = (LogArrayParam) reqParam;

                if (ParamMode.INPUT != reqLogArrayParam.getMode()) {
                    final JAXBElement<LogArrayParam> resParamElement = new JAXBElement<LogArrayParam>(
                            new QName(NS, "LogArray"), LogArrayParam.class, null);

                    final LogArrayParam resParam = OBJECT_FACTORY.createLogArrayParam();

                    resParam.setId(reqLogArrayParam.getId());

                    resParam.setName(reqLogArrayParam.getName());

                    final Boolean[] proParam = (Boolean[]) proParams.getOutputParameter(resParam.getId());

                    if (proParam != null) {

                        for (int i = 0; i < proParam.length; i++) {
                            final JAXBElement<String> valueElement = new JAXBElement<String>(
                                    new QName(NS, "Value"), String.class, null);

                            if (proParam[i] != null)
                                valueElement.setValue(DatatypeConverter.printBoolean(proParam[i]));
                            else
                                valueElement.setNil(true);

                            resParam.getValueElementList().add(valueElement);
                        }

                        resParamElement.setValue(resParam);
                    } else {
                        resParamElement.setNil(true);
                    }

                    res.getParamElementList().add(resParamElement);
                }

            } else if (reqParam instanceof LogParam) {
                final LogParam reqLogParam = (LogParam) reqParam;

                if (ParamMode.INPUT != reqLogParam.getMode()) {
                    final JAXBElement<LogParam> resParamElement = new JAXBElement<LogParam>(
                            new QName(NS, "Log"), LogParam.class, null);

                    final LogParam resParam = OBJECT_FACTORY.createLogParam();

                    resParam.setId(reqLogParam.getId());

                    resParam.setName(reqLogParam.getName());

                    final Boolean proParam = (Boolean) proParams.getOutputParameter(resParam.getId());

                    if (proParam != null) {
                        resParam.setContent(DatatypeConverter.printBoolean(proParam));

                        resParamElement.setValue(resParam);
                    } else {
                        resParamElement.setNil(true);
                    }

                    res.getParamElementList().add(resParamElement);
                }

            } else if (reqParam instanceof ResultSetParam) {
                final ResultSetParam reqResultSetParam = (ResultSetParam) reqParam;

                if (ParamMode.INPUT != reqResultSetParam.getMode()) {
                    final JAXBElement<ResultSetParam> resParamElement = new JAXBElement<ResultSetParam>(
                            new QName(NS, "ResultSet"), ResultSetParam.class, null);

                    final ResultSetParam resParam = OBJECT_FACTORY.createResultSetParam();

                    resParam.setId(reqResultSetParam.getId());

                    resParam.setName(reqResultSetParam.getName());

                    final ProResultSet proParam = (ProResultSet) proParams.getOutputParameter(resParam.getId());

                    if (proParam != null) {

                        while (proParam.next()) {
                            final Row row = OBJECT_FACTORY.createRow();

                            final ResultSetMetaData rsMetaData = reqResultSetParam.getResultSetMetaData();

                            for (final Serializable fieldMetaData : rsMetaData.getFieldMetaDataList()) {

                                if (fieldMetaData instanceof CharFieldMetaData) {
                                    final CharFieldMetaData charFieldMetaData = (CharFieldMetaData) fieldMetaData;

                                    final int extent = charFieldMetaData.getExtent();

                                    if (extent < 1) {
                                        final JAXBElement<CharField> fieldElement = new JAXBElement<CharField>(
                                                new QName(NS, "Char"), CharField.class, null);

                                        final CharField field = OBJECT_FACTORY.createCharField();

                                        field.setId(charFieldMetaData.getId());

                                        field.setName(charFieldMetaData.getName());

                                        final String value = proParam.getString(field.getId());

                                        if (value != null) {
                                            field.setContent(DatatypeConverter.printString(value));

                                            fieldElement.setValue(field);
                                        } else {
                                            fieldElement.setNil(true);
                                        }

                                        row.getFieldElementList().add(fieldElement);
                                    } else {

                                        for (int i = 1; i <= extent; i++) {
                                            final JAXBElement<CharField> fieldElement = new JAXBElement<CharField>(
                                                    new QName(NS, "Char"), CharField.class, null);

                                            final CharField field = OBJECT_FACTORY.createCharField();

                                            field.setId(charFieldMetaData.getId());

                                            field.setName(charFieldMetaData.getName());

                                            final String value = proParam.getString(field.getId(), i);

                                            if (value != null) {
                                                field.setContent(DatatypeConverter.printString(value));

                                                fieldElement.setValue(field);
                                            } else {
                                                fieldElement.setNil(true);
                                            }

                                            row.getFieldElementList().add(fieldElement);
                                        }

                                    }

                                } else if (fieldMetaData instanceof DateFieldMetaData) {
                                    final DateFieldMetaData dateFieldMetaData = (DateFieldMetaData) fieldMetaData;

                                    final int extent = dateFieldMetaData.getExtent();

                                    if (extent < 1) {
                                        final JAXBElement<DateField> fieldElement = new JAXBElement<DateField>(
                                                new QName(NS, "Date"), DateField.class, null);

                                        final DateField field = OBJECT_FACTORY.createDateField();

                                        field.setId(dateFieldMetaData.getId());

                                        field.setName(dateFieldMetaData.getName());

                                        final Date value = proParam.getDate(field.getId());

                                        if (value != null) {
                                            final Calendar cal = Calendar.getInstance();

                                            cal.setTime(value);

                                            field.setContent(DatatypeConverter.printDate(cal));

                                            fieldElement.setValue(field);
                                        } else {
                                            fieldElement.setNil(true);
                                        }

                                        row.getFieldElementList().add(fieldElement);
                                    } else {

                                        for (int i = 1; i <= extent; i++) {
                                            final JAXBElement<DateField> fieldElement = new JAXBElement<DateField>(
                                                    new QName(NS, "Date"), DateField.class, null);

                                            final DateField field = OBJECT_FACTORY.createDateField();

                                            field.setId(dateFieldMetaData.getId());

                                            field.setName(dateFieldMetaData.getName());

                                            final Date value = proParam.getDate(field.getId(), i);

                                            if (value != null) {
                                                final Calendar cal = Calendar.getInstance();

                                                cal.setTime(value);

                                                field.setContent(DatatypeConverter.printDate(cal));

                                                fieldElement.setValue(field);
                                            } else {
                                                fieldElement.setNil(true);
                                            }

                                            row.getFieldElementList().add(fieldElement);
                                        }

                                    }

                                } else if (fieldMetaData instanceof DateTimeFieldMetaData) {
                                    final DateTimeFieldMetaData dateTimeFieldMetaData = (DateTimeFieldMetaData) fieldMetaData;

                                    final int extent = dateTimeFieldMetaData.getExtent();

                                    if (extent < 1) {
                                        final JAXBElement<DateTimeField> fieldElement = new JAXBElement<DateTimeField>(
                                                new QName(NS, "DateTime"), DateTimeField.class, null);

                                        final DateTimeField field = OBJECT_FACTORY.createDateTimeField();

                                        field.setId(dateTimeFieldMetaData.getId());

                                        field.setName(dateTimeFieldMetaData.getName());

                                        final GregorianCalendar value = (GregorianCalendar) proParam
                                                .getObject(field.getId());

                                        if (value != null) {
                                            field.setContent(DatatypeConverter.printDateTime(value));

                                            fieldElement.setValue(field);
                                        } else {
                                            fieldElement.setNil(true);
                                        }

                                        row.getFieldElementList().add(fieldElement);
                                    } else {

                                        for (int i = 1; i <= extent; i++) {
                                            final JAXBElement<DateTimeField> fieldElement = new JAXBElement<DateTimeField>(
                                                    new QName(NS, "DateTime"), DateTimeField.class, null);

                                            final DateTimeField field = OBJECT_FACTORY.createDateTimeField();

                                            field.setId(dateTimeFieldMetaData.getId());

                                            field.setName(dateTimeFieldMetaData.getName());

                                            final GregorianCalendar value = (GregorianCalendar) proParam
                                                    .getObject(field.getId(), i);

                                            if (value != null) {
                                                field.setContent(DatatypeConverter.printDateTime(value));

                                                fieldElement.setValue(field);
                                            } else {
                                                fieldElement.setNil(true);
                                            }

                                            row.getFieldElementList().add(fieldElement);
                                        }

                                    }

                                } else if (fieldMetaData instanceof DateTimeTZFieldMetaData) {
                                    final DateTimeTZFieldMetaData dateTimeTZFieldMetaData = (DateTimeTZFieldMetaData) fieldMetaData;

                                    final int extent = dateTimeTZFieldMetaData.getExtent();

                                    if (extent < 1) {
                                        final JAXBElement<DateTimeTZField> fieldElement = new JAXBElement<DateTimeTZField>(
                                                new QName(NS, "DateTimeTZ"), DateTimeTZField.class, null);

                                        final DateTimeTZField field = OBJECT_FACTORY.createDateTimeTZField();

                                        field.setId(dateTimeTZFieldMetaData.getId());

                                        field.setName(dateTimeTZFieldMetaData.getName());

                                        final GregorianCalendar value = (GregorianCalendar) proParam
                                                .getObject(field.getId());

                                        if (value != null) {
                                            field.setContent(DatatypeConverter.printDateTime(value));

                                            fieldElement.setValue(field);
                                        } else {
                                            fieldElement.setNil(true);
                                        }

                                        row.getFieldElementList().add(fieldElement);
                                    } else {

                                        for (int i = 1; i <= extent; i++) {
                                            final JAXBElement<DateTimeTZField> fieldElement = new JAXBElement<DateTimeTZField>(
                                                    new QName(NS, "DateTimeTZ"), DateTimeTZField.class, null);

                                            final DateTimeTZField field = OBJECT_FACTORY
                                                    .createDateTimeTZField();

                                            field.setId(dateTimeTZFieldMetaData.getId());

                                            field.setName(dateTimeTZFieldMetaData.getName());

                                            final GregorianCalendar value = (GregorianCalendar) proParam
                                                    .getObject(field.getId(), i);

                                            if (value != null) {
                                                field.setContent(DatatypeConverter.printDateTime(value));

                                                fieldElement.setValue(field);
                                            } else {
                                                fieldElement.setNil(true);
                                            }

                                            row.getFieldElementList().add(fieldElement);
                                        }

                                    }

                                } else if (fieldMetaData instanceof DecFieldMetaData) {
                                    final DecFieldMetaData decFieldMetaData = (DecFieldMetaData) fieldMetaData;

                                    final int extent = decFieldMetaData.getExtent();

                                    if (extent < 1) {
                                        final JAXBElement<DecField> fieldElement = new JAXBElement<DecField>(
                                                new QName(NS, "Dec"), DecField.class, null);

                                        final DecField field = OBJECT_FACTORY.createDecField();

                                        field.setId(decFieldMetaData.getId());

                                        field.setName(decFieldMetaData.getName());

                                        final BigDecimal value = proParam.getBigDecimal(field.getId());

                                        if (value != null) {
                                            field.setContent(DatatypeConverter.printDecimal(value));

                                            fieldElement.setValue(field);
                                        } else {
                                            fieldElement.setNil(true);
                                        }

                                        row.getFieldElementList().add(fieldElement);
                                    } else {

                                        for (int i = 1; i <= extent; i++) {
                                            final JAXBElement<DecField> fieldElement = new JAXBElement<DecField>(
                                                    new QName(NS, "Dec"), DecField.class, null);

                                            final DecField field = OBJECT_FACTORY.createDecField();

                                            field.setId(decFieldMetaData.getId());

                                            field.setName(decFieldMetaData.getName());

                                            final BigDecimal value = proParam.getBigDecimal(field.getId(), i,
                                                    0);

                                            if (value != null) {
                                                field.setContent(DatatypeConverter.printDecimal(value));

                                                fieldElement.setValue(field);
                                            } else {
                                                fieldElement.setNil(true);
                                            }

                                            row.getFieldElementList().add(fieldElement);
                                        }

                                    }

                                } else if (fieldMetaData instanceof IntFieldMetaData) {
                                    final IntFieldMetaData intFieldMetaData = (IntFieldMetaData) fieldMetaData;

                                    final int extent = intFieldMetaData.getExtent();

                                    if (extent < 1) {
                                        final JAXBElement<IntField> fieldElement = new JAXBElement<IntField>(
                                                new QName(NS, "Int"), IntField.class, null);

                                        final IntField field = OBJECT_FACTORY.createIntField();

                                        field.setId(intFieldMetaData.getId());

                                        field.setName(intFieldMetaData.getName());

                                        final String value = proParam.getString(field.getId());

                                        if (value != null) {
                                            field.setContent(
                                                    DatatypeConverter.printInt(Integer.parseInt(value)));

                                            fieldElement.setValue(field);
                                        } else {
                                            fieldElement.setNil(true);
                                        }

                                        row.getFieldElementList().add(fieldElement);
                                    } else {

                                        for (int i = 1; i <= extent; i++) {
                                            final JAXBElement<IntField> fieldElement = new JAXBElement<IntField>(
                                                    new QName(NS, "Int"), IntField.class, null);

                                            final IntField field = OBJECT_FACTORY.createIntField();

                                            field.setId(intFieldMetaData.getId());

                                            field.setName(intFieldMetaData.getName());

                                            final String value = proParam.getString(field.getId(), i);

                                            if (value != null) {
                                                field.setContent(
                                                        DatatypeConverter.printInt(Integer.parseInt(value)));

                                                fieldElement.setValue(field);
                                            } else {
                                                fieldElement.setNil(true);
                                            }

                                            row.getFieldElementList().add(fieldElement);
                                        }

                                    }

                                } else if (fieldMetaData instanceof LogFieldMetaData) {
                                    final LogFieldMetaData logFieldMetaData = (LogFieldMetaData) fieldMetaData;

                                    final int extent = logFieldMetaData.getExtent();

                                    if (extent < 1) {
                                        final JAXBElement<LogField> fieldElement = new JAXBElement<LogField>(
                                                new QName(NS, "Log"), LogField.class, null);

                                        final LogField field = OBJECT_FACTORY.createLogField();

                                        field.setId(logFieldMetaData.getId());

                                        field.setName(logFieldMetaData.getName());

                                        final String value = proParam.getString(field.getId());

                                        if (value != null) {
                                            field.setContent(
                                                    DatatypeConverter.printBoolean(Boolean.valueOf(value)));

                                            fieldElement.setValue(field);
                                        } else {
                                            fieldElement.setNil(true);
                                        }

                                        row.getFieldElementList().add(fieldElement);
                                    } else {

                                        for (int i = 1; i <= extent; i++) {
                                            final JAXBElement<LogField> fieldElement = new JAXBElement<LogField>(
                                                    new QName(NS, "Log"), LogField.class, null);

                                            final LogField field = OBJECT_FACTORY.createLogField();

                                            field.setId(logFieldMetaData.getId());

                                            field.setName(logFieldMetaData.getName());

                                            final String value = proParam.getString(field.getId(), i);

                                            if (value != null) {
                                                field.setContent(
                                                        DatatypeConverter.printBoolean(Boolean.valueOf(value)));

                                                fieldElement.setValue(field);
                                            } else {
                                                fieldElement.setNil(true);
                                            }

                                            row.getFieldElementList().add(fieldElement);
                                        }

                                    }

                                }

                            }

                            resParam.getRowList().add(row);
                        }

                        resParamElement.setValue(resParam);
                    } else {
                        resParamElement.setNil(true);
                    }

                    res.getParamElementList().add(resParamElement);
                }

            }

        }

        final Document doc = builder.newDocument();

        marshaller.marshal(res, doc);

        exchange.getOut().setBody(doc);
    } catch (final RunTime4GLErrorException e) {
        LOG.error(e.getProcReturnString(), e);

        throw new OpenEdgeException(e.getProcReturnString(), e);
    }

}

From source file:com.microsoft.azure.management.network.RouteOperationsImpl.java

/**
* The Put route operation creates/updates a route in the specified route
* table//from  ww w. jav  a  2 s .  co  m
*
* @param resourceGroupName Required. The name of the resource group.
* @param routeTableName Required. The name of the route table.
* @param routeName Required. The name of the route.
* @param routeParameters Required. Parameters supplied to the create/update
* routeoperation
* @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 Response for PUT Routes Api servive call
*/
@Override
public RoutePutResponse beginCreateOrUpdating(String resourceGroupName, String routeTableName, String routeName,
        Route routeParameters) throws IOException, ServiceException {
    // Validate
    if (resourceGroupName == null) {
        throw new NullPointerException("resourceGroupName");
    }
    if (routeTableName == null) {
        throw new NullPointerException("routeTableName");
    }
    if (routeName == null) {
        throw new NullPointerException("routeName");
    }
    if (routeParameters == null) {
        throw new NullPointerException("routeParameters");
    }
    if (routeParameters.getNextHopType() == null) {
        throw new NullPointerException("routeParameters.NextHopType");
    }

    // 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("resourceGroupName", resourceGroupName);
        tracingParameters.put("routeTableName", routeTableName);
        tracingParameters.put("routeName", routeName);
        tracingParameters.put("routeParameters", routeParameters);
        CloudTracing.enter(invocationId, this, "beginCreateOrUpdatingAsync", tracingParameters);
    }

    // Construct URL
    String url = "";
    url = url + "/subscriptions/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/resourceGroups/";
    url = url + URLEncoder.encode(resourceGroupName, "UTF-8");
    url = url + "/providers/";
    url = url + "Microsoft.Network";
    url = url + "/routeTables/";
    url = url + URLEncoder.encode(routeTableName, "UTF-8");
    url = url + "/routes/";
    url = url + URLEncoder.encode(routeName, "UTF-8");
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("api-version=" + "2015-05-01-preview");
    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/json");

    // Serialize Request
    String requestContent = null;
    JsonNode requestDoc = null;

    ObjectMapper objectMapper = new ObjectMapper();
    ObjectNode routeJsonFormatValue = objectMapper.createObjectNode();
    requestDoc = routeJsonFormatValue;

    ObjectNode propertiesValue = objectMapper.createObjectNode();
    ((ObjectNode) routeJsonFormatValue).put("properties", propertiesValue);

    if (routeParameters.getAddressPrefix() != null) {
        ((ObjectNode) propertiesValue).put("addressPrefix", routeParameters.getAddressPrefix());
    }

    ((ObjectNode) propertiesValue).put("nextHopType", routeParameters.getNextHopType());

    if (routeParameters.getNextHopIpAddress() != null) {
        ((ObjectNode) propertiesValue).put("nextHopIpAddress", routeParameters.getNextHopIpAddress());
    }

    if (routeParameters.getProvisioningState() != null) {
        ((ObjectNode) propertiesValue).put("provisioningState", routeParameters.getProvisioningState());
    }

    if (routeParameters.getName() != null) {
        ((ObjectNode) routeJsonFormatValue).put("name", routeParameters.getName());
    }

    if (routeParameters.getEtag() != null) {
        ((ObjectNode) routeJsonFormatValue).put("etag", routeParameters.getEtag());
    }

    if (routeParameters.getId() != null) {
        ((ObjectNode) routeJsonFormatValue).put("id", routeParameters.getId());
    }

    StringWriter stringWriter = new StringWriter();
    objectMapper.writeValue(stringWriter, requestDoc);
    requestContent = stringWriter.toString();
    StringEntity entity = new StringEntity(requestContent);
    httpRequest.setEntity(entity);
    httpRequest.setHeader("Content-Type", "application/json");

    // 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 && statusCode != HttpStatus.SC_CREATED) {
            ServiceException ex = ServiceException.createFromJson(httpRequest, requestContent, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

        // Create Result
        RoutePutResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new RoutePutResponse();
            JsonNode responseDoc = null;
            String responseDocContent = IOUtils.toString(responseContent);
            if (responseDocContent == null == false && responseDocContent.length() > 0) {
                responseDoc = objectMapper.readTree(responseDocContent);
            }

            if (responseDoc != null && responseDoc instanceof NullNode == false) {
                Route routeInstance = new Route();
                result.setRoute(routeInstance);

                JsonNode propertiesValue2 = responseDoc.get("properties");
                if (propertiesValue2 != null && propertiesValue2 instanceof NullNode == false) {
                    JsonNode addressPrefixValue = propertiesValue2.get("addressPrefix");
                    if (addressPrefixValue != null && addressPrefixValue instanceof NullNode == false) {
                        String addressPrefixInstance;
                        addressPrefixInstance = addressPrefixValue.getTextValue();
                        routeInstance.setAddressPrefix(addressPrefixInstance);
                    }

                    JsonNode nextHopTypeValue = propertiesValue2.get("nextHopType");
                    if (nextHopTypeValue != null && nextHopTypeValue instanceof NullNode == false) {
                        String nextHopTypeInstance;
                        nextHopTypeInstance = nextHopTypeValue.getTextValue();
                        routeInstance.setNextHopType(nextHopTypeInstance);
                    }

                    JsonNode nextHopIpAddressValue = propertiesValue2.get("nextHopIpAddress");
                    if (nextHopIpAddressValue != null && nextHopIpAddressValue instanceof NullNode == false) {
                        String nextHopIpAddressInstance;
                        nextHopIpAddressInstance = nextHopIpAddressValue.getTextValue();
                        routeInstance.setNextHopIpAddress(nextHopIpAddressInstance);
                    }

                    JsonNode provisioningStateValue = propertiesValue2.get("provisioningState");
                    if (provisioningStateValue != null && provisioningStateValue instanceof NullNode == false) {
                        String provisioningStateInstance;
                        provisioningStateInstance = provisioningStateValue.getTextValue();
                        routeInstance.setProvisioningState(provisioningStateInstance);
                    }
                }

                JsonNode nameValue = responseDoc.get("name");
                if (nameValue != null && nameValue instanceof NullNode == false) {
                    String nameInstance;
                    nameInstance = nameValue.getTextValue();
                    routeInstance.setName(nameInstance);
                }

                JsonNode etagValue = responseDoc.get("etag");
                if (etagValue != null && etagValue instanceof NullNode == false) {
                    String etagInstance;
                    etagInstance = etagValue.getTextValue();
                    routeInstance.setEtag(etagInstance);
                }

                JsonNode idValue = responseDoc.get("id");
                if (idValue != null && idValue instanceof NullNode == false) {
                    String idInstance;
                    idInstance = idValue.getTextValue();
                    routeInstance.setId(idInstance);
                }

                JsonNode errorValue = responseDoc.get("error");
                if (errorValue != null && errorValue instanceof NullNode == false) {
                    Error errorInstance = new Error();
                    result.setError(errorInstance);

                    JsonNode codeValue = errorValue.get("code");
                    if (codeValue != null && codeValue instanceof NullNode == false) {
                        String codeInstance;
                        codeInstance = codeValue.getTextValue();
                        errorInstance.setCode(codeInstance);
                    }

                    JsonNode messageValue = errorValue.get("message");
                    if (messageValue != null && messageValue instanceof NullNode == false) {
                        String messageInstance;
                        messageInstance = messageValue.getTextValue();
                        errorInstance.setMessage(messageInstance);
                    }

                    JsonNode targetValue = errorValue.get("target");
                    if (targetValue != null && targetValue instanceof NullNode == false) {
                        String targetInstance;
                        targetInstance = targetValue.getTextValue();
                        errorInstance.setTarget(targetInstance);
                    }

                    JsonNode detailsArray = errorValue.get("details");
                    if (detailsArray != null && detailsArray instanceof NullNode == false) {
                        for (JsonNode detailsValue : ((ArrayNode) detailsArray)) {
                            ErrorDetails errorDetailsInstance = new ErrorDetails();
                            errorInstance.getDetails().add(errorDetailsInstance);

                            JsonNode codeValue2 = detailsValue.get("code");
                            if (codeValue2 != null && codeValue2 instanceof NullNode == false) {
                                String codeInstance2;
                                codeInstance2 = codeValue2.getTextValue();
                                errorDetailsInstance.setCode(codeInstance2);
                            }

                            JsonNode targetValue2 = detailsValue.get("target");
                            if (targetValue2 != null && targetValue2 instanceof NullNode == false) {
                                String targetInstance2;
                                targetInstance2 = targetValue2.getTextValue();
                                errorDetailsInstance.setTarget(targetInstance2);
                            }

                            JsonNode messageValue2 = detailsValue.get("message");
                            if (messageValue2 != null && messageValue2 instanceof NullNode == false) {
                                String messageInstance2;
                                messageInstance2 = messageValue2.getTextValue();
                                errorDetailsInstance.setMessage(messageInstance2);
                            }
                        }
                    }

                    JsonNode innerErrorValue = errorValue.get("innerError");
                    if (innerErrorValue != null && innerErrorValue instanceof NullNode == false) {
                        String innerErrorInstance;
                        innerErrorInstance = innerErrorValue.getTextValue();
                        errorInstance.setInnerError(innerErrorInstance);
                    }
                }
            }

        }
        result.setStatusCode(statusCode);
        if (httpResponse.getHeaders("Azure-AsyncOperation").length > 0) {
            result.setAzureAsyncOperation(httpResponse.getFirstHeader("Azure-AsyncOperation").getValue());
        }
        if (httpResponse.getHeaders("Retry-After").length > 0) {
            result.setRetryAfter(
                    DatatypeConverter.parseInt(httpResponse.getFirstHeader("Retry-After").getValue()));
        }
        if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
            result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
        }

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

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

/**
* The List OS Families operation lists the guest operating system families
* available in Azure, and also lists the operating system versions
* available for each family. Currently Azure supports two operating system
* families: the Azure guest operating system that is substantially
* compatible with Windows Server 2008 SP2, and the Azure guest operating
* system that is substantially compatible with Windows Server 2008 R2.
* (see http://msdn.microsoft.com/en-us/library/windowsazure/gg441291.aspx
* for more information)/*from   ww w.j a  v  a 2  s . c o  m*/
*
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @throws ParserConfigurationException Thrown if there was a serious
* configuration error with the document parser.
* @throws SAXException Thrown if there was an error parsing the XML
* response.
* @return The List Operating System Families operation response.
*/
@Override
public OperatingSystemListFamiliesResponse listFamilies()
        throws IOException, ServiceException, ParserConfigurationException, SAXException {
    // Validate

    // Tracing
    boolean shouldTrace = CloudTracing.getIsEnabled();
    String invocationId = null;
    if (shouldTrace) {
        invocationId = Long.toString(CloudTracing.getNextInvocationId());
        HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
        CloudTracing.enter(invocationId, this, "listFamiliesAsync", 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 + "/operatingsystemfamilies";
    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
    HttpGet httpRequest = new HttpGet(url);

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

    // 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, null, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

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

            Element operatingSystemFamiliesSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "OperatingSystemFamilies");
            if (operatingSystemFamiliesSequenceElement != null) {
                for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                        .getElementsByTagNameNS(operatingSystemFamiliesSequenceElement,
                                "http://schemas.microsoft.com/windowsazure", "OperatingSystemFamily")
                        .size(); i1 = i1 + 1) {
                    org.w3c.dom.Element operatingSystemFamiliesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(operatingSystemFamiliesSequenceElement,
                                    "http://schemas.microsoft.com/windowsazure", "OperatingSystemFamily")
                            .get(i1));
                    OperatingSystemListFamiliesResponse.OperatingSystemFamily operatingSystemFamilyInstance = new OperatingSystemListFamiliesResponse.OperatingSystemFamily();
                    result.getOperatingSystemFamilies().add(operatingSystemFamilyInstance);

                    Element nameElement = XmlUtility.getElementByTagNameNS(operatingSystemFamiliesElement,
                            "http://schemas.microsoft.com/windowsazure", "Name");
                    if (nameElement != null) {
                        int nameInstance;
                        nameInstance = DatatypeConverter.parseInt(nameElement.getTextContent());
                        operatingSystemFamilyInstance.setName(nameInstance);
                    }

                    Element labelElement = XmlUtility.getElementByTagNameNS(operatingSystemFamiliesElement,
                            "http://schemas.microsoft.com/windowsazure", "Label");
                    if (labelElement != null) {
                        String labelInstance;
                        labelInstance = labelElement.getTextContent() != null
                                ? new String(Base64.decode(labelElement.getTextContent()))
                                : null;
                        operatingSystemFamilyInstance.setLabel(labelInstance);
                    }

                    Element operatingSystemsSequenceElement = XmlUtility.getElementByTagNameNS(
                            operatingSystemFamiliesElement, "http://schemas.microsoft.com/windowsazure",
                            "OperatingSystems");
                    if (operatingSystemsSequenceElement != null) {
                        for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(operatingSystemsSequenceElement,
                                        "http://schemas.microsoft.com/windowsazure", "OperatingSystem")
                                .size(); i2 = i2 + 1) {
                            org.w3c.dom.Element operatingSystemsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(operatingSystemsSequenceElement,
                                            "http://schemas.microsoft.com/windowsazure", "OperatingSystem")
                                    .get(i2));
                            OperatingSystemListFamiliesResponse.OperatingSystem operatingSystemInstance = new OperatingSystemListFamiliesResponse.OperatingSystem();
                            operatingSystemFamilyInstance.getOperatingSystems().add(operatingSystemInstance);

                            Element versionElement = XmlUtility.getElementByTagNameNS(operatingSystemsElement,
                                    "http://schemas.microsoft.com/windowsazure", "Version");
                            if (versionElement != null) {
                                String versionInstance;
                                versionInstance = versionElement.getTextContent();
                                operatingSystemInstance.setVersion(versionInstance);
                            }

                            Element labelElement2 = XmlUtility.getElementByTagNameNS(operatingSystemsElement,
                                    "http://schemas.microsoft.com/windowsazure", "Label");
                            if (labelElement2 != null) {
                                String labelInstance2;
                                labelInstance2 = labelElement2.getTextContent() != null
                                        ? new String(Base64.decode(labelElement2.getTextContent()))
                                        : null;
                                operatingSystemInstance.setLabel(labelInstance2);
                            }

                            Element isDefaultElement = XmlUtility.getElementByTagNameNS(operatingSystemsElement,
                                    "http://schemas.microsoft.com/windowsazure", "IsDefault");
                            if (isDefaultElement != null) {
                                boolean isDefaultInstance;
                                isDefaultInstance = DatatypeConverter
                                        .parseBoolean(isDefaultElement.getTextContent().toLowerCase());
                                operatingSystemInstance.setIsDefault(isDefaultInstance);
                            }

                            Element isActiveElement = XmlUtility.getElementByTagNameNS(operatingSystemsElement,
                                    "http://schemas.microsoft.com/windowsazure", "IsActive");
                            if (isActiveElement != null) {
                                boolean isActiveInstance;
                                isActiveInstance = DatatypeConverter
                                        .parseBoolean(isActiveElement.getTextContent().toLowerCase());
                                operatingSystemInstance.setIsActive(isActiveInstance);
                            }
                        }
                    }
                }
            }

        }
        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.azure.management.sql.ServerAdministratorOperationsImpl.java

/**
* Begins creating a new Azure SQL Server Active Directory Administrator or
* updating an existing Azure SQL Server Active Directory Administrator. To
* determine the status of the operation call
* GetServerAdministratorOperationStatus.
*
* @param resourceGroupName Required. The name of the Resource Group to
* which the server belongs.//from w w  w  .  j av  a  2s.c o m
* @param serverName Required. The name of the Azure SQL Server to which the
* Azure SQL Server Active Directory administrator belongs
* @param administratorName Required. The name of the Azure SQL Server
* Active Directory Administrator.
* @param parameters Required. The required parameters for createing or
* updating an Active Directory Administrator.
* @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 Response for long running Azure SQL Server Active Directory
* Administrator operations.
*/
@Override
public ServerAdministratorCreateOrUpdateResponse beginCreateOrUpdate(String resourceGroupName,
        String serverName, String administratorName, ServerAdministratorCreateOrUpdateParameters parameters)
        throws IOException, ServiceException {
    // Validate
    if (resourceGroupName == null) {
        throw new NullPointerException("resourceGroupName");
    }
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }
    if (administratorName == null) {
        throw new NullPointerException("administratorName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getProperties() == null) {
        throw new NullPointerException("parameters.Properties");
    }
    if (parameters.getProperties().getAdministratorType() == null) {
        throw new NullPointerException("parameters.Properties.AdministratorType");
    }
    if (parameters.getProperties().getLogin() == null) {
        throw new NullPointerException("parameters.Properties.Login");
    }
    if (parameters.getProperties().getSid() == null) {
        throw new NullPointerException("parameters.Properties.Sid");
    }
    if (parameters.getProperties().getTenantId() == null) {
        throw new NullPointerException("parameters.Properties.TenantId");
    }

    // 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("resourceGroupName", resourceGroupName);
        tracingParameters.put("serverName", serverName);
        tracingParameters.put("administratorName", administratorName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "beginCreateOrUpdateAsync", tracingParameters);
    }

    // Construct URL
    String url = "";
    url = url + "/subscriptions/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/resourceGroups/";
    url = url + URLEncoder.encode(resourceGroupName, "UTF-8");
    url = url + "/providers/";
    url = url + "Microsoft.Sql";
    url = url + "/servers/";
    url = url + URLEncoder.encode(serverName, "UTF-8");
    url = url + "/administrators/";
    url = url + URLEncoder.encode(administratorName, "UTF-8");
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("api-version=" + "2014-04-01");
    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/json; charset=utf-8");

    // Serialize Request
    String requestContent = null;
    JsonNode requestDoc = null;

    ObjectMapper objectMapper = new ObjectMapper();
    ObjectNode serverAdministratorCreateOrUpdateParametersValue = objectMapper.createObjectNode();
    requestDoc = serverAdministratorCreateOrUpdateParametersValue;

    ObjectNode propertiesValue = objectMapper.createObjectNode();
    ((ObjectNode) serverAdministratorCreateOrUpdateParametersValue).put("properties", propertiesValue);

    ((ObjectNode) propertiesValue).put("login", parameters.getProperties().getLogin());

    ((ObjectNode) propertiesValue).put("sid", parameters.getProperties().getSid());

    ((ObjectNode) propertiesValue).put("administratorType", parameters.getProperties().getAdministratorType());

    ((ObjectNode) propertiesValue).put("tenantId", parameters.getProperties().getTenantId());

    StringWriter stringWriter = new StringWriter();
    objectMapper.writeValue(stringWriter, requestDoc);
    requestContent = stringWriter.toString();
    StringEntity entity = new StringEntity(requestContent);
    httpRequest.setEntity(entity);
    httpRequest.setHeader("Content-Type", "application/json; charset=utf-8");

    // 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 && statusCode != HttpStatus.SC_CREATED
                && statusCode != HttpStatus.SC_ACCEPTED) {
            ServiceException ex = ServiceException.createFromJson(httpRequest, requestContent, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

        // Create Result
        ServerAdministratorCreateOrUpdateResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED
                || statusCode == HttpStatus.SC_ACCEPTED) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new ServerAdministratorCreateOrUpdateResponse();
            JsonNode responseDoc = null;
            String responseDocContent = IOUtils.toString(responseContent);
            if (responseDocContent == null == false && responseDocContent.length() > 0) {
                responseDoc = objectMapper.readTree(responseDocContent);
            }

            if (responseDoc != null && responseDoc instanceof NullNode == false) {
                ErrorResponse errorInstance = new ErrorResponse();
                result.setError(errorInstance);

                JsonNode codeValue = responseDoc.get("code");
                if (codeValue != null && codeValue instanceof NullNode == false) {
                    String codeInstance;
                    codeInstance = codeValue.getTextValue();
                    errorInstance.setCode(codeInstance);
                }

                JsonNode messageValue = responseDoc.get("message");
                if (messageValue != null && messageValue instanceof NullNode == false) {
                    String messageInstance;
                    messageInstance = messageValue.getTextValue();
                    errorInstance.setMessage(messageInstance);
                }

                JsonNode targetValue = responseDoc.get("target");
                if (targetValue != null && targetValue instanceof NullNode == false) {
                    String targetInstance;
                    targetInstance = targetValue.getTextValue();
                    errorInstance.setTarget(targetInstance);
                }

                ServerAdministrator serverAdministratorInstance = new ServerAdministrator();
                result.setServerAdministrator(serverAdministratorInstance);

                JsonNode propertiesValue2 = responseDoc.get("properties");
                if (propertiesValue2 != null && propertiesValue2 instanceof NullNode == false) {
                    ServerAdministratorProperties propertiesInstance = new ServerAdministratorProperties();
                    serverAdministratorInstance.setProperties(propertiesInstance);

                    JsonNode administratorTypeValue = propertiesValue2.get("administratorType");
                    if (administratorTypeValue != null && administratorTypeValue instanceof NullNode == false) {
                        String administratorTypeInstance;
                        administratorTypeInstance = administratorTypeValue.getTextValue();
                        propertiesInstance.setAdministratorType(administratorTypeInstance);
                    }

                    JsonNode loginValue = propertiesValue2.get("login");
                    if (loginValue != null && loginValue instanceof NullNode == false) {
                        String loginInstance;
                        loginInstance = loginValue.getTextValue();
                        propertiesInstance.setLogin(loginInstance);
                    }

                    JsonNode sidValue = propertiesValue2.get("sid");
                    if (sidValue != null && sidValue instanceof NullNode == false) {
                        String sidInstance;
                        sidInstance = sidValue.getTextValue();
                        propertiesInstance.setSid(sidInstance);
                    }

                    JsonNode tenantIdValue = propertiesValue2.get("tenantId");
                    if (tenantIdValue != null && tenantIdValue instanceof NullNode == false) {
                        String tenantIdInstance;
                        tenantIdInstance = tenantIdValue.getTextValue();
                        propertiesInstance.setTenantId(tenantIdInstance);
                    }
                }

                JsonNode idValue = responseDoc.get("id");
                if (idValue != null && idValue instanceof NullNode == false) {
                    String idInstance;
                    idInstance = idValue.getTextValue();
                    serverAdministratorInstance.setId(idInstance);
                }

                JsonNode nameValue = responseDoc.get("name");
                if (nameValue != null && nameValue instanceof NullNode == false) {
                    String nameInstance;
                    nameInstance = nameValue.getTextValue();
                    serverAdministratorInstance.setName(nameInstance);
                }

                JsonNode typeValue = responseDoc.get("type");
                if (typeValue != null && typeValue instanceof NullNode == false) {
                    String typeInstance;
                    typeInstance = typeValue.getTextValue();
                    serverAdministratorInstance.setType(typeInstance);
                }

                JsonNode locationValue = responseDoc.get("location");
                if (locationValue != null && locationValue instanceof NullNode == false) {
                    String locationInstance;
                    locationInstance = locationValue.getTextValue();
                    serverAdministratorInstance.setLocation(locationInstance);
                }

                JsonNode tagsSequenceElement = ((JsonNode) responseDoc.get("tags"));
                if (tagsSequenceElement != null && tagsSequenceElement instanceof NullNode == false) {
                    Iterator<Map.Entry<String, JsonNode>> itr = tagsSequenceElement.getFields();
                    while (itr.hasNext()) {
                        Map.Entry<String, JsonNode> property = itr.next();
                        String tagsKey = property.getKey();
                        String tagsValue = property.getValue().getTextValue();
                        serverAdministratorInstance.getTags().put(tagsKey, tagsValue);
                    }
                }
            }

        }
        result.setStatusCode(statusCode);
        if (httpResponse.getHeaders("Location").length > 0) {
            result.setOperationStatusLink(httpResponse.getFirstHeader("Location").getValue());
        }
        if (httpResponse.getHeaders("Retry-After").length > 0) {
            result.setRetryAfter(
                    DatatypeConverter.parseInt(httpResponse.getFirstHeader("Retry-After").getValue()));
        }
        if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
            result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
        }
        if (statusCode == HttpStatus.SC_CREATED) {
            result.setStatus(OperationStatus.Succeeded);
        }
        if (statusCode == HttpStatus.SC_OK) {
            result.setStatus(OperationStatus.Succeeded);
        }

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

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

/**
* You can retrieve details for a specified web space name by issuing an
* HTTP GET request.  (see/*from  w w  w  . j a v  a2s  .c om*/
* http://msdn.microsoft.com/en-us/library/windowsazure/dn167017.aspx for
* more information)
*
* @param webSpaceName Required. The name of the web space.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @throws ParserConfigurationException Thrown if there was a serious
* configuration error with the document parser.
* @throws SAXException Thrown if there was an error parsing the XML
* response.
* @throws URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return The Get Web Space Details operation response.
*/
@Override
public WebSpacesGetResponse get(String webSpaceName)
        throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException {
    // Validate
    if (webSpaceName == null) {
        throw new NullPointerException("webSpaceName");
    }

    // Tracing
    boolean shouldTrace = CloudTracing.getIsEnabled();
    String invocationId = null;
    if (shouldTrace) {
        invocationId = Long.toString(CloudTracing.getNextInvocationId());
        HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
        tracingParameters.put("webSpaceName", webSpaceName);
        CloudTracing.enter(invocationId, this, "getAsync", tracingParameters);
    }

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/services/WebSpaces/";
    url = url + URLEncoder.encode(webSpaceName, "UTF-8");
    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
    HttpGet httpRequest = new HttpGet(url);

    // Set Headers
    httpRequest.setHeader("x-ms-version", "2014-04-01");

    // 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, null, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

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

            Element webSpaceElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "WebSpace");
            if (webSpaceElement != null) {
                Element availabilityStateElement = XmlUtility.getElementByTagNameNS(webSpaceElement,
                        "http://schemas.microsoft.com/windowsazure", "AvailabilityState");
                if (availabilityStateElement != null && availabilityStateElement.getTextContent() != null
                        && !availabilityStateElement.getTextContent().isEmpty()) {
                    WebSpaceAvailabilityState availabilityStateInstance;
                    availabilityStateInstance = WebSpaceAvailabilityState
                            .valueOf(availabilityStateElement.getTextContent());
                    result.setAvailabilityState(availabilityStateInstance);
                }

                Element currentNumberOfWorkersElement = XmlUtility.getElementByTagNameNS(webSpaceElement,
                        "http://schemas.microsoft.com/windowsazure", "CurrentNumberOfWorkers");
                if (currentNumberOfWorkersElement != null
                        && currentNumberOfWorkersElement.getTextContent() != null
                        && !currentNumberOfWorkersElement.getTextContent().isEmpty()) {
                    boolean isNil = false;
                    Attr nilAttribute = currentNumberOfWorkersElement
                            .getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil");
                    if (nilAttribute != null) {
                        isNil = "true".equals(nilAttribute.getValue());
                    }
                    if (isNil == false) {
                        int currentNumberOfWorkersInstance;
                        currentNumberOfWorkersInstance = DatatypeConverter
                                .parseInt(currentNumberOfWorkersElement.getTextContent());
                        result.setCurrentNumberOfWorkers(currentNumberOfWorkersInstance);
                    }
                }

                Element currentWorkerSizeElement = XmlUtility.getElementByTagNameNS(webSpaceElement,
                        "http://schemas.microsoft.com/windowsazure", "CurrentWorkerSize");
                if (currentWorkerSizeElement != null && currentWorkerSizeElement.getTextContent() != null
                        && !currentWorkerSizeElement.getTextContent().isEmpty()) {
                    boolean isNil2 = false;
                    Attr nilAttribute2 = currentWorkerSizeElement
                            .getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil");
                    if (nilAttribute2 != null) {
                        isNil2 = "true".equals(nilAttribute2.getValue());
                    }
                    if (isNil2 == false) {
                        WorkerSizeOptions currentWorkerSizeInstance;
                        currentWorkerSizeInstance = WorkerSizeOptions
                                .valueOf(currentWorkerSizeElement.getTextContent());
                        result.setCurrentWorkerSize(currentWorkerSizeInstance);
                    }
                }

                Element geoLocationElement = XmlUtility.getElementByTagNameNS(webSpaceElement,
                        "http://schemas.microsoft.com/windowsazure", "GeoLocation");
                if (geoLocationElement != null) {
                    String geoLocationInstance;
                    geoLocationInstance = geoLocationElement.getTextContent();
                    result.setGeoLocation(geoLocationInstance);
                }

                Element geoRegionElement = XmlUtility.getElementByTagNameNS(webSpaceElement,
                        "http://schemas.microsoft.com/windowsazure", "GeoRegion");
                if (geoRegionElement != null) {
                    String geoRegionInstance;
                    geoRegionInstance = geoRegionElement.getTextContent();
                    result.setGeoRegion(geoRegionInstance);
                }

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

                Element planElement = XmlUtility.getElementByTagNameNS(webSpaceElement,
                        "http://schemas.microsoft.com/windowsazure", "Plan");
                if (planElement != null) {
                    String planInstance;
                    planInstance = planElement.getTextContent();
                    result.setPlan(planInstance);
                }

                Element statusElement = XmlUtility.getElementByTagNameNS(webSpaceElement,
                        "http://schemas.microsoft.com/windowsazure", "Status");
                if (statusElement != null && statusElement.getTextContent() != null
                        && !statusElement.getTextContent().isEmpty()) {
                    WebSpaceStatus statusInstance;
                    statusInstance = WebSpaceStatus.valueOf(statusElement.getTextContent());
                    result.setStatus(statusInstance);
                }

                Element subscriptionElement = XmlUtility.getElementByTagNameNS(webSpaceElement,
                        "http://schemas.microsoft.com/windowsazure", "Subscription");
                if (subscriptionElement != null) {
                    String subscriptionInstance;
                    subscriptionInstance = subscriptionElement.getTextContent();
                    result.setSubscription(subscriptionInstance);
                }

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

        }
        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.azure.management.network.SubnetOperationsImpl.java

/**
* The Put Subnet operation creates/updates a subnet in thespecified virtual
* network/*  w w  w  .  j ava2  s  .c o m*/
*
* @param resourceGroupName Required. The name of the resource group.
* @param virtualNetworkName Required. The name of the virtual network.
* @param subnetName Required. The name of the subnet.
* @param subnetParameters Required. Parameters supplied to the
* create/update Subnet operation
* @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 Response for PutSubnet Api service call
*/
@Override
public SubnetPutResponse beginCreateOrUpdating(String resourceGroupName, String virtualNetworkName,
        String subnetName, Subnet subnetParameters) throws IOException, ServiceException {
    // Validate
    if (resourceGroupName == null) {
        throw new NullPointerException("resourceGroupName");
    }
    if (virtualNetworkName == null) {
        throw new NullPointerException("virtualNetworkName");
    }
    if (subnetName == null) {
        throw new NullPointerException("subnetName");
    }
    if (subnetParameters == null) {
        throw new NullPointerException("subnetParameters");
    }
    if (subnetParameters.getAddressPrefix() == null) {
        throw new NullPointerException("subnetParameters.AddressPrefix");
    }

    // 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("resourceGroupName", resourceGroupName);
        tracingParameters.put("virtualNetworkName", virtualNetworkName);
        tracingParameters.put("subnetName", subnetName);
        tracingParameters.put("subnetParameters", subnetParameters);
        CloudTracing.enter(invocationId, this, "beginCreateOrUpdatingAsync", tracingParameters);
    }

    // Construct URL
    String url = "";
    url = url + "/subscriptions/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/resourceGroups/";
    url = url + URLEncoder.encode(resourceGroupName, "UTF-8");
    url = url + "/providers/";
    url = url + "Microsoft.Network";
    url = url + "/virtualnetworks/";
    url = url + URLEncoder.encode(virtualNetworkName, "UTF-8");
    url = url + "/subnets/";
    url = url + URLEncoder.encode(subnetName, "UTF-8");
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("api-version=" + "2015-05-01-preview");
    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/json");

    // Serialize Request
    String requestContent = null;
    JsonNode requestDoc = null;

    ObjectMapper objectMapper = new ObjectMapper();
    ObjectNode subnetJsonFormatValue = objectMapper.createObjectNode();
    requestDoc = subnetJsonFormatValue;

    ObjectNode propertiesValue = objectMapper.createObjectNode();
    ((ObjectNode) subnetJsonFormatValue).put("properties", propertiesValue);

    ((ObjectNode) propertiesValue).put("addressPrefix", subnetParameters.getAddressPrefix());

    if (subnetParameters.getNetworkSecurityGroup() != null) {
        ObjectNode networkSecurityGroupValue = objectMapper.createObjectNode();
        ((ObjectNode) propertiesValue).put("networkSecurityGroup", networkSecurityGroupValue);

        if (subnetParameters.getNetworkSecurityGroup().getId() != null) {
            ((ObjectNode) networkSecurityGroupValue).put("id",
                    subnetParameters.getNetworkSecurityGroup().getId());
        }
    }

    if (subnetParameters.getRouteTable() != null) {
        ObjectNode routeTableValue = objectMapper.createObjectNode();
        ((ObjectNode) propertiesValue).put("routeTable", routeTableValue);

        if (subnetParameters.getRouteTable().getId() != null) {
            ((ObjectNode) routeTableValue).put("id", subnetParameters.getRouteTable().getId());
        }
    }

    if (subnetParameters.getIpConfigurations() != null) {
        if (subnetParameters.getIpConfigurations() instanceof LazyCollection == false
                || ((LazyCollection) subnetParameters.getIpConfigurations()).isInitialized()) {
            ArrayNode ipConfigurationsArray = objectMapper.createArrayNode();
            for (ResourceId ipConfigurationsItem : subnetParameters.getIpConfigurations()) {
                ObjectNode resourceIdValue = objectMapper.createObjectNode();
                ipConfigurationsArray.add(resourceIdValue);

                if (ipConfigurationsItem.getId() != null) {
                    ((ObjectNode) resourceIdValue).put("id", ipConfigurationsItem.getId());
                }
            }
            ((ObjectNode) propertiesValue).put("ipConfigurations", ipConfigurationsArray);
        }
    }

    if (subnetParameters.getProvisioningState() != null) {
        ((ObjectNode) propertiesValue).put("provisioningState", subnetParameters.getProvisioningState());
    }

    if (subnetParameters.getName() != null) {
        ((ObjectNode) subnetJsonFormatValue).put("name", subnetParameters.getName());
    }

    if (subnetParameters.getEtag() != null) {
        ((ObjectNode) subnetJsonFormatValue).put("etag", subnetParameters.getEtag());
    }

    if (subnetParameters.getId() != null) {
        ((ObjectNode) subnetJsonFormatValue).put("id", subnetParameters.getId());
    }

    StringWriter stringWriter = new StringWriter();
    objectMapper.writeValue(stringWriter, requestDoc);
    requestContent = stringWriter.toString();
    StringEntity entity = new StringEntity(requestContent);
    httpRequest.setEntity(entity);
    httpRequest.setHeader("Content-Type", "application/json");

    // 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 && statusCode != HttpStatus.SC_CREATED) {
            ServiceException ex = ServiceException.createFromJson(httpRequest, requestContent, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

        // Create Result
        SubnetPutResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new SubnetPutResponse();
            JsonNode responseDoc = null;
            String responseDocContent = IOUtils.toString(responseContent);
            if (responseDocContent == null == false && responseDocContent.length() > 0) {
                responseDoc = objectMapper.readTree(responseDocContent);
            }

            if (responseDoc != null && responseDoc instanceof NullNode == false) {
                Subnet subnetInstance = new Subnet();
                result.setSubnet(subnetInstance);

                JsonNode propertiesValue2 = responseDoc.get("properties");
                if (propertiesValue2 != null && propertiesValue2 instanceof NullNode == false) {
                    JsonNode addressPrefixValue = propertiesValue2.get("addressPrefix");
                    if (addressPrefixValue != null && addressPrefixValue instanceof NullNode == false) {
                        String addressPrefixInstance;
                        addressPrefixInstance = addressPrefixValue.getTextValue();
                        subnetInstance.setAddressPrefix(addressPrefixInstance);
                    }

                    JsonNode networkSecurityGroupValue2 = propertiesValue2.get("networkSecurityGroup");
                    if (networkSecurityGroupValue2 != null
                            && networkSecurityGroupValue2 instanceof NullNode == false) {
                        ResourceId networkSecurityGroupInstance = new ResourceId();
                        subnetInstance.setNetworkSecurityGroup(networkSecurityGroupInstance);

                        JsonNode idValue = networkSecurityGroupValue2.get("id");
                        if (idValue != null && idValue instanceof NullNode == false) {
                            String idInstance;
                            idInstance = idValue.getTextValue();
                            networkSecurityGroupInstance.setId(idInstance);
                        }
                    }

                    JsonNode routeTableValue2 = propertiesValue2.get("routeTable");
                    if (routeTableValue2 != null && routeTableValue2 instanceof NullNode == false) {
                        ResourceId routeTableInstance = new ResourceId();
                        subnetInstance.setRouteTable(routeTableInstance);

                        JsonNode idValue2 = routeTableValue2.get("id");
                        if (idValue2 != null && idValue2 instanceof NullNode == false) {
                            String idInstance2;
                            idInstance2 = idValue2.getTextValue();
                            routeTableInstance.setId(idInstance2);
                        }
                    }

                    JsonNode ipConfigurationsArray2 = propertiesValue2.get("ipConfigurations");
                    if (ipConfigurationsArray2 != null && ipConfigurationsArray2 instanceof NullNode == false) {
                        for (JsonNode ipConfigurationsValue : ((ArrayNode) ipConfigurationsArray2)) {
                            ResourceId resourceIdInstance = new ResourceId();
                            subnetInstance.getIpConfigurations().add(resourceIdInstance);

                            JsonNode idValue3 = ipConfigurationsValue.get("id");
                            if (idValue3 != null && idValue3 instanceof NullNode == false) {
                                String idInstance3;
                                idInstance3 = idValue3.getTextValue();
                                resourceIdInstance.setId(idInstance3);
                            }
                        }
                    }

                    JsonNode provisioningStateValue = propertiesValue2.get("provisioningState");
                    if (provisioningStateValue != null && provisioningStateValue instanceof NullNode == false) {
                        String provisioningStateInstance;
                        provisioningStateInstance = provisioningStateValue.getTextValue();
                        subnetInstance.setProvisioningState(provisioningStateInstance);
                    }
                }

                JsonNode nameValue = responseDoc.get("name");
                if (nameValue != null && nameValue instanceof NullNode == false) {
                    String nameInstance;
                    nameInstance = nameValue.getTextValue();
                    subnetInstance.setName(nameInstance);
                }

                JsonNode etagValue = responseDoc.get("etag");
                if (etagValue != null && etagValue instanceof NullNode == false) {
                    String etagInstance;
                    etagInstance = etagValue.getTextValue();
                    subnetInstance.setEtag(etagInstance);
                }

                JsonNode idValue4 = responseDoc.get("id");
                if (idValue4 != null && idValue4 instanceof NullNode == false) {
                    String idInstance4;
                    idInstance4 = idValue4.getTextValue();
                    subnetInstance.setId(idInstance4);
                }

                JsonNode errorValue = responseDoc.get("error");
                if (errorValue != null && errorValue instanceof NullNode == false) {
                    Error errorInstance = new Error();
                    result.setError(errorInstance);

                    JsonNode codeValue = errorValue.get("code");
                    if (codeValue != null && codeValue instanceof NullNode == false) {
                        String codeInstance;
                        codeInstance = codeValue.getTextValue();
                        errorInstance.setCode(codeInstance);
                    }

                    JsonNode messageValue = errorValue.get("message");
                    if (messageValue != null && messageValue instanceof NullNode == false) {
                        String messageInstance;
                        messageInstance = messageValue.getTextValue();
                        errorInstance.setMessage(messageInstance);
                    }

                    JsonNode targetValue = errorValue.get("target");
                    if (targetValue != null && targetValue instanceof NullNode == false) {
                        String targetInstance;
                        targetInstance = targetValue.getTextValue();
                        errorInstance.setTarget(targetInstance);
                    }

                    JsonNode detailsArray = errorValue.get("details");
                    if (detailsArray != null && detailsArray instanceof NullNode == false) {
                        for (JsonNode detailsValue : ((ArrayNode) detailsArray)) {
                            ErrorDetails errorDetailsInstance = new ErrorDetails();
                            errorInstance.getDetails().add(errorDetailsInstance);

                            JsonNode codeValue2 = detailsValue.get("code");
                            if (codeValue2 != null && codeValue2 instanceof NullNode == false) {
                                String codeInstance2;
                                codeInstance2 = codeValue2.getTextValue();
                                errorDetailsInstance.setCode(codeInstance2);
                            }

                            JsonNode targetValue2 = detailsValue.get("target");
                            if (targetValue2 != null && targetValue2 instanceof NullNode == false) {
                                String targetInstance2;
                                targetInstance2 = targetValue2.getTextValue();
                                errorDetailsInstance.setTarget(targetInstance2);
                            }

                            JsonNode messageValue2 = detailsValue.get("message");
                            if (messageValue2 != null && messageValue2 instanceof NullNode == false) {
                                String messageInstance2;
                                messageInstance2 = messageValue2.getTextValue();
                                errorDetailsInstance.setMessage(messageInstance2);
                            }
                        }
                    }

                    JsonNode innerErrorValue = errorValue.get("innerError");
                    if (innerErrorValue != null && innerErrorValue instanceof NullNode == false) {
                        String innerErrorInstance;
                        innerErrorInstance = innerErrorValue.getTextValue();
                        errorInstance.setInnerError(innerErrorInstance);
                    }
                }
            }

        }
        result.setStatusCode(statusCode);
        if (httpResponse.getHeaders("Azure-AsyncOperation").length > 0) {
            result.setAzureAsyncOperation(httpResponse.getFirstHeader("Azure-AsyncOperation").getValue());
        }
        if (httpResponse.getHeaders("Retry-After").length > 0) {
            result.setRetryAfter(
                    DatatypeConverter.parseInt(httpResponse.getFirstHeader("Retry-After").getValue()));
        }
        if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
            result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
        }

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