Example usage for javax.xml.bind DatatypeConverter parseDateTime

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

Introduction

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

Prototype

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

Source Link

Document

Converts the string argument into a Calendar value.

Usage

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

/**
* The Create OS Image operation adds an operating system image that is
* stored in a storage account and is available from the image repository.
* (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157192.aspx
* for more information)//from   w  ww .j  a  v a2s.c  o  m
*
* @param parameters Required. Parameters supplied to the Create Virtual
* Machine Image 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.
* @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 ServiceException Thrown if an unexpected response is found.
* @throws URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return Parameters returned from the Create Virtual Machine Image
* operation.
*/
@Override
public VirtualMachineOSImageCreateResponse create(VirtualMachineOSImageCreateParameters parameters)
        throws InterruptedException, ExecutionException, ServiceException, IOException,
        ParserConfigurationException, SAXException, TransformerException, URISyntaxException {
    // Validate
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getLabel() == null) {
        throw new NullPointerException("parameters.Label");
    }
    if (parameters.getMediaLinkUri() == null) {
        throw new NullPointerException("parameters.MediaLinkUri");
    }
    if (parameters.getName() == null) {
        throw new NullPointerException("parameters.Name");
    }
    if (parameters.getOperatingSystemType() == null) {
        throw new NullPointerException("parameters.OperatingSystemType");
    }

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

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

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

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

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

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

    Element labelElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Label");
    labelElement.appendChild(requestDoc.createTextNode(parameters.getLabel()));
    oSImageElement.appendChild(labelElement);

    Element mediaLinkElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "MediaLink");
    mediaLinkElement.appendChild(requestDoc.createTextNode(parameters.getMediaLinkUri().toString()));
    oSImageElement.appendChild(mediaLinkElement);

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

    Element osElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "OS");
    osElement.appendChild(requestDoc.createTextNode(parameters.getOperatingSystemType()));
    oSImageElement.appendChild(osElement);

    if (parameters.getEula() != null) {
        Element eulaElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Eula");
        eulaElement.appendChild(requestDoc.createTextNode(parameters.getEula()));
        oSImageElement.appendChild(eulaElement);
    }

    if (parameters.getDescription() != null) {
        Element descriptionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "Description");
        descriptionElement.appendChild(requestDoc.createTextNode(parameters.getDescription()));
        oSImageElement.appendChild(descriptionElement);
    }

    if (parameters.getImageFamily() != null) {
        Element imageFamilyElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "ImageFamily");
        imageFamilyElement.appendChild(requestDoc.createTextNode(parameters.getImageFamily()));
        oSImageElement.appendChild(imageFamilyElement);
    }

    if (parameters.getPublishedDate() != null) {
        Element publishedDateElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "PublishedDate");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
        simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        publishedDateElement.appendChild(
                requestDoc.createTextNode(simpleDateFormat.format(parameters.getPublishedDate().getTime())));
        oSImageElement.appendChild(publishedDateElement);
    }

    Element isPremiumElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "IsPremium");
    isPremiumElement
            .appendChild(requestDoc.createTextNode(Boolean.toString(parameters.isPremium()).toLowerCase()));
    oSImageElement.appendChild(isPremiumElement);

    Element showInGuiElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "ShowInGui");
    showInGuiElement
            .appendChild(requestDoc.createTextNode(Boolean.toString(parameters.isShowInGui()).toLowerCase()));
    oSImageElement.appendChild(showInGuiElement);

    if (parameters.getPrivacyUri() != null) {
        Element privacyUriElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "PrivacyUri");
        privacyUriElement.appendChild(requestDoc.createTextNode(parameters.getPrivacyUri().toString()));
        oSImageElement.appendChild(privacyUriElement);
    }

    if (parameters.getIconUri() != null) {
        Element iconUriElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "IconUri");
        iconUriElement.appendChild(requestDoc.createTextNode(parameters.getIconUri()));
        oSImageElement.appendChild(iconUriElement);
    }

    if (parameters.getRecommendedVMSize() != null) {
        Element recommendedVMSizeElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "RecommendedVMSize");
        recommendedVMSizeElement.appendChild(requestDoc.createTextNode(parameters.getRecommendedVMSize()));
        oSImageElement.appendChild(recommendedVMSizeElement);
    }

    if (parameters.getSmallIconUri() != null) {
        Element smallIconUriElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "SmallIconUri");
        smallIconUriElement.appendChild(requestDoc.createTextNode(parameters.getSmallIconUri()));
        oSImageElement.appendChild(smallIconUriElement);
    }

    if (parameters.getLanguage() != null) {
        Element languageElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "Language");
        languageElement.appendChild(requestDoc.createTextNode(parameters.getLanguage()));
        oSImageElement.appendChild(languageElement);
    }

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

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

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

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

                Element categoryElement = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "Category");
                if (categoryElement != null) {
                    String categoryInstance;
                    categoryInstance = categoryElement.getTextContent();
                    result.setCategory(categoryInstance);
                }

                Element labelElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "Label");
                if (labelElement2 != null) {
                    String labelInstance;
                    labelInstance = labelElement2.getTextContent();
                    result.setLabel(labelInstance);
                }

                Element logicalSizeInGBElement = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "LogicalSizeInGB");
                if (logicalSizeInGBElement != null) {
                    double logicalSizeInGBInstance;
                    logicalSizeInGBInstance = DatatypeConverter
                            .parseDouble(logicalSizeInGBElement.getTextContent());
                    result.setLogicalSizeInGB(logicalSizeInGBInstance);
                }

                Element mediaLinkElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "MediaLink");
                if (mediaLinkElement2 != null) {
                    URI mediaLinkInstance;
                    mediaLinkInstance = new URI(mediaLinkElement2.getTextContent());
                    result.setMediaLinkUri(mediaLinkInstance);
                }

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

                Element osElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "OS");
                if (osElement2 != null) {
                    String osInstance;
                    osInstance = osElement2.getTextContent();
                    result.setOperatingSystemType(osInstance);
                }

                Element eulaElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "Eula");
                if (eulaElement2 != null) {
                    String eulaInstance;
                    eulaInstance = eulaElement2.getTextContent();
                    result.setEula(eulaInstance);
                }

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

                Element imageFamilyElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "ImageFamily");
                if (imageFamilyElement2 != null) {
                    String imageFamilyInstance;
                    imageFamilyInstance = imageFamilyElement2.getTextContent();
                    result.setImageFamily(imageFamilyInstance);
                }

                Element publishedDateElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "PublishedDate");
                if (publishedDateElement2 != null && publishedDateElement2.getTextContent() != null
                        && !publishedDateElement2.getTextContent().isEmpty()) {
                    Calendar publishedDateInstance;
                    publishedDateInstance = DatatypeConverter
                            .parseDateTime(publishedDateElement2.getTextContent());
                    result.setPublishedDate(publishedDateInstance);
                }

                Element publisherNameElement = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "PublisherName");
                if (publisherNameElement != null) {
                    String publisherNameInstance;
                    publisherNameInstance = publisherNameElement.getTextContent();
                    result.setPublisherName(publisherNameInstance);
                }

                Element isPremiumElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "IsPremium");
                if (isPremiumElement2 != null && isPremiumElement2.getTextContent() != null
                        && !isPremiumElement2.getTextContent().isEmpty()) {
                    boolean isPremiumInstance;
                    isPremiumInstance = DatatypeConverter
                            .parseBoolean(isPremiumElement2.getTextContent().toLowerCase());
                    result.setIsPremium(isPremiumInstance);
                }

                Element showInGuiElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "ShowInGui");
                if (showInGuiElement2 != null && showInGuiElement2.getTextContent() != null
                        && !showInGuiElement2.getTextContent().isEmpty()) {
                    boolean showInGuiInstance;
                    showInGuiInstance = DatatypeConverter
                            .parseBoolean(showInGuiElement2.getTextContent().toLowerCase());
                    result.setShowInGui(showInGuiInstance);
                }

                Element privacyUriElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "PrivacyUri");
                if (privacyUriElement2 != null) {
                    URI privacyUriInstance;
                    privacyUriInstance = new URI(privacyUriElement2.getTextContent());
                    result.setPrivacyUri(privacyUriInstance);
                }

                Element iconUriElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "IconUri");
                if (iconUriElement2 != null) {
                    String iconUriInstance;
                    iconUriInstance = iconUriElement2.getTextContent();
                    result.setIconUri(iconUriInstance);
                }

                Element recommendedVMSizeElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "RecommendedVMSize");
                if (recommendedVMSizeElement2 != null) {
                    String recommendedVMSizeInstance;
                    recommendedVMSizeInstance = recommendedVMSizeElement2.getTextContent();
                    result.setRecommendedVMSize(recommendedVMSizeInstance);
                }

                Element smallIconUriElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "SmallIconUri");
                if (smallIconUriElement2 != null) {
                    String smallIconUriInstance;
                    smallIconUriInstance = smallIconUriElement2.getTextContent();
                    result.setSmallIconUri(smallIconUriInstance);
                }

                Element languageElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "Language");
                if (languageElement2 != null) {
                    String languageInstance;
                    languageInstance = languageElement2.getTextContent();
                    result.setLanguage(languageInstance);
                }

                Element iOTypeElement = XmlUtility.getElementByTagNameNS(oSImageElement2,
                        "http://schemas.microsoft.com/windowsazure", "IOType");
                if (iOTypeElement != null) {
                    String iOTypeInstance;
                    iOTypeInstance = iOTypeElement.getTextContent();
                    result.setIOType(iOTypeInstance);
                }
            }

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

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

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

