Example usage for org.apache.http.client.methods HttpPatch setEntity

List of usage examples for org.apache.http.client.methods HttpPatch setEntity

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpPatch setEntity.

Prototype

public void setEntity(final HttpEntity entity) 

Source Link

Usage

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

/**
* Resource groups can be updated through a simple PATCH operation to a
* group address. The format of the request is the same as that for
* creating a resource groups, though if a field is unspecified current
* value will be carried over.//from   www . j a va  2s .c o  m
*
* @param resourceGroupName Required. The name of the resource group to be
* created or updated. The name is case insensitive.
* @param parameters Required. Parameters supplied to the update state
* resource group service 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.
* @return Resource group information.
*/
@Override
public ResourceGroupPatchResult patch(String resourceGroupName, ResourceGroup parameters)
        throws IOException, ServiceException {
    // 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 (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getLocation() == null) {
        throw new NullPointerException("parameters.Location");
    }

    // Tracing
    boolean shouldTrace = CloudTracing.getIsEnabled();
    String invocationId = null;
    if (shouldTrace) {
        invocationId = Long.toString(CloudTracing.getNextInvocationId());
        HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
        tracingParameters.put("resourceGroupName", resourceGroupName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "patchAsync", 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");
    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
    HttpPatch httpRequest = new HttpPatch(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 resourceGroupValue = objectMapper.createObjectNode();
    requestDoc = resourceGroupValue;

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

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

    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) resourceGroupValue).put("tags", tagsDictionary);
        }
    }

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

    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
        ResourceGroupPatchResult result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new ResourceGroupPatchResult();
            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) {
                ResourceGroupExtended resourceGroupInstance = new ResourceGroupExtended();
                result.setResourceGroup(resourceGroupInstance);

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

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

                JsonNode propertiesValue = responseDoc.get("properties");
                if (propertiesValue != null && propertiesValue instanceof NullNode == false) {
                    JsonNode provisioningStateValue = propertiesValue.get("provisioningState");
                    if (provisioningStateValue != null && provisioningStateValue instanceof NullNode == false) {
                        String provisioningStateInstance;
                        provisioningStateInstance = provisioningStateValue.getTextValue();
                        resourceGroupInstance.setProvisioningState(provisioningStateInstance);
                    }
                }

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

                JsonNode propertiesValue2 = responseDoc.get("properties");
                if (propertiesValue2 != null && propertiesValue2 instanceof NullNode == false) {
                    String propertiesInstance;
                    propertiesInstance = propertiesValue2.getTextValue();
                    resourceGroupInstance.setProperties(propertiesInstance);
                }

                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();
                        resourceGroupInstance.getTags().put(tagsKey2, tagsValue2);
                    }
                }

                JsonNode provisioningStateValue2 = responseDoc.get("provisioningState");
                if (provisioningStateValue2 != null && provisioningStateValue2 instanceof NullNode == false) {
                    String provisioningStateInstance2;
                    provisioningStateInstance2 = provisioningStateValue2.getTextValue();
                    resourceGroupInstance.setProvisioningState(provisioningStateInstance2);
                }
            }

        }
        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.trafficmanager.EndpointOperationsImpl.java

