com.microsoft.windowsazure.management.sql.DatabaseOperationOperationsImpl.java Source code

Java tutorial

Introduction

Here is the source code for com.microsoft.windowsazure.management.sql.DatabaseOperationOperationsImpl.java

Source

/**
 * 
 * Copyright (c) Microsoft and contributors.  All rights reserved.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * 
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */

// Warning: This code was generated by a tool.
// 
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.

package com.microsoft.windowsazure.management.sql;

import com.microsoft.windowsazure.core.ServiceOperations;
import com.microsoft.windowsazure.core.utils.BOMInputStream;
import com.microsoft.windowsazure.core.utils.CollectionStringBuilder;
import com.microsoft.windowsazure.core.utils.XmlUtility;
import com.microsoft.windowsazure.exception.ServiceException;
import com.microsoft.windowsazure.management.sql.models.DatabaseOperation;
import com.microsoft.windowsazure.management.sql.models.DatabaseOperationGetResponse;
import com.microsoft.windowsazure.management.sql.models.DatabaseOperationListResponse;
import com.microsoft.windowsazure.tracing.CloudTracing;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

import javax.xml.bind.DatatypeConverter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;

/**
* The Azure SQL Database Management API includes operations for getting
* database operations. Specifically, this API allows you to get a specific
* operation, or to list all the operations that happened on a specific
* database or on all databases in the Azure SQL Database Server.
*/
public class DatabaseOperationOperationsImpl
        implements ServiceOperations<SqlManagementClientImpl>, DatabaseOperationOperations {
    /**
    * Initializes a new instance of the DatabaseOperationOperationsImpl class.
    *
    * @param client Reference to the service client.
    */
    DatabaseOperationOperationsImpl(SqlManagementClientImpl client) {
        this.client = client;
    }

    private SqlManagementClientImpl client;

    /**
    * Gets a reference to the
    * microsoft.windowsazure.management.sql.SqlManagementClientImpl.
    * @return The Client value.
    */
    public SqlManagementClientImpl getClient() {
        return this.client;
    }

    /**
    * Returns information about a specific operation by using the operation
    * Guid.
    *
    * @param serverName Required. The name of the Azure SQL Database Server
    * where the database is hosted.
    * @param operationGuid Required. The Guid of the Azure SQL Database
    * operation to be obtained.
    * @return Represents the database operation for a given operation Guid.
    */
    @Override
    public Future<DatabaseOperationGetResponse> getAsync(final String serverName, final String operationGuid) {
        return this.getClient().getExecutorService().submit(new Callable<DatabaseOperationGetResponse>() {
            @Override
            public DatabaseOperationGetResponse call() throws Exception {
                return get(serverName, operationGuid);
            }
        });
    }

    /**
    * Returns information about a specific operation by using the operation
    * Guid.
    *
    * @param serverName Required. The name of the Azure SQL Database Server
    * where the database is hosted.
    * @param operationGuid Required. The Guid of the Azure SQL Database
    * operation to be obtained.
    * @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 database operation for a given operation Guid.
    */
    @Override
    public DatabaseOperationGetResponse get(String serverName, String operationGuid)
            throws IOException, ServiceException, ParserConfigurationException, SAXException {
        // Validate
        if (serverName == null) {
            throw new NullPointerException("serverName");
        }
        if (operationGuid == null) {
            throw new NullPointerException("operationGuid");
        }

        // 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("operationGuid", operationGuid);
            CloudTracing.enter(invocationId, this, "getAsync", 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/";
        url = url + URLEncoder.encode(operationGuid, "UTF-8");
        String baseUrl = this.getClient().getBaseUri().toString();
        // Trim '/' character from the end of baseUrl and beginning of url.
        if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
            baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
        }
        if (url.charAt(0) == '/') {
            url = url.substring(1);
        }
        url = baseUrl + "/" + url;
        url = url.replace(" ", "%20");

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                    Element stateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement,
                            "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();
            }
        }
    }

    /**
    * Retrieves all of the operations that took place on a specific database.
    *
    * @param serverName Required. The name of the Azure SQL Database Server
    * that hosts the database.
    * @param databaseName Required. The name of the database for which the
    * operations should be retrieved.
    * @return Represents the response containing the list of database
    * operations for a given server or database.
    */
    @Override
    public Future<DatabaseOperationListResponse> listByDatabaseAsync(final String serverName,
            final String databaseName) {
        return this.getClient().getExecutorService().submit(new Callable<DatabaseOperationListResponse>() {
            @Override
            public DatabaseOperationListResponse call() throws Exception {
                return listByDatabase(serverName, databaseName);
            }
        });
    }

    /**
    * Retrieves all of the operations that took place on a specific database.
    *
    * @param serverName Required. The name of the Azure SQL Database Server
    * that hosts the database.
    * @param databaseName Required. The name of the database for which the
    * operations should 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.
    * @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 listByDatabase(String serverName, String databaseName)
            throws IOException, ServiceException, ParserConfigurationException, SAXException {
        // Validate
        if (serverName == null) {
            throw new NullPointerException("serverName");
        }
        if (databaseName == null) {
            throw new NullPointerException("databaseName");
        }

        // Tracing
        boolean shouldTrace = CloudTracing.getIsEnabled();
        String invocationId = null;
        if (shouldTrace) {
            invocationId = Long.toString(CloudTracing.getNextInvocationId());
            HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
            tracingParameters.put("serverName", serverName);
            tracingParameters.put("databaseName", databaseName);
            CloudTracing.enter(invocationId, this, "listByDatabaseAsync", 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("databaseName=" + URLEncoder.encode(databaseName, "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", "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();
            }
        }
    }

    /**
    * Retrieves all of the operations that occured on the Azure SQL Database
    * Server.
    *
    * @param serverName Required. The name of the Azure SQL Database Server to
    * be queried.
    * @return Represents the response containing the list of database
    * operations for a given server or database.
    */
    @Override
    public Future<DatabaseOperationListResponse> listByServerAsync(final String serverName) {
        return this.getClient().getExecutorService().submit(new Callable<DatabaseOperationListResponse>() {
            @Override
            public DatabaseOperationListResponse call() throws Exception {
                return listByServer(serverName);
            }
        });
    }

    /**
    * Retrieves all of the operations that occured on the Azure SQL Database
    * Server.
    *
    * @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();
            }
        }
    }
}