/**
* The List Subscription Operations operation returns a list of create,
* update, and delete operations that were performed on a subscription
* during the specified timeframe.  (see/* w ww .jav  a 2 s.  c om*/
* http://msdn.microsoft.com/en-us/library/windowsazure/gg715318.aspx for
* more information)
*
* @param parameters Required. Parameters supplied to the List Subscription
* Operations operation.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @throws ParserConfigurationException Thrown if there was a serious
* configuration error with the document parser.
* @throws SAXException Thrown if there was an error parsing the XML
* response.
* @return The List Subscription Operations operation response.
*/
@Override
public SubscriptionListOperationsResponse listOperations(SubscriptionListOperationsParameters parameters)
        throws IOException, ServiceException, ParserConfigurationException, SAXException {
    // Validate
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }

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

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/operations";
    ArrayList<String> queryParameters = new ArrayList<String>();
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
    simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    queryParameters.add("StartTime="
            + URLEncoder.encode(simpleDateFormat.format(parameters.getStartTime().getTime()), "UTF-8"));
    SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
    simpleDateFormat2.setTimeZone(TimeZone.getTimeZone("UTC"));
    queryParameters.add("EndTime="
            + URLEncoder.encode(simpleDateFormat2.format(parameters.getEndTime().getTime()), "UTF-8"));
    if (parameters.getObjectIdFilter() != null) {
        queryParameters.add("ObjectIdFilter=" + URLEncoder.encode(parameters.getObjectIdFilter(), "UTF-8"));
    }
    if (parameters.getOperationStatus() != null) {
        queryParameters.add("OperationResultFilter="
                + URLEncoder.encode(parameters.getOperationStatus().toString(), "UTF-8"));
    }
    if (parameters.getContinuationToken() != null) {
        queryParameters
                .add("ContinuationToken=" + URLEncoder.encode(parameters.getContinuationToken(), "UTF-8"));
    }
    if (queryParameters.size() > 0) {
        url = url + "?" + CollectionStringBuilder.join(queryParameters, "&");
    }
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

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

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

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

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

            Element subscriptionOperationCollectionElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "SubscriptionOperationCollection");
            if (subscriptionOperationCollectionElement != null) {
                Element continuationTokenElement = XmlUtility.getElementByTagNameNS(
                        subscriptionOperationCollectionElement, "http://schemas.microsoft.com/windowsazure",
                        "ContinuationToken");
                if (continuationTokenElement != null) {
                    String continuationTokenInstance;
                    continuationTokenInstance = continuationTokenElement.getTextContent();
                    result.setContinuationToken(continuationTokenInstance);
                }

                Element subscriptionOperationsSequenceElement = XmlUtility.getElementByTagNameNS(
                        subscriptionOperationCollectionElement, "http://schemas.microsoft.com/windowsazure",
                        "SubscriptionOperations");
                if (subscriptionOperationsSequenceElement != null) {
                    for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(subscriptionOperationsSequenceElement,
                                    "http://schemas.microsoft.com/windowsazure", "SubscriptionOperation")
                            .size(); i1 = i1 + 1) {
                        org.w3c.dom.Element subscriptionOperationsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(subscriptionOperationsSequenceElement,
                                        "http://schemas.microsoft.com/windowsazure", "SubscriptionOperation")
                                .get(i1));
                        SubscriptionListOperationsResponse.SubscriptionOperation subscriptionOperationInstance = new SubscriptionListOperationsResponse.SubscriptionOperation();
                        result.getSubscriptionOperations().add(subscriptionOperationInstance);

                        Element operationIdElement = XmlUtility.getElementByTagNameNS(
                                subscriptionOperationsElement, "http://schemas.microsoft.com/windowsazure",
                                "OperationId");
                        if (operationIdElement != null) {
                            String operationIdInstance;
                            operationIdInstance = operationIdElement.getTextContent();
                            subscriptionOperationInstance.setOperationId(operationIdInstance);
                        }

                        Element operationObjectIdElement = XmlUtility.getElementByTagNameNS(
                                subscriptionOperationsElement, "http://schemas.microsoft.com/windowsazure",
                                "OperationObjectId");
                        if (operationObjectIdElement != null) {
                            String operationObjectIdInstance;
                            operationObjectIdInstance = operationObjectIdElement.getTextContent();
                            subscriptionOperationInstance.setOperationObjectId(operationObjectIdInstance);
                        }

                        Element operationNameElement = XmlUtility.getElementByTagNameNS(
                                subscriptionOperationsElement, "http://schemas.microsoft.com/windowsazure",
                                "OperationName");
                        if (operationNameElement != null) {
                            String operationNameInstance;
                            operationNameInstance = operationNameElement.getTextContent();
                            subscriptionOperationInstance.setOperationName(operationNameInstance);
                        }

                        Element operationParametersSequenceElement = XmlUtility.getElementByTagNameNS(
                                subscriptionOperationsElement, "http://schemas.microsoft.com/windowsazure",
                                "OperationParameters");
                        if (operationParametersSequenceElement != null) {
                            for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(operationParametersSequenceElement,
                                            "http://schemas.microsoft.com/windowsazure", "OperationParameter")
                                    .size(); i2 = i2 + 1) {
                                org.w3c.dom.Element operationParametersElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                        .getElementsByTagNameNS(operationParametersSequenceElement,
                                                "http://schemas.microsoft.com/windowsazure",
                                                "OperationParameter")
                                        .get(i2));
                                String operationParametersKey = XmlUtility.getElementByTagNameNS(
                                        operationParametersElement,
                                        "http://schemas.datacontract.org/2004/07/Microsoft.WindowsAzure.ServiceManagement",
                                        "Name").getTextContent();
                                String operationParametersValue = XmlUtility.getElementByTagNameNS(
                                        operationParametersElement,
                                        "http://schemas.datacontract.org/2004/07/Microsoft.WindowsAzure.ServiceManagement",
                                        "Value").getTextContent();
                                subscriptionOperationInstance.getOperationParameters()
                                        .put(operationParametersKey, operationParametersValue);
                            }
                        }

                        Element operationCallerElement = XmlUtility.getElementByTagNameNS(
                                subscriptionOperationsElement, "http://schemas.microsoft.com/windowsazure",
                                "OperationCaller");
                        if (operationCallerElement != null) {
                            SubscriptionListOperationsResponse.OperationCallerDetails operationCallerInstance = new SubscriptionListOperationsResponse.OperationCallerDetails();
                            subscriptionOperationInstance.setOperationCaller(operationCallerInstance);

                            Element usedServiceManagementApiElement = XmlUtility.getElementByTagNameNS(
                                    operationCallerElement, "http://schemas.microsoft.com/windowsazure",
                                    "UsedServiceManagementApi");
                            if (usedServiceManagementApiElement != null) {
                                boolean usedServiceManagementApiInstance;
                                usedServiceManagementApiInstance = DatatypeConverter.parseBoolean(
                                        usedServiceManagementApiElement.getTextContent().toLowerCase());
                                operationCallerInstance
                                        .setUsedServiceManagementApi(usedServiceManagementApiInstance);
                            }

                            Element userEmailAddressElement = XmlUtility.getElementByTagNameNS(
                                    operationCallerElement, "http://schemas.microsoft.com/windowsazure",
                                    "UserEmailAddress");
                            if (userEmailAddressElement != null) {
                                String userEmailAddressInstance;
                                userEmailAddressInstance = userEmailAddressElement.getTextContent();
                                operationCallerInstance.setUserEmailAddress(userEmailAddressInstance);
                            }

                            Element subscriptionCertificateThumbprintElement = XmlUtility.getElementByTagNameNS(
                                    operationCallerElement, "http://schemas.microsoft.com/windowsazure",
                                    "SubscriptionCertificateThumbprint");
                            if (subscriptionCertificateThumbprintElement != null) {
                                String subscriptionCertificateThumbprintInstance;
                                subscriptionCertificateThumbprintInstance = subscriptionCertificateThumbprintElement
                                        .getTextContent();
                                operationCallerInstance.setSubscriptionCertificateThumbprint(
                                        subscriptionCertificateThumbprintInstance);
                            }

                            Element clientIPElement = XmlUtility.getElementByTagNameNS(operationCallerElement,
                                    "http://schemas.microsoft.com/windowsazure", "ClientIP");
                            if (clientIPElement != null) {
                                InetAddress clientIPInstance;
                                clientIPInstance = InetAddress.getByName(clientIPElement.getTextContent());
                                operationCallerInstance.setClientIPAddress(clientIPInstance);
                            }
                        }

                        Element operationStatusElement = XmlUtility.getElementByTagNameNS(
                                subscriptionOperationsElement, "http://schemas.microsoft.com/windowsazure",
                                "OperationStatus");
                        if (operationStatusElement != null) {
                            String operationStatusInstance;
                            operationStatusInstance = operationStatusElement.getTextContent();
                            subscriptionOperationInstance.setOperationStatus(operationStatusInstance);
                        }

                        Element operationStartedTimeElement = XmlUtility.getElementByTagNameNS(
                                subscriptionOperationsElement, "http://schemas.microsoft.com/windowsazure",
                                "OperationStartedTime");
                        if (operationStartedTimeElement != null) {
                            Calendar operationStartedTimeInstance;
                            operationStartedTimeInstance = DatatypeConverter
                                    .parseDateTime(operationStartedTimeElement.getTextContent());
                            subscriptionOperationInstance.setOperationStartedTime(operationStartedTimeInstance);
                        }

                        Element operationCompletedTimeElement = XmlUtility.getElementByTagNameNS(
                                subscriptionOperationsElement, "http://schemas.microsoft.com/windowsazure",
                                "OperationCompletedTime");
                        if (operationCompletedTimeElement != null) {
                            Calendar operationCompletedTimeInstance;
                            operationCompletedTimeInstance = DatatypeConverter
                                    .parseDateTime(operationCompletedTimeElement.getTextContent());
                            subscriptionOperationInstance
                                    .setOperationCompletedTime(operationCompletedTimeInstance);
                        }
                    }
                }
            }

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

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

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

/**
* We execute or cancel index operations by updating index state. Allowed
* state transitions are :Active          -> Pending          - Start index
* creation processPending         -> Active           - Cancel index
* creationActive/Pending  -> Ignored          - Ignore index
* recommendation so it will no longer show in active
* recommendationsIgnored         -> Active           - Restore index
* recommendationSuccess         -> Pending Revert   - Revert index that
* has been createdPending Revert  -> Revert Canceled  - Cancel index
* revert operation/*from  w  w  w . j ava  2s.co  m*/
*
* @param resourceGroupName Required. The name of the Resource Group to
* which the Azure SQL Database Server belongs.
* @param serverName Required. The name of the Azure SQL Database Server on
* which the database is hosted.
* @param databaseName Required. The name of the Azure SQL Database.
* @param schemaName Required. The name of the Azure SQL Database schema.
* @param tableName Required. The name of the Azure SQL Database table.
* @param indexName Required. The name of the Azure SQL Database recommended
* index.
* @param parameters Required. The required parameters for updating index
* state.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return Represents the response to a get recommended index request.
*/
@Override
public RecommendedIndexUpdateResponse update(String resourceGroupName, String serverName, String databaseName,
        String schemaName, String tableName, String indexName, RecommendedIndexUpdateParameters parameters)
        throws IOException, ServiceException {
    // Validate
    if (resourceGroupName == null) {
        throw new NullPointerException("resourceGroupName");
    }
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }
    if (databaseName == null) {
        throw new NullPointerException("databaseName");
    }
    if (schemaName == null) {
        throw new NullPointerException("schemaName");
    }
    if (tableName == null) {
        throw new NullPointerException("tableName");
    }
    if (indexName == null) {
        throw new NullPointerException("indexName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getProperties() == null) {
        throw new NullPointerException("parameters.Properties");
    }

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

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

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

    // Set Headers
    httpRequest.setHeader("Content-Type", "application/json; charset=utf-8");

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

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

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

    if (parameters.getProperties().getState() != null) {
        ((ObjectNode) propertiesValue).put("state", parameters.getProperties().getState());
    }

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

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

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

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

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

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

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

                RecommendedIndex recommendedIndexInstance = new RecommendedIndex();
                result.setRecommendedIndex(recommendedIndexInstance);

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

                    JsonNode actionValue = propertiesValue2.get("action");
                    if (actionValue != null && actionValue instanceof NullNode == false) {
                        String actionInstance;
                        actionInstance = actionValue.getTextValue();
                        propertiesInstance.setAction(actionInstance);
                    }

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

                    JsonNode createdValue = propertiesValue2.get("created");
                    if (createdValue != null && createdValue instanceof NullNode == false) {
                        Calendar createdInstance;
                        createdInstance = DatatypeConverter.parseDateTime(createdValue.getTextValue());
                        propertiesInstance.setCreated(createdInstance);
                    }

                    JsonNode lastModifiedValue = propertiesValue2.get("lastModified");
                    if (lastModifiedValue != null && lastModifiedValue instanceof NullNode == false) {
                        Calendar lastModifiedInstance;
                        lastModifiedInstance = DatatypeConverter
                                .parseDateTime(lastModifiedValue.getTextValue());
                        propertiesInstance.setLastModified(lastModifiedInstance);
                    }

                    JsonNode indexTypeValue = propertiesValue2.get("indexType");
                    if (indexTypeValue != null && indexTypeValue instanceof NullNode == false) {
                        String indexTypeInstance;
                        indexTypeInstance = indexTypeValue.getTextValue();
                        propertiesInstance.setIndexType(indexTypeInstance);
                    }

                    JsonNode schemaValue = propertiesValue2.get("schema");
                    if (schemaValue != null && schemaValue instanceof NullNode == false) {
                        String schemaInstance;
                        schemaInstance = schemaValue.getTextValue();
                        propertiesInstance.setSchema(schemaInstance);
                    }

                    JsonNode tableValue = propertiesValue2.get("table");
                    if (tableValue != null && tableValue instanceof NullNode == false) {
                        String tableInstance;
                        tableInstance = tableValue.getTextValue();
                        propertiesInstance.setTable(tableInstance);
                    }

                    JsonNode columnsArray = propertiesValue2.get("columns");
                    if (columnsArray != null && columnsArray instanceof NullNode == false) {
                        for (JsonNode columnsValue : ((ArrayNode) columnsArray)) {
                            propertiesInstance.getColumns().add(columnsValue.getTextValue());
                        }
                    }

                    JsonNode includedColumnsArray = propertiesValue2.get("includedColumns");
                    if (includedColumnsArray != null && includedColumnsArray instanceof NullNode == false) {
                        for (JsonNode includedColumnsValue : ((ArrayNode) includedColumnsArray)) {
                            propertiesInstance.getIncludedColumns().add(includedColumnsValue.getTextValue());
                        }
                    }

                    JsonNode indexScriptValue = propertiesValue2.get("indexScript");
                    if (indexScriptValue != null && indexScriptValue instanceof NullNode == false) {
                        String indexScriptInstance;
                        indexScriptInstance = indexScriptValue.getTextValue();
                        propertiesInstance.setIndexScript(indexScriptInstance);
                    }

                    JsonNode estimatedImpactArray = propertiesValue2.get("estimatedImpact");
                    if (estimatedImpactArray != null && estimatedImpactArray instanceof NullNode == false) {
                        for (JsonNode estimatedImpactValue : ((ArrayNode) estimatedImpactArray)) {
                            OperationImpact operationImpactInstance = new OperationImpact();
                            propertiesInstance.getEstimatedImpact().add(operationImpactInstance);

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

                            JsonNode unitValue = estimatedImpactValue.get("unit");
                            if (unitValue != null && unitValue instanceof NullNode == false) {
                                String unitInstance;
                                unitInstance = unitValue.getTextValue();
                                operationImpactInstance.setUnit(unitInstance);
                            }

                            JsonNode changeValueAbsoluteValue = estimatedImpactValue.get("changeValueAbsolute");
                            if (changeValueAbsoluteValue != null
                                    && changeValueAbsoluteValue instanceof NullNode == false) {
                                double changeValueAbsoluteInstance;
                                changeValueAbsoluteInstance = changeValueAbsoluteValue.getDoubleValue();
                                operationImpactInstance.setChangeValueAbsolute(changeValueAbsoluteInstance);
                            }

                            JsonNode changeValueRelativeValue = estimatedImpactValue.get("changeValueRelative");
                            if (changeValueRelativeValue != null
                                    && changeValueRelativeValue instanceof NullNode == false) {
                                double changeValueRelativeInstance;
                                changeValueRelativeInstance = changeValueRelativeValue.getDoubleValue();
                                operationImpactInstance.setChangeValueRelative(changeValueRelativeInstance);
                            }
                        }
                    }

                    JsonNode reportedImpactArray = propertiesValue2.get("reportedImpact");
                    if (reportedImpactArray != null && reportedImpactArray instanceof NullNode == false) {
                        for (JsonNode reportedImpactValue : ((ArrayNode) reportedImpactArray)) {
                            OperationImpact operationImpactInstance2 = new OperationImpact();
                            propertiesInstance.getReportedImpact().add(operationImpactInstance2);

                            JsonNode nameValue2 = reportedImpactValue.get("name");
                            if (nameValue2 != null && nameValue2 instanceof NullNode == false) {
                                String nameInstance2;
                                nameInstance2 = nameValue2.getTextValue();
                                operationImpactInstance2.setName(nameInstance2);
                            }

                            JsonNode unitValue2 = reportedImpactValue.get("unit");
                            if (unitValue2 != null && unitValue2 instanceof NullNode == false) {
                                String unitInstance2;
                                unitInstance2 = unitValue2.getTextValue();
                                operationImpactInstance2.setUnit(unitInstance2);
                            }

                            JsonNode changeValueAbsoluteValue2 = reportedImpactValue.get("changeValueAbsolute");
                            if (changeValueAbsoluteValue2 != null
                                    && changeValueAbsoluteValue2 instanceof NullNode == false) {
                                double changeValueAbsoluteInstance2;
                                changeValueAbsoluteInstance2 = changeValueAbsoluteValue2.getDoubleValue();
                                operationImpactInstance2.setChangeValueAbsolute(changeValueAbsoluteInstance2);
                            }

                            JsonNode changeValueRelativeValue2 = reportedImpactValue.get("changeValueRelative");
                            if (changeValueRelativeValue2 != null
                                    && changeValueRelativeValue2 instanceof NullNode == false) {
                                double changeValueRelativeInstance2;
                                changeValueRelativeInstance2 = changeValueRelativeValue2.getDoubleValue();
                                operationImpactInstance2.setChangeValueRelative(changeValueRelativeInstance2);
                            }
                        }
                    }
                }

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

                JsonNode nameValue3 = responseDoc.get("name");
                if (nameValue3 != null && nameValue3 instanceof NullNode == false) {
                    String nameInstance3;
                    nameInstance3 = nameValue3.getTextValue();
                    recommendedIndexInstance.setName(nameInstance3);
                }

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

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

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

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

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

