com.microsoft.windowsazure.management.scheduler.JobCollectionOperationsImpl.java Source code

Java tutorial

Introduction

Here is the source code for com.microsoft.windowsazure.management.scheduler.JobCollectionOperationsImpl.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.scheduler;

import com.microsoft.windowsazure.core.OperationResponse;
import com.microsoft.windowsazure.core.ServiceOperations;
import com.microsoft.windowsazure.core.pipeline.apache.CustomHttpDelete;
import com.microsoft.windowsazure.core.utils.BOMInputStream;
import com.microsoft.windowsazure.core.utils.Base64;
import com.microsoft.windowsazure.core.utils.CollectionStringBuilder;
import com.microsoft.windowsazure.core.utils.XmlUtility;
import com.microsoft.windowsazure.exception.CloudError;
import com.microsoft.windowsazure.exception.ServiceException;
import com.microsoft.windowsazure.management.scheduler.models.JobCollectionCheckNameAvailabilityResponse;
import com.microsoft.windowsazure.management.scheduler.models.JobCollectionCreateParameters;
import com.microsoft.windowsazure.management.scheduler.models.JobCollectionCreateResponse;
import com.microsoft.windowsazure.management.scheduler.models.JobCollectionGetResponse;
import com.microsoft.windowsazure.management.scheduler.models.JobCollectionIntrinsicSettings;
import com.microsoft.windowsazure.management.scheduler.models.JobCollectionMaxRecurrence;
import com.microsoft.windowsazure.management.scheduler.models.JobCollectionPlan;
import com.microsoft.windowsazure.management.scheduler.models.JobCollectionQuota;
import com.microsoft.windowsazure.management.scheduler.models.JobCollectionRecurrenceFrequency;
import com.microsoft.windowsazure.management.scheduler.models.JobCollectionState;
import com.microsoft.windowsazure.management.scheduler.models.JobCollectionUpdateParameters;
import com.microsoft.windowsazure.management.scheduler.models.JobCollectionUpdateResponse;
import com.microsoft.windowsazure.management.scheduler.models.SchedulerOperationStatus;
import com.microsoft.windowsazure.management.scheduler.models.SchedulerOperationStatusResponse;
import com.microsoft.windowsazure.tracing.ClientRequestTrackingHandler;
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.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
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 javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

