Example usage for javax.xml.bind DatatypeConverter parseDateTime

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

Introduction

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

Prototype

public static java.util.Calendar parseDateTime(String lexicalXSDDateTime) 

Source Link

Document

Converts the string argument into a Calendar value.

Usage

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

/**
* Retrieves all of the operations that occured on the Azure SQL Database
* Server./*  w  ww  .  ja v a 2 s .c o m*/
*
* @param serverName Required. The name of the Azure SQL Database Server to
* be queried.
* @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 Represents the response containing the list of database
* operations for a given server or database.
*/
@Override
public DatabaseOperationListResponse listByServer(String serverName)
        throws IOException, ServiceException, ParserConfigurationException, SAXException {
    // Validate
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }

    // 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);
        CloudTracing.enter(invocationId, this, "listByServerAsync", tracingParameters);
    }

    // Construct URL
    String 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 + "/databaseoperations";
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("contentview=generic");
    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
    HttpGet httpRequest = new HttpGet(url);

    // Set Headers
    httpRequest.setHeader("x-ms-version", "2012-03-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
        DatabaseOperationListResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new DatabaseOperationListResponse();
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setNamespaceAware(true);
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));

            Element serviceResourcesSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "ServiceResources");
            if (serviceResourcesSequenceElement != null) {
                for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                        .getElementsByTagNameNS(serviceResourcesSequenceElement,
                                "http://schemas.microsoft.com/windowsazure", "ServiceResource")
                        .size(); i1 = i1 + 1) {
                    org.w3c.dom.Element serviceResourcesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(serviceResourcesSequenceElement,
                                    "http://schemas.microsoft.com/windowsazure", "ServiceResource")
                            .get(i1));
                    DatabaseOperation serviceResourceInstance = new DatabaseOperation();
                    result.getDatabaseOperations().add(serviceResourceInstance);

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

                    Element stateIdElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                            "http://schemas.microsoft.com/windowsazure", "StateId");
                    if (stateIdElement != null) {
                        int stateIdInstance;
                        stateIdInstance = DatatypeConverter.parseInt(stateIdElement.getTextContent());
                        serviceResourceInstance.setStateId(stateIdInstance);
                    }

                    Element sessionActivityIdElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                            "http://schemas.microsoft.com/windowsazure", "SessionActivityId");
                    if (sessionActivityIdElement != null) {
                        String sessionActivityIdInstance;
                        sessionActivityIdInstance = sessionActivityIdElement.getTextContent();
                        serviceResourceInstance.setSessionActivityId(sessionActivityIdInstance);
                    }

                    Element databaseNameElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                            "http://schemas.microsoft.com/windowsazure", "DatabaseName");
                    if (databaseNameElement != null) {
                        String databaseNameInstance;
                        databaseNameInstance = databaseNameElement.getTextContent();
                        serviceResourceInstance.setDatabaseName(databaseNameInstance);
                    }

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

                    Element errorCodeElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                            "http://schemas.microsoft.com/windowsazure", "ErrorCode");
                    if (errorCodeElement != null) {
                        int errorCodeInstance;
                        errorCodeInstance = DatatypeConverter.parseInt(errorCodeElement.getTextContent());
                        serviceResourceInstance.setErrorCode(errorCodeInstance);
                    }

                    Element errorElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                            "http://schemas.microsoft.com/windowsazure", "Error");
                    if (errorElement != null) {
                        String errorInstance;
                        errorInstance = errorElement.getTextContent();
                        serviceResourceInstance.setError(errorInstance);
                    }

                    Element errorSeverityElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                            "http://schemas.microsoft.com/windowsazure", "ErrorSeverity");
                    if (errorSeverityElement != null) {
                        int errorSeverityInstance;
                        errorSeverityInstance = DatatypeConverter
                                .parseInt(errorSeverityElement.getTextContent());
                        serviceResourceInstance.setErrorSeverity(errorSeverityInstance);
                    }

                    Element errorStateElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                            "http://schemas.microsoft.com/windowsazure", "ErrorState");
                    if (errorStateElement != null) {
                        int errorStateInstance;
                        errorStateInstance = DatatypeConverter.parseInt(errorStateElement.getTextContent());
                        serviceResourceInstance.setErrorState(errorStateInstance);
                    }

                    Element startTimeElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                            "http://schemas.microsoft.com/windowsazure", "StartTime");
                    if (startTimeElement != null) {
                        Calendar startTimeInstance;
                        startTimeInstance = DatatypeConverter.parseDateTime(startTimeElement.getTextContent());
                        serviceResourceInstance.setStartTime(startTimeInstance);
                    }

                    Element lastModifyTimeElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                            "http://schemas.microsoft.com/windowsazure", "LastModifyTime");
                    if (lastModifyTimeElement != null) {
                        Calendar lastModifyTimeInstance;
                        lastModifyTimeInstance = DatatypeConverter
                                .parseDateTime(lastModifyTimeElement.getTextContent());
                        serviceResourceInstance.setLastModifyTime(lastModifyTimeInstance);
                    }

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

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

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

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

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

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