From source file:com.microsoft.azure.management.resources.DeploymentOperationsImpl.java

/**
* Create a named template deployment using a template.
*
* @param resourceGroupName Required. The name of the resource group. The
* name is case insensitive./*from   w  w  w  .  j  av a  2  s. c  om*/
* @param deploymentName Required. The name of the deployment.
* @param parameters Required. Additional parameters supplied to the
* operation.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @throws URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return Template deployment operation create result.
*/
@Override
public DeploymentOperationsCreateResult createOrUpdate(String resourceGroupName, String deploymentName,
        Deployment parameters) throws IOException, ServiceException, URISyntaxException {
    // Validate
    if (resourceGroupName == null) {
        throw new NullPointerException("resourceGroupName");
    }
    if (resourceGroupName != null && resourceGroupName.length() > 1000) {
        throw new IllegalArgumentException("resourceGroupName");
    }
    if (Pattern.matches("^[-\\w\\._]+$", resourceGroupName) == false) {
        throw new IllegalArgumentException("resourceGroupName");
    }
    if (deploymentName == null) {
        throw new NullPointerException("deploymentName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getProperties() != null) {
        if (parameters.getProperties().getParametersLink() != null) {
            if (parameters.getProperties().getParametersLink().getUri() == null) {
                throw new NullPointerException("parameters.Properties.ParametersLink.Uri");
            }
        }
        if (parameters.getProperties().getTemplateLink() != null) {
            if (parameters.getProperties().getTemplateLink().getUri() == null) {
                throw new NullPointerException("parameters.Properties.TemplateLink.Uri");
            }
        }
    }

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

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

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

    // Set Headers
    httpRequest.setHeader("Content-Type", "application/json; charset=utf-8");

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

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

    if (parameters.getProperties() != null) {
        ObjectNode propertiesValue = objectMapper.createObjectNode();
        ((ObjectNode) deploymentValue).put("properties", propertiesValue);

        if (parameters.getProperties().getTemplate() != null) {
            ((ObjectNode) propertiesValue).put("template",
                    objectMapper.readTree(parameters.getProperties().getTemplate()));
        }

        if (parameters.getProperties().getTemplateLink() != null) {
            ObjectNode templateLinkValue = objectMapper.createObjectNode();
            ((ObjectNode) propertiesValue).put("templateLink", templateLinkValue);

            ((ObjectNode) templateLinkValue).put("uri",
                    parameters.getProperties().getTemplateLink().getUri().toString());

            if (parameters.getProperties().getTemplateLink().getContentVersion() != null) {
                ((ObjectNode) templateLinkValue).put("contentVersion",
                        parameters.getProperties().getTemplateLink().getContentVersion());
            }
        }

        if (parameters.getProperties().getParameters() != null) {
            ((ObjectNode) propertiesValue).put("parameters",
                    objectMapper.readTree(parameters.getProperties().getParameters()));
        }

        if (parameters.getProperties().getParametersLink() != null) {
            ObjectNode parametersLinkValue = objectMapper.createObjectNode();
            ((ObjectNode) propertiesValue).put("parametersLink", parametersLinkValue);

            ((ObjectNode) parametersLinkValue).put("uri",
                    parameters.getProperties().getParametersLink().getUri().toString());

            if (parameters.getProperties().getParametersLink().getContentVersion() != null) {
                ((ObjectNode) parametersLinkValue).put("contentVersion",
                        parameters.getProperties().getParametersLink().getContentVersion());
            }
        }

        if (parameters.getProperties().getMode() != null) {
            ((ObjectNode) propertiesValue).put("mode", parameters.getProperties().getMode().toString());
        }
    }

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

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

        // Create Result
        DeploymentOperationsCreateResult result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new DeploymentOperationsCreateResult();
            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) {
                DeploymentExtended deploymentInstance = new DeploymentExtended();
                result.setDeployment(deploymentInstance);

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

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

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

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

                    JsonNode correlationIdValue = propertiesValue2.get("correlationId");
                    if (correlationIdValue != null && correlationIdValue instanceof NullNode == false) {
                        String correlationIdInstance;
                        correlationIdInstance = correlationIdValue.getTextValue();
                        propertiesInstance.setCorrelationId(correlationIdInstance);
                    }

                    JsonNode timestampValue = propertiesValue2.get("timestamp");
                    if (timestampValue != null && timestampValue instanceof NullNode == false) {
                        Calendar timestampInstance;
                        timestampInstance = DatatypeConverter.parseDateTime(timestampValue.getTextValue());
                        propertiesInstance.setTimestamp(timestampInstance);
                    }

                    JsonNode outputsValue = propertiesValue2.get("outputs");
                    if (outputsValue != null && outputsValue instanceof NullNode == false) {
                        String outputsInstance;
                        outputsInstance = outputsValue.getTextValue();
                        propertiesInstance.setOutputs(outputsInstance);
                    }

                    JsonNode providersArray = propertiesValue2.get("providers");
                    if (providersArray != null && providersArray instanceof NullNode == false) {
                        for (JsonNode providersValue : ((ArrayNode) providersArray)) {
                            Provider providerInstance = new Provider();
                            propertiesInstance.getProviders().add(providerInstance);

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

                            JsonNode namespaceValue = providersValue.get("namespace");
                            if (namespaceValue != null && namespaceValue instanceof NullNode == false) {
                                String namespaceInstance;
                                namespaceInstance = namespaceValue.getTextValue();
                                providerInstance.setNamespace(namespaceInstance);
                            }

                            JsonNode registrationStateValue = providersValue.get("registrationState");
                            if (registrationStateValue != null
                                    && registrationStateValue instanceof NullNode == false) {
                                String registrationStateInstance;
                                registrationStateInstance = registrationStateValue.getTextValue();
                                providerInstance.setRegistrationState(registrationStateInstance);
                            }

                            JsonNode resourceTypesArray = providersValue.get("resourceTypes");
                            if (resourceTypesArray != null && resourceTypesArray instanceof NullNode == false) {
                                for (JsonNode resourceTypesValue : ((ArrayNode) resourceTypesArray)) {
                                    ProviderResourceType providerResourceTypeInstance = new ProviderResourceType();
                                    providerInstance.getResourceTypes().add(providerResourceTypeInstance);

                                    JsonNode resourceTypeValue = resourceTypesValue.get("resourceType");
                                    if (resourceTypeValue != null
                                            && resourceTypeValue instanceof NullNode == false) {
                                        String resourceTypeInstance;
                                        resourceTypeInstance = resourceTypeValue.getTextValue();
                                        providerResourceTypeInstance.setName(resourceTypeInstance);
                                    }

                                    JsonNode locationsArray = resourceTypesValue.get("locations");
                                    if (locationsArray != null && locationsArray instanceof NullNode == false) {
                                        for (JsonNode locationsValue : ((ArrayNode) locationsArray)) {
                                            providerResourceTypeInstance.getLocations()
                                                    .add(locationsValue.getTextValue());
                                        }
                                    }

                                    JsonNode apiVersionsArray = resourceTypesValue.get("apiVersions");
                                    if (apiVersionsArray != null
                                            && apiVersionsArray instanceof NullNode == false) {
                                        for (JsonNode apiVersionsValue : ((ArrayNode) apiVersionsArray)) {
                                            providerResourceTypeInstance.getApiVersions()
                                                    .add(apiVersionsValue.getTextValue());
                                        }
                                    }

                                    JsonNode propertiesSequenceElement = ((JsonNode) resourceTypesValue
                                            .get("properties"));
                                    if (propertiesSequenceElement != null
                                            && propertiesSequenceElement instanceof NullNode == false) {
                                        Iterator<Map.Entry<String, JsonNode>> itr = propertiesSequenceElement
                                                .getFields();
                                        while (itr.hasNext()) {
                                            Map.Entry<String, JsonNode> property = itr.next();
                                            String propertiesKey = property.getKey();
                                            String propertiesValue3 = property.getValue().getTextValue();
                                            providerResourceTypeInstance.getProperties().put(propertiesKey,
                                                    propertiesValue3);
                                        }
                                    }
                                }
                            }
                        }
                    }

                    JsonNode dependenciesArray = propertiesValue2.get("dependencies");
                    if (dependenciesArray != null && dependenciesArray instanceof NullNode == false) {
                        for (JsonNode dependenciesValue : ((ArrayNode) dependenciesArray)) {
                            Dependency dependencyInstance = new Dependency();
                            propertiesInstance.getDependencies().add(dependencyInstance);

                            JsonNode dependsOnArray = dependenciesValue.get("dependsOn");
                            if (dependsOnArray != null && dependsOnArray instanceof NullNode == false) {
                                for (JsonNode dependsOnValue : ((ArrayNode) dependsOnArray)) {
                                    BasicDependency basicDependencyInstance = new BasicDependency();
                                    dependencyInstance.getDependsOn().add(basicDependencyInstance);

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

                                    JsonNode resourceTypeValue2 = dependsOnValue.get("resourceType");
                                    if (resourceTypeValue2 != null
                                            && resourceTypeValue2 instanceof NullNode == false) {
                                        String resourceTypeInstance2;
                                        resourceTypeInstance2 = resourceTypeValue2.getTextValue();
                                        basicDependencyInstance.setResourceType(resourceTypeInstance2);
                                    }

                                    JsonNode resourceNameValue = dependsOnValue.get("resourceName");
                                    if (resourceNameValue != null
                                            && resourceNameValue instanceof NullNode == false) {
                                        String resourceNameInstance;
                                        resourceNameInstance = resourceNameValue.getTextValue();
                                        basicDependencyInstance.setResourceName(resourceNameInstance);
                                    }
                                }
                            }

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

                            JsonNode resourceTypeValue3 = dependenciesValue.get("resourceType");
                            if (resourceTypeValue3 != null && resourceTypeValue3 instanceof NullNode == false) {
                                String resourceTypeInstance3;
                                resourceTypeInstance3 = resourceTypeValue3.getTextValue();
                                dependencyInstance.setResourceType(resourceTypeInstance3);
                            }

                            JsonNode resourceNameValue2 = dependenciesValue.get("resourceName");
                            if (resourceNameValue2 != null && resourceNameValue2 instanceof NullNode == false) {
                                String resourceNameInstance2;
                                resourceNameInstance2 = resourceNameValue2.getTextValue();
                                dependencyInstance.setResourceName(resourceNameInstance2);
                            }
                        }
                    }

                    JsonNode templateValue = propertiesValue2.get("template");
                    if (templateValue != null && templateValue instanceof NullNode == false) {
                        String templateInstance;
                        templateInstance = templateValue.getTextValue();
                        propertiesInstance.setTemplate(templateInstance);
                    }

                    JsonNode templateLinkValue2 = propertiesValue2.get("templateLink");
                    if (templateLinkValue2 != null && templateLinkValue2 instanceof NullNode == false) {
                        TemplateLink templateLinkInstance = new TemplateLink();
                        propertiesInstance.setTemplateLink(templateLinkInstance);

                        JsonNode uriValue = templateLinkValue2.get("uri");
                        if (uriValue != null && uriValue instanceof NullNode == false) {
                            URI uriInstance;
                            uriInstance = new URI(uriValue.getTextValue());
                            templateLinkInstance.setUri(uriInstance);
                        }

                        JsonNode contentVersionValue = templateLinkValue2.get("contentVersion");
                        if (contentVersionValue != null && contentVersionValue instanceof NullNode == false) {
                            String contentVersionInstance;
                            contentVersionInstance = contentVersionValue.getTextValue();
                            templateLinkInstance.setContentVersion(contentVersionInstance);
                        }
                    }

                    JsonNode parametersValue = propertiesValue2.get("parameters");
                    if (parametersValue != null && parametersValue instanceof NullNode == false) {
                        String parametersInstance;
                        parametersInstance = parametersValue.getTextValue();
                        propertiesInstance.setParameters(parametersInstance);
                    }

                    JsonNode parametersLinkValue2 = propertiesValue2.get("parametersLink");
                    if (parametersLinkValue2 != null && parametersLinkValue2 instanceof NullNode == false) {
                        ParametersLink parametersLinkInstance = new ParametersLink();
                        propertiesInstance.setParametersLink(parametersLinkInstance);

                        JsonNode uriValue2 = parametersLinkValue2.get("uri");
                        if (uriValue2 != null && uriValue2 instanceof NullNode == false) {
                            URI uriInstance2;
                            uriInstance2 = new URI(uriValue2.getTextValue());
                            parametersLinkInstance.setUri(uriInstance2);
                        }

                        JsonNode contentVersionValue2 = parametersLinkValue2.get("contentVersion");
                        if (contentVersionValue2 != null && contentVersionValue2 instanceof NullNode == false) {
                            String contentVersionInstance2;
                            contentVersionInstance2 = contentVersionValue2.getTextValue();
                            parametersLinkInstance.setContentVersion(contentVersionInstance2);
                        }
                    }

                    JsonNode modeValue = propertiesValue2.get("mode");
                    if (modeValue != null && modeValue instanceof NullNode == false) {
                        DeploymentMode modeInstance;
                        modeInstance = Enum.valueOf(DeploymentMode.class, modeValue.getTextValue());
                        propertiesInstance.setMode(modeInstance);
                    }
                }
            }

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

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

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