/**
* Create or update a Traffic Manager endpoint.
*
* @param resourceGroupName Required. The name of the resource group
* containing the Traffic Manager endpoint to be created or updated.
* @param profileName Required. The name of the Traffic Manager endpoint to
* be created or updated.//ww w.j av  a2s.  c  o m
* @param endpointType Required. The type of the Traffic Manager endpoint to
* be created or updated.
* @param endpointName Required. The name of the Traffic Manager endpoint to
* be created or updated.
* @param parameters Required. The Traffic Manager endpoint parameters
* supplied to the Update 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.
* @return The response to a Traffic Manager endpoint 'CreateOrUpdate'
* operation.
*/
@Override
public EndpointUpdateResponse update(String resourceGroupName, String profileName, String endpointType,
        String endpointName, EndpointUpdateParameters parameters) throws IOException, ServiceException {
    // Validate
    if (resourceGroupName == null) {
        throw new NullPointerException("resourceGroupName");
    }
    if (profileName == null) {
        throw new NullPointerException("profileName");
    }
    if (endpointType == null) {
        throw new NullPointerException("endpointType");
    }
    if (endpointName == null) {
        throw new NullPointerException("endpointName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getEndpoint() == null) {
        throw new NullPointerException("parameters.Endpoint");
    }

    // 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("profileName", profileName);
        tracingParameters.put("endpointType", endpointType);
        tracingParameters.put("endpointName", endpointName);
        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.Network";
    url = url + "/trafficmanagerprofiles/";
    url = url + URLEncoder.encode(profileName, "UTF-8");
    url = url + "/";
    url = url + URLEncoder.encode(endpointType, "UTF-8");
    url = url + "/";
    url = url + URLEncoder.encode(endpointName, "UTF-8");
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("api-version=" + "2015-11-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
    HttpPatch httpRequest = new HttpPatch(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 endpointUpdateParametersValue = objectMapper.createObjectNode();
    requestDoc = endpointUpdateParametersValue;

    if (parameters.getEndpoint().getId() != null) {
        ((ObjectNode) endpointUpdateParametersValue).put("id", parameters.getEndpoint().getId());
    }

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

    if (parameters.getEndpoint().getType() != null) {
        ((ObjectNode) endpointUpdateParametersValue).put("type", parameters.getEndpoint().getType());
    }

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

        if (parameters.getEndpoint().getProperties().getTargetResourceId() != null) {
            ((ObjectNode) propertiesValue).put("targetResourceId",
                    parameters.getEndpoint().getProperties().getTargetResourceId());
        }

        if (parameters.getEndpoint().getProperties().getTarget() != null) {
            ((ObjectNode) propertiesValue).put("target", parameters.getEndpoint().getProperties().getTarget());
        }

        if (parameters.getEndpoint().getProperties().getEndpointStatus() != null) {
            ((ObjectNode) propertiesValue).put("endpointStatus",
                    parameters.getEndpoint().getProperties().getEndpointStatus());
        }

        if (parameters.getEndpoint().getProperties().getWeight() != null) {
            ((ObjectNode) propertiesValue).put("weight", parameters.getEndpoint().getProperties().getWeight());
        }

        if (parameters.getEndpoint().getProperties().getPriority() != null) {
            ((ObjectNode) propertiesValue).put("priority",
                    parameters.getEndpoint().getProperties().getPriority());
        }

        if (parameters.getEndpoint().getProperties().getEndpointLocation() != null) {
            ((ObjectNode) propertiesValue).put("endpointLocation",
                    parameters.getEndpoint().getProperties().getEndpointLocation());
        }

        if (parameters.getEndpoint().getProperties().getEndpointMonitorStatus() != null) {
            ((ObjectNode) propertiesValue).put("endpointMonitorStatus",
                    parameters.getEndpoint().getProperties().getEndpointMonitorStatus());
        }

        if (parameters.getEndpoint().getProperties().getMinChildEndpoints() != null) {
            ((ObjectNode) propertiesValue).put("minChildEndpoints",
                    parameters.getEndpoint().getProperties().getMinChildEndpoints());
        }
    }

    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_BAD_REQUEST) {
            ServiceException ex = ServiceException.createFromJson(httpRequest, requestContent, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

        // Create Result
        EndpointUpdateResponse result = null;
        // Deserialize Response
        InputStream responseContent = httpResponse.getEntity().getContent();
        result = new EndpointUpdateResponse();
        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) {
            Endpoint endpointInstance = new Endpoint();
            result.setEndpoint(endpointInstance);

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

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

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

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

                JsonNode targetResourceIdValue = propertiesValue2.get("targetResourceId");
                if (targetResourceIdValue != null && targetResourceIdValue instanceof NullNode == false) {
                    String targetResourceIdInstance;
                    targetResourceIdInstance = targetResourceIdValue.getTextValue();
                    propertiesInstance.setTargetResourceId(targetResourceIdInstance);
                }

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

                JsonNode endpointStatusValue = propertiesValue2.get("endpointStatus");
                if (endpointStatusValue != null && endpointStatusValue instanceof NullNode == false) {
                    String endpointStatusInstance;
                    endpointStatusInstance = endpointStatusValue.getTextValue();
                    propertiesInstance.setEndpointStatus(endpointStatusInstance);
                }

                JsonNode weightValue = propertiesValue2.get("weight");
                if (weightValue != null && weightValue instanceof NullNode == false) {
                    long weightInstance;
                    weightInstance = weightValue.getLongValue();
                    propertiesInstance.setWeight(weightInstance);
                }

                JsonNode priorityValue = propertiesValue2.get("priority");
                if (priorityValue != null && priorityValue instanceof NullNode == false) {
                    long priorityInstance;
                    priorityInstance = priorityValue.getLongValue();
                    propertiesInstance.setPriority(priorityInstance);
                }

                JsonNode endpointLocationValue = propertiesValue2.get("endpointLocation");
                if (endpointLocationValue != null && endpointLocationValue instanceof NullNode == false) {
                    String endpointLocationInstance;
                    endpointLocationInstance = endpointLocationValue.getTextValue();
                    propertiesInstance.setEndpointLocation(endpointLocationInstance);
                }

                JsonNode endpointMonitorStatusValue = propertiesValue2.get("endpointMonitorStatus");
                if (endpointMonitorStatusValue != null
                        && endpointMonitorStatusValue instanceof NullNode == false) {
                    String endpointMonitorStatusInstance;
                    endpointMonitorStatusInstance = endpointMonitorStatusValue.getTextValue();
                    propertiesInstance.setEndpointMonitorStatus(endpointMonitorStatusInstance);
                }

                JsonNode minChildEndpointsValue = propertiesValue2.get("minChildEndpoints");
                if (minChildEndpointsValue != null && minChildEndpointsValue instanceof NullNode == false) {
                    long minChildEndpointsInstance;
                    minChildEndpointsInstance = minChildEndpointsValue.getLongValue();
                    propertiesInstance.setMinChildEndpoints(minChildEndpointsInstance);
                }
            }
        }

        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.storage.StorageAccountOperationsImpl.java

/**
* Updates the account type or tags for a storage account. It can also be
* used to add a custom domain (note that custom domains cannot be added
* via the Create operation). Only one custom domain is supported per
* storage account. In order to replace a custom domain, the old value must
* be cleared before a new value may be set. To clear a custom domain,
* simply update the custom domain with empty string. Then call update
* again with the new cutsom domain name. The update API can only be used
* to update one of tags, accountType, or customDomain per call. To update
* multiple of these properties, call the API multiple times with one
* change per call. This call does not change the storage keys for the
* account. If you want to change storage account keys, use the
* RegenerateKey operation. The location and name of the storage account
* cannot be changed after creation.//from  w w  w .  ja  v  a2 s  . c o m
*
* @param resourceGroupName Required. The name of the resource group within
* the user's subscription.
* @param accountName Required. The name of the storage account within the
* specified resource group. Storage account names must be between 3 and 24
* characters in length and use numbers and lower-case letters only.
* @param parameters Required. The parameters to update on the account. Note
* that only one property can be changed at a time using this API.
* @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 Update storage account operation response.
*/
@Override
public StorageAccountUpdateResponse update(String resourceGroupName, String accountName,
        StorageAccountUpdateParameters parameters) throws IOException, ServiceException, URISyntaxException {
    // Validate
    if (resourceGroupName == null) {
        throw new NullPointerException("resourceGroupName");
    }
    if (accountName == null) {
        throw new NullPointerException("accountName");
    }
    if (accountName.length() < 3) {
        throw new IllegalArgumentException("accountName");
    }
    if (accountName.length() > 24) {
        throw new IllegalArgumentException("accountName");
    }
    for (char accountNameChar : accountName.toCharArray()) {
        if (Character.isLowerCase(accountNameChar) == false && Character.isDigit(accountNameChar) == false) {
            throw new IllegalArgumentException("accountName");
        }
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getCustomDomain() != null) {
        if (parameters.getCustomDomain().getName() == null) {
            throw new NullPointerException("parameters.CustomDomain.Name");
        }
    }

    // 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("accountName", accountName);
        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/Microsoft.Storage/storageAccounts/";
    url = url + URLEncoder.encode(accountName, "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
    HttpPatch httpRequest = new HttpPatch(url);

    // Set Headers
    httpRequest.setHeader("Content-Type", "application/json");
    httpRequest.setHeader("x-ms-client-request-id", UUID.randomUUID().toString());

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

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

    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) storageAccountUpdateParametersJsonValue).put("tags", tagsDictionary);
        }
    }

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

    if (parameters.getAccountType() != null) {
        ((ObjectNode) propertiesValue).put("accountType",
                StorageManagementClientImpl.accountTypeToString(parameters.getAccountType()));
    }

    if (parameters.getCustomDomain() != null) {
        ObjectNode customDomainValue = objectMapper.createObjectNode();
        ((ObjectNode) propertiesValue).put("customDomain", customDomainValue);

        ((ObjectNode) customDomainValue).put("name", parameters.getCustomDomain().getName());

        if (parameters.getCustomDomain().isUseSubDomain() != null) {
            ((ObjectNode) customDomainValue).put("useSubDomain", parameters.getCustomDomain().isUseSubDomain());
        }
    }

    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) {
            ServiceException ex = ServiceException.createFromJson(httpRequest, requestContent, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

        // Create Result
        StorageAccountUpdateResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new StorageAccountUpdateResponse();
            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) {
                StorageAccount storageAccountInstance = new StorageAccount();
                result.setStorageAccount(storageAccountInstance);

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

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

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

                JsonNode locationValue = responseDoc.get("location");
                if (locationValue != null && locationValue instanceof NullNode == false) {
                    String locationInstance;
                    locationInstance = locationValue.getTextValue();
                    storageAccountInstance.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 tagsKey2 = property.getKey();
                        String tagsValue2 = property.getValue().getTextValue();
                        storageAccountInstance.getTags().put(tagsKey2, tagsValue2);
                    }
                }

                JsonNode propertiesValue2 = responseDoc.get("properties");
                if (propertiesValue2 != null && propertiesValue2 instanceof NullNode == false) {
                    JsonNode provisioningStateValue = propertiesValue2.get("provisioningState");
                    if (provisioningStateValue != null && provisioningStateValue instanceof NullNode == false) {
                        ProvisioningState provisioningStateInstance;
                        provisioningStateInstance = EnumUtility.fromString(ProvisioningState.class,
                                provisioningStateValue.getTextValue());
                        storageAccountInstance.setProvisioningState(provisioningStateInstance);
                    }

                    JsonNode accountTypeValue = propertiesValue2.get("accountType");
                    if (accountTypeValue != null && accountTypeValue instanceof NullNode == false) {
                        AccountType accountTypeInstance;
                        accountTypeInstance = StorageManagementClientImpl
                                .parseAccountType(accountTypeValue.getTextValue());
                        storageAccountInstance.setAccountType(accountTypeInstance);
                    }

                    JsonNode primaryEndpointsValue = propertiesValue2.get("primaryEndpoints");
                    if (primaryEndpointsValue != null && primaryEndpointsValue instanceof NullNode == false) {
                        Endpoints primaryEndpointsInstance = new Endpoints();
                        storageAccountInstance.setPrimaryEndpoints(primaryEndpointsInstance);

                        JsonNode blobValue = primaryEndpointsValue.get("blob");
                        if (blobValue != null && blobValue instanceof NullNode == false) {
                            URI blobInstance;
                            blobInstance = new URI(blobValue.getTextValue());
                            primaryEndpointsInstance.setBlob(blobInstance);
                        }

                        JsonNode queueValue = primaryEndpointsValue.get("queue");
                        if (queueValue != null && queueValue instanceof NullNode == false) {
                            URI queueInstance;
                            queueInstance = new URI(queueValue.getTextValue());
                            primaryEndpointsInstance.setQueue(queueInstance);
                        }

                        JsonNode tableValue = primaryEndpointsValue.get("table");
                        if (tableValue != null && tableValue instanceof NullNode == false) {
                            URI tableInstance;
                            tableInstance = new URI(tableValue.getTextValue());
                            primaryEndpointsInstance.setTable(tableInstance);
                        }

                        JsonNode fileValue = primaryEndpointsValue.get("file");
                        if (fileValue != null && fileValue instanceof NullNode == false) {
                            URI fileInstance;
                            fileInstance = new URI(fileValue.getTextValue());
                            primaryEndpointsInstance.setFile(fileInstance);
                        }
                    }

                    JsonNode primaryLocationValue = propertiesValue2.get("primaryLocation");
                    if (primaryLocationValue != null && primaryLocationValue instanceof NullNode == false) {
                        String primaryLocationInstance;
                        primaryLocationInstance = primaryLocationValue.getTextValue();
                        storageAccountInstance.setPrimaryLocation(primaryLocationInstance);
                    }

                    JsonNode statusOfPrimaryValue = propertiesValue2.get("statusOfPrimary");
                    if (statusOfPrimaryValue != null && statusOfPrimaryValue instanceof NullNode == false) {
                        AccountStatus statusOfPrimaryInstance;
                        statusOfPrimaryInstance = EnumUtility.fromString(AccountStatus.class,
                                statusOfPrimaryValue.getTextValue());
                        storageAccountInstance.setStatusOfPrimary(statusOfPrimaryInstance);
                    }

                    JsonNode lastGeoFailoverTimeValue = propertiesValue2.get("lastGeoFailoverTime");
                    if (lastGeoFailoverTimeValue != null
                            && lastGeoFailoverTimeValue instanceof NullNode == false) {
                        Calendar lastGeoFailoverTimeInstance;
                        lastGeoFailoverTimeInstance = DatatypeConverter
                                .parseDateTime(lastGeoFailoverTimeValue.getTextValue());
                        storageAccountInstance.setLastGeoFailoverTime(lastGeoFailoverTimeInstance);
                    }

                    JsonNode secondaryLocationValue = propertiesValue2.get("secondaryLocation");
                    if (secondaryLocationValue != null && secondaryLocationValue instanceof NullNode == false) {
                        String secondaryLocationInstance;
                        secondaryLocationInstance = secondaryLocationValue.getTextValue();
                        storageAccountInstance.setSecondaryLocation(secondaryLocationInstance);
                    }

                    JsonNode statusOfSecondaryValue = propertiesValue2.get("statusOfSecondary");
                    if (statusOfSecondaryValue != null && statusOfSecondaryValue instanceof NullNode == false) {
                        AccountStatus statusOfSecondaryInstance;
                        statusOfSecondaryInstance = EnumUtility.fromString(AccountStatus.class,
                                statusOfSecondaryValue.getTextValue());
                        storageAccountInstance.setStatusOfSecondary(statusOfSecondaryInstance);
                    }

                    JsonNode creationTimeValue = propertiesValue2.get("creationTime");
                    if (creationTimeValue != null && creationTimeValue instanceof NullNode == false) {
                        Calendar creationTimeInstance;
                        creationTimeInstance = DatatypeConverter
                                .parseDateTime(creationTimeValue.getTextValue());
                        storageAccountInstance.setCreationTime(creationTimeInstance);
                    }

                    JsonNode customDomainValue2 = propertiesValue2.get("customDomain");
                    if (customDomainValue2 != null && customDomainValue2 instanceof NullNode == false) {
                        CustomDomain customDomainInstance = new CustomDomain();
                        storageAccountInstance.setCustomDomain(customDomainInstance);

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

                        JsonNode useSubDomainValue = customDomainValue2.get("useSubDomain");
                        if (useSubDomainValue != null && useSubDomainValue instanceof NullNode == false) {
                            boolean useSubDomainInstance;
                            useSubDomainInstance = useSubDomainValue.getBooleanValue();
                            customDomainInstance.setUseSubDomain(useSubDomainInstance);
                        }
                    }

                    JsonNode secondaryEndpointsValue = propertiesValue2.get("secondaryEndpoints");
                    if (secondaryEndpointsValue != null
                            && secondaryEndpointsValue instanceof NullNode == false) {
                        Endpoints secondaryEndpointsInstance = new Endpoints();
                        storageAccountInstance.setSecondaryEndpoints(secondaryEndpointsInstance);

                        JsonNode blobValue2 = secondaryEndpointsValue.get("blob");
                        if (blobValue2 != null && blobValue2 instanceof NullNode == false) {
                            URI blobInstance2;
                            blobInstance2 = new URI(blobValue2.getTextValue());
                            secondaryEndpointsInstance.setBlob(blobInstance2);
                        }

                        JsonNode queueValue2 = secondaryEndpointsValue.get("queue");
                        if (queueValue2 != null && queueValue2 instanceof NullNode == false) {
                            URI queueInstance2;
                            queueInstance2 = new URI(queueValue2.getTextValue());
                            secondaryEndpointsInstance.setQueue(queueInstance2);
                        }

                        JsonNode tableValue2 = secondaryEndpointsValue.get("table");
                        if (tableValue2 != null && tableValue2 instanceof NullNode == false) {
                            URI tableInstance2;
                            tableInstance2 = new URI(tableValue2.getTextValue());
                            secondaryEndpointsInstance.setTable(tableInstance2);
                        }

                        JsonNode fileValue2 = secondaryEndpointsValue.get("file");
                        if (fileValue2 != null && fileValue2 instanceof NullNode == false) {
                            URI fileInstance2;
                            fileInstance2 = new URI(fileValue2.getTextValue());
                            secondaryEndpointsInstance.setFile(fileInstance2);
                        }
                    }
                }
            }

        }
        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.ibm.iotf.client.api.APIClient.java