/**
* You can retrieve historical usage metrics for a site by issuing an HTTP
* GET request.  (see// w  w  w .  ja  va 2 s.  com
* http://msdn.microsoft.com/en-us/library/windowsazure/dn166964.aspx for
* more information)
*
* @param webSpaceName Required. The name of the web space.
* @param webHostingPlanName Required. The name of the web hosting plan.
* @param parameters Required. Parameters supplied to the Get Historical
* Usage Metrics Web hosting plan 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.
* @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 Get Historical Usage Metrics Web hosting plan operation
* response.
*/
@Override
public WebHostingPlanGetHistoricalUsageMetricsResponse getHistoricalUsageMetrics(String webSpaceName,
        String webHostingPlanName, WebHostingPlanGetHistoricalUsageMetricsParameters parameters)
        throws IOException, ServiceException, ParserConfigurationException, SAXException {
    // Validate
    if (webSpaceName == null) {
        throw new NullPointerException("webSpaceName");
    }
    if (webHostingPlanName == null) {
        throw new NullPointerException("webHostingPlanName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }

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

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/services/WebSpaces/";
    url = url + URLEncoder.encode(webSpaceName, "UTF-8");
    url = url + "/serverFarms/";
    url = url + URLEncoder.encode(webHostingPlanName, "UTF-8");
    url = url + "/metrics";
    ArrayList<String> queryParameters = new ArrayList<String>();
    if (parameters.getMetricNames() != null && parameters.getMetricNames().size() > 0) {
        queryParameters.add("names="
                + URLEncoder.encode(CollectionStringBuilder.join(parameters.getMetricNames(), ","), "UTF-8"));
    }
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
    simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    if (parameters.getStartTime() != null) {
        queryParameters.add("StartTime="
                + URLEncoder.encode(simpleDateFormat.format(parameters.getStartTime().getTime()), "UTF-8"));
    }
    SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
    simpleDateFormat2.setTimeZone(TimeZone.getTimeZone("UTC"));
    if (parameters.getEndTime() != null) {
        queryParameters.add("EndTime="
                + URLEncoder.encode(simpleDateFormat2.format(parameters.getEndTime().getTime()), "UTF-8"));
    }
    if (parameters.getTimeGrain() != null) {
        queryParameters.add("timeGrain=" + URLEncoder.encode(parameters.getTimeGrain(), "UTF-8"));
    }
    queryParameters.add("details=" + URLEncoder
            .encode(Boolean.toString(parameters.isIncludeInstanceBreakdown()).toLowerCase(), "UTF-8"));
    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
    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
        WebHostingPlanGetHistoricalUsageMetricsResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new WebHostingPlanGetHistoricalUsageMetricsResponse();
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setNamespaceAware(true);
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));

            Element metricResponsesElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "MetricResponses");
            if (metricResponsesElement != null) {
                if (metricResponsesElement != null) {
                    for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(metricResponsesElement,
                                    "http://schemas.microsoft.com/windowsazure", "MetricResponse")
                            .size(); i1 = i1 + 1) {
                        org.w3c.dom.Element usageMetricsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(metricResponsesElement,
                                        "http://schemas.microsoft.com/windowsazure", "MetricResponse")
                                .get(i1));
                        HistoricalUsageMetric metricResponseInstance = new HistoricalUsageMetric();
                        result.getUsageMetrics().add(metricResponseInstance);

                        Element codeElement = XmlUtility.getElementByTagNameNS(usageMetricsElement,
                                "http://schemas.microsoft.com/windowsazure", "Code");
                        if (codeElement != null) {
                            String codeInstance;
                            codeInstance = codeElement.getTextContent();
                            metricResponseInstance.setCode(codeInstance);
                        }

                        Element dataElement = XmlUtility.getElementByTagNameNS(usageMetricsElement,
                                "http://schemas.microsoft.com/windowsazure", "Data");
                        if (dataElement != null) {
                            HistoricalUsageMetricData dataInstance = new HistoricalUsageMetricData();
                            metricResponseInstance.setData(dataInstance);

                            Element displayNameElement = XmlUtility.getElementByTagNameNS(dataElement,
                                    "http://schemas.microsoft.com/windowsazure", "DisplayName");
                            if (displayNameElement != null) {
                                String displayNameInstance;
                                displayNameInstance = displayNameElement.getTextContent();
                                dataInstance.setDisplayName(displayNameInstance);
                            }

                            Element endTimeElement = XmlUtility.getElementByTagNameNS(dataElement,
                                    "http://schemas.microsoft.com/windowsazure", "EndTime");
                            if (endTimeElement != null) {
                                Calendar endTimeInstance;
                                endTimeInstance = DatatypeConverter
                                        .parseDateTime(endTimeElement.getTextContent());
                                dataInstance.setEndTime(endTimeInstance);
                            }

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

                            Element primaryAggregationTypeElement = XmlUtility.getElementByTagNameNS(
                                    dataElement, "http://schemas.microsoft.com/windowsazure",
                                    "PrimaryAggregationType");
                            if (primaryAggregationTypeElement != null) {
                                String primaryAggregationTypeInstance;
                                primaryAggregationTypeInstance = primaryAggregationTypeElement.getTextContent();
                                dataInstance.setPrimaryAggregationType(primaryAggregationTypeInstance);
                            }

                            Element startTimeElement = XmlUtility.getElementByTagNameNS(dataElement,
                                    "http://schemas.microsoft.com/windowsazure", "StartTime");
                            if (startTimeElement != null) {
                                Calendar startTimeInstance;
                                startTimeInstance = DatatypeConverter
                                        .parseDateTime(startTimeElement.getTextContent());
                                dataInstance.setStartTime(startTimeInstance);
                            }

                            Element timeGrainElement = XmlUtility.getElementByTagNameNS(dataElement,
                                    "http://schemas.microsoft.com/windowsazure", "TimeGrain");
                            if (timeGrainElement != null) {
                                String timeGrainInstance;
                                timeGrainInstance = timeGrainElement.getTextContent();
                                dataInstance.setTimeGrain(timeGrainInstance);
                            }

                            Element unitElement = XmlUtility.getElementByTagNameNS(dataElement,
                                    "http://schemas.microsoft.com/windowsazure", "Unit");
                            if (unitElement != null) {
                                String unitInstance;
                                unitInstance = unitElement.getTextContent();
                                dataInstance.setUnit(unitInstance);
                            }

                            Element valuesSequenceElement = XmlUtility.getElementByTagNameNS(dataElement,
                                    "http://schemas.microsoft.com/windowsazure", "Values");
                            if (valuesSequenceElement != null) {
                                for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility
                                        .getElementsByTagNameNS(valuesSequenceElement,
                                                "http://schemas.microsoft.com/windowsazure", "MetricSample")
                                        .size(); i2 = i2 + 1) {
                                    org.w3c.dom.Element valuesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                            .getElementsByTagNameNS(valuesSequenceElement,
                                                    "http://schemas.microsoft.com/windowsazure", "MetricSample")
                                            .get(i2));
                                    HistoricalUsageMetricSample metricSampleInstance = new HistoricalUsageMetricSample();
                                    dataInstance.getValues().add(metricSampleInstance);

                                    Element countElement = XmlUtility.getElementByTagNameNS(valuesElement,
                                            "http://schemas.microsoft.com/windowsazure", "Count");
                                    if (countElement != null) {
                                        int countInstance;
                                        countInstance = DatatypeConverter
                                                .parseInt(countElement.getTextContent());
                                        metricSampleInstance.setCount(countInstance);
                                    }

                                    Element maximumElement = XmlUtility.getElementByTagNameNS(valuesElement,
                                            "http://schemas.microsoft.com/windowsazure", "Maximum");
                                    if (maximumElement != null) {
                                        boolean isNil = false;
                                        Attr nilAttribute = maximumElement.getAttributeNodeNS(
                                                "http://www.w3.org/2001/XMLSchema-instance", "nil");
                                        if (nilAttribute != null) {
                                            isNil = "true".equals(nilAttribute.getValue());
                                        }
                                        if (isNil == false) {
                                            String maximumInstance;
                                            maximumInstance = maximumElement.getTextContent();
                                            metricSampleInstance.setMaximum(maximumInstance);
                                        }
                                    }

                                    Element minimumElement = XmlUtility.getElementByTagNameNS(valuesElement,
                                            "http://schemas.microsoft.com/windowsazure", "Minimum");
                                    if (minimumElement != null) {
                                        boolean isNil2 = false;
                                        Attr nilAttribute2 = minimumElement.getAttributeNodeNS(
                                                "http://www.w3.org/2001/XMLSchema-instance", "nil");
                                        if (nilAttribute2 != null) {
                                            isNil2 = "true".equals(nilAttribute2.getValue());
                                        }
                                        if (isNil2 == false) {
                                            String minimumInstance;
                                            minimumInstance = minimumElement.getTextContent();
                                            metricSampleInstance.setMinimum(minimumInstance);
                                        }
                                    }

                                    Element timeCreatedElement = XmlUtility.getElementByTagNameNS(valuesElement,
                                            "http://schemas.microsoft.com/windowsazure", "TimeCreated");
                                    if (timeCreatedElement != null) {
                                        Calendar timeCreatedInstance;
                                        timeCreatedInstance = DatatypeConverter
                                                .parseDateTime(timeCreatedElement.getTextContent());
                                        metricSampleInstance.setTimeCreated(timeCreatedInstance);
                                    }

                                    Element totalElement = XmlUtility.getElementByTagNameNS(valuesElement,
                                            "http://schemas.microsoft.com/windowsazure", "Total");
                                    if (totalElement != null) {
                                        String totalInstance;
                                        totalInstance = totalElement.getTextContent();
                                        metricSampleInstance.setTotal(totalInstance);
                                    }

                                    Element instanceNameElement = XmlUtility.getElementByTagNameNS(
                                            valuesElement, "http://schemas.microsoft.com/windowsazure",
                                            "InstanceName");
                                    if (instanceNameElement != null) {
                                        String instanceNameInstance;
                                        instanceNameInstance = instanceNameElement.getTextContent();
                                        metricSampleInstance.setInstanceName(instanceNameInstance);
                                    }
                                }
                            }
                        }

                        Element messageElement = XmlUtility.getElementByTagNameNS(usageMetricsElement,
                                "http://schemas.microsoft.com/windowsazure", "Message");
                        if (messageElement != null) {
                            String messageInstance;
                            messageInstance = messageElement.getTextContent();
                            metricResponseInstance.setMessage(messageInstance);
                        }
                    }
                }
            }

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

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

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