/**
* Returns information about service tier advisors for specified database.
*
* @param resourceGroupName Required. The name of the Resource Group.
* @param serverName Required. The name of server.
* @param databaseName Required. The name of database.
* @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./*w  w  w .j  a  v  a 2s. co  m*/
* @throws ServiceException Thrown if an unexpected response is found.
* @return Represents the response to a list service tier advisor request.
*/
@Override
public ServiceTierAdvisorListResponse list(String resourceGroupName, String serverName, String databaseName)
        throws IOException, ServiceException {
    // Validate
    if (resourceGroupName == null) {
        throw new NullPointerException("resourceGroupName");
    }
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }
    if (databaseName == null) {
        throw new NullPointerException("databaseName");
    }

    // Tracing
    boolean shouldTrace = CloudTracing.getIsEnabled();
    String invocationId = null;
    if (shouldTrace) {
        invocationId = Long.toString(CloudTracing.getNextInvocationId());
        HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
        tracingParameters.put("resourceGroupName", resourceGroupName);
        tracingParameters.put("serverName", serverName);
        tracingParameters.put("databaseName", databaseName);
        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 + "/resourceGroups/";
    url = url + URLEncoder.encode(resourceGroupName, "UTF-8");
    url = url + "/providers/";
    url = url + "Microsoft.Sql";
    url = url + "/servers/";
    url = url + URLEncoder.encode(serverName, "UTF-8");
    url = url + "/databases/";
    url = url + URLEncoder.encode(databaseName, "UTF-8");
    url = url + "/serviceTierAdvisors";
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("api-version=" + "2014-04-01");
    if (queryParameters.size() > 0) {
        url = url + "?" + CollectionStringBuilder.join(queryParameters, "&");
    }
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

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

    // Set Headers

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

        // Create Result
        ServiceTierAdvisorListResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new ServiceTierAdvisorListResponse();
            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)) {
                        ServiceTierAdvisor serviceTierAdvisorInstance = new ServiceTierAdvisor();
                        result.getServiceTierAdvisors().add(serviceTierAdvisorInstance);

                        JsonNode propertiesValue = valueValue.get("properties");
                        if (propertiesValue != null && propertiesValue instanceof NullNode == false) {
                            ServiceTierAdvisorProperties propertiesInstance = new ServiceTierAdvisorProperties();
                            serviceTierAdvisorInstance.setProperties(propertiesInstance);

                            JsonNode observationPeriodStartValue = propertiesValue
                                    .get("observationPeriodStart");
                            if (observationPeriodStartValue != null
                                    && observationPeriodStartValue instanceof NullNode == false) {
                                Calendar observationPeriodStartInstance;
                                observationPeriodStartInstance = DatatypeConverter
                                        .parseDateTime(observationPeriodStartValue.getTextValue());
                                propertiesInstance.setObservationPeriodStart(observationPeriodStartInstance);
                            }

                            JsonNode observationPeriodEndValue = propertiesValue.get("observationPeriodEnd");
                            if (observationPeriodEndValue != null
                                    && observationPeriodEndValue instanceof NullNode == false) {
                                Calendar observationPeriodEndInstance;
                                observationPeriodEndInstance = DatatypeConverter
                                        .parseDateTime(observationPeriodEndValue.getTextValue());
                                propertiesInstance.setObservationPeriodEnd(observationPeriodEndInstance);
                            }

                            JsonNode activeTimeRatioValue = propertiesValue.get("activeTimeRatio");
                            if (activeTimeRatioValue != null
                                    && activeTimeRatioValue instanceof NullNode == false) {
                                double activeTimeRatioInstance;
                                activeTimeRatioInstance = activeTimeRatioValue.getDoubleValue();
                                propertiesInstance.setActiveTimeRatio(activeTimeRatioInstance);
                            }

                            JsonNode minDtuValue = propertiesValue.get("minDtu");
                            if (minDtuValue != null && minDtuValue instanceof NullNode == false) {
                                double minDtuInstance;
                                minDtuInstance = minDtuValue.getDoubleValue();
                                propertiesInstance.setMinDtu(minDtuInstance);
                            }

                            JsonNode avgDtuValue = propertiesValue.get("avgDtu");
                            if (avgDtuValue != null && avgDtuValue instanceof NullNode == false) {
                                double avgDtuInstance;
                                avgDtuInstance = avgDtuValue.getDoubleValue();
                                propertiesInstance.setAvgDtu(avgDtuInstance);
                            }

                            JsonNode maxDtuValue = propertiesValue.get("maxDtu");
                            if (maxDtuValue != null && maxDtuValue instanceof NullNode == false) {
                                double maxDtuInstance;
                                maxDtuInstance = maxDtuValue.getDoubleValue();
                                propertiesInstance.setMaxDtu(maxDtuInstance);
                            }

                            JsonNode maxSizeInGBValue = propertiesValue.get("maxSizeInGB");
                            if (maxSizeInGBValue != null && maxSizeInGBValue instanceof NullNode == false) {
                                double maxSizeInGBInstance;
                                maxSizeInGBInstance = maxSizeInGBValue.getDoubleValue();
                                propertiesInstance.setMaxSizeInGB(maxSizeInGBInstance);
                            }

                            JsonNode serviceLevelObjectiveUsageMetricsArray = propertiesValue
                                    .get("serviceLevelObjectiveUsageMetrics");
                            if (serviceLevelObjectiveUsageMetricsArray != null
                                    && serviceLevelObjectiveUsageMetricsArray instanceof NullNode == false) {
                                for (JsonNode serviceLevelObjectiveUsageMetricsValue : ((ArrayNode) serviceLevelObjectiveUsageMetricsArray)) {
                                    SloUsageMetric sloUsageMetricInstance = new SloUsageMetric();
                                    propertiesInstance.getServiceLevelObjectiveUsageMetrics()
                                            .add(sloUsageMetricInstance);

                                    JsonNode serviceLevelObjectiveValue = serviceLevelObjectiveUsageMetricsValue
                                            .get("serviceLevelObjective");
                                    if (serviceLevelObjectiveValue != null
                                            && serviceLevelObjectiveValue instanceof NullNode == false) {
                                        String serviceLevelObjectiveInstance;
                                        serviceLevelObjectiveInstance = serviceLevelObjectiveValue
                                                .getTextValue();
                                        sloUsageMetricInstance
                                                .setServiceLevelObjective(serviceLevelObjectiveInstance);
                                    }

                                    JsonNode serviceLevelObjectiveIdValue = serviceLevelObjectiveUsageMetricsValue
                                            .get("serviceLevelObjectiveId");
                                    if (serviceLevelObjectiveIdValue != null
                                            && serviceLevelObjectiveIdValue instanceof NullNode == false) {
                                        String serviceLevelObjectiveIdInstance;
                                        serviceLevelObjectiveIdInstance = serviceLevelObjectiveIdValue
                                                .getTextValue();
                                        sloUsageMetricInstance
                                                .setServiceLevelObjectiveId(serviceLevelObjectiveIdInstance);
                                    }

                                    JsonNode inRangeTimeRatioValue = serviceLevelObjectiveUsageMetricsValue
                                            .get("inRangeTimeRatio");
                                    if (inRangeTimeRatioValue != null
                                            && inRangeTimeRatioValue instanceof NullNode == false) {
                                        double inRangeTimeRatioInstance;
                                        inRangeTimeRatioInstance = inRangeTimeRatioValue.getDoubleValue();
                                        sloUsageMetricInstance.setInRangeTimeRatio(inRangeTimeRatioInstance);
                                    }

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

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

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

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

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

                            JsonNode currentServiceLevelObjectiveValue = propertiesValue
                                    .get("currentServiceLevelObjective");
                            if (currentServiceLevelObjectiveValue != null
                                    && currentServiceLevelObjectiveValue instanceof NullNode == false) {
                                String currentServiceLevelObjectiveInstance;
                                currentServiceLevelObjectiveInstance = currentServiceLevelObjectiveValue
                                        .getTextValue();
                                propertiesInstance
                                        .setCurrentServiceLevelObjective(currentServiceLevelObjectiveInstance);
                            }

                            JsonNode currentServiceLevelObjectiveIdValue = propertiesValue
                                    .get("currentServiceLevelObjectiveId");
                            if (currentServiceLevelObjectiveIdValue != null
                                    && currentServiceLevelObjectiveIdValue instanceof NullNode == false) {
                                String currentServiceLevelObjectiveIdInstance;
                                currentServiceLevelObjectiveIdInstance = currentServiceLevelObjectiveIdValue
                                        .getTextValue();
                                propertiesInstance.setCurrentServiceLevelObjectiveId(
                                        currentServiceLevelObjectiveIdInstance);
                            }

                            JsonNode usageBasedRecommendationServiceLevelObjectiveValue = propertiesValue
                                    .get("usageBasedRecommendationServiceLevelObjective");
                            if (usageBasedRecommendationServiceLevelObjectiveValue != null
                                    && usageBasedRecommendationServiceLevelObjectiveValue instanceof NullNode == false) {
                                String usageBasedRecommendationServiceLevelObjectiveInstance;
                                usageBasedRecommendationServiceLevelObjectiveInstance = usageBasedRecommendationServiceLevelObjectiveValue
                                        .getTextValue();
                                propertiesInstance.setUsageBasedRecommendationServiceLevelObjective(
                                        usageBasedRecommendationServiceLevelObjectiveInstance);
                            }

                            JsonNode usageBasedRecommendationServiceLevelObjectiveIdValue = propertiesValue
                                    .get("usageBasedRecommendationServiceLevelObjectiveId");
                            if (usageBasedRecommendationServiceLevelObjectiveIdValue != null
                                    && usageBasedRecommendationServiceLevelObjectiveIdValue instanceof NullNode == false) {
                                String usageBasedRecommendationServiceLevelObjectiveIdInstance;
                                usageBasedRecommendationServiceLevelObjectiveIdInstance = usageBasedRecommendationServiceLevelObjectiveIdValue
                                        .getTextValue();
                                propertiesInstance.setUsageBasedRecommendationServiceLevelObjectiveId(
                                        usageBasedRecommendationServiceLevelObjectiveIdInstance);
                            }

                            JsonNode databaseSizeBasedRecommendationServiceLevelObjectiveValue = propertiesValue
                                    .get("databaseSizeBasedRecommendationServiceLevelObjective");
                            if (databaseSizeBasedRecommendationServiceLevelObjectiveValue != null
                                    && databaseSizeBasedRecommendationServiceLevelObjectiveValue instanceof NullNode == false) {
                                String databaseSizeBasedRecommendationServiceLevelObjectiveInstance;
                                databaseSizeBasedRecommendationServiceLevelObjectiveInstance = databaseSizeBasedRecommendationServiceLevelObjectiveValue
                                        .getTextValue();
                                propertiesInstance.setDatabaseSizeBasedRecommendationServiceLevelObjective(
                                        databaseSizeBasedRecommendationServiceLevelObjectiveInstance);
                            }

                            JsonNode databaseSizeBasedRecommendationServiceLevelObjectiveIdValue = propertiesValue
                                    .get("databaseSizeBasedRecommendationServiceLevelObjectiveId");
                            if (databaseSizeBasedRecommendationServiceLevelObjectiveIdValue != null
                                    && databaseSizeBasedRecommendationServiceLevelObjectiveIdValue instanceof NullNode == false) {
                                String databaseSizeBasedRecommendationServiceLevelObjectiveIdInstance;
                                databaseSizeBasedRecommendationServiceLevelObjectiveIdInstance = databaseSizeBasedRecommendationServiceLevelObjectiveIdValue
                                        .getTextValue();
                                propertiesInstance.setDatabaseSizeBasedRecommendationServiceLevelObjectiveId(
                                        databaseSizeBasedRecommendationServiceLevelObjectiveIdInstance);
                            }

                            JsonNode disasterPlanBasedRecommendationServiceLevelObjectiveValue = propertiesValue
                                    .get("disasterPlanBasedRecommendationServiceLevelObjective");
                            if (disasterPlanBasedRecommendationServiceLevelObjectiveValue != null
                                    && disasterPlanBasedRecommendationServiceLevelObjectiveValue instanceof NullNode == false) {
                                String disasterPlanBasedRecommendationServiceLevelObjectiveInstance;
                                disasterPlanBasedRecommendationServiceLevelObjectiveInstance = disasterPlanBasedRecommendationServiceLevelObjectiveValue
                                        .getTextValue();
                                propertiesInstance.setDisasterPlanBasedRecommendationServiceLevelObjective(
                                        disasterPlanBasedRecommendationServiceLevelObjectiveInstance);
                            }

                            JsonNode disasterPlanBasedRecommendationServiceLevelObjectiveIdValue = propertiesValue
                                    .get("disasterPlanBasedRecommendationServiceLevelObjectiveId");
                            if (disasterPlanBasedRecommendationServiceLevelObjectiveIdValue != null
                                    && disasterPlanBasedRecommendationServiceLevelObjectiveIdValue instanceof NullNode == false) {
                                String disasterPlanBasedRecommendationServiceLevelObjectiveIdInstance;
                                disasterPlanBasedRecommendationServiceLevelObjectiveIdInstance = disasterPlanBasedRecommendationServiceLevelObjectiveIdValue
                                        .getTextValue();
                                propertiesInstance.setDisasterPlanBasedRecommendationServiceLevelObjectiveId(
                                        disasterPlanBasedRecommendationServiceLevelObjectiveIdInstance);
                            }

                            JsonNode overallRecommendationServiceLevelObjectiveValue = propertiesValue
                                    .get("overallRecommendationServiceLevelObjective");
                            if (overallRecommendationServiceLevelObjectiveValue != null
                                    && overallRecommendationServiceLevelObjectiveValue instanceof NullNode == false) {
                                String overallRecommendationServiceLevelObjectiveInstance;
                                overallRecommendationServiceLevelObjectiveInstance = overallRecommendationServiceLevelObjectiveValue
                                        .getTextValue();
                                propertiesInstance.setOverallRecommendationServiceLevelObjective(
                                        overallRecommendationServiceLevelObjectiveInstance);
                            }

                            JsonNode overallRecommendationServiceLevelObjectiveIdValue = propertiesValue
                                    .get("overallRecommendationServiceLevelObjectiveId");
                            if (overallRecommendationServiceLevelObjectiveIdValue != null
                                    && overallRecommendationServiceLevelObjectiveIdValue instanceof NullNode == false) {
                                String overallRecommendationServiceLevelObjectiveIdInstance;
                                overallRecommendationServiceLevelObjectiveIdInstance = overallRecommendationServiceLevelObjectiveIdValue
                                        .getTextValue();
                                propertiesInstance.setOverallRecommendationServiceLevelObjectiveId(
                                        overallRecommendationServiceLevelObjectiveIdInstance);
                            }

                            JsonNode confidenceValue = propertiesValue.get("confidence");
                            if (confidenceValue != null && confidenceValue instanceof NullNode == false) {
                                double confidenceInstance;
                                confidenceInstance = confidenceValue.getDoubleValue();
                                propertiesInstance.setConfidence(confidenceInstance);
                            }
                        }

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

                        JsonNode nameValue2 = valueValue.get("name");
                        if (nameValue2 != null && nameValue2 instanceof NullNode == false) {
                            String nameInstance2;
                            nameInstance2 = nameValue2.getTextValue();
                            serviceTierAdvisorInstance.setName(nameInstance2);
                        }

                        JsonNode typeValue2 = valueValue.get("type");
                        if (typeValue2 != null && typeValue2 instanceof NullNode == false) {
                            String typeInstance2;
                            typeInstance2 = typeValue2.getTextValue();
                            serviceTierAdvisorInstance.setType(typeInstance2);
                        }

                        JsonNode locationValue2 = valueValue.get("location");
                        if (locationValue2 != null && locationValue2 instanceof NullNode == false) {
                            String locationInstance2;
                            locationInstance2 = locationValue2.getTextValue();
                            serviceTierAdvisorInstance.setLocation(locationInstance2);
                        }

                        JsonNode tagsSequenceElement2 = ((JsonNode) valueValue.get("tags"));
                        if (tagsSequenceElement2 != null && tagsSequenceElement2 instanceof NullNode == false) {
                            Iterator<Map.Entry<String, JsonNode>> itr2 = tagsSequenceElement2.getFields();
                            while (itr2.hasNext()) {
                                Map.Entry<String, JsonNode> property2 = itr2.next();
                                String tagsKey2 = property2.getKey();
                                String tagsValue2 = property2.getValue().getTextValue();
                                serviceTierAdvisorInstance.getTags().put(tagsKey2, tagsValue2);
                            }
                        }
                    }
                }
            }

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

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

