com.microsoft.azure.management.compute.VirtualMachineSizeOperationsImpl.java Source code

Java tutorial

Introduction

Here is the source code for com.microsoft.azure.management.compute.VirtualMachineSizeOperationsImpl.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.azure.management.compute;

import com.microsoft.azure.management.compute.models.VirtualMachineSize;
import com.microsoft.azure.management.compute.models.VirtualMachineSizeListResponse;
import com.microsoft.windowsazure.core.ServiceOperations;
import com.microsoft.windowsazure.core.utils.CollectionStringBuilder;
import com.microsoft.windowsazure.exception.ServiceException;
import com.microsoft.windowsazure.tracing.CloudTracing;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.ArrayNode;
import org.codehaus.jackson.node.NullNode;

import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.regex.Pattern;

/**
* Operations for listing virtual machine sizes available in a region.
*/
public class VirtualMachineSizeOperationsImpl
        implements ServiceOperations<ComputeManagementClientImpl>, VirtualMachineSizeOperations {
    /**
    * Initializes a new instance of the VirtualMachineSizeOperationsImpl class.
    *
    * @param client Reference to the service client.
    */
    VirtualMachineSizeOperationsImpl(ComputeManagementClientImpl client) {
        this.client = client;
    }

    private ComputeManagementClientImpl client;

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

    /**
    * Lists virtual-machine-sizes available in a location for a subscription.
    *
    * @param location Required. The location upon which virtual-machine-sizes
    * is queried.
    * @return The List Virtual Machine operation response.
    */
    @Override
    public Future<VirtualMachineSizeListResponse> listAsync(final String location) {
        return this.getClient().getExecutorService().submit(new Callable<VirtualMachineSizeListResponse>() {
            @Override
            public VirtualMachineSizeListResponse call() throws Exception {
                return list(location);
            }
        });
    }

    /**
    * Lists virtual-machine-sizes available in a location for a subscription.
    *
    * @param location Required. The location upon which virtual-machine-sizes
    * is 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 URISyntaxException Thrown if there was an error parsing a URI in
    * the response.
    * @return The List Virtual Machine operation response.
    */
    @Override
    public VirtualMachineSizeListResponse list(String location)
            throws IOException, ServiceException, URISyntaxException {
        // Validate
        if (location == null) {
            throw new NullPointerException("location");
        }
        if (location != null && location.length() > 1000) {
            throw new IllegalArgumentException("location");
        }
        if (Pattern.matches("^[-\\w\\._]+$", location) == false) {
            throw new IllegalArgumentException("location");
        }

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

        // Construct URL
        String url = "";
        url = url + "/subscriptions/";
        if (this.getClient().getCredentials().getSubscriptionId() != null) {
            url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
        }
        url = url + "/providers/";
        url = url + "Microsoft.Compute";
        url = url + "/locations/";
        url = url + URLEncoder.encode(location, "UTF-8");
        url = url + "/vmSizes";
        ArrayList<String> queryParameters = new ArrayList<String>();
        queryParameters.add("api-version=" + "2015-06-15");
        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("Content-Type", "application/json");

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

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

                if (responseDoc != null && responseDoc instanceof NullNode == false) {
                    JsonNode valueArray = responseDoc.get("value");
                    if (valueArray != null && valueArray instanceof NullNode == false) {
                        for (JsonNode valueValue : ((ArrayNode) valueArray)) {
                            VirtualMachineSize virtualMachineSizeInstance = new VirtualMachineSize();
                            result.getVirtualMachineSizes().add(virtualMachineSizeInstance);

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

                            JsonNode numberOfCoresValue = valueValue.get("numberOfCores");
                            if (numberOfCoresValue != null && numberOfCoresValue instanceof NullNode == false) {
                                int numberOfCoresInstance;
                                numberOfCoresInstance = numberOfCoresValue.getIntValue();
                                virtualMachineSizeInstance.setNumberOfCores(numberOfCoresInstance);
                            }

                            JsonNode osDiskSizeInMBValue = valueValue.get("osDiskSizeInMB");
                            if (osDiskSizeInMBValue != null && osDiskSizeInMBValue instanceof NullNode == false) {
                                int osDiskSizeInMBInstance;
                                osDiskSizeInMBInstance = osDiskSizeInMBValue.getIntValue();
                                virtualMachineSizeInstance.setOSDiskSizeInMB(osDiskSizeInMBInstance);
                            }

                            JsonNode resourceDiskSizeInMBValue = valueValue.get("resourceDiskSizeInMB");
                            if (resourceDiskSizeInMBValue != null
                                    && resourceDiskSizeInMBValue instanceof NullNode == false) {
                                int resourceDiskSizeInMBInstance;
                                resourceDiskSizeInMBInstance = resourceDiskSizeInMBValue.getIntValue();
                                virtualMachineSizeInstance.setResourceDiskSizeInMB(resourceDiskSizeInMBInstance);
                            }

                            JsonNode memoryInMBValue = valueValue.get("memoryInMB");
                            if (memoryInMBValue != null && memoryInMBValue instanceof NullNode == false) {
                                int memoryInMBInstance;
                                memoryInMBInstance = memoryInMBValue.getIntValue();
                                virtualMachineSizeInstance.setMemoryInMB(memoryInMBInstance);
                            }

                            JsonNode maxDataDiskCountValue = valueValue.get("maxDataDiskCount");
                            if (maxDataDiskCountValue != null
                                    && maxDataDiskCountValue instanceof NullNode == false) {
                                int maxDataDiskCountInstance;
                                maxDataDiskCountInstance = maxDataDiskCountValue.getIntValue();
                                virtualMachineSizeInstance.setMaxDataDiskCount(maxDataDiskCountInstance);
                            }
                        }
                    }
                }

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