/**
* The List Affinity Groups operation lists the affinity groups associated
* with the specified subscription.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/ee460797.aspx for
* more information)//from   w w w  . j ava 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 Affinity Groups operation response.
*/
@Override
public AffinityGroupListResponse list()
        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, "listAsync", tracingParameters);
    }

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

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

    // Set Headers
    httpRequest.setHeader("x-ms-version", "2014-10-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
        AffinityGroupListResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new AffinityGroupListResponse();
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setNamespaceAware(true);
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));

            Element affinityGroupsSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "AffinityGroups");
            if (affinityGroupsSequenceElement != null) {
                for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                        .getElementsByTagNameNS(affinityGroupsSequenceElement,
                                "http://schemas.microsoft.com/windowsazure", "AffinityGroup")
                        .size(); i1 = i1 + 1) {
                    org.w3c.dom.Element affinityGroupsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(affinityGroupsSequenceElement,
                                    "http://schemas.microsoft.com/windowsazure", "AffinityGroup")
                            .get(i1));
                    AffinityGroupListResponse.AffinityGroup affinityGroupInstance = new AffinityGroupListResponse.AffinityGroup();
                    result.getAffinityGroups().add(affinityGroupInstance);

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

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

                    Element descriptionElement = XmlUtility.getElementByTagNameNS(affinityGroupsElement,
                            "http://schemas.microsoft.com/windowsazure", "Description");
                    if (descriptionElement != null) {
                        String descriptionInstance;
                        descriptionInstance = descriptionElement.getTextContent();
                        affinityGroupInstance.setDescription(descriptionInstance);
                    }

                    Element locationElement = XmlUtility.getElementByTagNameNS(affinityGroupsElement,
                            "http://schemas.microsoft.com/windowsazure", "Location");
                    if (locationElement != null) {
                        String locationInstance;
                        locationInstance = locationElement.getTextContent();
                        affinityGroupInstance.setLocation(locationInstance);
                    }

                    Element capabilitiesSequenceElement = XmlUtility.getElementByTagNameNS(
                            affinityGroupsElement, "http://schemas.microsoft.com/windowsazure", "Capabilities");
                    if (capabilitiesSequenceElement != null) {
                        for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(capabilitiesSequenceElement,
                                        "http://schemas.microsoft.com/windowsazure", "Capability")
                                .size(); i2 = i2 + 1) {
                            org.w3c.dom.Element capabilitiesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(capabilitiesSequenceElement,
                                            "http://schemas.microsoft.com/windowsazure", "Capability")
                                    .get(i2));
                            affinityGroupInstance.getCapabilities().add(capabilitiesElement.getTextContent());
                        }
                    }

                    Element createdTimeElement = XmlUtility.getElementByTagNameNS(affinityGroupsElement,
                            "http://schemas.microsoft.com/windowsazure", "CreatedTime");
                    if (createdTimeElement != null && createdTimeElement.getTextContent() != null
                            && !createdTimeElement.getTextContent().isEmpty()) {
                        Calendar createdTimeInstance;
                        createdTimeInstance = DatatypeConverter
                                .parseDateTime(createdTimeElement.getTextContent());
                        affinityGroupInstance.setCreatedTime(createdTimeInstance);
                    }

                    Element computeCapabilitiesElement = XmlUtility.getElementByTagNameNS(affinityGroupsElement,
                            "http://schemas.microsoft.com/windowsazure", "ComputeCapabilities");
                    if (computeCapabilitiesElement != null) {
                        ComputeCapabilities computeCapabilitiesInstance = new ComputeCapabilities();
                        affinityGroupInstance.setComputeCapabilities(computeCapabilitiesInstance);

                        Element virtualMachinesRoleSizesSequenceElement = XmlUtility.getElementByTagNameNS(
                                computeCapabilitiesElement, "http://schemas.microsoft.com/windowsazure",
                                "VirtualMachinesRoleSizes");
                        if (virtualMachinesRoleSizesSequenceElement != null) {
                            for (int i3 = 0; i3 < com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(virtualMachinesRoleSizesSequenceElement,
                                            "http://schemas.microsoft.com/windowsazure", "RoleSize")
                                    .size(); i3 = i3 + 1) {
                                org.w3c.dom.Element virtualMachinesRoleSizesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                        .getElementsByTagNameNS(virtualMachinesRoleSizesSequenceElement,
                                                "http://schemas.microsoft.com/windowsazure", "RoleSize")
                                        .get(i3));
                                computeCapabilitiesInstance.getVirtualMachinesRoleSizes()
                                        .add(virtualMachinesRoleSizesElement.getTextContent());
                            }
                        }

                        Element webWorkerRoleSizesSequenceElement = XmlUtility.getElementByTagNameNS(
                                computeCapabilitiesElement, "http://schemas.microsoft.com/windowsazure",
                                "WebWorkerRoleSizes");
                        if (webWorkerRoleSizesSequenceElement != null) {
                            for (int i4 = 0; i4 < com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(webWorkerRoleSizesSequenceElement,
                                            "http://schemas.microsoft.com/windowsazure", "RoleSize")
                                    .size(); i4 = i4 + 1) {
                                org.w3c.dom.Element webWorkerRoleSizesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                        .getElementsByTagNameNS(webWorkerRoleSizesSequenceElement,
                                                "http://schemas.microsoft.com/windowsazure", "RoleSize")
                                        .get(i4));
                                computeCapabilitiesInstance.getWebWorkerRoleSizes()
                                        .add(webWorkerRoleSizesElement.getTextContent());
                            }
                        }
                    }
                }
            }

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

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

From source file:com.microsoft.windowsazure.management.servicebus.TopicOperationsImpl.java