From source file:com.microsoft.azure.management.notificationhubs.NamespaceOperationsImpl.java

/**
* Creates/Updates a service namespace. Once created, this namespace's
* resource manifest is immutable. This operation is idempotent.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/jj856303.aspx for
* more information)// w  ww .  j a  va  2  s  . com
*
* @param resourceGroupName Required. The name of the resource group.
* @param namespaceName Required. The namespace name.
* @param parameters Required. Parameters supplied to the create a Namespace
* Resource.
* @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 response of the CreateOrUpdate Namespace.
*/
@Override
public NamespaceCreateOrUpdateResponse createOrUpdate(String resourceGroupName, String namespaceName,
        NamespaceCreateOrUpdateParameters parameters) throws IOException, ServiceException, URISyntaxException {
    // Validate
    if (resourceGroupName == null) {
        throw new NullPointerException("resourceGroupName");
    }
    if (namespaceName == null) {
        throw new NullPointerException("namespaceName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getLocation() == null) {
        throw new NullPointerException("parameters.Location");
    }
    if (parameters.getProperties() == null) {
        throw new NullPointerException("parameters.Properties");
    }

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

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

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

    // Set Headers
    httpRequest.setHeader("Content-Type", "application/json");

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

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

    ((ObjectNode) namespaceCreateOrUpdateParametersValue).put("location", parameters.getLocation());

    if (parameters.getTags() != null) {
        if (parameters.getTags() instanceof LazyCollection == false
                || ((LazyCollection) parameters.getTags()).isInitialized()) {
            ObjectNode tagsDictionary = objectMapper.createObjectNode();
            for (Map.Entry<String, String> entry : parameters.getTags().entrySet()) {
                String tagsKey = entry.getKey();
                String tagsValue = entry.getValue();
                ((ObjectNode) tagsDictionary).put(tagsKey, tagsValue);
            }
            ((ObjectNode) namespaceCreateOrUpdateParametersValue).put("tags", tagsDictionary);
        }
    }

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

    if (parameters.getProperties().getName() != null) {
        ((ObjectNode) propertiesValue).put("name", parameters.getProperties().getName());
    }

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

    if (parameters.getProperties().getRegion() != null) {
        ((ObjectNode) propertiesValue).put("region", parameters.getProperties().getRegion());
    }

    if (parameters.getProperties().getStatus() != null) {
        ((ObjectNode) propertiesValue).put("status", parameters.getProperties().getStatus());
    }

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
    simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    ((ObjectNode) propertiesValue).put("createdAt",
            simpleDateFormat.format(parameters.getProperties().getCreatedAt().getTime()));

    if (parameters.getProperties().getServiceBusEndpoint() != null) {
        ((ObjectNode) propertiesValue).put("serviceBusEndpoint",
                parameters.getProperties().getServiceBusEndpoint().toString());
    }

    if (parameters.getProperties().getSubscriptionId() != null) {
        ((ObjectNode) propertiesValue).put("subscriptionId", parameters.getProperties().getSubscriptionId());
    }

    if (parameters.getProperties().getScaleUnit() != null) {
        ((ObjectNode) propertiesValue).put("scaleUnit", parameters.getProperties().getScaleUnit());
    }

    ((ObjectNode) propertiesValue).put("enabled", parameters.getProperties().isEnabled());

    ((ObjectNode) propertiesValue).put("critical", parameters.getProperties().isCritical());

    if (parameters.getProperties().getNamespaceType() != null) {
        ((ObjectNode) propertiesValue).put("namespaceType",
                parameters.getProperties().getNamespaceType().toString());
    }

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

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

        // Create Result
        NamespaceCreateOrUpdateResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new NamespaceCreateOrUpdateResponse();
            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) {
                NamespaceResource valueInstance = new NamespaceResource();
                result.setValue(valueInstance);

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

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

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

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

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

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

                    JsonNode nameValue2 = propertiesValue2.get("name");
                    if (nameValue2 != null && nameValue2 instanceof NullNode == false) {
                        String nameInstance2;
                        nameInstance2 = nameValue2.getTextValue();
                        propertiesInstance.setName(nameInstance2);
                    }

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

                    JsonNode regionValue = propertiesValue2.get("region");
                    if (regionValue != null && regionValue instanceof NullNode == false) {
                        String regionInstance;
                        regionInstance = regionValue.getTextValue();
                        propertiesInstance.setRegion(regionInstance);
                    }

                    JsonNode statusValue = propertiesValue2.get("status");
                    if (statusValue != null && statusValue instanceof NullNode == false) {
                        String statusInstance;
                        statusInstance = statusValue.getTextValue();
                        propertiesInstance.setStatus(statusInstance);
                    }

                    JsonNode createdAtValue = propertiesValue2.get("createdAt");
                    if (createdAtValue != null && createdAtValue instanceof NullNode == false) {
                        Calendar createdAtInstance;
                        createdAtInstance = DatatypeConverter.parseDateTime(createdAtValue.getTextValue());
                        propertiesInstance.setCreatedAt(createdAtInstance);
                    }

                    JsonNode serviceBusEndpointValue = propertiesValue2.get("serviceBusEndpoint");
                    if (serviceBusEndpointValue != null
                            && serviceBusEndpointValue instanceof NullNode == false) {
                        URI serviceBusEndpointInstance;
                        serviceBusEndpointInstance = new URI(serviceBusEndpointValue.getTextValue());
                        propertiesInstance.setServiceBusEndpoint(serviceBusEndpointInstance);
                    }

                    JsonNode subscriptionIdValue = propertiesValue2.get("subscriptionId");
                    if (subscriptionIdValue != null && subscriptionIdValue instanceof NullNode == false) {
                        String subscriptionIdInstance;
                        subscriptionIdInstance = subscriptionIdValue.getTextValue();
                        propertiesInstance.setSubscriptionId(subscriptionIdInstance);
                    }

                    JsonNode scaleUnitValue = propertiesValue2.get("scaleUnit");
                    if (scaleUnitValue != null && scaleUnitValue instanceof NullNode == false) {
                        String scaleUnitInstance;
                        scaleUnitInstance = scaleUnitValue.getTextValue();
                        propertiesInstance.setScaleUnit(scaleUnitInstance);
                    }

                    JsonNode enabledValue = propertiesValue2.get("enabled");
                    if (enabledValue != null && enabledValue instanceof NullNode == false) {
                        boolean enabledInstance;
                        enabledInstance = enabledValue.getBooleanValue();
                        propertiesInstance.setEnabled(enabledInstance);
                    }

                    JsonNode criticalValue = propertiesValue2.get("critical");
                    if (criticalValue != null && criticalValue instanceof NullNode == false) {
                        boolean criticalInstance;
                        criticalInstance = criticalValue.getBooleanValue();
                        propertiesInstance.setCritical(criticalInstance);
                    }

                    JsonNode namespaceTypeValue = propertiesValue2.get("namespaceType");
                    if (namespaceTypeValue != null && namespaceTypeValue instanceof NullNode == false) {
                        NamespaceType namespaceTypeInstance;
                        namespaceTypeInstance = Enum.valueOf(NamespaceType.class,
                                namespaceTypeValue.getTextValue());
                        propertiesInstance.setNamespaceType(namespaceTypeInstance);
                    }
                }
            }

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

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

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