private HttpResponse casePatchFromConnect(List<NameValuePair> queryParameters, String url, String method,
        StringEntity input, String encodedString) throws URISyntaxException, IOException {
    URIBuilder putBuilder = new URIBuilder(url);
    if (queryParameters != null) {
        putBuilder.setParameters(queryParameters);
    }/*from  ww w.j av a 2  s. c  om*/
    HttpPatch patch = new HttpPatch(putBuilder.build());
    patch.setEntity(input);
    patch.addHeader("Content-Type", "application/json");
    patch.addHeader("Accept", "application/json");
    patch.addHeader("Authorization", "Basic " + encodedString);
    try {
        HttpClient client = HttpClientBuilder.create().useSystemProperties().setSslcontext(sslContext).build();
        return client.execute(patch);
    } catch (IOException e) {
        LoggerUtility.warn(CLASS_NAME, method, e.getMessage());
        throw e;
    }

}

From source file:com.microsoft.azure.management.trafficmanager.ProfileOperationsImpl.java

/**
* Update a Traffic Manager profile.//from w w  w.ja v  a 2 s  . com
*
* @param resourceGroupName Required. The name of the resource group
* containing the Traffic Manager profile.
* @param profileName Required. The name of the Traffic Manager profile.
* @param parameters Required. The Traffic Manager profile parameters
* supplied to the Update 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.
* @return Parameters supplied to update a Traffic Manager profile.
*/
@Override
public ProfileUpdateResponse update(String resourceGroupName, String profileName,
        ProfileUpdateParameters parameters) throws IOException, ServiceException {
    // Validate
    if (resourceGroupName == null) {
        throw new NullPointerException("resourceGroupName");
    }
    if (profileName == null) {
        throw new NullPointerException("profileName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getProfile() == null) {
        throw new NullPointerException("parameters.Profile");
    }
    if (parameters.getProfile().getLocation() == null) {
        throw new NullPointerException("parameters.Profile.Location");
    }
    if (parameters.getProfile().getProperties() != null) {
        if (parameters.getProfile().getProperties().getDnsConfig() != null) {
            if (parameters.getProfile().getProperties().getDnsConfig().getRelativeName() == null) {
                throw new NullPointerException("parameters.Profile.Properties.DnsConfig.RelativeName");
            }
        }
        if (parameters.getProfile().getProperties().getMonitorConfig() != null) {
            if (parameters.getProfile().getProperties().getMonitorConfig().getPath() == null) {
                throw new NullPointerException("parameters.Profile.Properties.MonitorConfig.Path");
            }
            if (parameters.getProfile().getProperties().getMonitorConfig().getProtocol() == null) {
                throw new NullPointerException("parameters.Profile.Properties.MonitorConfig.Protocol");
            }
        }
    }

    // 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("profileName", profileName);
        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.Network";
    url = url + "/trafficmanagerprofiles/";
    url = url + URLEncoder.encode(profileName, "UTF-8");
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("api-version=" + "2015-11-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
    HttpPatch httpRequest = new HttpPatch(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 profileUpdateParametersValue = objectMapper.createObjectNode();
    requestDoc = profileUpdateParametersValue;

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

        if (parameters.getProfile().getProperties().getProfileStatus() != null) {
            ((ObjectNode) propertiesValue).put("profileStatus",
                    parameters.getProfile().getProperties().getProfileStatus());
        }

        if (parameters.getProfile().getProperties().getTrafficRoutingMethod() != null) {
            ((ObjectNode) propertiesValue).put("trafficRoutingMethod",
                    parameters.getProfile().getProperties().getTrafficRoutingMethod());
        }

        if (parameters.getProfile().getProperties().getDnsConfig() != null) {
            ObjectNode dnsConfigValue = objectMapper.createObjectNode();
            ((ObjectNode) propertiesValue).put("dnsConfig", dnsConfigValue);

            ((ObjectNode) dnsConfigValue).put("relativeName",
                    parameters.getProfile().getProperties().getDnsConfig().getRelativeName());

            if (parameters.getProfile().getProperties().getDnsConfig().getFqdn() != null) {
                ((ObjectNode) dnsConfigValue).put("fqdn",
                        parameters.getProfile().getProperties().getDnsConfig().getFqdn());
            }

            ((ObjectNode) dnsConfigValue).put("ttl",
                    parameters.getProfile().getProperties().getDnsConfig().getTtl());
        }

        if (parameters.getProfile().getProperties().getMonitorConfig() != null) {
            ObjectNode monitorConfigValue = objectMapper.createObjectNode();
            ((ObjectNode) propertiesValue).put("monitorConfig", monitorConfigValue);

            if (parameters.getProfile().getProperties().getMonitorConfig().getProfileMonitorStatus() != null) {
                ((ObjectNode) monitorConfigValue).put("profileMonitorStatus",
                        parameters.getProfile().getProperties().getMonitorConfig().getProfileMonitorStatus());
            }

            ((ObjectNode) monitorConfigValue).put("protocol",
                    parameters.getProfile().getProperties().getMonitorConfig().getProtocol());

            ((ObjectNode) monitorConfigValue).put("port",
                    parameters.getProfile().getProperties().getMonitorConfig().getPort());

            ((ObjectNode) monitorConfigValue).put("path",
                    parameters.getProfile().getProperties().getMonitorConfig().getPath());
        }

        if (parameters.getProfile().getProperties().getEndpoints() != null) {
            ArrayNode endpointsArray = objectMapper.createArrayNode();
            for (Endpoint endpointsItem : parameters.getProfile().getProperties().getEndpoints()) {
                ObjectNode endpointValue = objectMapper.createObjectNode();
                endpointsArray.add(endpointValue);

                if (endpointsItem.getId() != null) {
                    ((ObjectNode) endpointValue).put("id", endpointsItem.getId());
                }

                if (endpointsItem.getName() != null) {
                    ((ObjectNode) endpointValue).put("name", endpointsItem.getName());
                }

                if (endpointsItem.getType() != null) {
                    ((ObjectNode) endpointValue).put("type", endpointsItem.getType());
                }

                if (endpointsItem.getProperties() != null) {
                    ObjectNode propertiesValue2 = objectMapper.createObjectNode();
                    ((ObjectNode) endpointValue).put("properties", propertiesValue2);

                    if (endpointsItem.getProperties().getTargetResourceId() != null) {
                        ((ObjectNode) propertiesValue2).put("targetResourceId",
                                endpointsItem.getProperties().getTargetResourceId());
                    }

                    if (endpointsItem.getProperties().getTarget() != null) {
                        ((ObjectNode) propertiesValue2).put("target",
                                endpointsItem.getProperties().getTarget());
                    }

                    if (endpointsItem.getProperties().getEndpointStatus() != null) {
                        ((ObjectNode) propertiesValue2).put("endpointStatus",
                                endpointsItem.getProperties().getEndpointStatus());
                    }

                    if (endpointsItem.getProperties().getWeight() != null) {
                        ((ObjectNode) propertiesValue2).put("weight",
                                endpointsItem.getProperties().getWeight());
                    }

                    if (endpointsItem.getProperties().getPriority() != null) {
                        ((ObjectNode) propertiesValue2).put("priority",
                                endpointsItem.getProperties().getPriority());
                    }

                    if (endpointsItem.getProperties().getEndpointLocation() != null) {
                        ((ObjectNode) propertiesValue2).put("endpointLocation",
                                endpointsItem.getProperties().getEndpointLocation());
                    }

                    if (endpointsItem.getProperties().getEndpointMonitorStatus() != null) {
                        ((ObjectNode) propertiesValue2).put("endpointMonitorStatus",
                                endpointsItem.getProperties().getEndpointMonitorStatus());
                    }

                    if (endpointsItem.getProperties().getMinChildEndpoints() != null) {
                        ((ObjectNode) propertiesValue2).put("minChildEndpoints",
                                endpointsItem.getProperties().getMinChildEndpoints());
                    }
                }
            }
            ((ObjectNode) propertiesValue).put("endpoints", endpointsArray);
        }
    }

    if (parameters.getProfile().getId() != null) {
        ((ObjectNode) profileUpdateParametersValue).put("id", parameters.getProfile().getId());
    }

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

    if (parameters.getProfile().getType() != null) {
        ((ObjectNode) profileUpdateParametersValue).put("type", parameters.getProfile().getType());
    }

    ((ObjectNode) profileUpdateParametersValue).put("location", parameters.getProfile().getLocation());

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

    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_BAD_REQUEST) {
            ServiceException ex = ServiceException.createFromJson(httpRequest, requestContent, httpResponse,
                    httpResponse.getEntity());
            if (shouldTrace) {
                CloudTracing.error(invocationId, ex);
            }
            throw ex;
        }

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

        JsonNode profileUpdateResponseValue = responseDoc.get("ProfileUpdateResponse");
        if (profileUpdateResponseValue != null && profileUpdateResponseValue instanceof NullNode == false) {
            ProfileUpdateParameters profileUpdateResponseInstance = new ProfileUpdateParameters();

            Profile profileInstance = new Profile();
            result.setProfile(profileInstance);

            JsonNode propertiesValue3 = profileUpdateResponseValue.get("properties");
            if (propertiesValue3 != null && propertiesValue3 instanceof NullNode == false) {
                ProfileProperties propertiesInstance = new ProfileProperties();
                profileInstance.setProperties(propertiesInstance);

                JsonNode profileStatusValue = propertiesValue3.get("profileStatus");
                if (profileStatusValue != null && profileStatusValue instanceof NullNode == false) {
                    String profileStatusInstance;
                    profileStatusInstance = profileStatusValue.getTextValue();
                    propertiesInstance.setProfileStatus(profileStatusInstance);
                }

                JsonNode trafficRoutingMethodValue = propertiesValue3.get("trafficRoutingMethod");
                if (trafficRoutingMethodValue != null
                        && trafficRoutingMethodValue instanceof NullNode == false) {
                    String trafficRoutingMethodInstance;
                    trafficRoutingMethodInstance = trafficRoutingMethodValue.getTextValue();
                    propertiesInstance.setTrafficRoutingMethod(trafficRoutingMethodInstance);
                }

                JsonNode dnsConfigValue2 = propertiesValue3.get("dnsConfig");
                if (dnsConfigValue2 != null && dnsConfigValue2 instanceof NullNode == false) {
                    DnsConfig dnsConfigInstance = new DnsConfig();
                    propertiesInstance.setDnsConfig(dnsConfigInstance);

                    JsonNode relativeNameValue = dnsConfigValue2.get("relativeName");
                    if (relativeNameValue != null && relativeNameValue instanceof NullNode == false) {
                        String relativeNameInstance;
                        relativeNameInstance = relativeNameValue.getTextValue();
                        dnsConfigInstance.setRelativeName(relativeNameInstance);
                    }

                    JsonNode fqdnValue = dnsConfigValue2.get("fqdn");
                    if (fqdnValue != null && fqdnValue instanceof NullNode == false) {
                        String fqdnInstance;
                        fqdnInstance = fqdnValue.getTextValue();
                        dnsConfigInstance.setFqdn(fqdnInstance);
                    }

                    JsonNode ttlValue = dnsConfigValue2.get("ttl");
                    if (ttlValue != null && ttlValue instanceof NullNode == false) {
                        long ttlInstance;
                        ttlInstance = ttlValue.getLongValue();
                        dnsConfigInstance.setTtl(ttlInstance);
                    }
                }

                JsonNode monitorConfigValue2 = propertiesValue3.get("monitorConfig");
                if (monitorConfigValue2 != null && monitorConfigValue2 instanceof NullNode == false) {
                    MonitorConfig monitorConfigInstance = new MonitorConfig();
                    propertiesInstance.setMonitorConfig(monitorConfigInstance);

                    JsonNode profileMonitorStatusValue = monitorConfigValue2.get("profileMonitorStatus");
                    if (profileMonitorStatusValue != null
                            && profileMonitorStatusValue instanceof NullNode == false) {
                        String profileMonitorStatusInstance;
                        profileMonitorStatusInstance = profileMonitorStatusValue.getTextValue();
                        monitorConfigInstance.setProfileMonitorStatus(profileMonitorStatusInstance);
                    }

                    JsonNode protocolValue = monitorConfigValue2.get("protocol");
                    if (protocolValue != null && protocolValue instanceof NullNode == false) {
                        String protocolInstance;
                        protocolInstance = protocolValue.getTextValue();
                        monitorConfigInstance.setProtocol(protocolInstance);
                    }

                    JsonNode portValue = monitorConfigValue2.get("port");
                    if (portValue != null && portValue instanceof NullNode == false) {
                        long portInstance;
                        portInstance = portValue.getLongValue();
                        monitorConfigInstance.setPort(portInstance);
                    }

                    JsonNode pathValue = monitorConfigValue2.get("path");
                    if (pathValue != null && pathValue instanceof NullNode == false) {
                        String pathInstance;
                        pathInstance = pathValue.getTextValue();
                        monitorConfigInstance.setPath(pathInstance);
                    }
                }

                JsonNode endpointsArray2 = propertiesValue3.get("endpoints");
                if (endpointsArray2 != null && endpointsArray2 instanceof NullNode == false) {
                    propertiesInstance.setEndpoints(new ArrayList<Endpoint>());
                    for (JsonNode endpointsValue : ((ArrayNode) endpointsArray2)) {
                        Endpoint endpointInstance = new Endpoint();
                        propertiesInstance.getEndpoints().add(endpointInstance);

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

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

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

                        JsonNode propertiesValue4 = endpointsValue.get("properties");
                        if (propertiesValue4 != null && propertiesValue4 instanceof NullNode == false) {
                            EndpointProperties propertiesInstance2 = new EndpointProperties();
                            endpointInstance.setProperties(propertiesInstance2);

                            JsonNode targetResourceIdValue = propertiesValue4.get("targetResourceId");
                            if (targetResourceIdValue != null
                                    && targetResourceIdValue instanceof NullNode == false) {
                                String targetResourceIdInstance;
                                targetResourceIdInstance = targetResourceIdValue.getTextValue();
                                propertiesInstance2.setTargetResourceId(targetResourceIdInstance);
                            }

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

                            JsonNode endpointStatusValue = propertiesValue4.get("endpointStatus");
                            if (endpointStatusValue != null
                                    && endpointStatusValue instanceof NullNode == false) {
                                String endpointStatusInstance;
                                endpointStatusInstance = endpointStatusValue.getTextValue();
                                propertiesInstance2.setEndpointStatus(endpointStatusInstance);
                            }

                            JsonNode weightValue = propertiesValue4.get("weight");
                            if (weightValue != null && weightValue instanceof NullNode == false) {
                                long weightInstance;
                                weightInstance = weightValue.getLongValue();
                                propertiesInstance2.setWeight(weightInstance);
                            }

                            JsonNode priorityValue = propertiesValue4.get("priority");
                            if (priorityValue != null && priorityValue instanceof NullNode == false) {
                                long priorityInstance;
                                priorityInstance = priorityValue.getLongValue();
                                propertiesInstance2.setPriority(priorityInstance);
                            }

                            JsonNode endpointLocationValue = propertiesValue4.get("endpointLocation");
                            if (endpointLocationValue != null
                                    && endpointLocationValue instanceof NullNode == false) {
                                String endpointLocationInstance;
                                endpointLocationInstance = endpointLocationValue.getTextValue();
                                propertiesInstance2.setEndpointLocation(endpointLocationInstance);
                            }

                            JsonNode endpointMonitorStatusValue = propertiesValue4.get("endpointMonitorStatus");
                            if (endpointMonitorStatusValue != null
                                    && endpointMonitorStatusValue instanceof NullNode == false) {
                                String endpointMonitorStatusInstance;
                                endpointMonitorStatusInstance = endpointMonitorStatusValue.getTextValue();
                                propertiesInstance2.setEndpointMonitorStatus(endpointMonitorStatusInstance);
                            }

                            JsonNode minChildEndpointsValue = propertiesValue4.get("minChildEndpoints");
                            if (minChildEndpointsValue != null
                                    && minChildEndpointsValue instanceof NullNode == false) {
                                long minChildEndpointsInstance;
                                minChildEndpointsInstance = minChildEndpointsValue.getLongValue();
                                propertiesInstance2.setMinChildEndpoints(minChildEndpointsInstance);
                            }
                        }
                    }
                }
            }

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

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

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

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

            JsonNode tagsSequenceElement = ((JsonNode) profileUpdateResponseValue.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();
                    profileInstance.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.windowsazure.management.network.GatewayOperationsImpl.java

/**
* The Begin Reset Virtual Network Gateway Shared Key V2 operation resets
* the shared key used between the gateway and customer vpn.
*
* @param gatewayId Required. The virtual network for this gateway Id.
* @param connectedentityId Required. The connected entity Id.
* @param parameters Required. Parameters supplied to the Begin Virtual
* Network Gateway Reset Shared Key V2 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.//from   w w  w. ja v a  2  s. c om
* @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 A standard service response including an HTTP status code and
* request ID.
*/
@Override
public GatewayOperationResponse beginResetSharedKeyV2(String gatewayId, String connectedentityId,
        GatewayResetSharedKeyParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (gatewayId == null) {
        throw new NullPointerException("gatewayId");
    }
    if (connectedentityId == null) {
        throw new NullPointerException("connectedentityId");
    }
    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("gatewayId", gatewayId);
        tracingParameters.put("connectedentityId", connectedentityId);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "beginResetSharedKeyV2Async", 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/networking/virtualnetworkgateways/";
    url = url + URLEncoder.encode(gatewayId, "UTF-8");
    url = url + "/connectedentity/";
    url = url + URLEncoder.encode(connectedentityId, "UTF-8");
    url = url + "/sharedkey";
    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
    HttpPatch httpRequest = new HttpPatch(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 resetSharedKeyElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "ResetSharedKey");
    requestDoc.appendChild(resetSharedKeyElement);

    Element keyLengthElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "KeyLength");
    keyLengthElement.appendChild(requestDoc.createTextNode(Integer.toString(parameters.getKeyLength())));
    resetSharedKeyElement.appendChild(keyLengthElement);

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

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

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

            Element gatewayOperationAsyncResponseElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "GatewayOperationAsyncResponse");
            if (gatewayOperationAsyncResponseElement != null) {
                Element idElement = XmlUtility.getElementByTagNameNS(gatewayOperationAsyncResponseElement,
                        "http://schemas.microsoft.com/windowsazure", "ID");
                if (idElement != null) {
                    String idInstance;
                    idInstance = idElement.getTextContent();
                    result.setOperationId(idInstance);
                }
            }

        }
        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.network.GatewayOperationsImpl.java

/**
* The Begin Reset Virtual network Gateway operation resets an existing
* gateway.//  w  ww.j  a v a 2s.  c om
*
* @param networkName Required. The name of the virtual network for this
* gateway.
* @param parameters Required. Parameters supplied to the Begin Reset
* Virtual Network Gateway operation.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return A standard service response including an HTTP status code and
* request ID.
*/
@Override
public GatewayOperationResponse beginReset(String networkName, ResetGatewayParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (networkName == null) {
        throw new NullPointerException("networkName");
    }
    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("networkName", networkName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "beginResetAsync", 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/networking/";
    url = url + URLEncoder.encode(networkName, "UTF-8");
    url = url + "/gateway";
    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
    HttpPatch httpRequest = new HttpPatch(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 updateGatewayParametersElement = requestDoc
            .createElementNS("http://schemas.microsoft.com/windowsazure", "UpdateGatewayParameters");
    requestDoc.appendChild(updateGatewayParametersElement);

    if (parameters.getOperation() != null) {
        Element operationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "Operation");
        operationElement.appendChild(requestDoc.createTextNode("Reset"));
        updateGatewayParametersElement.appendChild(operationElement);
    }

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

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

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

            Element gatewayOperationAsyncResponseElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "GatewayOperationAsyncResponse");
            if (gatewayOperationAsyncResponseElement != null) {
                Element idElement = XmlUtility.getElementByTagNameNS(gatewayOperationAsyncResponseElement,
                        "http://schemas.microsoft.com/windowsazure", "ID");
                if (idElement != null) {
                    String idInstance;
                    idInstance = idElement.getTextContent();
                    result.setOperationId(idInstance);
                }
            }

        }
        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.network.GatewayOperationsImpl.java

/**
* The Begin Reset Virtual network Gateway operation resets an existing
* gateway./*from  www . j av  a  2  s  . c  om*/
*
* @param gatewayId Required. The virtual network for this gateway.
* @param parameters Required. Parameters supplied to the Begin Reset
* Virtual Network Gateway operation.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return A standard service response including an HTTP status code and
* request ID.
*/
@Override
public GatewayOperationResponse beginResetVirtualNetworkGateway(String gatewayId,
        ResetGatewayParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (gatewayId == null) {
        throw new NullPointerException("gatewayId");
    }
    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("gatewayId", gatewayId);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "beginResetVirtualNetworkGatewayAsync", 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/networking/virtualnetworkgateways/";
    url = url + URLEncoder.encode(gatewayId, "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
    HttpPatch httpRequest = new HttpPatch(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 updateGatewayParametersElement = requestDoc
            .createElementNS("http://schemas.microsoft.com/windowsazure", "UpdateGatewayParameters");
    requestDoc.appendChild(updateGatewayParametersElement);

    if (parameters.getOperation() != null) {
        Element operationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "Operation");
        operationElement.appendChild(requestDoc.createTextNode("Reset"));
        updateGatewayParametersElement.appendChild(operationElement);
    }

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

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

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

            Element gatewayOperationAsyncResponseElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "GatewayOperationAsyncResponse");
            if (gatewayOperationAsyncResponseElement != null) {
                Element idElement = XmlUtility.getElementByTagNameNS(gatewayOperationAsyncResponseElement,
                        "http://schemas.microsoft.com/windowsazure", "ID");
                if (idElement != null) {
                    String idInstance;
                    idInstance = idElement.getTextContent();
                    result.setOperationId(idInstance);
                }
            }

        }
        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.network.GatewayOperationsImpl.java

/**
* The Begin Resize Virtual network Gateway operation resizes an existing
* gateway to a different GatewaySKU./*  w  w  w  .j  av a2  s.  c o  m*/
*
* @param networkName Required. The name of the virtual network for this
* gateway.
* @param parameters Required. Parameters supplied to the Begin Resize
* Virtual Network Gateway operation.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return A standard service response including an HTTP status code and
* request ID.
*/
@Override
public GatewayOperationResponse beginResize(String networkName, ResizeGatewayParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (networkName == null) {
        throw new NullPointerException("networkName");
    }
    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("networkName", networkName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "beginResizeAsync", 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/networking/";
    url = url + URLEncoder.encode(networkName, "UTF-8");
    url = url + "/gateway";
    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
    HttpPatch httpRequest = new HttpPatch(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 updateGatewayParametersElement = requestDoc
            .createElementNS("http://schemas.microsoft.com/windowsazure", "UpdateGatewayParameters");
    requestDoc.appendChild(updateGatewayParametersElement);

    if (parameters.getGatewaySKU() != null) {
        Element gatewaySizeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "GatewaySize");
        gatewaySizeElement.appendChild(requestDoc.createTextNode(parameters.getGatewaySKU()));
        updateGatewayParametersElement.appendChild(gatewaySizeElement);
    }

    if (parameters.getOperation() != null) {
        Element operationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "Operation");
        operationElement.appendChild(requestDoc.createTextNode("Resize"));
        updateGatewayParametersElement.appendChild(operationElement);
    }

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

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

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

            Element gatewayOperationAsyncResponseElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "GatewayOperationAsyncResponse");
            if (gatewayOperationAsyncResponseElement != null) {
                Element idElement = XmlUtility.getElementByTagNameNS(gatewayOperationAsyncResponseElement,
                        "http://schemas.microsoft.com/windowsazure", "ID");
                if (idElement != null) {
                    String idInstance;
                    idInstance = idElement.getTextContent();
                    result.setOperationId(idInstance);
                }
            }

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