/**
* Creates a new topic. Once created, this topic resource manifest is
* immutable. This operation is not idempotent. Repeating the create call,
* after a topic with same name has been created successfully, will result
* in a 409 Conflict error message.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/hh780728.aspx for
* more information)/*w  w w.  j a  v a2s . c om*/
*
* @param namespaceName Required. The namespace name.
* @param topic Required. The Service Bus topic.
* @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 A response to a request for a particular topic.
*/
@Override
public ServiceBusTopicResponse create(String namespaceName, ServiceBusTopic topic)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException,
        URISyntaxException {
    // Validate
    if (namespaceName == null) {
        throw new NullPointerException("namespaceName");
    }
    if (topic == null) {
        throw new NullPointerException("topic");
    }

    // 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("namespaceName", namespaceName);
        tracingParameters.put("topic", topic);
        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/servicebus/namespaces/";
    url = url + URLEncoder.encode(namespaceName, "UTF-8");
    url = url + "/topics/";
    if (topic.getName() != null) {
        url = url + URLEncoder.encode(topic.getName(), "UTF-8");
    }
    url = url + "/";
    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/atom+xml");
    httpRequest.setHeader("type", "entry");
    httpRequest.setHeader("x-ms-version", "2013-08-01");
    httpRequest.setHeader("x-process-at", "ServiceBus");

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

    Element entryElement = requestDoc.createElementNS("http://www.w3.org/2005/Atom", "entry");
    requestDoc.appendChild(entryElement);

    Element contentElement = requestDoc.createElementNS("http://www.w3.org/2005/Atom", "content");
    entryElement.appendChild(contentElement);

    Attr typeAttribute = requestDoc.createAttribute("type");
    typeAttribute.setValue("application/atom+xml;type=entry;charset=utf-8");
    contentElement.setAttributeNode(typeAttribute);

    Element topicDescriptionElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "TopicDescription");
    contentElement.appendChild(topicDescriptionElement);

    if (topic.getDefaultMessageTimeToLive() != null) {
        Element defaultMessageTimeToLiveElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                "DefaultMessageTimeToLive");
        defaultMessageTimeToLiveElement
                .appendChild(requestDoc.createTextNode(topic.getDefaultMessageTimeToLive()));
        topicDescriptionElement.appendChild(defaultMessageTimeToLiveElement);
    }

    Element maxSizeInMegabytesElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "MaxSizeInMegabytes");
    maxSizeInMegabytesElement
            .appendChild(requestDoc.createTextNode(Integer.toString(topic.getMaxSizeInMegabytes())));
    topicDescriptionElement.appendChild(maxSizeInMegabytesElement);

    Element requiresDuplicateDetectionElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
            "RequiresDuplicateDetection");
    requiresDuplicateDetectionElement.appendChild(
            requestDoc.createTextNode(Boolean.toString(topic.isRequiresDuplicateDetection()).toLowerCase()));
    topicDescriptionElement.appendChild(requiresDuplicateDetectionElement);

    if (topic.getDuplicateDetectionHistoryTimeWindow() != null) {
        Element duplicateDetectionHistoryTimeWindowElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                "DuplicateDetectionHistoryTimeWindow");
        duplicateDetectionHistoryTimeWindowElement
                .appendChild(requestDoc.createTextNode(topic.getDuplicateDetectionHistoryTimeWindow()));
        topicDescriptionElement.appendChild(duplicateDetectionHistoryTimeWindowElement);
    }

    Element enableBatchedOperationsElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "EnableBatchedOperations");
    enableBatchedOperationsElement.appendChild(
            requestDoc.createTextNode(Boolean.toString(topic.isEnableBatchedOperations()).toLowerCase()));
    topicDescriptionElement.appendChild(enableBatchedOperationsElement);

    Element sizeInBytesElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "SizeInBytes");
    sizeInBytesElement.appendChild(requestDoc.createTextNode(Integer.toString(topic.getSizeInBytes())));
    topicDescriptionElement.appendChild(sizeInBytesElement);

    Element filteringMessagesBeforePublishingElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
            "FilteringMessagesBeforePublishing");
    filteringMessagesBeforePublishingElement.appendChild(requestDoc
            .createTextNode(Boolean.toString(topic.isFilteringMessagesBeforePublishing()).toLowerCase()));
    topicDescriptionElement.appendChild(filteringMessagesBeforePublishingElement);

    Element isAnonymousAccessibleElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "IsAnonymousAccessible");
    isAnonymousAccessibleElement.appendChild(
            requestDoc.createTextNode(Boolean.toString(topic.isAnonymousAccessible()).toLowerCase()));
    topicDescriptionElement.appendChild(isAnonymousAccessibleElement);

    if (topic.getAuthorizationRules() != null) {
        if (topic.getAuthorizationRules() instanceof LazyCollection == false
                || ((LazyCollection) topic.getAuthorizationRules()).isInitialized()) {
            Element authorizationRulesSequenceElement = requestDoc.createElementNS(
                    "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                    "AuthorizationRules");
            for (ServiceBusSharedAccessAuthorizationRule authorizationRulesItem : topic
                    .getAuthorizationRules()) {
                Element authorizationRuleElement = requestDoc.createElementNS(
                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                        "AuthorizationRule");
                authorizationRulesSequenceElement.appendChild(authorizationRuleElement);

                Attr typeAttribute2 = requestDoc.createAttributeNS("http://www.w3.org/2001/XMLSchema-instance",
                        "type");
                typeAttribute2.setValue("SharedAccessAuthorizationRule");
                authorizationRuleElement.setAttributeNode(typeAttribute2);

                if (authorizationRulesItem.getClaimType() != null) {
                    Element claimTypeElement = requestDoc.createElementNS(
                            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "ClaimType");
                    claimTypeElement
                            .appendChild(requestDoc.createTextNode(authorizationRulesItem.getClaimType()));
                    authorizationRuleElement.appendChild(claimTypeElement);
                }

                if (authorizationRulesItem.getClaimValue() != null) {
                    Element claimValueElement = requestDoc.createElementNS(
                            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                            "ClaimValue");
                    claimValueElement
                            .appendChild(requestDoc.createTextNode(authorizationRulesItem.getClaimValue()));
                    authorizationRuleElement.appendChild(claimValueElement);
                }

                if (authorizationRulesItem.getRights() != null) {
                    if (authorizationRulesItem.getRights() instanceof LazyCollection == false
                            || ((LazyCollection) authorizationRulesItem.getRights()).isInitialized()) {
                        Element rightsSequenceElement = requestDoc.createElementNS(
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "Rights");
                        for (AccessRight rightsItem : authorizationRulesItem.getRights()) {
                            Element rightsItemElement = requestDoc.createElementNS(
                                    "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                    "AccessRights");
                            rightsItemElement.appendChild(requestDoc.createTextNode(rightsItem.toString()));
                            rightsSequenceElement.appendChild(rightsItemElement);
                        }
                        authorizationRuleElement.appendChild(rightsSequenceElement);
                    }
                }

                Element createdTimeElement = requestDoc.createElementNS(
                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "CreatedTime");
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
                simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
                createdTimeElement.appendChild(requestDoc.createTextNode(
                        simpleDateFormat.format(authorizationRulesItem.getCreatedTime().getTime())));
                authorizationRuleElement.appendChild(createdTimeElement);

                if (authorizationRulesItem.getKeyName() != null) {
                    Element keyNameElement = requestDoc.createElementNS(
                            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "KeyName");
                    keyNameElement.appendChild(requestDoc.createTextNode(authorizationRulesItem.getKeyName()));
                    authorizationRuleElement.appendChild(keyNameElement);
                }

                Element modifiedTimeElement = requestDoc.createElementNS(
                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "ModifiedTime");
                SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
                simpleDateFormat2.setTimeZone(TimeZone.getTimeZone("UTC"));
                modifiedTimeElement.appendChild(requestDoc.createTextNode(
                        simpleDateFormat2.format(authorizationRulesItem.getModifiedTime().getTime())));
                authorizationRuleElement.appendChild(modifiedTimeElement);

                if (authorizationRulesItem.getPrimaryKey() != null) {
                    Element primaryKeyElement = requestDoc.createElementNS(
                            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                            "PrimaryKey");
                    primaryKeyElement
                            .appendChild(requestDoc.createTextNode(authorizationRulesItem.getPrimaryKey()));
                    authorizationRuleElement.appendChild(primaryKeyElement);
                }

                if (authorizationRulesItem.getSecondaryKey() != null) {
                    Element secondaryKeyElement = requestDoc.createElementNS(
                            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                            "SecondaryKey");
                    secondaryKeyElement
                            .appendChild(requestDoc.createTextNode(authorizationRulesItem.getSecondaryKey()));
                    authorizationRuleElement.appendChild(secondaryKeyElement);
                }
            }
            topicDescriptionElement.appendChild(authorizationRulesSequenceElement);
        }
    }

    if (topic.getStatus() != null) {
        Element statusElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "Status");
        statusElement.appendChild(requestDoc.createTextNode(topic.getStatus()));
        topicDescriptionElement.appendChild(statusElement);
    }

    Element createdAtElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "CreatedAt");
    SimpleDateFormat simpleDateFormat3 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
    simpleDateFormat3.setTimeZone(TimeZone.getTimeZone("UTC"));
    createdAtElement
            .appendChild(requestDoc.createTextNode(simpleDateFormat3.format(topic.getCreatedAt().getTime())));
    topicDescriptionElement.appendChild(createdAtElement);

    Element updatedAtElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "UpdatedAt");
    SimpleDateFormat simpleDateFormat4 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
    simpleDateFormat4.setTimeZone(TimeZone.getTimeZone("UTC"));
    updatedAtElement
            .appendChild(requestDoc.createTextNode(simpleDateFormat4.format(topic.getUpdatedAt().getTime())));
    topicDescriptionElement.appendChild(updatedAtElement);

    Element accessedAtElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "AccessedAt");
    SimpleDateFormat simpleDateFormat5 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
    simpleDateFormat5.setTimeZone(TimeZone.getTimeZone("UTC"));
    accessedAtElement
            .appendChild(requestDoc.createTextNode(simpleDateFormat5.format(topic.getAccessedAt().getTime())));
    topicDescriptionElement.appendChild(accessedAtElement);

    Element supportOrderingElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "SupportOrdering");
    supportOrderingElement
            .appendChild(requestDoc.createTextNode(Boolean.toString(topic.isSupportOrdering()).toLowerCase()));
    topicDescriptionElement.appendChild(supportOrderingElement);

    if (topic.getCountDetails() != null) {
        Element countDetailsElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "CountDetails");
        topicDescriptionElement.appendChild(countDetailsElement);

        Element activeMessageCountElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2011/06/servicebus", "ActiveMessageCount");
        activeMessageCountElement.appendChild(
                requestDoc.createTextNode(Integer.toString(topic.getCountDetails().getActiveMessageCount())));
        countDetailsElement.appendChild(activeMessageCountElement);

        Element deadLetterMessageCountElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2011/06/servicebus", "DeadLetterMessageCount");
        deadLetterMessageCountElement.appendChild(requestDoc
                .createTextNode(Integer.toString(topic.getCountDetails().getDeadLetterMessageCount())));
        countDetailsElement.appendChild(deadLetterMessageCountElement);

        Element scheduledMessageCountElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2011/06/servicebus", "ScheduledMessageCount");
        scheduledMessageCountElement.appendChild(requestDoc
                .createTextNode(Integer.toString(topic.getCountDetails().getScheduledMessageCount())));
        countDetailsElement.appendChild(scheduledMessageCountElement);

        Element transferDeadLetterMessageCountElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2011/06/servicebus",
                "TransferDeadLetterMessageCount");
        transferDeadLetterMessageCountElement.appendChild(requestDoc
                .createTextNode(Integer.toString(topic.getCountDetails().getTransferDeadLetterMessageCount())));
        countDetailsElement.appendChild(transferDeadLetterMessageCountElement);

        Element transferMessageCountElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2011/06/servicebus", "TransferMessageCount");
        transferMessageCountElement.appendChild(
                requestDoc.createTextNode(Integer.toString(topic.getCountDetails().getTransferMessageCount())));
        countDetailsElement.appendChild(transferMessageCountElement);
    }

    Element subscriptionCountElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "SubscriptionCount");
    subscriptionCountElement
            .appendChild(requestDoc.createTextNode(Integer.toString(topic.getSubscriptionCount())));
    topicDescriptionElement.appendChild(subscriptionCountElement);

    if (topic.getAutoDeleteOnIdle() != null) {
        Element autoDeleteOnIdleElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "AutoDeleteOnIdle");
        autoDeleteOnIdleElement.appendChild(requestDoc.createTextNode(topic.getAutoDeleteOnIdle()));
        topicDescriptionElement.appendChild(autoDeleteOnIdleElement);
    }

    if (topic.getEntityAvailabilityStatus() != null) {
        Element entityAvailabilityStatusElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                "EntityAvailabilityStatus");
        entityAvailabilityStatusElement
                .appendChild(requestDoc.createTextNode(topic.getEntityAvailabilityStatus()));
        topicDescriptionElement.appendChild(entityAvailabilityStatusElement);
    }

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

            Element entryElement2 = XmlUtility.getElementByTagNameNS(responseDoc, "http://www.w3.org/2005/Atom",
                    "entry");
            if (entryElement2 != null) {
                Element titleElement = XmlUtility.getElementByTagNameNS(entryElement2,
                        "http://www.w3.org/2005/Atom", "title");
                if (titleElement != null) {
                }

                Element contentElement2 = XmlUtility.getElementByTagNameNS(entryElement2,
                        "http://www.w3.org/2005/Atom", "content");
                if (contentElement2 != null) {
                    Element topicDescriptionElement2 = XmlUtility.getElementByTagNameNS(contentElement2,
                            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                            "TopicDescription");
                    if (topicDescriptionElement2 != null) {
                        ServiceBusTopic topicDescriptionInstance = new ServiceBusTopic();
                        result.setTopic(topicDescriptionInstance);

                        Element defaultMessageTimeToLiveElement2 = XmlUtility.getElementByTagNameNS(
                                topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "DefaultMessageTimeToLive");
                        if (defaultMessageTimeToLiveElement2 != null) {
                            String defaultMessageTimeToLiveInstance;
                            defaultMessageTimeToLiveInstance = defaultMessageTimeToLiveElement2
                                    .getTextContent();
                            topicDescriptionInstance
                                    .setDefaultMessageTimeToLive(defaultMessageTimeToLiveInstance);
                        }

                        Element maxSizeInMegabytesElement2 = XmlUtility.getElementByTagNameNS(
                                topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "MaxSizeInMegabytes");
                        if (maxSizeInMegabytesElement2 != null) {
                            int maxSizeInMegabytesInstance;
                            maxSizeInMegabytesInstance = DatatypeConverter
                                    .parseInt(maxSizeInMegabytesElement2.getTextContent());
                            topicDescriptionInstance.setMaxSizeInMegabytes(maxSizeInMegabytesInstance);
                        }

                        Element requiresDuplicateDetectionElement2 = XmlUtility.getElementByTagNameNS(
                                topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "RequiresDuplicateDetection");
                        if (requiresDuplicateDetectionElement2 != null) {
                            boolean requiresDuplicateDetectionInstance;
                            requiresDuplicateDetectionInstance = DatatypeConverter.parseBoolean(
                                    requiresDuplicateDetectionElement2.getTextContent().toLowerCase());
                            topicDescriptionInstance
                                    .setRequiresDuplicateDetection(requiresDuplicateDetectionInstance);
                        }

                        Element duplicateDetectionHistoryTimeWindowElement2 = XmlUtility.getElementByTagNameNS(
                                topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "DuplicateDetectionHistoryTimeWindow");
                        if (duplicateDetectionHistoryTimeWindowElement2 != null) {
                            String duplicateDetectionHistoryTimeWindowInstance;
                            duplicateDetectionHistoryTimeWindowInstance = duplicateDetectionHistoryTimeWindowElement2
                                    .getTextContent();
                            topicDescriptionInstance.setDuplicateDetectionHistoryTimeWindow(
                                    duplicateDetectionHistoryTimeWindowInstance);
                        }

                        Element enableBatchedOperationsElement2 = XmlUtility.getElementByTagNameNS(
                                topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "EnableBatchedOperations");
                        if (enableBatchedOperationsElement2 != null) {
                            boolean enableBatchedOperationsInstance;
                            enableBatchedOperationsInstance = DatatypeConverter.parseBoolean(
                                    enableBatchedOperationsElement2.getTextContent().toLowerCase());
                            topicDescriptionInstance
                                    .setEnableBatchedOperations(enableBatchedOperationsInstance);
                        }

                        Element sizeInBytesElement2 = XmlUtility.getElementByTagNameNS(topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "SizeInBytes");
                        if (sizeInBytesElement2 != null) {
                            int sizeInBytesInstance;
                            sizeInBytesInstance = DatatypeConverter
                                    .parseInt(sizeInBytesElement2.getTextContent());
                            topicDescriptionInstance.setSizeInBytes(sizeInBytesInstance);
                        }

                        Element filteringMessagesBeforePublishingElement2 = XmlUtility.getElementByTagNameNS(
                                topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "FilteringMessagesBeforePublishing");
                        if (filteringMessagesBeforePublishingElement2 != null) {
                            boolean filteringMessagesBeforePublishingInstance;
                            filteringMessagesBeforePublishingInstance = DatatypeConverter.parseBoolean(
                                    filteringMessagesBeforePublishingElement2.getTextContent().toLowerCase());
                            topicDescriptionInstance.setFilteringMessagesBeforePublishing(
                                    filteringMessagesBeforePublishingInstance);
                        }

                        Element isAnonymousAccessibleElement2 = XmlUtility.getElementByTagNameNS(
                                topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "IsAnonymousAccessible");
                        if (isAnonymousAccessibleElement2 != null) {
                            boolean isAnonymousAccessibleInstance;
                            isAnonymousAccessibleInstance = DatatypeConverter
                                    .parseBoolean(isAnonymousAccessibleElement2.getTextContent().toLowerCase());
                            topicDescriptionInstance.setIsAnonymousAccessible(isAnonymousAccessibleInstance);
                        }

                        Element authorizationRulesSequenceElement2 = XmlUtility.getElementByTagNameNS(
                                topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "AuthorizationRules");
                        if (authorizationRulesSequenceElement2 != null) {
                            for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(authorizationRulesSequenceElement2,
                                            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                            "AuthorizationRule")
                                    .size(); i1 = i1 + 1) {
                                org.w3c.dom.Element authorizationRulesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                        .getElementsByTagNameNS(authorizationRulesSequenceElement2,
                                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                                "AuthorizationRule")
                                        .get(i1));
                                ServiceBusSharedAccessAuthorizationRule authorizationRuleInstance = new ServiceBusSharedAccessAuthorizationRule();
                                topicDescriptionInstance.getAuthorizationRules().add(authorizationRuleInstance);

                                Element claimTypeElement2 = XmlUtility.getElementByTagNameNS(
                                        authorizationRulesElement,
                                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                        "ClaimType");
                                if (claimTypeElement2 != null) {
                                    String claimTypeInstance;
                                    claimTypeInstance = claimTypeElement2.getTextContent();
                                    authorizationRuleInstance.setClaimType(claimTypeInstance);
                                }

                                Element claimValueElement2 = XmlUtility.getElementByTagNameNS(
                                        authorizationRulesElement,
                                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                        "ClaimValue");
                                if (claimValueElement2 != null) {
                                    String claimValueInstance;
                                    claimValueInstance = claimValueElement2.getTextContent();
                                    authorizationRuleInstance.setClaimValue(claimValueInstance);
                                }

                                Element rightsSequenceElement2 = XmlUtility.getElementByTagNameNS(
                                        authorizationRulesElement,
                                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                        "Rights");
                                if (rightsSequenceElement2 != null) {
                                    for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility
                                            .getElementsByTagNameNS(rightsSequenceElement2,
                                                    "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                                    "AccessRights")
                                            .size(); i2 = i2 + 1) {
                                        org.w3c.dom.Element rightsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                                .getElementsByTagNameNS(rightsSequenceElement2,
                                                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                                        "AccessRights")
                                                .get(i2));
                                        authorizationRuleInstance.getRights()
                                                .add(AccessRight.valueOf(rightsElement.getTextContent()));
                                    }
                                }

                                Element createdTimeElement2 = XmlUtility.getElementByTagNameNS(
                                        authorizationRulesElement,
                                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                        "CreatedTime");
                                if (createdTimeElement2 != null) {
                                    Calendar createdTimeInstance;
                                    createdTimeInstance = DatatypeConverter
                                            .parseDateTime(createdTimeElement2.getTextContent());
                                    authorizationRuleInstance.setCreatedTime(createdTimeInstance);
                                }

                                Element keyNameElement2 = XmlUtility.getElementByTagNameNS(
                                        authorizationRulesElement,
                                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                        "KeyName");
                                if (keyNameElement2 != null) {
                                    String keyNameInstance;
                                    keyNameInstance = keyNameElement2.getTextContent();
                                    authorizationRuleInstance.setKeyName(keyNameInstance);
                                }

                                Element modifiedTimeElement2 = XmlUtility.getElementByTagNameNS(
                                        authorizationRulesElement,
                                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                        "ModifiedTime");
                                if (modifiedTimeElement2 != null) {
                                    Calendar modifiedTimeInstance;
                                    modifiedTimeInstance = DatatypeConverter
                                            .parseDateTime(modifiedTimeElement2.getTextContent());
                                    authorizationRuleInstance.setModifiedTime(modifiedTimeInstance);
                                }

                                Element primaryKeyElement2 = XmlUtility.getElementByTagNameNS(
                                        authorizationRulesElement,
                                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                        "PrimaryKey");
                                if (primaryKeyElement2 != null) {
                                    String primaryKeyInstance;
                                    primaryKeyInstance = primaryKeyElement2.getTextContent();
                                    authorizationRuleInstance.setPrimaryKey(primaryKeyInstance);
                                }

                                Element secondaryKeyElement2 = XmlUtility.getElementByTagNameNS(
                                        authorizationRulesElement,
                                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                        "SecondaryKey");
                                if (secondaryKeyElement2 != null) {
                                    String secondaryKeyInstance;
                                    secondaryKeyInstance = secondaryKeyElement2.getTextContent();
                                    authorizationRuleInstance.setSecondaryKey(secondaryKeyInstance);
                                }
                            }
                        }

                        Element statusElement2 = XmlUtility.getElementByTagNameNS(topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "Status");
                        if (statusElement2 != null) {
                            String statusInstance;
                            statusInstance = statusElement2.getTextContent();
                            topicDescriptionInstance.setStatus(statusInstance);
                        }

                        Element createdAtElement2 = XmlUtility.getElementByTagNameNS(topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "CreatedAt");
                        if (createdAtElement2 != null) {
                            Calendar createdAtInstance;
                            createdAtInstance = DatatypeConverter
                                    .parseDateTime(createdAtElement2.getTextContent());
                            topicDescriptionInstance.setCreatedAt(createdAtInstance);
                        }

                        Element updatedAtElement2 = XmlUtility.getElementByTagNameNS(topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "UpdatedAt");
                        if (updatedAtElement2 != null) {
                            Calendar updatedAtInstance;
                            updatedAtInstance = DatatypeConverter
                                    .parseDateTime(updatedAtElement2.getTextContent());
                            topicDescriptionInstance.setUpdatedAt(updatedAtInstance);
                        }

                        Element accessedAtElement2 = XmlUtility.getElementByTagNameNS(topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "AccessedAt");
                        if (accessedAtElement2 != null) {
                            Calendar accessedAtInstance;
                            accessedAtInstance = DatatypeConverter
                                    .parseDateTime(accessedAtElement2.getTextContent());
                            topicDescriptionInstance.setAccessedAt(accessedAtInstance);
                        }

                        Element supportOrderingElement2 = XmlUtility.getElementByTagNameNS(
                                topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "SupportOrdering");
                        if (supportOrderingElement2 != null) {
                            boolean supportOrderingInstance;
                            supportOrderingInstance = DatatypeConverter
                                    .parseBoolean(supportOrderingElement2.getTextContent().toLowerCase());
                            topicDescriptionInstance.setSupportOrdering(supportOrderingInstance);
                        }

                        Element countDetailsElement2 = XmlUtility.getElementByTagNameNS(
                                topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "CountDetails");
                        if (countDetailsElement2 != null) {
                            CountDetails countDetailsInstance = new CountDetails();
                            topicDescriptionInstance.setCountDetails(countDetailsInstance);
                        }

                        Element subscriptionCountElement2 = XmlUtility.getElementByTagNameNS(
                                topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "SubscriptionCount");
                        if (subscriptionCountElement2 != null) {
                            int subscriptionCountInstance;
                            subscriptionCountInstance = DatatypeConverter
                                    .parseInt(subscriptionCountElement2.getTextContent());
                            topicDescriptionInstance.setSubscriptionCount(subscriptionCountInstance);
                        }

                        Element autoDeleteOnIdleElement2 = XmlUtility.getElementByTagNameNS(
                                topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "AutoDeleteOnIdle");
                        if (autoDeleteOnIdleElement2 != null) {
                            String autoDeleteOnIdleInstance;
                            autoDeleteOnIdleInstance = autoDeleteOnIdleElement2.getTextContent();
                            topicDescriptionInstance.setAutoDeleteOnIdle(autoDeleteOnIdleInstance);
                        }

                        Element entityAvailabilityStatusElement2 = XmlUtility.getElementByTagNameNS(
                                topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "EntityAvailabilityStatus");
                        if (entityAvailabilityStatusElement2 != null) {
                            String entityAvailabilityStatusInstance;
                            entityAvailabilityStatusInstance = entityAvailabilityStatusElement2
                                    .getTextContent();
                            topicDescriptionInstance
                                    .setEntityAvailabilityStatus(entityAvailabilityStatusInstance);
                        }
                    }
                }
            }

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

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