/**
* Backups a site on-demand.//from w ww  .j a va  2s .  c  o  m
*
* @param webSpaceName Required. The name of the web space.
* @param webSiteName Required. The name of the web site.
* @param backupRequest Required. A backup specification.
* @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 backup record created based on the backup request.
*/
@Override
public WebSiteBackupResponse backup(String webSpaceName, String webSiteName, BackupRequest backupRequest)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (webSpaceName == null) {
        throw new NullPointerException("webSpaceName");
    }
    if (webSiteName == null) {
        throw new NullPointerException("webSiteName");
    }
    if (backupRequest == null) {
        throw new NullPointerException("backupRequest");
    }

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

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

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

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

    if (backupRequest.getBackupSchedule() != null) {
        Element backupScheduleElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "BackupSchedule");
        backupRequestElement.appendChild(backupScheduleElement);

        Element frequencyIntervalElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "FrequencyInterval");
        frequencyIntervalElement.appendChild(requestDoc
                .createTextNode(Integer.toString(backupRequest.getBackupSchedule().getFrequencyInterval())));
        backupScheduleElement.appendChild(frequencyIntervalElement);

        if (backupRequest.getBackupSchedule().getFrequencyUnit() != null) {
            Element frequencyUnitElement = requestDoc
                    .createElementNS("http://schemas.microsoft.com/windowsazure", "FrequencyUnit");
            frequencyUnitElement.appendChild(
                    requestDoc.createTextNode(backupRequest.getBackupSchedule().getFrequencyUnit().toString()));
            backupScheduleElement.appendChild(frequencyUnitElement);
        }

        Element keepAtLeastOneBackupElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "KeepAtLeastOneBackup");
        keepAtLeastOneBackupElement.appendChild(requestDoc.createTextNode(
                Boolean.toString(backupRequest.getBackupSchedule().isKeepAtLeastOneBackup()).toLowerCase()));
        backupScheduleElement.appendChild(keepAtLeastOneBackupElement);

        if (backupRequest.getBackupSchedule().getLastExecutionTime() != null) {
            Element lastExecutionTimeElement = requestDoc
                    .createElementNS("http://schemas.microsoft.com/windowsazure", "LastExecutionTime");
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
            simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
            lastExecutionTimeElement.appendChild(requestDoc.createTextNode(simpleDateFormat
                    .format(backupRequest.getBackupSchedule().getLastExecutionTime().getTime())));
            backupScheduleElement.appendChild(lastExecutionTimeElement);
        }

        Element retentionPeriodInDaysElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "RetentionPeriodInDays");
        retentionPeriodInDaysElement.appendChild(requestDoc.createTextNode(
                Integer.toString(backupRequest.getBackupSchedule().getRetentionPeriodInDays())));
        backupScheduleElement.appendChild(retentionPeriodInDaysElement);

        if (backupRequest.getBackupSchedule().getStartTime() != null) {
            Element startTimeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "StartTime");
            SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
            simpleDateFormat2.setTimeZone(TimeZone.getTimeZone("UTC"));
            startTimeElement.appendChild(requestDoc.createTextNode(
                    simpleDateFormat2.format(backupRequest.getBackupSchedule().getStartTime().getTime())));
            backupScheduleElement.appendChild(startTimeElement);
        }
    }

    if (backupRequest.getDatabases() != null) {
        if (backupRequest.getDatabases() instanceof LazyCollection == false
                || ((LazyCollection) backupRequest.getDatabases()).isInitialized()) {
            Element databasesSequenceElement = requestDoc
                    .createElementNS("http://schemas.microsoft.com/windowsazure", "Databases");
            for (DatabaseBackupSetting databasesItem : backupRequest.getDatabases()) {
                Element databaseBackupSettingElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "DatabaseBackupSetting");
                databasesSequenceElement.appendChild(databaseBackupSettingElement);

                if (databasesItem.getConnectionString() != null) {
                    Element connectionStringElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "ConnectionString");
                    connectionStringElement
                            .appendChild(requestDoc.createTextNode(databasesItem.getConnectionString()));
                    databaseBackupSettingElement.appendChild(connectionStringElement);
                }

                if (databasesItem.getConnectionStringName() != null) {
                    Element connectionStringNameElement = requestDoc.createElementNS(
                            "http://schemas.microsoft.com/windowsazure", "ConnectionStringName");
                    connectionStringNameElement
                            .appendChild(requestDoc.createTextNode(databasesItem.getConnectionStringName()));
                    databaseBackupSettingElement.appendChild(connectionStringNameElement);
                }

                if (databasesItem.getDatabaseType() != null) {
                    Element databaseTypeElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "DatabaseType");
                    databaseTypeElement.appendChild(requestDoc.createTextNode(databasesItem.getDatabaseType()));
                    databaseBackupSettingElement.appendChild(databaseTypeElement);
                }

                if (databasesItem.getName() != null) {
                    Element nameElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Name");
                    nameElement.appendChild(requestDoc.createTextNode(databasesItem.getName()));
                    databaseBackupSettingElement.appendChild(nameElement);
                }
            }
            backupRequestElement.appendChild(databasesSequenceElement);
        }
    }

    if (backupRequest.isEnabled() != null) {
        Element enabledElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "Enabled");
        enabledElement.appendChild(
                requestDoc.createTextNode(Boolean.toString(backupRequest.isEnabled()).toLowerCase()));
        backupRequestElement.appendChild(enabledElement);
    }

    if (backupRequest.getName() != null) {
        Element nameElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name");
        nameElement2.appendChild(requestDoc.createTextNode(backupRequest.getName()));
        backupRequestElement.appendChild(nameElement2);
    }

    if (backupRequest.getStorageAccountUrl() != null) {
        Element storageAccountUrlElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "StorageAccountUrl");
        storageAccountUrlElement.appendChild(requestDoc.createTextNode(backupRequest.getStorageAccountUrl()));
        backupRequestElement.appendChild(storageAccountUrlElement);
    }

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

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

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

            Element backupItemElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "BackupItem");
            if (backupItemElement != null) {
                BackupItem backupItemInstance = new BackupItem();
                result.setBackupItem(backupItemInstance);

                Element storageAccountUrlElement2 = XmlUtility.getElementByTagNameNS(backupItemElement,
                        "http://schemas.microsoft.com/windowsazure", "StorageAccountUrl");
                if (storageAccountUrlElement2 != null) {
                    String storageAccountUrlInstance;
                    storageAccountUrlInstance = storageAccountUrlElement2.getTextContent();
                    backupItemInstance.setStorageAccountUrl(storageAccountUrlInstance);
                }

                Element blobNameElement = XmlUtility.getElementByTagNameNS(backupItemElement,
                        "http://schemas.microsoft.com/windowsazure", "BlobName");
                if (blobNameElement != null) {
                    String blobNameInstance;
                    blobNameInstance = blobNameElement.getTextContent();
                    backupItemInstance.setBlobName(blobNameInstance);
                }

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

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

                Element sizeInBytesElement = XmlUtility.getElementByTagNameNS(backupItemElement,
                        "http://schemas.microsoft.com/windowsazure", "SizeInBytes");
                if (sizeInBytesElement != null) {
                    long sizeInBytesInstance;
                    sizeInBytesInstance = DatatypeConverter.parseLong(sizeInBytesElement.getTextContent());
                    backupItemInstance.setSizeInBytes(sizeInBytesInstance);
                }

                Element createdElement = XmlUtility.getElementByTagNameNS(backupItemElement,
                        "http://schemas.microsoft.com/windowsazure", "Created");
                if (createdElement != null && createdElement.getTextContent() != null
                        && !createdElement.getTextContent().isEmpty()) {
                    Calendar createdInstance;
                    createdInstance = DatatypeConverter.parseDateTime(createdElement.getTextContent());
                    backupItemInstance.setCreated(createdInstance);
                }

                Element logElement = XmlUtility.getElementByTagNameNS(backupItemElement,
                        "http://schemas.microsoft.com/windowsazure", "Log");
                if (logElement != null) {
                    String logInstance;
                    logInstance = logElement.getTextContent();
                    backupItemInstance.setLog(logInstance);
                }

                Element databasesSequenceElement2 = XmlUtility.getElementByTagNameNS(backupItemElement,
                        "http://schemas.microsoft.com/windowsazure", "Databases");
                if (databasesSequenceElement2 != null) {
                    for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(databasesSequenceElement2,
                                    "http://schemas.microsoft.com/windowsazure", "DatabaseBackupSetting")
                            .size(); i1 = i1 + 1) {
                        org.w3c.dom.Element databasesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(databasesSequenceElement2,
                                        "http://schemas.microsoft.com/windowsazure", "DatabaseBackupSetting")
                                .get(i1));
                        DatabaseBackupSetting databaseBackupSettingInstance = new DatabaseBackupSetting();
                        backupItemInstance.getDatabases().add(databaseBackupSettingInstance);

                        Element connectionStringElement2 = XmlUtility.getElementByTagNameNS(databasesElement,
                                "http://schemas.microsoft.com/windowsazure", "ConnectionString");
                        if (connectionStringElement2 != null) {
                            String connectionStringInstance;
                            connectionStringInstance = connectionStringElement2.getTextContent();
                            databaseBackupSettingInstance.setConnectionString(connectionStringInstance);
                        }

                        Element connectionStringNameElement2 = XmlUtility.getElementByTagNameNS(
                                databasesElement, "http://schemas.microsoft.com/windowsazure",
                                "ConnectionStringName");
                        if (connectionStringNameElement2 != null) {
                            String connectionStringNameInstance;
                            connectionStringNameInstance = connectionStringNameElement2.getTextContent();
                            databaseBackupSettingInstance.setConnectionStringName(connectionStringNameInstance);
                        }

                        Element databaseTypeElement2 = XmlUtility.getElementByTagNameNS(databasesElement,
                                "http://schemas.microsoft.com/windowsazure", "DatabaseType");
                        if (databaseTypeElement2 != null) {
                            String databaseTypeInstance;
                            databaseTypeInstance = databaseTypeElement2.getTextContent();
                            databaseBackupSettingInstance.setDatabaseType(databaseTypeInstance);
                        }

                        Element nameElement4 = XmlUtility.getElementByTagNameNS(databasesElement,
                                "http://schemas.microsoft.com/windowsazure", "Name");
                        if (nameElement4 != null) {
                            String nameInstance2;
                            nameInstance2 = nameElement4.getTextContent();
                            databaseBackupSettingInstance.setName(nameInstance2);
                        }
                    }
                }

                Element scheduledElement = XmlUtility.getElementByTagNameNS(backupItemElement,
                        "http://schemas.microsoft.com/windowsazure", "Scheduled");
                if (scheduledElement != null) {
                    boolean scheduledInstance;
                    scheduledInstance = DatatypeConverter
                            .parseBoolean(scheduledElement.getTextContent().toLowerCase());
                    backupItemInstance.setScheduled(scheduledInstance);
                }

                Element lastRestoreTimeStampElement = XmlUtility.getElementByTagNameNS(backupItemElement,
                        "http://schemas.microsoft.com/windowsazure", "LastRestoreTimeStamp");
                if (lastRestoreTimeStampElement != null && lastRestoreTimeStampElement.getTextContent() != null
                        && !lastRestoreTimeStampElement.getTextContent().isEmpty()) {
                    Calendar lastRestoreTimeStampInstance;
                    lastRestoreTimeStampInstance = DatatypeConverter
                            .parseDateTime(lastRestoreTimeStampElement.getTextContent());
                    backupItemInstance.setLastRestoreTimeStamp(lastRestoreTimeStampInstance);
                }

                Element finishedTimeStampElement = XmlUtility.getElementByTagNameNS(backupItemElement,
                        "http://schemas.microsoft.com/windowsazure", "FinishedTimeStamp");
                if (finishedTimeStampElement != null && finishedTimeStampElement.getTextContent() != null
                        && !finishedTimeStampElement.getTextContent().isEmpty()) {
                    Calendar finishedTimeStampInstance;
                    finishedTimeStampInstance = DatatypeConverter
                            .parseDateTime(finishedTimeStampElement.getTextContent());
                    backupItemInstance.setFinishedTimeStamp(finishedTimeStampInstance);
                }

                Element correlationIdElement = XmlUtility.getElementByTagNameNS(backupItemElement,
                        "http://schemas.microsoft.com/windowsazure", "CorrelationId");
                if (correlationIdElement != null) {
                    String correlationIdInstance;
                    correlationIdInstance = correlationIdElement.getTextContent();
                    backupItemInstance.setCorrelationId(correlationIdInstance);
                }
            }

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

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