public class JobCollectionOperationsImpl
        implements ServiceOperations<SchedulerManagementClientImpl>, JobCollectionOperations {
    /**
    * Initializes a new instance of the JobCollectionOperationsImpl class.
    *
    * @param client Reference to the service client.
    */
    JobCollectionOperationsImpl(SchedulerManagementClientImpl client) {
        this.client = client;
    }

    private SchedulerManagementClientImpl client;

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

    /**
    * Create a job collection.
    *
    * @param cloudServiceName Required. The name of the cloud service
    * containing the job collection.
    * @param jobCollectionName Required. The name of the job collection to
    * create.
    * @param parameters Required. Parameters supplied to the Create Job
    * Collection operation.
    * @return The Create Job Collection operation response.
    */
    @Override
    public Future<JobCollectionCreateResponse> beginCreatingAsync(final String cloudServiceName,
            final String jobCollectionName, final JobCollectionCreateParameters parameters) {
        return this.getClient().getExecutorService().submit(new Callable<JobCollectionCreateResponse>() {
            @Override
            public JobCollectionCreateResponse call() throws Exception {
                return beginCreating(cloudServiceName, jobCollectionName, parameters);
            }
        });
    }

    /**
    * Create a job collection.
    *
    * @param cloudServiceName Required. The name of the cloud service
    * containing the job collection.
    * @param jobCollectionName Required. The name of the job collection to
    * create.
    * @param parameters Required. Parameters supplied to the Create Job
    * Collection operation.
    * @throws ParserConfigurationException Thrown if there was an error
    * configuring the parser for the response body.
    * @throws SAXException Thrown if there was an error parsing the response
    * body.
    * @throws TransformerException Thrown if there was an error creating the
    * DOM transformer.
    * @throws IOException Signals that an I/O exception of some sort has
    * occurred. This class is the general class of exceptions produced by
    * failed or interrupted I/O operations.
    * @throws ServiceException Thrown if an unexpected response is found.
    * @return The Create Job Collection operation response.
    */
    @Override
    public JobCollectionCreateResponse beginCreating(String cloudServiceName, String jobCollectionName,
            JobCollectionCreateParameters parameters)
            throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
        // Validate
        if (cloudServiceName == null) {
            throw new NullPointerException("cloudServiceName");
        }
        if (jobCollectionName == null) {
            throw new NullPointerException("jobCollectionName");
        }
        if (jobCollectionName.length() > 100) {
            throw new IllegalArgumentException("jobCollectionName");
        }
        if (parameters == null) {
            throw new NullPointerException("parameters");
        }
        if (parameters.getIntrinsicSettings() != null) {
            if (parameters.getIntrinsicSettings().getQuota() != null) {
                if (parameters.getIntrinsicSettings().getQuota().getMaxRecurrence() != null) {
                    if (parameters.getIntrinsicSettings().getQuota().getMaxRecurrence().getFrequency() == null) {
                        throw new NullPointerException(
                                "parameters.IntrinsicSettings.Quota.MaxRecurrence.Frequency");
                    }
                }
            }
        }

        // 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("cloudServiceName", cloudServiceName);
            tracingParameters.put("jobCollectionName", jobCollectionName);
            tracingParameters.put("parameters", parameters);
            CloudTracing.enter(invocationId, this, "beginCreatingAsync", tracingParameters);
        }

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

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

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

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

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

        if (parameters.getSchemaVersion() != null) {
            Element schemaVersionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "SchemaVersion");
            schemaVersionElement.appendChild(requestDoc.createTextNode(parameters.getSchemaVersion()));
            resourceElement.appendChild(schemaVersionElement);
        }

        if (parameters.getIntrinsicSettings() != null) {
            Element intrinsicSettingsElement = requestDoc
                    .createElementNS("http://schemas.microsoft.com/windowsazure", "IntrinsicSettings");
            resourceElement.appendChild(intrinsicSettingsElement);

            if (parameters.getIntrinsicSettings().getPlan() != null) {
                Element planElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                        "Plan");
                planElement.appendChild(
                        requestDoc.createTextNode(parameters.getIntrinsicSettings().getPlan().toString()));
                intrinsicSettingsElement.appendChild(planElement);
            }

            if (parameters.getIntrinsicSettings().getQuota() != null) {
                Element quotaElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                        "Quota");
                intrinsicSettingsElement.appendChild(quotaElement);

                if (parameters.getIntrinsicSettings().getQuota().getMaxJobCount() != null) {
                    Element maxJobCountElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "MaxJobCount");
                    maxJobCountElement.appendChild(requestDoc.createTextNode(
                            Integer.toString(parameters.getIntrinsicSettings().getQuota().getMaxJobCount())));
                    quotaElement.appendChild(maxJobCountElement);
                }

                if (parameters.getIntrinsicSettings().getQuota().getMaxJobOccurrence() != null) {
                    Element maxJobOccurrenceElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "MaxJobOccurrence");
                    maxJobOccurrenceElement.appendChild(requestDoc.createTextNode(
                            Integer.toString(parameters.getIntrinsicSettings().getQuota().getMaxJobOccurrence())));
                    quotaElement.appendChild(maxJobOccurrenceElement);
                }

                if (parameters.getIntrinsicSettings().getQuota().getMaxRecurrence() != null) {
                    Element maxRecurrenceElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "MaxRecurrence");
                    quotaElement.appendChild(maxRecurrenceElement);

                    Element frequencyElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Frequency");
                    frequencyElement.appendChild(requestDoc.createTextNode(parameters.getIntrinsicSettings()
                            .getQuota().getMaxRecurrence().getFrequency().toString()));
                    maxRecurrenceElement.appendChild(frequencyElement);

                    Element intervalElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Interval");
                    intervalElement.appendChild(requestDoc.createTextNode(Integer.toString(
                            parameters.getIntrinsicSettings().getQuota().getMaxRecurrence().getInterval())));
                    maxRecurrenceElement.appendChild(intervalElement);
                }
            }
        }

        if (parameters.getLabel() != null) {
            Element labelElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Label");
            labelElement.appendChild(requestDoc.createTextNode(Base64.encode(parameters.getLabel().getBytes())));
            resourceElement.appendChild(labelElement);
        }

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

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

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

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

    /**
    * Deletes a job collection.
    *
    * @param cloudServiceName Required. The name of the cloud service.
    * @param jobCollectionName Required. The name of the job collection to
    * delete.
    * @return A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public Future<OperationResponse> beginDeletingAsync(final String cloudServiceName,
            final String jobCollectionName) {
        return this.getClient().getExecutorService().submit(new Callable<OperationResponse>() {
            @Override
            public OperationResponse call() throws Exception {
                return beginDeleting(cloudServiceName, jobCollectionName);
            }
        });
    }

    /**
    * Deletes a job collection.
    *
    * @param cloudServiceName Required. The name of the cloud service.
    * @param jobCollectionName Required. The name of the job collection to
    * delete.
    * @throws IOException Signals that an I/O exception of some sort has
    * occurred. This class is the general class of exceptions produced by
    * failed or interrupted I/O operations.
    * @throws ServiceException Thrown if an unexpected response is found.
    * @return A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public OperationResponse beginDeleting(String cloudServiceName, String jobCollectionName)
            throws IOException, ServiceException {
        // Validate
        if (cloudServiceName == null) {
            throw new NullPointerException("cloudServiceName");
        }
        if (jobCollectionName == null) {
            throw new NullPointerException("jobCollectionName");
        }

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

        // Construct URL
        String url = "";
        if (this.getClient().getCredentials().getSubscriptionId() != null) {
            url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
        }
        url = url + "/cloudservices/";
        url = url + URLEncoder.encode(cloudServiceName, "UTF-8");
        url = url + "/resources/";
        url = url + "scheduler";
        url = url + "/";
        url = url + "JobCollections";
        url = url + "/";
        url = url + URLEncoder.encode(jobCollectionName, "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
        CustomHttpDelete httpRequest = new CustomHttpDelete(url);

        // Set Headers
        httpRequest.setHeader("x-ms-version", "2013-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_ACCEPTED) {
                ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse,
                        httpResponse.getEntity());
                if (shouldTrace) {
                    CloudTracing.error(invocationId, ex);
                }
                throw ex;
            }

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

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

    /**
    * Update a job collection.
    *
    * @param cloudServiceName Required. The name of the cloud service
    * containing the job collection.
    * @param jobCollectionName Required. The name of the job collection to
    * update.
    * @param parameters Required. Parameters supplied to the Update Job
    * Collection operation.
    * @return The Update Job Collection operation response.
    */
    @Override
    public Future<JobCollectionUpdateResponse> beginUpdatingAsync(final String cloudServiceName,
            final String jobCollectionName, final JobCollectionUpdateParameters parameters) {
        return this.getClient().getExecutorService().submit(new Callable<JobCollectionUpdateResponse>() {
            @Override
            public JobCollectionUpdateResponse call() throws Exception {
                return beginUpdating(cloudServiceName, jobCollectionName, parameters);
            }
        });
    }

    /**
    * Update a job collection.
    *
    * @param cloudServiceName Required. The name of the cloud service
    * containing the job collection.
    * @param jobCollectionName Required. The name of the job collection to
    * update.
    * @param parameters Required. Parameters supplied to the Update Job
    * Collection operation.
    * @throws ParserConfigurationException Thrown if there was an error
    * configuring the parser for the response body.
    * @throws SAXException Thrown if there was an error parsing the response
    * body.
    * @throws TransformerException Thrown if there was an error creating the
    * DOM transformer.
    * @throws IOException Signals that an I/O exception of some sort has
    * occurred. This class is the general class of exceptions produced by
    * failed or interrupted I/O operations.
    * @throws ServiceException Thrown if an unexpected response is found.
    * @return The Update Job Collection operation response.
    */
    @Override
    public JobCollectionUpdateResponse beginUpdating(String cloudServiceName, String jobCollectionName,
            JobCollectionUpdateParameters parameters)
            throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
        // Validate
        if (cloudServiceName == null) {
            throw new NullPointerException("cloudServiceName");
        }
        if (jobCollectionName == null) {
            throw new NullPointerException("jobCollectionName");
        }
        if (jobCollectionName.length() > 100) {
            throw new IllegalArgumentException("jobCollectionName");
        }
        if (parameters == null) {
            throw new NullPointerException("parameters");
        }
        if (parameters.getETag() == null) {
            throw new NullPointerException("parameters.ETag");
        }
        if (parameters.getIntrinsicSettings() != null) {
            if (parameters.getIntrinsicSettings().getQuota() != null) {
                if (parameters.getIntrinsicSettings().getQuota().getMaxRecurrence() != null) {
                    if (parameters.getIntrinsicSettings().getQuota().getMaxRecurrence().getFrequency() == null) {
                        throw new NullPointerException(
                                "parameters.IntrinsicSettings.Quota.MaxRecurrence.Frequency");
                    }
                }
            }
        }

        // 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("cloudServiceName", cloudServiceName);
            tracingParameters.put("jobCollectionName", jobCollectionName);
            tracingParameters.put("parameters", parameters);
            CloudTracing.enter(invocationId, this, "beginUpdatingAsync", tracingParameters);
        }

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

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

        // Set Headers
        httpRequest.setHeader("Content-Type", "application/xml");
        httpRequest.setHeader("If-Match", parameters.getETag());
        httpRequest.setHeader("x-ms-version", "2013-03-01");

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

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

        if (parameters.getSchemaVersion() != null) {
            Element schemaVersionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "SchemaVersion");
            schemaVersionElement.appendChild(requestDoc.createTextNode(parameters.getSchemaVersion()));
            resourceElement.appendChild(schemaVersionElement);
        }

        Element eTagElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ETag");
        resourceElement.appendChild(eTagElement);

        if (parameters.getIntrinsicSettings() != null) {
            Element intrinsicSettingsElement = requestDoc
                    .createElementNS("http://schemas.microsoft.com/windowsazure", "IntrinsicSettings");
            resourceElement.appendChild(intrinsicSettingsElement);

            if (parameters.getIntrinsicSettings().getPlan() != null) {
                Element planElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                        "Plan");
                planElement.appendChild(
                        requestDoc.createTextNode(parameters.getIntrinsicSettings().getPlan().toString()));
                intrinsicSettingsElement.appendChild(planElement);
            }

            if (parameters.getIntrinsicSettings().getQuota() != null) {
                Element quotaElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                        "Quota");
                intrinsicSettingsElement.appendChild(quotaElement);

                if (parameters.getIntrinsicSettings().getQuota().getMaxJobCount() != null) {
                    Element maxJobCountElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "MaxJobCount");
                    maxJobCountElement.appendChild(requestDoc.createTextNode(
                            Integer.toString(parameters.getIntrinsicSettings().getQuota().getMaxJobCount())));
                    quotaElement.appendChild(maxJobCountElement);
                }

                if (parameters.getIntrinsicSettings().getQuota().getMaxJobOccurrence() != null) {
                    Element maxJobOccurrenceElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "MaxJobOccurrence");
                    maxJobOccurrenceElement.appendChild(requestDoc.createTextNode(
                            Integer.toString(parameters.getIntrinsicSettings().getQuota().getMaxJobOccurrence())));
                    quotaElement.appendChild(maxJobOccurrenceElement);
                }

                if (parameters.getIntrinsicSettings().getQuota().getMaxRecurrence() != null) {
                    Element maxRecurrenceElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "MaxRecurrence");
                    quotaElement.appendChild(maxRecurrenceElement);

                    Element frequencyElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Frequency");
                    frequencyElement.appendChild(requestDoc.createTextNode(parameters.getIntrinsicSettings()
                            .getQuota().getMaxRecurrence().getFrequency().toString()));
                    maxRecurrenceElement.appendChild(frequencyElement);

                    Element intervalElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Interval");
                    intervalElement.appendChild(requestDoc.createTextNode(Integer.toString(
                            parameters.getIntrinsicSettings().getQuota().getMaxRecurrence().getInterval())));
                    maxRecurrenceElement.appendChild(intervalElement);
                }
            }
        }

        if (parameters.getLabel() != null) {
            Element labelElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Label");
            labelElement.appendChild(requestDoc.createTextNode(Base64.encode(parameters.getLabel().getBytes())));
            resourceElement.appendChild(labelElement);
        }

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

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

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

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

    /**
    * Determine if the JobCollection name is available to be used.
    * JobCollection names must be unique within a cloud-service.
    *
    * @param cloudServiceName Required. The name of the cloud service.
    * @param jobCollectionName Required. A name for the JobCollection. The name
    * must be unique as scoped within the CloudService.  The name can be up to
    * 100 characters in length.
    * @return The Check Name Availability operation response.
    */
    @Override
    public Future<JobCollectionCheckNameAvailabilityResponse> checkNameAvailabilityAsync(
            final String cloudServiceName, final String jobCollectionName) {
        return this.getClient().getExecutorService()
                .submit(new Callable<JobCollectionCheckNameAvailabilityResponse>() {
                    @Override
                    public JobCollectionCheckNameAvailabilityResponse call() throws Exception {
                        return checkNameAvailability(cloudServiceName, jobCollectionName);
                    }
                });
    }

    /**
    * Determine if the JobCollection name is available to be used.
    * JobCollection names must be unique within a cloud-service.
    *
    * @param cloudServiceName Required. The name of the cloud service.
    * @param jobCollectionName Required. A name for the JobCollection. The name
    * must be unique as scoped within the CloudService.  The name can be up to
    * 100 characters in length.
    * @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 Check Name Availability operation response.
    */
    @Override
    public JobCollectionCheckNameAvailabilityResponse checkNameAvailability(String cloudServiceName,
            String jobCollectionName)
            throws IOException, ServiceException, ParserConfigurationException, SAXException {
        // Validate
        if (cloudServiceName == null) {
            throw new NullPointerException("cloudServiceName");
        }
        if (jobCollectionName == null) {
            throw new NullPointerException("jobCollectionName");
        }
        if (jobCollectionName.length() > 100) {
            throw new IllegalArgumentException("jobCollectionName");
        }

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

        // Construct URL
        String url = "";
        if (this.getClient().getCredentials().getSubscriptionId() != null) {
            url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
        }
        url = url + "/cloudservices/";
        url = url + URLEncoder.encode(cloudServiceName, "UTF-8");
        url = url + "/resources/";
        url = url + "scheduler";
        url = url + "/";
        url = url + "JobCollections";
        url = url + "/";
        ArrayList<String> queryParameters = new ArrayList<String>();
        queryParameters.add("op=checknameavailability");
        queryParameters.add("resourceName=" + URLEncoder.encode(jobCollectionName, "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", "2013-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
            JobCollectionCheckNameAvailabilityResponse result = null;
            // Deserialize Response
            if (statusCode == HttpStatus.SC_OK) {
                InputStream responseContent = httpResponse.getEntity().getContent();
                result = new JobCollectionCheckNameAvailabilityResponse();
                DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                documentBuilderFactory.setNamespaceAware(true);
                DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
                Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));

                Element resourceNameAvailabilityResponseElement = XmlUtility.getElementByTagNameNS(responseDoc,
                        "http://schemas.microsoft.com/windowsazure", "ResourceNameAvailabilityResponse");
                if (resourceNameAvailabilityResponseElement != null) {
                    Element isAvailableElement = XmlUtility.getElementByTagNameNS(
                            resourceNameAvailabilityResponseElement, "http://schemas.microsoft.com/windowsazure",
                            "IsAvailable");
                    if (isAvailableElement != null) {
                        boolean isAvailableInstance;
                        isAvailableInstance = DatatypeConverter
                                .parseBoolean(isAvailableElement.getTextContent().toLowerCase());
                        result.setIsAvailable(isAvailableInstance);
                    }
                }

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

    /**
    * Create a job collection.
    *
    * @param cloudServiceName Required. The name of the cloud service
    * containing the job collection.
    * @param jobCollectionName Required. The name of the job collection to
    * create.
    * @param parameters Required. Parameters supplied to the Create Job
    * Collection operation.
    * @return The response body contains the status of the specified
    * asynchronous operation, indicating whether it has succeeded, is
    * inprogress, or has failed. Note that this status is distinct from the
    * HTTP status code returned for the Get Operation Status operation itself.
    * If the asynchronous operation succeeded, the response body includes the
    * HTTP status code for the successful request.  If the asynchronous
    * operation failed, the response body includes the HTTP status code for
    * the failed request, and also includes error information regarding the
    * failure.
    */
    @Override
    public Future<SchedulerOperationStatusResponse> createAsync(final String cloudServiceName,
            final String jobCollectionName, final JobCollectionCreateParameters parameters) {
        return this.getClient().getExecutorService().submit(new Callable<SchedulerOperationStatusResponse>() {
            @Override
            public SchedulerOperationStatusResponse call() throws Exception {
                return create(cloudServiceName, jobCollectionName, parameters);
            }
        });
    }

    /**
    * Create a job collection.
    *
    * @param cloudServiceName Required. The name of the cloud service
    * containing the job collection.
    * @param jobCollectionName Required. The name of the job collection to
    * create.
    * @param parameters Required. Parameters supplied to the Create Job
    * Collection operation.
    * @throws InterruptedException Thrown when a thread is waiting, sleeping,
    * or otherwise occupied, and the thread is interrupted, either before or
    * during the activity. Occasionally a method may wish to test whether the
    * current thread has been interrupted, and if so, to immediately throw
    * this exception. The following code can be used to achieve this effect:
    * @throws ExecutionException Thrown when attempting to retrieve the result
    * of a task that aborted by throwing an exception. This exception can be
    * inspected using the Throwable.getCause() method.
    * @throws ServiceException Thrown if the server returned an error for the
    * request.
    * @throws IOException Thrown if there was an error setting up tracing for
    * the request.
    * @return The response body contains the status of the specified
    * asynchronous operation, indicating whether it has succeeded, is
    * inprogress, or has failed. Note that this status is distinct from the
    * HTTP status code returned for the Get Operation Status operation itself.
    * If the asynchronous operation succeeded, the response body includes the
    * HTTP status code for the successful request.  If the asynchronous
    * operation failed, the response body includes the HTTP status code for
    * the failed request, and also includes error information regarding the
    * failure.
    */
    @Override
    public SchedulerOperationStatusResponse create(String cloudServiceName, String jobCollectionName,
            JobCollectionCreateParameters parameters)
            throws InterruptedException, ExecutionException, ServiceException, IOException {
        SchedulerManagementClient client2 = this.getClient();
        boolean shouldTrace = CloudTracing.getIsEnabled();
        String invocationId = null;
        if (shouldTrace) {
            invocationId = Long.toString(CloudTracing.getNextInvocationId());
            HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
            tracingParameters.put("cloudServiceName", cloudServiceName);
            tracingParameters.put("jobCollectionName", jobCollectionName);
            tracingParameters.put("parameters", parameters);
            CloudTracing.enter(invocationId, this, "createAsync", tracingParameters);
        }
        try {
            if (shouldTrace) {
                client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId))
                        .withResponseFilterLast(new ClientRequestTrackingHandler(invocationId));
            }

            JobCollectionCreateResponse response = client2.getJobCollectionsOperations()
                    .beginCreatingAsync(cloudServiceName, jobCollectionName, parameters).get();
            SchedulerOperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId())
                    .get();
            int delayInSeconds = 15;
            if (client2.getLongRunningOperationInitialTimeout() >= 0) {
                delayInSeconds = client2.getLongRunningOperationInitialTimeout();
            }
            while (result.getStatus() != null && result.getStatus().equals(SchedulerOperationStatus.InProgress)) {
                Thread.sleep(delayInSeconds * 1000);
                result = client2.getOperationStatusAsync(response.getRequestId()).get();
                delayInSeconds = 10;
                if (client2.getLongRunningOperationRetryTimeout() >= 0) {
                    delayInSeconds = client2.getLongRunningOperationRetryTimeout();
                }
            }

            if (shouldTrace) {
                CloudTracing.exit(invocationId, result);
            }

            if (result.getStatus() != SchedulerOperationStatus.Succeeded) {
                if (result.getError() != null) {
                    ServiceException ex = new ServiceException(
                            result.getError().getCode() + " : " + result.getError().getMessage());
                    ex.setError(new CloudError());
                    ex.getError().setCode(result.getError().getCode());
                    ex.getError().setMessage(result.getError().getMessage());
                    if (shouldTrace) {
                        CloudTracing.error(invocationId, ex);
                    }
                    throw ex;
                } else {
                    ServiceException ex = new ServiceException("");
                    if (shouldTrace) {
                        CloudTracing.error(invocationId, ex);
                    }
                    throw ex;
                }
            }

            result.setETag(response.getETag());
            return result;
        } finally {
            if (client2 != null && shouldTrace) {
                client2.close();
            }
        }
    }

    /**
    * Deletes a job collection.
    *
    * @param cloudServiceName Required. The name of the cloud service.
    * @param jobCollectionName Required. The name of the job collection to
    * delete.
    * @return The response body contains the status of the specified
    * asynchronous operation, indicating whether it has succeeded, is
    * inprogress, or has failed. Note that this status is distinct from the
    * HTTP status code returned for the Get Operation Status operation itself.
    * If the asynchronous operation succeeded, the response body includes the
    * HTTP status code for the successful request.  If the asynchronous
    * operation failed, the response body includes the HTTP status code for
    * the failed request, and also includes error information regarding the
    * failure.
    */
    @Override
    public Future<SchedulerOperationStatusResponse> deleteAsync(final String cloudServiceName,
            final String jobCollectionName) {
        return this.getClient().getExecutorService().submit(new Callable<SchedulerOperationStatusResponse>() {
            @Override
            public SchedulerOperationStatusResponse call() throws Exception {
                return delete(cloudServiceName, jobCollectionName);
            }
        });
    }

    /**
    * Deletes a job collection.
    *
    * @param cloudServiceName Required. The name of the cloud service.
    * @param jobCollectionName Required. The name of the job collection to
    * delete.
    * @throws InterruptedException Thrown when a thread is waiting, sleeping,
    * or otherwise occupied, and the thread is interrupted, either before or
    * during the activity. Occasionally a method may wish to test whether the
    * current thread has been interrupted, and if so, to immediately throw
    * this exception. The following code can be used to achieve this effect:
    * @throws ExecutionException Thrown when attempting to retrieve the result
    * of a task that aborted by throwing an exception. This exception can be
    * inspected using the Throwable.getCause() method.
    * @throws ServiceException Thrown if the server returned an error for the
    * request.
    * @throws IOException Thrown if there was an error setting up tracing for
    * the request.
    * @return The response body contains the status of the specified
    * asynchronous operation, indicating whether it has succeeded, is
    * inprogress, or has failed. Note that this status is distinct from the
    * HTTP status code returned for the Get Operation Status operation itself.
    * If the asynchronous operation succeeded, the response body includes the
    * HTTP status code for the successful request.  If the asynchronous
    * operation failed, the response body includes the HTTP status code for
    * the failed request, and also includes error information regarding the
    * failure.
    */
    @Override
    public SchedulerOperationStatusResponse delete(String cloudServiceName, String jobCollectionName)
            throws InterruptedException, ExecutionException, ServiceException, IOException {
        SchedulerManagementClient client2 = this.getClient();
        boolean shouldTrace = CloudTracing.getIsEnabled();
        String invocationId = null;
        if (shouldTrace) {
            invocationId = Long.toString(CloudTracing.getNextInvocationId());
            HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
            tracingParameters.put("cloudServiceName", cloudServiceName);
            tracingParameters.put("jobCollectionName", jobCollectionName);
            CloudTracing.enter(invocationId, this, "deleteAsync", tracingParameters);
        }
        try {
            if (shouldTrace) {
                client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId))
                        .withResponseFilterLast(new ClientRequestTrackingHandler(invocationId));
            }

            OperationResponse response = client2.getJobCollectionsOperations()
                    .beginDeletingAsync(cloudServiceName, jobCollectionName).get();
            SchedulerOperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId())
                    .get();
            int delayInSeconds = 15;
            if (client2.getLongRunningOperationInitialTimeout() >= 0) {
                delayInSeconds = client2.getLongRunningOperationInitialTimeout();
            }
            while (result.getStatus() != null && result.getStatus().equals(SchedulerOperationStatus.InProgress)) {
                Thread.sleep(delayInSeconds * 1000);
                result = client2.getOperationStatusAsync(response.getRequestId()).get();
                delayInSeconds = 10;
                if (client2.getLongRunningOperationRetryTimeout() >= 0) {
                    delayInSeconds = client2.getLongRunningOperationRetryTimeout();
                }
            }

            if (shouldTrace) {
                CloudTracing.exit(invocationId, result);
            }

            if (result.getStatus() != SchedulerOperationStatus.Succeeded) {
                if (result.getError() != null) {
                    ServiceException ex = new ServiceException(
                            result.getError().getCode() + " : " + result.getError().getMessage());
                    ex.setError(new CloudError());
                    ex.getError().setCode(result.getError().getCode());
                    ex.getError().setMessage(result.getError().getMessage());
                    if (shouldTrace) {
                        CloudTracing.error(invocationId, ex);
                    }
                    throw ex;
                } else {
                    ServiceException ex = new ServiceException("");
                    if (shouldTrace) {
                        CloudTracing.error(invocationId, ex);
                    }
                    throw ex;
                }
            }

            return result;
        } finally {
            if (client2 != null && shouldTrace) {
                client2.close();
            }
        }
    }

    /**
    * Retreive a job collection.
    *
    * @param cloudServiceName Required. Name of the cloud service.
    * @param jobCollectionName Required. Name of the job collection.
    * @return The Get Job Collection operation response.
    */
    @Override
    public Future<JobCollectionGetResponse> getAsync(final String cloudServiceName,
            final String jobCollectionName) {
        return this.getClient().getExecutorService().submit(new Callable<JobCollectionGetResponse>() {
            @Override
            public JobCollectionGetResponse call() throws Exception {
                return get(cloudServiceName, jobCollectionName);
            }
        });
    }

    /**
    * Retreive a job collection.
    *
    * @param cloudServiceName Required. Name of the cloud service.
    * @param jobCollectionName Required. Name of the job collection.
    * @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 Job Collection operation response.
    */
    @Override
    public JobCollectionGetResponse get(String cloudServiceName, String jobCollectionName)
            throws IOException, ServiceException, ParserConfigurationException, SAXException {
        // Validate
        if (cloudServiceName == null) {
            throw new NullPointerException("cloudServiceName");
        }
        if (jobCollectionName == null) {
            throw new NullPointerException("jobCollectionName");
        }

        // 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("cloudServiceName", cloudServiceName);
            tracingParameters.put("jobCollectionName", jobCollectionName);
            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 + "/cloudservices/";
        url = url + URLEncoder.encode(cloudServiceName, "UTF-8");
        url = url + "/resources/";
        url = url + "scheduler";
        url = url + "/~/";
        url = url + "JobCollections";
        url = url + "/";
        url = url + URLEncoder.encode(jobCollectionName, "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", "2013-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
            JobCollectionGetResponse result = null;
            // Deserialize Response
            if (statusCode == HttpStatus.SC_OK) {
                InputStream responseContent = httpResponse.getEntity().getContent();
                result = new JobCollectionGetResponse();
                DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                documentBuilderFactory.setNamespaceAware(true);
                DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
                Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));

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

                    Element eTagElement = XmlUtility.getElementByTagNameNS(resourceElement,
                            "http://schemas.microsoft.com/windowsazure", "ETag");
                    if (eTagElement != null) {
                        String eTagInstance;
                        eTagInstance = eTagElement.getTextContent();
                        result.setETag(eTagInstance);
                    }

                    Element stateElement = XmlUtility.getElementByTagNameNS(resourceElement,
                            "http://schemas.microsoft.com/windowsazure", "State");
                    if (stateElement != null && stateElement.getTextContent() != null
                            && !stateElement.getTextContent().isEmpty()) {
                        JobCollectionState stateInstance;
                        stateInstance = JobCollectionState.valueOf(stateElement.getTextContent());
                        result.setState(stateInstance);
                    }

                    Element schemaVersionElement = XmlUtility.getElementByTagNameNS(resourceElement,
                            "http://schemas.microsoft.com/windowsazure", "SchemaVersion");
                    if (schemaVersionElement != null) {
                        String schemaVersionInstance;
                        schemaVersionInstance = schemaVersionElement.getTextContent();
                        result.setSchemaVersion(schemaVersionInstance);
                    }

                    Element promotionCodeElement = XmlUtility.getElementByTagNameNS(resourceElement,
                            "http://schemas.microsoft.com/windowsazure", "PromotionCode");
                    if (promotionCodeElement != null) {
                        String promotionCodeInstance;
                        promotionCodeInstance = promotionCodeElement.getTextContent();
                        result.setPromotionCode(promotionCodeInstance);
                    }

                    Element intrinsicSettingsElement = XmlUtility.getElementByTagNameNS(resourceElement,
                            "http://schemas.microsoft.com/windowsazure", "IntrinsicSettings");
                    if (intrinsicSettingsElement != null) {
                        JobCollectionIntrinsicSettings intrinsicSettingsInstance = new JobCollectionIntrinsicSettings();
                        result.setIntrinsicSettings(intrinsicSettingsInstance);

                        Element planElement = XmlUtility.getElementByTagNameNS(intrinsicSettingsElement,
                                "http://schemas.microsoft.com/windowsazure", "Plan");
                        if (planElement != null && planElement.getTextContent() != null
                                && !planElement.getTextContent().isEmpty()) {
                            JobCollectionPlan planInstance;
                            planInstance = JobCollectionPlan.valueOf(planElement.getTextContent());
                            intrinsicSettingsInstance.setPlan(planInstance);
                        }

                        Element quotaElement = XmlUtility.getElementByTagNameNS(intrinsicSettingsElement,
                                "http://schemas.microsoft.com/windowsazure", "Quota");
                        if (quotaElement != null) {
                            JobCollectionQuota quotaInstance = new JobCollectionQuota();
                            intrinsicSettingsInstance.setQuota(quotaInstance);

                            Element maxJobCountElement = XmlUtility.getElementByTagNameNS(quotaElement,
                                    "http://schemas.microsoft.com/windowsazure", "MaxJobCount");
                            if (maxJobCountElement != null && maxJobCountElement.getTextContent() != null
                                    && !maxJobCountElement.getTextContent().isEmpty()) {
                                int maxJobCountInstance;
                                maxJobCountInstance = DatatypeConverter
                                        .parseInt(maxJobCountElement.getTextContent());
                                quotaInstance.setMaxJobCount(maxJobCountInstance);
                            }

                            Element maxJobOccurrenceElement = XmlUtility.getElementByTagNameNS(quotaElement,
                                    "http://schemas.microsoft.com/windowsazure", "MaxJobOccurrence");
                            if (maxJobOccurrenceElement != null && maxJobOccurrenceElement.getTextContent() != null
                                    && !maxJobOccurrenceElement.getTextContent().isEmpty()) {
                                int maxJobOccurrenceInstance;
                                maxJobOccurrenceInstance = DatatypeConverter
                                        .parseInt(maxJobOccurrenceElement.getTextContent());
                                quotaInstance.setMaxJobOccurrence(maxJobOccurrenceInstance);
                            }

                            Element maxRecurrenceElement = XmlUtility.getElementByTagNameNS(quotaElement,
                                    "http://schemas.microsoft.com/windowsazure", "MaxRecurrence");
                            if (maxRecurrenceElement != null) {
                                JobCollectionMaxRecurrence maxRecurrenceInstance = new JobCollectionMaxRecurrence();
                                quotaInstance.setMaxRecurrence(maxRecurrenceInstance);

                                Element frequencyElement = XmlUtility.getElementByTagNameNS(maxRecurrenceElement,
                                        "http://schemas.microsoft.com/windowsazure", "Frequency");
                                if (frequencyElement != null && frequencyElement.getTextContent() != null
                                        && !frequencyElement.getTextContent().isEmpty()) {
                                    JobCollectionRecurrenceFrequency frequencyInstance;
                                    frequencyInstance = JobCollectionRecurrenceFrequency
                                            .valueOf(frequencyElement.getTextContent());
                                    maxRecurrenceInstance.setFrequency(frequencyInstance);
                                }

                                Element intervalElement = XmlUtility.getElementByTagNameNS(maxRecurrenceElement,
                                        "http://schemas.microsoft.com/windowsazure", "Interval");
                                if (intervalElement != null) {
                                    int intervalInstance;
                                    intervalInstance = DatatypeConverter.parseInt(intervalElement.getTextContent());
                                    maxRecurrenceInstance.setInterval(intervalInstance);
                                }
                            }
                        }
                    }

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

                    Element operationStatusElement = XmlUtility.getElementByTagNameNS(resourceElement,
                            "http://schemas.microsoft.com/windowsazure", "OperationStatus");
                    if (operationStatusElement != null) {
                        JobCollectionGetResponse.OperationStatus operationStatusInstance = new JobCollectionGetResponse.OperationStatus();
                        result.setLastOperationStatus(operationStatusInstance);

                        Element errorElement = XmlUtility.getElementByTagNameNS(operationStatusElement,
                                "http://schemas.microsoft.com/windowsazure", "Error");
                        if (errorElement != null) {
                            JobCollectionGetResponse.OperationStatusResponseDetails errorInstance = new JobCollectionGetResponse.OperationStatusResponseDetails();
                            operationStatusInstance.setResponseDetails(errorInstance);

                            Element httpCodeElement = XmlUtility.getElementByTagNameNS(errorElement,
                                    "http://schemas.microsoft.com/windowsazure", "HttpCode");
                            if (httpCodeElement != null && httpCodeElement.getTextContent() != null
                                    && !httpCodeElement.getTextContent().isEmpty()) {
                                Integer httpCodeInstance;
                                httpCodeInstance = Integer.valueOf(httpCodeElement.getTextContent());
                                errorInstance.setStatusCode(httpCodeInstance);
                            }

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

                        Element resultElement = XmlUtility.getElementByTagNameNS(operationStatusElement,
                                "http://schemas.microsoft.com/windowsazure", "Result");
                        if (resultElement != null && resultElement.getTextContent() != null
                                && !resultElement.getTextContent().isEmpty()) {
                            SchedulerOperationStatus resultInstance;
                            resultInstance = SchedulerOperationStatus.valueOf(resultElement.getTextContent());
                            operationStatusInstance.setStatus(resultInstance);
                        }
                    }
                }

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

    /**
    * Update a job collection.
    *
    * @param cloudServiceName Required. The name of the cloud service
    * containing the job collection.
    * @param jobCollectionName Required. The name of the job collection to
    * update.
    * @param parameters Required. Parameters supplied to the Update Job
    * Collection operation.
    * @return The response body contains the status of the specified
    * asynchronous operation, indicating whether it has succeeded, is
    * inprogress, or has failed. Note that this status is distinct from the
    * HTTP status code returned for the Get Operation Status operation itself.
    * If the asynchronous operation succeeded, the response body includes the
    * HTTP status code for the successful request.  If the asynchronous
    * operation failed, the response body includes the HTTP status code for
    * the failed request, and also includes error information regarding the
    * failure.
    */
    @Override
    public Future<SchedulerOperationStatusResponse> updateAsync(final String cloudServiceName,
            final String jobCollectionName, final JobCollectionUpdateParameters parameters) {
        return this.getClient().getExecutorService().submit(new Callable<SchedulerOperationStatusResponse>() {
            @Override
            public SchedulerOperationStatusResponse call() throws Exception {
                return update(cloudServiceName, jobCollectionName, parameters);
            }
        });
    }

    /**
    * Update a job collection.
    *
    * @param cloudServiceName Required. The name of the cloud service
    * containing the job collection.
    * @param jobCollectionName Required. The name of the job collection to
    * update.
    * @param parameters Required. Parameters supplied to the Update Job
    * Collection operation.
    * @throws InterruptedException Thrown when a thread is waiting, sleeping,
    * or otherwise occupied, and the thread is interrupted, either before or
    * during the activity. Occasionally a method may wish to test whether the
    * current thread has been interrupted, and if so, to immediately throw
    * this exception. The following code can be used to achieve this effect:
    * @throws ExecutionException Thrown when attempting to retrieve the result
    * of a task that aborted by throwing an exception. This exception can be
    * inspected using the Throwable.getCause() method.
    * @throws ServiceException Thrown if the server returned an error for the
    * request.
    * @throws IOException Thrown if there was an error setting up tracing for
    * the request.
    * @return The response body contains the status of the specified
    * asynchronous operation, indicating whether it has succeeded, is
    * inprogress, or has failed. Note that this status is distinct from the
    * HTTP status code returned for the Get Operation Status operation itself.
    * If the asynchronous operation succeeded, the response body includes the
    * HTTP status code for the successful request.  If the asynchronous
    * operation failed, the response body includes the HTTP status code for
    * the failed request, and also includes error information regarding the
    * failure.
    */
    @Override
    public SchedulerOperationStatusResponse update(String cloudServiceName, String jobCollectionName,
            JobCollectionUpdateParameters parameters)
            throws InterruptedException, ExecutionException, ServiceException, IOException {
        SchedulerManagementClient client2 = this.getClient();
        boolean shouldTrace = CloudTracing.getIsEnabled();
        String invocationId = null;
        if (shouldTrace) {
            invocationId = Long.toString(CloudTracing.getNextInvocationId());
            HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
            tracingParameters.put("cloudServiceName", cloudServiceName);
            tracingParameters.put("jobCollectionName", jobCollectionName);
            tracingParameters.put("parameters", parameters);
            CloudTracing.enter(invocationId, this, "updateAsync", tracingParameters);
        }
        try {
            if (shouldTrace) {
                client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId))
                        .withResponseFilterLast(new ClientRequestTrackingHandler(invocationId));
            }

            JobCollectionUpdateResponse response = client2.getJobCollectionsOperations()
                    .beginUpdatingAsync(cloudServiceName, jobCollectionName, parameters).get();
            SchedulerOperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId())
                    .get();
            int delayInSeconds = 15;
            if (client2.getLongRunningOperationInitialTimeout() >= 0) {
                delayInSeconds = client2.getLongRunningOperationInitialTimeout();
            }
            while (result.getStatus() != null && result.getStatus().equals(SchedulerOperationStatus.InProgress)) {
                Thread.sleep(delayInSeconds * 1000);
                result = client2.getOperationStatusAsync(response.getRequestId()).get();
                delayInSeconds = 10;
                if (client2.getLongRunningOperationRetryTimeout() >= 0) {
                    delayInSeconds = client2.getLongRunningOperationRetryTimeout();
                }
            }

            if (shouldTrace) {
                CloudTracing.exit(invocationId, result);
            }

            if (result.getStatus() != SchedulerOperationStatus.Succeeded) {
                if (result.getError() != null) {
                    ServiceException ex = new ServiceException(
                            result.getError().getCode() + " : " + result.getError().getMessage());
                    ex.setError(new CloudError());
                    ex.getError().setCode(result.getError().getCode());
                    ex.getError().setMessage(result.getError().getMessage());
                    if (shouldTrace) {
                        CloudTracing.error(invocationId, ex);
                    }
                    throw ex;
                } else {
                    ServiceException ex = new ServiceException("");
                    if (shouldTrace) {
                        CloudTracing.error(invocationId, ex);
                    }
                    throw ex;
                }
            }

            result.setETag(response.getETag());
            return result;
        } finally {
            if (client2 != null && shouldTrace) {
                client2.close();
            }
        }
    }
}