From source file:dk.statsbiblioteket.doms.central.CentralWebserviceImpl.java

@Override
public SearchResultList findObjects(@WebParam(name = "query", targetNamespace = "") String query,
        @WebParam(name = "offset", targetNamespace = "") int offset,
        @WebParam(name = "pageSize", targetNamespace = "") int pageSize) throws MethodFailedException {
    try {/*from  w ww. j a va  2  s  . c  o  m*/
        log.trace("Entering findObjects with param query=" + query + ", offset=" + offset + ", pageSize="
                + pageSize);

        JSONObject jsonQuery = new JSONObject();
        jsonQuery.put("search.document.resultfields", "recordID, domsshortrecord");
        jsonQuery.put("search.document.query", query);
        jsonQuery.put("search.document.startindex", offset);
        jsonQuery.put("search.document.maxrecords", pageSize);

        SearchWS summaSearch = getSearchWSService();
        String searchResultString = summaSearch.directJSON(jsonQuery.toString());

        Document searchResultDOM = DOM.stringToDOM(searchResultString);
        XPath xPath = XPathFactory.newInstance().newXPath();

        NodeList nodeList = (NodeList) xPath.evaluate("//responsecollection/response/documentresult/record",
                searchResultDOM.getDocumentElement(), XPathConstants.NODESET);

        java.lang.Long hitCount = java.lang.Long
                .parseLong((String) (xPath.evaluate("//responsecollection/response/documentresult/@hitCount",
                        searchResultDOM.getDocumentElement(), XPathConstants.STRING)));

        SearchResultList searchResultList = new SearchResultList();
        searchResultList.setHitCount(hitCount);

        for (int i = 0; i < nodeList.getLength(); ++i) {
            Node node = nodeList.item(i);
            SearchResult searchResult = new SearchResult();

            Node shortRecordNode = (Node) xPath.evaluate("field[@name='domsshortrecord']", node,
                    XPathConstants.NODE);

            if (shortRecordNode != null) {
                Node shortRecord = DOM.stringToDOM(shortRecordNode.getTextContent()).getDocumentElement();
                String pid = xPath.evaluate("pid", shortRecord);
                String title = xPath.evaluate("title", shortRecord);
                searchResult.setPid(pid);
                if (title != null && !title.equals("")) {
                    searchResult.setTitle(title);
                } else {
                    searchResult.setTitle(pid);
                }
                searchResult.setType(xPath.evaluate("type", shortRecord));
                searchResult.setSource(xPath.evaluate("source", shortRecord));
                searchResult.setTime(xPath.evaluate("time", shortRecord));
                searchResult.setDescription(xPath.evaluate("description", shortRecord));
                searchResult.setState(xPath.evaluate("state", shortRecord));

                try {
                    searchResult.setCreatedDate(DatatypeConverter
                            .parseDateTime(xPath.evaluate("createdDate", shortRecord)).getTimeInMillis());
                } catch (IllegalArgumentException ignored) {
                }
                try {
                    searchResult.setModifiedDate(DatatypeConverter
                            .parseDateTime(xPath.evaluate("modifiedDate", shortRecord)).getTimeInMillis());
                } catch (IllegalArgumentException ignored) {
                }
            } else {
                String pid = xPath.evaluate("field[@name='recordID']/text()", node);
                pid = pid.substring(pid.indexOf(':') + 1);
                searchResult.setPid(pid);
                searchResult.setTitle(pid);
                searchResult.setDescription("");
                searchResult.setSource("");
                searchResult.setState("");
                searchResult.setTime("");
                searchResult.setType("");
            }

            searchResultList.getSearchResult().add(searchResult);
        }

        return searchResultList;

    } catch (XPathExpressionException e) {
        log.warn("Failed to execute method", e);
        throw new MethodFailedException("Method failed to execute", "Method failed to execute", e);
    } catch (Exception e) {
        log.warn("Caught Unknown Exception", e);
        throw new MethodFailedException("Server error", "Server error", e);
    }
}