From source file:com.microsoft.azure.management.compute.AvailabilitySetOperationsImpl.java

/**
* The operation to get the availability set.
*
* @param resourceGroupName Required. The name of the resource group.
* @param availabilitySetName Required. The name of the availability set.
* @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./*w ww . j  a v a 2  s. c  o  m*/
* @throws ServiceException Thrown if an unexpected response is found.
* @throws URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return GET Availability Set operation response.
*/
@Override
public AvailabilitySetGetResponse get(String resourceGroupName, String availabilitySetName)
        throws IOException, ServiceException, URISyntaxException {
    // Validate
    if (resourceGroupName == null) {
        throw new NullPointerException("resourceGroupName");
    }
    if (availabilitySetName == null) {
        throw new NullPointerException("availabilitySetName");
    }

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

    // Construct URL
    String url = "";
    url = url + "/subscriptions/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/resourceGroups/";
    url = url + URLEncoder.encode(resourceGroupName, "UTF-8");
    url = url + "/providers/";
    url = url + "Microsoft.Compute";
    url = url + "/availabilitySets/";
    url = url + URLEncoder.encode(availabilitySetName, "UTF-8");
    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
        AvailabilitySetGetResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new AvailabilitySetGetResponse();
            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) {
                AvailabilitySet availabilitySetInstance = new AvailabilitySet();
                result.setAvailabilitySet(availabilitySetInstance);

                JsonNode propertiesValue = responseDoc.get("properties");
                if (propertiesValue != null && propertiesValue instanceof NullNode == false) {
                    JsonNode platformUpdateDomainCountValue = propertiesValue.get("platformUpdateDomainCount");
                    if (platformUpdateDomainCountValue != null
                            && platformUpdateDomainCountValue instanceof NullNode == false) {
                        int platformUpdateDomainCountInstance;
                        platformUpdateDomainCountInstance = platformUpdateDomainCountValue.getIntValue();
                        availabilitySetInstance.setPlatformUpdateDomainCount(platformUpdateDomainCountInstance);
                    }

                    JsonNode platformFaultDomainCountValue = propertiesValue.get("platformFaultDomainCount");
                    if (platformFaultDomainCountValue != null
                            && platformFaultDomainCountValue instanceof NullNode == false) {
                        int platformFaultDomainCountInstance;
                        platformFaultDomainCountInstance = platformFaultDomainCountValue.getIntValue();
                        availabilitySetInstance.setPlatformFaultDomainCount(platformFaultDomainCountInstance);
                    }

                    JsonNode virtualMachinesArray = propertiesValue.get("virtualMachines");
                    if (virtualMachinesArray != null && virtualMachinesArray instanceof NullNode == false) {
                        for (JsonNode virtualMachinesValue : ((ArrayNode) virtualMachinesArray)) {
                            VirtualMachineReference virtualMachineReferenceInstance = new VirtualMachineReference();
                            availabilitySetInstance.getVirtualMachinesReferences()
                                    .add(virtualMachineReferenceInstance);

                            JsonNode idValue = virtualMachinesValue.get("id");
                            if (idValue != null && idValue instanceof NullNode == false) {
                                String idInstance;
                                idInstance = idValue.getTextValue();
                                virtualMachineReferenceInstance.setReferenceUri(idInstance);
                            }
                        }
                    }

                    JsonNode statusesArray = propertiesValue.get("statuses");
                    if (statusesArray != null && statusesArray instanceof NullNode == false) {
                        for (JsonNode statusesValue : ((ArrayNode) statusesArray)) {
                            InstanceViewStatus instanceViewStatusInstance = new InstanceViewStatus();
                            availabilitySetInstance.getStatuses().add(instanceViewStatusInstance);

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

                            JsonNode levelValue = statusesValue.get("level");
                            if (levelValue != null && levelValue instanceof NullNode == false) {
                                String levelInstance;
                                levelInstance = levelValue.getTextValue();
                                instanceViewStatusInstance.setLevel(levelInstance);
                            }

                            JsonNode displayStatusValue = statusesValue.get("displayStatus");
                            if (displayStatusValue != null && displayStatusValue instanceof NullNode == false) {
                                String displayStatusInstance;
                                displayStatusInstance = displayStatusValue.getTextValue();
                                instanceViewStatusInstance.setDisplayStatus(displayStatusInstance);
                            }

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

                            JsonNode timeValue = statusesValue.get("time");
                            if (timeValue != null && timeValue instanceof NullNode == false) {
                                Calendar timeInstance;
                                timeInstance = DatatypeConverter.parseDateTime(timeValue.getTextValue());
                                instanceViewStatusInstance.setTime(timeInstance);
                            }
                        }
                    }
                }

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

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

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

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

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

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

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

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

/**
* Returns information about an Azure SQL Database.
*
* @param serverName Required. The name of the Azure SQL Database Server on
* which the database is hosted.//from  w w w  .  ja  va2  s.c o m
* @param databaseName Required. The name of the Azure SQL Database to be
* retrieved.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @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 Contains the response to a Get Database request.
*/
@Override
public DatabaseGetResponse get(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, "getAsync", tracingParameters);
    }

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/services/sqlservers/servers/";
    url = url + URLEncoder.encode(serverName, "UTF-8");
    url = url + "/databases/";
    url = url + URLEncoder.encode(databaseName, "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
        DatabaseGetResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new DatabaseGetResponse();
            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) {
                Database serviceResourceInstance = new Database();
                result.setDatabase(serviceResourceInstance);

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

                Element editionElement = XmlUtility.getElementByTagNameNS(serviceResourceElement,
                        "http://schemas.microsoft.com/windowsazure", "Edition");
                if (editionElement != null) {
                    String editionInstance;
                    editionInstance = editionElement.getTextContent();
                    serviceResourceInstance.setEdition(editionInstance);
                }

                Element maxSizeGBElement = XmlUtility.getElementByTagNameNS(serviceResourceElement,
                        "http://schemas.microsoft.com/windowsazure", "MaxSizeGB");
                if (maxSizeGBElement != null) {
                    int maxSizeGBInstance;
                    maxSizeGBInstance = DatatypeConverter.parseInt(maxSizeGBElement.getTextContent());
                    serviceResourceInstance.setMaximumDatabaseSizeInGB(maxSizeGBInstance);
                }

                Element maxSizeBytesElement = XmlUtility.getElementByTagNameNS(serviceResourceElement,
                        "http://schemas.microsoft.com/windowsazure", "MaxSizeBytes");
                if (maxSizeBytesElement != null) {
                    long maxSizeBytesInstance;
                    maxSizeBytesInstance = DatatypeConverter.parseLong(maxSizeBytesElement.getTextContent());
                    serviceResourceInstance.setMaximumDatabaseSizeInBytes(maxSizeBytesInstance);
                }

                Element collationNameElement = XmlUtility.getElementByTagNameNS(serviceResourceElement,
                        "http://schemas.microsoft.com/windowsazure", "CollationName");
                if (collationNameElement != null) {
                    String collationNameInstance;
                    collationNameInstance = collationNameElement.getTextContent();
                    serviceResourceInstance.setCollationName(collationNameInstance);
                }

                Element creationDateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement,
                        "http://schemas.microsoft.com/windowsazure", "CreationDate");
                if (creationDateElement != null) {
                    Calendar creationDateInstance;
                    creationDateInstance = DatatypeConverter
                            .parseDateTime(creationDateElement.getTextContent());
                    serviceResourceInstance.setCreationDate(creationDateInstance);
                }

                Element isFederationRootElement = XmlUtility.getElementByTagNameNS(serviceResourceElement,
                        "http://schemas.microsoft.com/windowsazure", "IsFederationRoot");
                if (isFederationRootElement != null) {
                    boolean isFederationRootInstance;
                    isFederationRootInstance = DatatypeConverter
                            .parseBoolean(isFederationRootElement.getTextContent().toLowerCase());
                    serviceResourceInstance.setIsFederationRoot(isFederationRootInstance);
                }

                Element isSystemObjectElement = XmlUtility.getElementByTagNameNS(serviceResourceElement,
                        "http://schemas.microsoft.com/windowsazure", "IsSystemObject");
                if (isSystemObjectElement != null) {
                    boolean isSystemObjectInstance;
                    isSystemObjectInstance = DatatypeConverter
                            .parseBoolean(isSystemObjectElement.getTextContent().toLowerCase());
                    serviceResourceInstance.setIsSystemObject(isSystemObjectInstance);
                }

                Element sizeMBElement = XmlUtility.getElementByTagNameNS(serviceResourceElement,
                        "http://schemas.microsoft.com/windowsazure", "SizeMB");
                if (sizeMBElement != null) {
                    String sizeMBInstance;
                    sizeMBInstance = sizeMBElement.getTextContent();
                    serviceResourceInstance.setSizeMB(sizeMBInstance);
                }

                Element serviceObjectiveAssignmentErrorCodeElement = XmlUtility.getElementByTagNameNS(
                        serviceResourceElement, "http://schemas.microsoft.com/windowsazure",
                        "ServiceObjectiveAssignmentErrorCode");
                if (serviceObjectiveAssignmentErrorCodeElement != null) {
                    String serviceObjectiveAssignmentErrorCodeInstance;
                    serviceObjectiveAssignmentErrorCodeInstance = serviceObjectiveAssignmentErrorCodeElement
                            .getTextContent();
                    serviceResourceInstance.setServiceObjectiveAssignmentErrorCode(
                            serviceObjectiveAssignmentErrorCodeInstance);
                }

                Element serviceObjectiveAssignmentErrorDescriptionElement = XmlUtility.getElementByTagNameNS(
                        serviceResourceElement, "http://schemas.microsoft.com/windowsazure",
                        "ServiceObjectiveAssignmentErrorDescription");
                if (serviceObjectiveAssignmentErrorDescriptionElement != null) {
                    String serviceObjectiveAssignmentErrorDescriptionInstance;
                    serviceObjectiveAssignmentErrorDescriptionInstance = serviceObjectiveAssignmentErrorDescriptionElement
                            .getTextContent();
                    serviceResourceInstance.setServiceObjectiveAssignmentErrorDescription(
                            serviceObjectiveAssignmentErrorDescriptionInstance);
                }

                Element serviceObjectiveAssignmentStateElement = XmlUtility.getElementByTagNameNS(
                        serviceResourceElement, "http://schemas.microsoft.com/windowsazure",
                        "ServiceObjectiveAssignmentState");
                if (serviceObjectiveAssignmentStateElement != null) {
                    String serviceObjectiveAssignmentStateInstance;
                    serviceObjectiveAssignmentStateInstance = serviceObjectiveAssignmentStateElement
                            .getTextContent();
                    serviceResourceInstance
                            .setServiceObjectiveAssignmentState(serviceObjectiveAssignmentStateInstance);
                }

                Element serviceObjectiveAssignmentStateDescriptionElement = XmlUtility.getElementByTagNameNS(
                        serviceResourceElement, "http://schemas.microsoft.com/windowsazure",
                        "ServiceObjectiveAssignmentStateDescription");
                if (serviceObjectiveAssignmentStateDescriptionElement != null) {
                    String serviceObjectiveAssignmentStateDescriptionInstance;
                    serviceObjectiveAssignmentStateDescriptionInstance = serviceObjectiveAssignmentStateDescriptionElement
                            .getTextContent();
                    serviceResourceInstance.setServiceObjectiveAssignmentStateDescription(
                            serviceObjectiveAssignmentStateDescriptionInstance);
                }

                Element serviceObjectiveAssignmentSuccessDateElement = XmlUtility.getElementByTagNameNS(
                        serviceResourceElement, "http://schemas.microsoft.com/windowsazure",
                        "ServiceObjectiveAssignmentSuccessDate");
                if (serviceObjectiveAssignmentSuccessDateElement != null) {
                    String serviceObjectiveAssignmentSuccessDateInstance;
                    serviceObjectiveAssignmentSuccessDateInstance = serviceObjectiveAssignmentSuccessDateElement
                            .getTextContent();
                    serviceResourceInstance.setServiceObjectiveAssignmentSuccessDate(
                            serviceObjectiveAssignmentSuccessDateInstance);
                }

                Element serviceObjectiveIdElement = XmlUtility.getElementByTagNameNS(serviceResourceElement,
                        "http://schemas.microsoft.com/windowsazure", "ServiceObjectiveId");
                if (serviceObjectiveIdElement != null) {
                    String serviceObjectiveIdInstance;
                    serviceObjectiveIdInstance = serviceObjectiveIdElement.getTextContent();
                    serviceResourceInstance.setServiceObjectiveId(serviceObjectiveIdInstance);
                }

                Element assignedServiceObjectiveIdElement = XmlUtility.getElementByTagNameNS(
                        serviceResourceElement, "http://schemas.microsoft.com/windowsazure",
                        "AssignedServiceObjectiveId");
                if (assignedServiceObjectiveIdElement != null) {
                    String assignedServiceObjectiveIdInstance;
                    assignedServiceObjectiveIdInstance = assignedServiceObjectiveIdElement.getTextContent();
                    serviceResourceInstance.setAssignedServiceObjectiveId(assignedServiceObjectiveIdInstance);
                }

                Element recoveryPeriodStartDateElement = XmlUtility.getElementByTagNameNS(
                        serviceResourceElement, "http://schemas.microsoft.com/windowsazure",
                        "RecoveryPeriodStartDate");
                if (recoveryPeriodStartDateElement != null
                        && recoveryPeriodStartDateElement.getTextContent() != null
                        && !recoveryPeriodStartDateElement.getTextContent().isEmpty()) {
                    Calendar recoveryPeriodStartDateInstance;
                    recoveryPeriodStartDateInstance = DatatypeConverter
                            .parseDateTime(recoveryPeriodStartDateElement.getTextContent());
                    serviceResourceInstance.setRecoveryPeriodStartDate(recoveryPeriodStartDateInstance);
                }

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

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