From source file:com.bluexml.xforms.controller.mapping.MappingToolCommon.java

/**
 * Gets the time from date time.//from   ww  w . j a  v  a 2  s.c om
 * 
 * @param value
 *            the value
 * @return the time from date time
 */
protected String getTimeFromDateTime(String value) {
    Calendar date = DatatypeConverter.parseDateTime(value);
    return DateTimeConverter.convert_AlfrescoToXForms_Time(date.getTimeInMillis());
}

From source file:com.bluexml.xforms.controller.mapping.MappingToolCommon.java

/**
 * Gets the date from date time./*  w w  w .  j a  v  a2 s  . c  o m*/
 * 
 * @param value
 *            the value
 * @return the date from date time
 */
protected String getDateFromDateTime(String value) {
    Calendar date = DatatypeConverter.parseDateTime(value);
    return DateTimeConverter.convert_AlfrescoToXForms_Date(date.getTimeInMillis());
}

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

/**
* Gets the status of the import or export operation in the specified server
* with the corresponding request ID.  The request ID is provided in the
* responses of the import or export operation.
*
* @param serverName Required. The name of the server in which the import or
* export operation is taking place./* ww w  .  j a  v a2 s  .  c  om*/
* @param parameters Required. The parameters needed to get the status of an
* import or export operation.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @throws URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return Represents a list of import or export status values returned from
* GetStatus.
*/
@Override
public DacGetStatusResponse getStatusPost(String serverName, DacGetStatusParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException,
        URISyntaxException {
    // Validate
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getPassword() == null) {
        throw new NullPointerException("parameters.Password");
    }
    if (parameters.getRequestId() == null) {
        throw new NullPointerException("parameters.RequestId");
    }
    if (parameters.getServerName() == null) {
        throw new NullPointerException("parameters.ServerName");
    }
    if (parameters.getUserName() == null) {
        throw new NullPointerException("parameters.UserName");
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

From source file:com.microsoft.azure.management.sql.ReplicationLinkOperationsImpl.java

/**
* Returns information about an Azure SQL Database Replication Link.
*
* @param resourceGroupName Required. The name of the Resource Group to
* which the server belongs.//  ww w. j  a v  a  2 s  .c  om
* @param serverName Required. The name of the Azure SQL Server on which the
* database is hosted.
* @param databaseName Required. The name of the Azure SQL Database to get
* the link for.
* @param linkId Required. The replication link id to be retrieved.
* @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 Get Azure Sql Database Replication
* Link request.
*/
@Override
public ReplicationLinkGetResponse get(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, "getAsync", 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");
    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
    HttpGet httpRequest = new HttpGet(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_OK) {
            ServiceException ex = ServiceException.createFromJson(httpRequest, null, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

        // Create Result
        ReplicationLinkGetResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new ReplicationLinkGetResponse();
            ObjectMapper objectMapper = new ObjectMapper();
            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) {
                ReplicationLink replicationLinkInstance = new ReplicationLink();
                result.setReplicationLink(replicationLinkInstance);

                JsonNode propertiesValue = responseDoc.get("properties");
                if (propertiesValue != null && propertiesValue instanceof NullNode == false) {
                    ReplicationLinkProperties propertiesInstance = new ReplicationLinkProperties();
                    replicationLinkInstance.setProperties(propertiesInstance);

                    JsonNode partnerServerValue = propertiesValue.get("partnerServer");
                    if (partnerServerValue != null && partnerServerValue instanceof NullNode == false) {
                        String partnerServerInstance;
                        partnerServerInstance = partnerServerValue.getTextValue();
                        propertiesInstance.setPartnerServer(partnerServerInstance);
                    }

                    JsonNode partnerDatabaseValue = propertiesValue.get("partnerDatabase");
                    if (partnerDatabaseValue != null && partnerDatabaseValue instanceof NullNode == false) {
                        String partnerDatabaseInstance;
                        partnerDatabaseInstance = partnerDatabaseValue.getTextValue();
                        propertiesInstance.setPartnerDatabase(partnerDatabaseInstance);
                    }

                    JsonNode partnerLocationValue = propertiesValue.get("partnerLocation");
                    if (partnerLocationValue != null && partnerLocationValue instanceof NullNode == false) {
                        String partnerLocationInstance;
                        partnerLocationInstance = partnerLocationValue.getTextValue();
                        propertiesInstance.setPartnerLocation(partnerLocationInstance);
                    }

                    JsonNode roleValue = propertiesValue.get("role");
                    if (roleValue != null && roleValue instanceof NullNode == false) {
                        String roleInstance;
                        roleInstance = roleValue.getTextValue();
                        propertiesInstance.setRole(roleInstance);
                    }

                    JsonNode partnerRoleValue = propertiesValue.get("partnerRole");
                    if (partnerRoleValue != null && partnerRoleValue instanceof NullNode == false) {
                        String partnerRoleInstance;
                        partnerRoleInstance = partnerRoleValue.getTextValue();
                        propertiesInstance.setPartnerRole(partnerRoleInstance);
                    }

                    JsonNode startTimeValue = propertiesValue.get("startTime");
                    if (startTimeValue != null && startTimeValue instanceof NullNode == false) {
                        Calendar startTimeInstance;
                        startTimeInstance = DatatypeConverter.parseDateTime(startTimeValue.getTextValue());
                        propertiesInstance.setStartTime(startTimeInstance);
                    }

                    JsonNode percentCompleteValue = propertiesValue.get("percentComplete");
                    if (percentCompleteValue != null && percentCompleteValue instanceof NullNode == false) {
                        String percentCompleteInstance;
                        percentCompleteInstance = percentCompleteValue.getTextValue();
                        propertiesInstance.setPercentComplete(percentCompleteInstance);
                    }

                    JsonNode replicationStateValue = propertiesValue.get("replicationState");
                    if (replicationStateValue != null && replicationStateValue instanceof NullNode == false) {
                        String replicationStateInstance;
                        replicationStateInstance = replicationStateValue.getTextValue();
                        propertiesInstance.setReplicationState(replicationStateInstance);
                    }
                }

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

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

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

                JsonNode locationValue = responseDoc.get("location");
                if (locationValue != null && locationValue instanceof NullNode == false) {
                    String locationInstance;
                    locationInstance = locationValue.getTextValue();
                    replicationLinkInstance.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();
                        replicationLinkInstance.getTags().put(tagsKey, tagsValue);
                    }
                }
            }

        }
        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.ElasticPoolOperationsImpl.java

/**
* Returns information about an Azure SQL Database Elastic Pool.
*
* @param resourceGroupName Required. The name of the Resource Group to
* which the Azure SQL Database Server belongs.
* @param serverName Required. The name of the Azure SQL Database Server on
* which the Azure SQL Database Elastic Pool is hosted.
* @param elasticPoolName Required. The name of the Azure SQL Database
* Elastic Pool to be retrieved.//from   w  ww . j  ava 2  s  .c om
* @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 Get Azure Sql Elastic Pool request.
*/
@Override
public ElasticPoolGetResponse get(String resourceGroupName, String serverName, String elasticPoolName)
        throws IOException, ServiceException {
    // Validate
    if (resourceGroupName == null) {
        throw new NullPointerException("resourceGroupName");
    }
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }
    if (elasticPoolName == null) {
        throw new NullPointerException("elasticPoolName");
    }

    // 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("elasticPoolName", elasticPoolName);
        CloudTracing.enter(invocationId, this, "getAsync", 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 + "/elasticPools/";
    url = url + URLEncoder.encode(elasticPoolName, "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
    HttpGet httpRequest = new HttpGet(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_OK) {
            ServiceException ex = ServiceException.createFromJson(httpRequest, null, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

        // Create Result
        ElasticPoolGetResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new ElasticPoolGetResponse();
            ObjectMapper objectMapper = new ObjectMapper();
            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) {
                ElasticPool elasticPoolInstance = new ElasticPool();
                result.setElasticPool(elasticPoolInstance);

                JsonNode propertiesValue = responseDoc.get("properties");
                if (propertiesValue != null && propertiesValue instanceof NullNode == false) {
                    ElasticPoolProperties propertiesInstance = new ElasticPoolProperties();
                    elasticPoolInstance.setProperties(propertiesInstance);

                    JsonNode creationDateValue = propertiesValue.get("creationDate");
                    if (creationDateValue != null && creationDateValue instanceof NullNode == false) {
                        Calendar creationDateInstance;
                        creationDateInstance = DatatypeConverter
                                .parseDateTime(creationDateValue.getTextValue());
                        propertiesInstance.setCreationDate(creationDateInstance);
                    }

                    JsonNode stateValue = propertiesValue.get("state");
                    if (stateValue != null && stateValue instanceof NullNode == false) {
                        String stateInstance;
                        stateInstance = stateValue.getTextValue();
                        propertiesInstance.setState(stateInstance);
                    }

                    JsonNode editionValue = propertiesValue.get("edition");
                    if (editionValue != null && editionValue instanceof NullNode == false) {
                        String editionInstance;
                        editionInstance = editionValue.getTextValue();
                        propertiesInstance.setEdition(editionInstance);
                    }

                    JsonNode dtuValue = propertiesValue.get("dtu");
                    if (dtuValue != null && dtuValue instanceof NullNode == false) {
                        int dtuInstance;
                        dtuInstance = dtuValue.getIntValue();
                        propertiesInstance.setDtu(dtuInstance);
                    }

                    JsonNode databaseDtuMaxValue = propertiesValue.get("databaseDtuMax");
                    if (databaseDtuMaxValue != null && databaseDtuMaxValue instanceof NullNode == false) {
                        int databaseDtuMaxInstance;
                        databaseDtuMaxInstance = databaseDtuMaxValue.getIntValue();
                        propertiesInstance.setDatabaseDtuMax(databaseDtuMaxInstance);
                    }

                    JsonNode databaseDtuMinValue = propertiesValue.get("databaseDtuMin");
                    if (databaseDtuMinValue != null && databaseDtuMinValue instanceof NullNode == false) {
                        int databaseDtuMinInstance;
                        databaseDtuMinInstance = databaseDtuMinValue.getIntValue();
                        propertiesInstance.setDatabaseDtuMin(databaseDtuMinInstance);
                    }

                    JsonNode storageMBValue = propertiesValue.get("storageMB");
                    if (storageMBValue != null && storageMBValue instanceof NullNode == false) {
                        int storageMBInstance;
                        storageMBInstance = storageMBValue.getIntValue();
                        propertiesInstance.setStorageMB(storageMBInstance);
                    }
                }

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

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

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

                JsonNode locationValue = responseDoc.get("location");
                if (locationValue != null && locationValue instanceof NullNode == false) {
                    String locationInstance;
                    locationInstance = locationValue.getTextValue();
                    elasticPoolInstance.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();
                        elasticPoolInstance.getTags().put(tagsKey, tagsValue);
                    }
                }
            }

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