/**
* The List Resource Extension Versions operation lists the versions of a
* resource extension that are available to add to a Virtual Machine. In
* Azure, a process can run as a resource extension of a Virtual Machine.
* For example, Remote Desktop Access or the Azure Diagnostics Agent can
* run as resource extensions to the Virtual Machine.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/dn495440.aspx for
* more information)//w ww .j a  va  2  s. co  m
*
* @param publisherName Required. The name of the publisher.
* @param extensionName Required. The name of the extension.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @throws ParserConfigurationException Thrown if there was a serious
* configuration error with the document parser.
* @throws SAXException Thrown if there was an error parsing the XML
* response.
* @throws URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return The List Resource Extensions operation response.
*/
@Override
public VirtualMachineExtensionListResponse listVersions(String publisherName, String extensionName)
        throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException {
    // Validate
    if (publisherName == null) {
        throw new NullPointerException("publisherName");
    }
    if (extensionName == null) {
        throw new NullPointerException("extensionName");
    }

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

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/services/resourceextensions/";
    url = url + URLEncoder.encode(publisherName, "UTF-8");
    url = url + "/";
    url = url + URLEncoder.encode(extensionName, "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", "2015-04-01");

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

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

            Element resourceExtensionsSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "ResourceExtensions");
            if (resourceExtensionsSequenceElement != null) {
                for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                        .getElementsByTagNameNS(resourceExtensionsSequenceElement,
                                "http://schemas.microsoft.com/windowsazure", "ResourceExtension")
                        .size(); i1 = i1 + 1) {
                    org.w3c.dom.Element resourceExtensionsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(resourceExtensionsSequenceElement,
                                    "http://schemas.microsoft.com/windowsazure", "ResourceExtension")
                            .get(i1));
                    VirtualMachineExtensionListResponse.ResourceExtension resourceExtensionInstance = new VirtualMachineExtensionListResponse.ResourceExtension();
                    result.getResourceExtensions().add(resourceExtensionInstance);

                    Element publisherElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement,
                            "http://schemas.microsoft.com/windowsazure", "Publisher");
                    if (publisherElement != null) {
                        String publisherInstance;
                        publisherInstance = publisherElement.getTextContent();
                        resourceExtensionInstance.setPublisher(publisherInstance);
                    }

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

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

                    Element labelElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement,
                            "http://schemas.microsoft.com/windowsazure", "Label");
                    if (labelElement != null) {
                        String labelInstance;
                        labelInstance = labelElement.getTextContent();
                        resourceExtensionInstance.setLabel(labelInstance);
                    }

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

                    Element publicConfigurationSchemaElement = XmlUtility.getElementByTagNameNS(
                            resourceExtensionsElement, "http://schemas.microsoft.com/windowsazure",
                            "PublicConfigurationSchema");
                    if (publicConfigurationSchemaElement != null) {
                        String publicConfigurationSchemaInstance;
                        publicConfigurationSchemaInstance = publicConfigurationSchemaElement
                                .getTextContent() != null ? new String(
                                        Base64.decode(publicConfigurationSchemaElement.getTextContent()))
                                        : null;
                        resourceExtensionInstance
                                .setPublicConfigurationSchema(publicConfigurationSchemaInstance);
                    }

                    Element privateConfigurationSchemaElement = XmlUtility.getElementByTagNameNS(
                            resourceExtensionsElement, "http://schemas.microsoft.com/windowsazure",
                            "PrivateConfigurationSchema");
                    if (privateConfigurationSchemaElement != null) {
                        String privateConfigurationSchemaInstance;
                        privateConfigurationSchemaInstance = privateConfigurationSchemaElement
                                .getTextContent() != null ? new String(
                                        Base64.decode(privateConfigurationSchemaElement.getTextContent()))
                                        : null;
                        resourceExtensionInstance
                                .setPrivateConfigurationSchema(privateConfigurationSchemaInstance);
                    }

                    Element sampleConfigElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement,
                            "http://schemas.microsoft.com/windowsazure", "SampleConfig");
                    if (sampleConfigElement != null) {
                        String sampleConfigInstance;
                        sampleConfigInstance = sampleConfigElement.getTextContent() != null
                                ? new String(Base64.decode(sampleConfigElement.getTextContent()))
                                : null;
                        resourceExtensionInstance.setSampleConfig(sampleConfigInstance);
                    }

                    Element replicationCompletedElement = XmlUtility.getElementByTagNameNS(
                            resourceExtensionsElement, "http://schemas.microsoft.com/windowsazure",
                            "ReplicationCompleted");
                    if (replicationCompletedElement != null
                            && replicationCompletedElement.getTextContent() != null
                            && !replicationCompletedElement.getTextContent().isEmpty()) {
                        boolean replicationCompletedInstance;
                        replicationCompletedInstance = DatatypeConverter
                                .parseBoolean(replicationCompletedElement.getTextContent().toLowerCase());
                        resourceExtensionInstance.setReplicationCompleted(replicationCompletedInstance);
                    }

                    Element eulaElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement,
                            "http://schemas.microsoft.com/windowsazure", "Eula");
                    if (eulaElement != null) {
                        URI eulaInstance;
                        eulaInstance = new URI(eulaElement.getTextContent());
                        resourceExtensionInstance.setEula(eulaInstance);
                    }

                    Element privacyUriElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement,
                            "http://schemas.microsoft.com/windowsazure", "PrivacyUri");
                    if (privacyUriElement != null) {
                        URI privacyUriInstance;
                        privacyUriInstance = new URI(privacyUriElement.getTextContent());
                        resourceExtensionInstance.setPrivacyUri(privacyUriInstance);
                    }

                    Element homepageUriElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement,
                            "http://schemas.microsoft.com/windowsazure", "HomepageUri");
                    if (homepageUriElement != null) {
                        URI homepageUriInstance;
                        homepageUriInstance = new URI(homepageUriElement.getTextContent());
                        resourceExtensionInstance.setHomepageUri(homepageUriInstance);
                    }

                    Element isJsonExtensionElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement,
                            "http://schemas.microsoft.com/windowsazure", "IsJsonExtension");
                    if (isJsonExtensionElement != null && isJsonExtensionElement.getTextContent() != null
                            && !isJsonExtensionElement.getTextContent().isEmpty()) {
                        boolean isJsonExtensionInstance;
                        isJsonExtensionInstance = DatatypeConverter
                                .parseBoolean(isJsonExtensionElement.getTextContent().toLowerCase());
                        resourceExtensionInstance.setIsJsonExtension(isJsonExtensionInstance);
                    }

                    Element isInternalExtensionElement = XmlUtility.getElementByTagNameNS(
                            resourceExtensionsElement, "http://schemas.microsoft.com/windowsazure",
                            "IsInternalExtension");
                    if (isInternalExtensionElement != null
                            && isInternalExtensionElement.getTextContent() != null
                            && !isInternalExtensionElement.getTextContent().isEmpty()) {
                        boolean isInternalExtensionInstance;
                        isInternalExtensionInstance = DatatypeConverter
                                .parseBoolean(isInternalExtensionElement.getTextContent().toLowerCase());
                        resourceExtensionInstance.setIsInternalExtension(isInternalExtensionInstance);
                    }

                    Element disallowMajorVersionUpgradeElement = XmlUtility.getElementByTagNameNS(
                            resourceExtensionsElement, "http://schemas.microsoft.com/windowsazure",
                            "DisallowMajorVersionUpgrade");
                    if (disallowMajorVersionUpgradeElement != null
                            && disallowMajorVersionUpgradeElement.getTextContent() != null
                            && !disallowMajorVersionUpgradeElement.getTextContent().isEmpty()) {
                        boolean disallowMajorVersionUpgradeInstance;
                        disallowMajorVersionUpgradeInstance = DatatypeConverter.parseBoolean(
                                disallowMajorVersionUpgradeElement.getTextContent().toLowerCase());
                        resourceExtensionInstance
                                .setDisallowMajorVersionUpgrade(disallowMajorVersionUpgradeInstance);
                    }

                    Element supportedOSElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement,
                            "http://schemas.microsoft.com/windowsazure", "SupportedOS");
                    if (supportedOSElement != null) {
                        String supportedOSInstance;
                        supportedOSInstance = supportedOSElement.getTextContent();
                        resourceExtensionInstance.setSupportedOS(supportedOSInstance);
                    }

                    Element companyNameElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement,
                            "http://schemas.microsoft.com/windowsazure", "CompanyName");
                    if (companyNameElement != null) {
                        String companyNameInstance;
                        companyNameInstance = companyNameElement.getTextContent();
                        resourceExtensionInstance.setCompanyName(companyNameInstance);
                    }

                    Element publishedDateElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement,
                            "http://schemas.microsoft.com/windowsazure", "PublishedDate");
                    if (publishedDateElement != null && publishedDateElement.getTextContent() != null
                            && !publishedDateElement.getTextContent().isEmpty()) {
                        Calendar publishedDateInstance;
                        publishedDateInstance = DatatypeConverter
                                .parseDateTime(publishedDateElement.getTextContent());
                        resourceExtensionInstance.setPublishedDate(publishedDateInstance);
                    }

                    Element regionsElement = XmlUtility.getElementByTagNameNS(resourceExtensionsElement,
                            "http://schemas.microsoft.com/windowsazure", "Regions");
                    if (regionsElement != null) {
                        String regionsInstance;
                        regionsInstance = regionsElement.getTextContent();
                        resourceExtensionInstance.setRegions(regionsInstance);
                    }
                }
            }

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