Example usage for javax.xml.bind DatatypeConverter parseDateTime

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

Introduction

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

Prototype

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

Source Link

Document

Converts the string argument into a Calendar value.

Usage

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

/**
* Lists the PNS Credentials associated with a notification hub .
*
* @param resourceGroupName Required. The name of the resource group.
* @param namespaceName Required. The namespace name.
* @param notificationHubName Required. The notification hub name.
* @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.//from  w  w w  . ja  va 2s  . c  o m
* @throws ServiceException Thrown if an unexpected response is found.
* @return The response of the Get NotificationHub operation.
*/
@Override
public NotificationHubGetResponse getPnsCredentials(String resourceGroupName, String namespaceName,
        String notificationHubName) throws IOException, ServiceException {
    // Validate
    if (resourceGroupName == null) {
        throw new NullPointerException("resourceGroupName");
    }
    if (namespaceName == null) {
        throw new NullPointerException("namespaceName");
    }
    if (notificationHubName == null) {
        throw new NullPointerException("notificationHubName");
    }

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

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

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

    // Set Headers

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

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

            if (responseDoc != null && responseDoc instanceof NullNode == false) {
                NotificationHubResource valueInstance = new NotificationHubResource();
                result.setValue(valueInstance);

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

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

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

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

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

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

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

                    JsonNode registrationTtlValue = propertiesValue.get("registrationTtl");
                    if (registrationTtlValue != null && registrationTtlValue instanceof NullNode == false) {
                        String registrationTtlInstance;
                        registrationTtlInstance = registrationTtlValue.getTextValue();
                        propertiesInstance.setRegistrationTtl(registrationTtlInstance);
                    }

                    JsonNode authorizationRulesArray = propertiesValue.get("authorizationRules");
                    if (authorizationRulesArray != null
                            && authorizationRulesArray instanceof NullNode == false) {
                        for (JsonNode authorizationRulesValue : ((ArrayNode) authorizationRulesArray)) {
                            SharedAccessAuthorizationRuleProperties sharedAccessAuthorizationRulePropertiesInstance = new SharedAccessAuthorizationRuleProperties();
                            propertiesInstance.getAuthorizationRules()
                                    .add(sharedAccessAuthorizationRulePropertiesInstance);

                            JsonNode primaryKeyValue = authorizationRulesValue.get("primaryKey");
                            if (primaryKeyValue != null && primaryKeyValue instanceof NullNode == false) {
                                String primaryKeyInstance;
                                primaryKeyInstance = primaryKeyValue.getTextValue();
                                sharedAccessAuthorizationRulePropertiesInstance
                                        .setPrimaryKey(primaryKeyInstance);
                            }

                            JsonNode secondaryKeyValue = authorizationRulesValue.get("secondaryKey");
                            if (secondaryKeyValue != null && secondaryKeyValue instanceof NullNode == false) {
                                String secondaryKeyInstance;
                                secondaryKeyInstance = secondaryKeyValue.getTextValue();
                                sharedAccessAuthorizationRulePropertiesInstance
                                        .setSecondaryKey(secondaryKeyInstance);
                            }

                            JsonNode keyNameValue = authorizationRulesValue.get("keyName");
                            if (keyNameValue != null && keyNameValue instanceof NullNode == false) {
                                String keyNameInstance;
                                keyNameInstance = keyNameValue.getTextValue();
                                sharedAccessAuthorizationRulePropertiesInstance.setKeyName(keyNameInstance);
                            }

                            JsonNode claimTypeValue = authorizationRulesValue.get("claimType");
                            if (claimTypeValue != null && claimTypeValue instanceof NullNode == false) {
                                String claimTypeInstance;
                                claimTypeInstance = claimTypeValue.getTextValue();
                                sharedAccessAuthorizationRulePropertiesInstance.setClaimType(claimTypeInstance);
                            }

                            JsonNode claimValueValue = authorizationRulesValue.get("claimValue");
                            if (claimValueValue != null && claimValueValue instanceof NullNode == false) {
                                String claimValueInstance;
                                claimValueInstance = claimValueValue.getTextValue();
                                sharedAccessAuthorizationRulePropertiesInstance
                                        .setClaimValue(claimValueInstance);
                            }

                            JsonNode rightsArray = authorizationRulesValue.get("rights");
                            if (rightsArray != null && rightsArray instanceof NullNode == false) {
                                for (JsonNode rightsValue : ((ArrayNode) rightsArray)) {
                                    sharedAccessAuthorizationRulePropertiesInstance.getRights()
                                            .add(Enum.valueOf(AccessRights.class, rightsValue.getTextValue()));
                                }
                            }

                            JsonNode createdTimeValue = authorizationRulesValue.get("createdTime");
                            if (createdTimeValue != null && createdTimeValue instanceof NullNode == false) {
                                Calendar createdTimeInstance;
                                createdTimeInstance = DatatypeConverter
                                        .parseDateTime(createdTimeValue.getTextValue());
                                sharedAccessAuthorizationRulePropertiesInstance
                                        .setCreatedTime(createdTimeInstance);
                            }

                            JsonNode modifiedTimeValue = authorizationRulesValue.get("modifiedTime");
                            if (modifiedTimeValue != null && modifiedTimeValue instanceof NullNode == false) {
                                Calendar modifiedTimeInstance;
                                modifiedTimeInstance = DatatypeConverter
                                        .parseDateTime(modifiedTimeValue.getTextValue());
                                sharedAccessAuthorizationRulePropertiesInstance
                                        .setModifiedTime(modifiedTimeInstance);
                            }

                            JsonNode revisionValue = authorizationRulesValue.get("revision");
                            if (revisionValue != null && revisionValue instanceof NullNode == false) {
                                int revisionInstance;
                                revisionInstance = revisionValue.getIntValue();
                                sharedAccessAuthorizationRulePropertiesInstance.setRevision(revisionInstance);
                            }
                        }
                    }

                    JsonNode apnsCredentialValue = propertiesValue.get("apnsCredential");
                    if (apnsCredentialValue != null && apnsCredentialValue instanceof NullNode == false) {
                        ApnsCredential apnsCredentialInstance = new ApnsCredential();
                        propertiesInstance.setApnsCredential(apnsCredentialInstance);

                        JsonNode propertiesValue2 = apnsCredentialValue.get("properties");
                        if (propertiesValue2 != null && propertiesValue2 instanceof NullNode == false) {
                            ApnsCredentialProperties propertiesInstance2 = new ApnsCredentialProperties();
                            apnsCredentialInstance.setProperties(propertiesInstance2);

                            JsonNode apnsCertificateValue = propertiesValue2.get("apnsCertificate");
                            if (apnsCertificateValue != null
                                    && apnsCertificateValue instanceof NullNode == false) {
                                String apnsCertificateInstance;
                                apnsCertificateInstance = apnsCertificateValue.getTextValue();
                                propertiesInstance2.setApnsCertificate(apnsCertificateInstance);
                            }

                            JsonNode certificateKeyValue = propertiesValue2.get("certificateKey");
                            if (certificateKeyValue != null
                                    && certificateKeyValue instanceof NullNode == false) {
                                String certificateKeyInstance;
                                certificateKeyInstance = certificateKeyValue.getTextValue();
                                propertiesInstance2.setCertificateKey(certificateKeyInstance);
                            }

                            JsonNode endpointValue = propertiesValue2.get("endpoint");
                            if (endpointValue != null && endpointValue instanceof NullNode == false) {
                                String endpointInstance;
                                endpointInstance = endpointValue.getTextValue();
                                propertiesInstance2.setEndpoint(endpointInstance);
                            }

                            JsonNode thumbprintValue = propertiesValue2.get("thumbprint");
                            if (thumbprintValue != null && thumbprintValue instanceof NullNode == false) {
                                String thumbprintInstance;
                                thumbprintInstance = thumbprintValue.getTextValue();
                                propertiesInstance2.setThumbprint(thumbprintInstance);
                            }
                        }
                    }

                    JsonNode wnsCredentialValue = propertiesValue.get("wnsCredential");
                    if (wnsCredentialValue != null && wnsCredentialValue instanceof NullNode == false) {
                        WnsCredential wnsCredentialInstance = new WnsCredential();
                        propertiesInstance.setWnsCredential(wnsCredentialInstance);

                        JsonNode propertiesValue3 = wnsCredentialValue.get("properties");
                        if (propertiesValue3 != null && propertiesValue3 instanceof NullNode == false) {
                            WnsCredentialProperties propertiesInstance3 = new WnsCredentialProperties();
                            wnsCredentialInstance.setProperties(propertiesInstance3);

                            JsonNode packageSidValue = propertiesValue3.get("packageSid");
                            if (packageSidValue != null && packageSidValue instanceof NullNode == false) {
                                String packageSidInstance;
                                packageSidInstance = packageSidValue.getTextValue();
                                propertiesInstance3.setPackageSid(packageSidInstance);
                            }

                            JsonNode secretKeyValue = propertiesValue3.get("secretKey");
                            if (secretKeyValue != null && secretKeyValue instanceof NullNode == false) {
                                String secretKeyInstance;
                                secretKeyInstance = secretKeyValue.getTextValue();
                                propertiesInstance3.setSecretKey(secretKeyInstance);
                            }

                            JsonNode windowsLiveEndpointValue = propertiesValue3.get("windowsLiveEndpoint");
                            if (windowsLiveEndpointValue != null
                                    && windowsLiveEndpointValue instanceof NullNode == false) {
                                String windowsLiveEndpointInstance;
                                windowsLiveEndpointInstance = windowsLiveEndpointValue.getTextValue();
                                propertiesInstance3.setWindowsLiveEndpoint(windowsLiveEndpointInstance);
                            }
                        }
                    }

                    JsonNode gcmCredentialValue = propertiesValue.get("gcmCredential");
                    if (gcmCredentialValue != null && gcmCredentialValue instanceof NullNode == false) {
                        GcmCredential gcmCredentialInstance = new GcmCredential();
                        propertiesInstance.setGcmCredential(gcmCredentialInstance);

                        JsonNode propertiesValue4 = gcmCredentialValue.get("properties");
                        if (propertiesValue4 != null && propertiesValue4 instanceof NullNode == false) {
                            GcmCredentialProperties propertiesInstance4 = new GcmCredentialProperties();
                            gcmCredentialInstance.setProperties(propertiesInstance4);

                            JsonNode gcmEndpointValue = propertiesValue4.get("gcmEndpoint");
                            if (gcmEndpointValue != null && gcmEndpointValue instanceof NullNode == false) {
                                String gcmEndpointInstance;
                                gcmEndpointInstance = gcmEndpointValue.getTextValue();
                                propertiesInstance4.setGcmEndpoint(gcmEndpointInstance);
                            }

                            JsonNode googleApiKeyValue = propertiesValue4.get("googleApiKey");
                            if (googleApiKeyValue != null && googleApiKeyValue instanceof NullNode == false) {
                                String googleApiKeyInstance;
                                googleApiKeyInstance = googleApiKeyValue.getTextValue();
                                propertiesInstance4.setGoogleApiKey(googleApiKeyInstance);
                            }
                        }
                    }

                    JsonNode mpnsCredentialValue = propertiesValue.get("mpnsCredential");
                    if (mpnsCredentialValue != null && mpnsCredentialValue instanceof NullNode == false) {
                        MpnsCredential mpnsCredentialInstance = new MpnsCredential();
                        propertiesInstance.setMpnsCredential(mpnsCredentialInstance);

                        JsonNode propertiesValue5 = mpnsCredentialValue.get("properties");
                        if (propertiesValue5 != null && propertiesValue5 instanceof NullNode == false) {
                            MpnsCredentialProperties propertiesInstance5 = new MpnsCredentialProperties();
                            mpnsCredentialInstance.setProperties(propertiesInstance5);

                            JsonNode mpnsCertificateValue = propertiesValue5.get("mpnsCertificate");
                            if (mpnsCertificateValue != null
                                    && mpnsCertificateValue instanceof NullNode == false) {
                                String mpnsCertificateInstance;
                                mpnsCertificateInstance = mpnsCertificateValue.getTextValue();
                                propertiesInstance5.setMpnsCertificate(mpnsCertificateInstance);
                            }

                            JsonNode certificateKeyValue2 = propertiesValue5.get("certificateKey");
                            if (certificateKeyValue2 != null
                                    && certificateKeyValue2 instanceof NullNode == false) {
                                String certificateKeyInstance2;
                                certificateKeyInstance2 = certificateKeyValue2.getTextValue();
                                propertiesInstance5.setCertificateKey(certificateKeyInstance2);
                            }

                            JsonNode thumbprintValue2 = propertiesValue5.get("thumbprint");
                            if (thumbprintValue2 != null && thumbprintValue2 instanceof NullNode == false) {
                                String thumbprintInstance2;
                                thumbprintInstance2 = thumbprintValue2.getTextValue();
                                propertiesInstance5.setThumbprint(thumbprintInstance2);
                            }
                        }
                    }

                    JsonNode admCredentialValue = propertiesValue.get("admCredential");
                    if (admCredentialValue != null && admCredentialValue instanceof NullNode == false) {
                        AdmCredential admCredentialInstance = new AdmCredential();
                        propertiesInstance.setAdmCredential(admCredentialInstance);

                        JsonNode propertiesValue6 = admCredentialValue.get("properties");
                        if (propertiesValue6 != null && propertiesValue6 instanceof NullNode == false) {
                            AdmCredentialProperties propertiesInstance6 = new AdmCredentialProperties();
                            admCredentialInstance.setProperties(propertiesInstance6);

                            JsonNode clientIdValue = propertiesValue6.get("clientId");
                            if (clientIdValue != null && clientIdValue instanceof NullNode == false) {
                                String clientIdInstance;
                                clientIdInstance = clientIdValue.getTextValue();
                                propertiesInstance6.setClientId(clientIdInstance);
                            }

                            JsonNode clientSecretValue = propertiesValue6.get("clientSecret");
                            if (clientSecretValue != null && clientSecretValue instanceof NullNode == false) {
                                String clientSecretInstance;
                                clientSecretInstance = clientSecretValue.getTextValue();
                                propertiesInstance6.setClientSecret(clientSecretInstance);
                            }

                            JsonNode authTokenUrlValue = propertiesValue6.get("authTokenUrl");
                            if (authTokenUrlValue != null && authTokenUrlValue instanceof NullNode == false) {
                                String authTokenUrlInstance;
                                authTokenUrlInstance = authTokenUrlValue.getTextValue();
                                propertiesInstance6.setAuthTokenUrl(authTokenUrlInstance);
                            }
                        }
                    }

                    JsonNode baiduCredentialValue = propertiesValue.get("baiduCredential");
                    if (baiduCredentialValue != null && baiduCredentialValue instanceof NullNode == false) {
                        BaiduCredential baiduCredentialInstance = new BaiduCredential();
                        propertiesInstance.setBaiduCredential(baiduCredentialInstance);

                        JsonNode propertiesValue7 = baiduCredentialValue.get("properties");
                        if (propertiesValue7 != null && propertiesValue7 instanceof NullNode == false) {
                            BaiduCredentialProperties propertiesInstance7 = new BaiduCredentialProperties();
                            baiduCredentialInstance.setProperties(propertiesInstance7);

                            JsonNode baiduApiKeyValue = propertiesValue7.get("baiduApiKey");
                            if (baiduApiKeyValue != null && baiduApiKeyValue instanceof NullNode == false) {
                                String baiduApiKeyInstance;
                                baiduApiKeyInstance = baiduApiKeyValue.getTextValue();
                                propertiesInstance7.setBaiduApiKey(baiduApiKeyInstance);
                            }

                            JsonNode baiduEndPointValue = propertiesValue7.get("baiduEndPoint");
                            if (baiduEndPointValue != null && baiduEndPointValue instanceof NullNode == false) {
                                String baiduEndPointInstance;
                                baiduEndPointInstance = baiduEndPointValue.getTextValue();
                                propertiesInstance7.setBaiduEndPoint(baiduEndPointInstance);
                            }

                            JsonNode baiduSecretKeyValue = propertiesValue7.get("baiduSecretKey");
                            if (baiduSecretKeyValue != null
                                    && baiduSecretKeyValue instanceof NullNode == false) {
                                String baiduSecretKeyInstance;
                                baiduSecretKeyInstance = baiduSecretKeyValue.getTextValue();
                                propertiesInstance7.setBaiduSecretKey(baiduSecretKeyInstance);
                            }
                        }
                    }
                }
            }

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

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

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

/**
* Returns information about Azure SQL Database Elastic Pools.
*
* @param resourceGroupName Required. The name of the Resource Group to
* which the Azure SQL Database Serve belongs.
* @param serverName Required. The name of the Azure SQL Database Server in
* which Azure SQL Database Elastic Pools are hosted.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations./*w w w. j  ava  2  s  .  co  m*/
* @throws ServiceException Thrown if an unexpected response is found.
* @return Represents the response to a List Azure Sql Elastic Pool request.
*/
@Override
public ElasticPoolListResponse list(String resourceGroupName, String serverName)
        throws IOException, ServiceException {
    // Validate
    if (resourceGroupName == null) {
        throw new NullPointerException("resourceGroupName");
    }
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }

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

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

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

    // Set Headers

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

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

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

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

                            JsonNode creationDateValue = propertiesValue.get("creationDate");
                            if (creationDateValue != null && creationDateValue instanceof NullNode == false) {
                                Calendar creationDateInstance;
                                creationDateInstance = DatatypeConverter
                                        .parseDateTime(creationDateValue.getTextValue());
                                propertiesInstance.setCreationDate(creationDateInstance);
                            }

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

                            JsonNode editionValue = propertiesValue.get("edition");
                            if (editionValue != null && editionValue instanceof NullNode == false) {
                                String editionInstance;
                                editionInstance = editionValue.getTextValue();
                                propertiesInstance.setEdition(editionInstance);
                            }

                            JsonNode dtuValue = propertiesValue.get("dtu");
                            if (dtuValue != null && dtuValue instanceof NullNode == false) {
                                int dtuInstance;
                                dtuInstance = dtuValue.getIntValue();
                                propertiesInstance.setDtu(dtuInstance);
                            }

                            JsonNode databaseDtuMaxValue = propertiesValue.get("databaseDtuMax");
                            if (databaseDtuMaxValue != null
                                    && databaseDtuMaxValue instanceof NullNode == false) {
                                int databaseDtuMaxInstance;
                                databaseDtuMaxInstance = databaseDtuMaxValue.getIntValue();
                                propertiesInstance.setDatabaseDtuMax(databaseDtuMaxInstance);
                            }

                            JsonNode databaseDtuMinValue = propertiesValue.get("databaseDtuMin");
                            if (databaseDtuMinValue != null
                                    && databaseDtuMinValue instanceof NullNode == false) {
                                int databaseDtuMinInstance;
                                databaseDtuMinInstance = databaseDtuMinValue.getIntValue();
                                propertiesInstance.setDatabaseDtuMin(databaseDtuMinInstance);
                            }

                            JsonNode storageMBValue = propertiesValue.get("storageMB");
                            if (storageMBValue != null && storageMBValue instanceof NullNode == false) {
                                int storageMBInstance;
                                storageMBInstance = storageMBValue.getIntValue();
                                propertiesInstance.setStorageMB(storageMBInstance);
                            }
                        }

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

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

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

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

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

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

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

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

/**
* The get authorization rules operation gets the authorization rules for a
* namespace.//  ww w .ja  v a2 s.c o  m
*
* @param resourceGroupName Required. The name of the resource group.
* @param namespaceName Required. The namespace to get the authorization
* rule for.
* @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 of the List Namespace operation.
*/
@Override
public SharedAccessAuthorizationRuleListResponse listAuthorizationRules(String resourceGroupName,
        String namespaceName) throws IOException, ServiceException {
    // Validate
    if (resourceGroupName == null) {
        throw new NullPointerException("resourceGroupName");
    }
    if (namespaceName == null) {
        throw new NullPointerException("namespaceName");
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

                            JsonNode primaryKeyValue = propertiesValue.get("primaryKey");
                            if (primaryKeyValue != null && primaryKeyValue instanceof NullNode == false) {
                                String primaryKeyInstance;
                                primaryKeyInstance = primaryKeyValue.getTextValue();
                                propertiesInstance.setPrimaryKey(primaryKeyInstance);
                            }

                            JsonNode secondaryKeyValue = propertiesValue.get("secondaryKey");
                            if (secondaryKeyValue != null && secondaryKeyValue instanceof NullNode == false) {
                                String secondaryKeyInstance;
                                secondaryKeyInstance = secondaryKeyValue.getTextValue();
                                propertiesInstance.setSecondaryKey(secondaryKeyInstance);
                            }

                            JsonNode keyNameValue = propertiesValue.get("keyName");
                            if (keyNameValue != null && keyNameValue instanceof NullNode == false) {
                                String keyNameInstance;
                                keyNameInstance = keyNameValue.getTextValue();
                                propertiesInstance.setKeyName(keyNameInstance);
                            }

                            JsonNode claimTypeValue = propertiesValue.get("claimType");
                            if (claimTypeValue != null && claimTypeValue instanceof NullNode == false) {
                                String claimTypeInstance;
                                claimTypeInstance = claimTypeValue.getTextValue();
                                propertiesInstance.setClaimType(claimTypeInstance);
                            }

                            JsonNode claimValueValue = propertiesValue.get("claimValue");
                            if (claimValueValue != null && claimValueValue instanceof NullNode == false) {
                                String claimValueInstance;
                                claimValueInstance = claimValueValue.getTextValue();
                                propertiesInstance.setClaimValue(claimValueInstance);
                            }

                            JsonNode rightsArray = propertiesValue.get("rights");
                            if (rightsArray != null && rightsArray instanceof NullNode == false) {
                                for (JsonNode rightsValue : ((ArrayNode) rightsArray)) {
                                    propertiesInstance.getRights()
                                            .add(Enum.valueOf(AccessRights.class, rightsValue.getTextValue()));
                                }
                            }

                            JsonNode createdTimeValue = propertiesValue.get("createdTime");
                            if (createdTimeValue != null && createdTimeValue instanceof NullNode == false) {
                                Calendar createdTimeInstance;
                                createdTimeInstance = DatatypeConverter
                                        .parseDateTime(createdTimeValue.getTextValue());
                                propertiesInstance.setCreatedTime(createdTimeInstance);
                            }

                            JsonNode modifiedTimeValue = propertiesValue.get("modifiedTime");
                            if (modifiedTimeValue != null && modifiedTimeValue instanceof NullNode == false) {
                                Calendar modifiedTimeInstance;
                                modifiedTimeInstance = DatatypeConverter
                                        .parseDateTime(modifiedTimeValue.getTextValue());
                                propertiesInstance.setModifiedTime(modifiedTimeInstance);
                            }

                            JsonNode revisionValue = propertiesValue.get("revision");
                            if (revisionValue != null && revisionValue instanceof NullNode == false) {
                                int revisionInstance;
                                revisionInstance = revisionValue.getIntValue();
                                propertiesInstance.setRevision(revisionInstance);
                            }
                        }
                    }
                }

                JsonNode nextLinkValue = responseDoc.get("nextLink");
                if (nextLinkValue != null && nextLinkValue instanceof NullNode == false) {
                    String nextLinkInstance;
                    nextLinkInstance = nextLinkValue.getTextValue();
                    result.setNextLink(nextLinkInstance);
                }
            }

        }
        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:i5.las2peer.services.mobsos.SurveyService.java

/**
 * Parses incoming content to a survey JSON representation including checks for completeness, illegal fields and values.
 *///from  ww w.  jav a2 s.c  om
private JSONObject parseSurvey(String content) throws IllegalArgumentException {

    JSONObject o;
    try {
        o = (JSONObject) JSONValue.parseWithException(content);
    } catch (ParseException e1) {
        throw new IllegalArgumentException("Survey data *" + content + "* is not valid JSON!");
    }
    // check result for unknown illegal fields. If so, parsing fails.
    String[] fields = { "id", "owner", "organization", "logo", "name", "description", "resource", "start",
            "end", "lang", "qid" };
    for (Object key : o.keySet()) {
        if (!Arrays.asList(fields).contains(key)) {

            throw new IllegalArgumentException("Illegal survey field '" + key + "' detected!");

        } else {
            if (key.equals("name") && !(o.get(key) instanceof String)) {
                throw new IllegalArgumentException(
                        "Illegal value for survey field 'name'. Should be a string.");
            } else if (key.equals("description") && !(o.get(key) instanceof String)) {
                throw new IllegalArgumentException(
                        "Illegal value for survey field 'description'. Should be a string.");
            } else if (key.equals("organization") && !(o.get(key) instanceof String)) {
                throw new IllegalArgumentException(
                        "Illegal value for survey field 'organization'. Should be a string.");
            } else if (key.equals("logo")) {
                try {
                    URL u = new URL((String) o.get(key));
                    HttpURLConnection con = (HttpURLConnection) u.openConnection();
                    if (404 == con.getResponseCode()) {
                        throw new IllegalArgumentException(
                                "Illegal value for survey field logo. Should be a valid URL to an image resource.");
                    }
                    if (!con.getContentType().matches("image/.*")) {
                        throw new IllegalArgumentException(
                                "Illegal value for survey field logo. Should be a valid URL to an image resource.");
                    }
                } catch (MalformedURLException e) {
                    throw new IllegalArgumentException(
                            "Illegal value for survey field 'logo'. Should be a valid URL to an image resource.");
                } catch (IOException e) {
                    throw new IllegalArgumentException(
                            "Illegal value for survey field 'logo'. Should be a valid URL to an image resource.");
                }
            } else if (key.equals("resource")) {

                HttpResponse h = getClientMetadata((String) o.get(key));
                if (h.getStatus() == 404) {
                    throw new IllegalArgumentException(
                            "Illegal value for survey field 'resource'. Should be an existing OpenID Client ID.");
                }
                /*try {
                   URL u = new URL((String) o.get(key));
                   HttpURLConnection con = (HttpURLConnection) u.openConnection();
                   if(404 == con.getResponseCode()){
                      throw new IllegalArgumentException("Illegal value for survey field 'resource'. Should be a valid URL.");
                   }
                } catch (MalformedURLException e) {
                   throw new IllegalArgumentException("Illegal value for survey field 'resource'. Should be a valid URL.");
                } catch (IOException e) {
                   throw new IllegalArgumentException("Illegal value for survey field 'resource'. Should be a valid URL.");
                }*/
            } else if (key.equals("start")) {
                try {
                    DatatypeConverter.parseDateTime((String) o.get("start"));
                } catch (IllegalArgumentException e) {
                    throw new IllegalArgumentException(
                            "Illegal value for survey field 'start'. Should be an ISO-8601 formatted time string.");
                }
            } else if (key.equals("end")) {
                try {
                    DatatypeConverter.parseDateTime((String) o.get("end"));
                } catch (IllegalArgumentException e) {
                    throw new IllegalArgumentException(
                            "Illegal value for survey field 'end'. Should be an ISO-8601 formatted time string.");
                }
            } else if (key.equals("lang")) {

                String lang = (String) o.get(key);

                Pattern p = Pattern.compile("[a-z]+-[A-Z]+");
                Matcher m = p.matcher(lang);

                // do not iterate over all locales found, but only use first option with highest preference.

                Locale l = null;

                if (m.find()) {
                    String[] tokens = m.group().split("-");
                    l = new Locale(tokens[0], tokens[1]);
                } else {
                    throw new IllegalArgumentException(
                            "Illegal value for survey field 'lang'. Should be a valid locale such as 'en-US' or 'de-DE'.");
                }
            }
        }
    }

    // check if all necessary fields are specified.
    if (o.get("name") == null || o.get("organization") == null || o.get("logo") == null
            || o.get("description") == null || o.get("resource") == null || o.get("start") == null
            || o.get("end") == null || o.get("lang") == null) {
        throw new IllegalArgumentException(
                "Survey data incomplete! All fields name, organization, logo, description, resource, start, end, and lang must be defined!");
    }

    // finally check time integrity constraint: start must be before end (possibly not enforced by database; mySQL does not support this check)
    long d_start = DatatypeConverter.parseDateTime((String) o.get("start")).getTimeInMillis();
    long d_end = DatatypeConverter.parseDateTime((String) o.get("end")).getTimeInMillis();

    if (d_start >= d_end) {
        throw new IllegalArgumentException("Survey data invalid! Start time must be before end time!");
    }

    return o;
}

From source file:com.microsoft.windowsazure.management.servicebus.NamespaceOperationsImpl.java

/**
* The update authorization rule operation updates an authorization rule for
* a namespace./*from www  .j  a  v a2s .  com*/
*
* @param namespaceName Required. The namespace name.
* @param rule Optional. Updated access authorization rule.
* @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 response to a request for a particular authorization rule.
*/
@Override
public ServiceBusAuthorizationRuleResponse updateAuthorizationRule(String namespaceName,
        ServiceBusSharedAccessAuthorizationRule rule)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (namespaceName == null) {
        throw new NullPointerException("namespaceName");
    }

    // 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("namespaceName", namespaceName);
        tracingParameters.put("rule", rule);
        CloudTracing.enter(invocationId, this, "updateAuthorizationRuleAsync", 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/servicebus/namespaces/";
    url = url + URLEncoder.encode(namespaceName, "UTF-8");
    url = url + "/AuthorizationRules/";
    if (rule != null && rule.getKeyName() != null) {
        url = url + URLEncoder.encode(rule.getKeyName(), "UTF-8");
    }
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

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

    // Set Headers
    httpRequest.setHeader("Accept", "application/atom+xml");
    httpRequest.setHeader("Content-Type", "application/atom+xml");
    httpRequest.setHeader("if-match", "*");
    httpRequest.setHeader("type", "entry");
    httpRequest.setHeader("x-ms-version", "2012-03-01");

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

    if (rule != null) {
        Element entryElement = requestDoc.createElementNS("http://www.w3.org/2005/Atom", "entry");
        requestDoc.appendChild(entryElement);

        Element contentElement = requestDoc.createElementNS("http://www.w3.org/2005/Atom", "content");
        entryElement.appendChild(contentElement);

        Attr typeAttribute = requestDoc.createAttribute("type");
        typeAttribute.setValue("application/atom+xml");
        contentElement.setAttributeNode(typeAttribute);

        Element sharedAccessAuthorizationRuleElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                "SharedAccessAuthorizationRule");
        contentElement.appendChild(sharedAccessAuthorizationRuleElement);

        if (rule.getClaimType() != null) {
            Element claimTypeElement = requestDoc.createElementNS(
                    "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "ClaimType");
            claimTypeElement.appendChild(requestDoc.createTextNode(rule.getClaimType()));
            sharedAccessAuthorizationRuleElement.appendChild(claimTypeElement);
        }

        if (rule.getClaimValue() != null) {
            Element claimValueElement = requestDoc.createElementNS(
                    "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "ClaimValue");
            claimValueElement.appendChild(requestDoc.createTextNode(rule.getClaimValue()));
            sharedAccessAuthorizationRuleElement.appendChild(claimValueElement);
        }

        if (rule.getRights() != null) {
            if (rule.getRights() instanceof LazyCollection == false
                    || ((LazyCollection) rule.getRights()).isInitialized()) {
                Element rightsSequenceElement = requestDoc.createElementNS(
                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "Rights");
                for (AccessRight rightsItem : rule.getRights()) {
                    Element rightsItemElement = requestDoc.createElementNS(
                            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                            "AccessRights");
                    rightsItemElement.appendChild(requestDoc.createTextNode(rightsItem.toString()));
                    rightsSequenceElement.appendChild(rightsItemElement);
                }
                sharedAccessAuthorizationRuleElement.appendChild(rightsSequenceElement);
            }
        }

        Element createdTimeElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "CreatedTime");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
        simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        createdTimeElement.appendChild(
                requestDoc.createTextNode(simpleDateFormat.format(rule.getCreatedTime().getTime())));
        sharedAccessAuthorizationRuleElement.appendChild(createdTimeElement);

        Element modifiedTimeElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "ModifiedTime");
        SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
        simpleDateFormat2.setTimeZone(TimeZone.getTimeZone("UTC"));
        modifiedTimeElement.appendChild(
                requestDoc.createTextNode(simpleDateFormat2.format(rule.getModifiedTime().getTime())));
        sharedAccessAuthorizationRuleElement.appendChild(modifiedTimeElement);

        Element revisionElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "Revision");
        revisionElement.appendChild(requestDoc.createTextNode(Integer.toString(rule.getRevision())));
        sharedAccessAuthorizationRuleElement.appendChild(revisionElement);

        if (rule.getKeyName() != null) {
            Element keyNameElement = requestDoc.createElementNS(
                    "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "KeyName");
            keyNameElement.appendChild(requestDoc.createTextNode(rule.getKeyName()));
            sharedAccessAuthorizationRuleElement.appendChild(keyNameElement);
        }

        if (rule.getPrimaryKey() != null) {
            Element primaryKeyElement = requestDoc.createElementNS(
                    "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "PrimaryKey");
            primaryKeyElement.appendChild(requestDoc.createTextNode(rule.getPrimaryKey()));
            sharedAccessAuthorizationRuleElement.appendChild(primaryKeyElement);
        }
    }

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

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

            Element entryElement2 = XmlUtility.getElementByTagNameNS(responseDoc, "http://www.w3.org/2005/Atom",
                    "entry");
            if (entryElement2 != null) {
                Element contentElement2 = XmlUtility.getElementByTagNameNS(entryElement2,
                        "http://www.w3.org/2005/Atom", "content");
                if (contentElement2 != null) {
                    Element sharedAccessAuthorizationRuleElement2 = XmlUtility.getElementByTagNameNS(
                            contentElement2,
                            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                            "SharedAccessAuthorizationRule");
                    if (sharedAccessAuthorizationRuleElement2 != null) {
                        ServiceBusSharedAccessAuthorizationRule sharedAccessAuthorizationRuleInstance = new ServiceBusSharedAccessAuthorizationRule();
                        result.setAuthorizationRule(sharedAccessAuthorizationRuleInstance);

                        Element claimTypeElement2 = XmlUtility.getElementByTagNameNS(
                                sharedAccessAuthorizationRuleElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "ClaimType");
                        if (claimTypeElement2 != null) {
                            String claimTypeInstance;
                            claimTypeInstance = claimTypeElement2.getTextContent();
                            sharedAccessAuthorizationRuleInstance.setClaimType(claimTypeInstance);
                        }

                        Element claimValueElement2 = XmlUtility.getElementByTagNameNS(
                                sharedAccessAuthorizationRuleElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "ClaimValue");
                        if (claimValueElement2 != null) {
                            String claimValueInstance;
                            claimValueInstance = claimValueElement2.getTextContent();
                            sharedAccessAuthorizationRuleInstance.setClaimValue(claimValueInstance);
                        }

                        Element rightsSequenceElement2 = XmlUtility.getElementByTagNameNS(
                                sharedAccessAuthorizationRuleElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "Rights");
                        if (rightsSequenceElement2 != null) {
                            for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(rightsSequenceElement2,
                                            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                            "AccessRights")
                                    .size(); i1 = i1 + 1) {
                                org.w3c.dom.Element rightsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                        .getElementsByTagNameNS(rightsSequenceElement2,
                                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                                "AccessRights")
                                        .get(i1));
                                sharedAccessAuthorizationRuleInstance.getRights()
                                        .add(AccessRight.valueOf(rightsElement.getTextContent()));
                            }
                        }

                        Element createdTimeElement2 = XmlUtility.getElementByTagNameNS(
                                sharedAccessAuthorizationRuleElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "CreatedTime");
                        if (createdTimeElement2 != null) {
                            Calendar createdTimeInstance;
                            createdTimeInstance = DatatypeConverter
                                    .parseDateTime(createdTimeElement2.getTextContent());
                            sharedAccessAuthorizationRuleInstance.setCreatedTime(createdTimeInstance);
                        }

                        Element modifiedTimeElement2 = XmlUtility.getElementByTagNameNS(
                                sharedAccessAuthorizationRuleElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "ModifiedTime");
                        if (modifiedTimeElement2 != null) {
                            Calendar modifiedTimeInstance;
                            modifiedTimeInstance = DatatypeConverter
                                    .parseDateTime(modifiedTimeElement2.getTextContent());
                            sharedAccessAuthorizationRuleInstance.setModifiedTime(modifiedTimeInstance);
                        }

                        Element keyNameElement2 = XmlUtility.getElementByTagNameNS(
                                sharedAccessAuthorizationRuleElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "KeyName");
                        if (keyNameElement2 != null) {
                            String keyNameInstance;
                            keyNameInstance = keyNameElement2.getTextContent();
                            sharedAccessAuthorizationRuleInstance.setKeyName(keyNameInstance);
                        }

                        Element primaryKeyElement2 = XmlUtility.getElementByTagNameNS(
                                sharedAccessAuthorizationRuleElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "PrimaryKey");
                        if (primaryKeyElement2 != null) {
                            String primaryKeyInstance;
                            primaryKeyInstance = primaryKeyElement2.getTextContent();
                            sharedAccessAuthorizationRuleInstance.setPrimaryKey(primaryKeyInstance);
                        }

                        Element secondaryKeyElement = XmlUtility.getElementByTagNameNS(
                                sharedAccessAuthorizationRuleElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "SecondaryKey");
                        if (secondaryKeyElement != null) {
                            String secondaryKeyInstance;
                            secondaryKeyInstance = secondaryKeyElement.getTextContent();
                            sharedAccessAuthorizationRuleInstance.setSecondaryKey(secondaryKeyInstance);
                        }

                        Element revisionElement2 = XmlUtility.getElementByTagNameNS(
                                sharedAccessAuthorizationRuleElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "Revision");
                        if (revisionElement2 != null) {
                            int revisionInstance;
                            revisionInstance = DatatypeConverter.parseInt(revisionElement2.getTextContent());
                            sharedAccessAuthorizationRuleInstance.setRevision(revisionInstance);
                        }
                    }
                }
            }

        }
        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.servicebus.TopicOperationsImpl.java

/**
* Updates a topic.  (see//w w  w  .  ja  v a  2s.  c  o  m
* http://msdn.microsoft.com/en-us/library/windowsazure/jj839740.aspx for
* more information)
*
* @param namespaceName Required. The namespace name.
* @param topic Required. The Service Bus topic.
* @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 response to a request for a particular topic.
*/
@Override
public ServiceBusTopicResponse update(String namespaceName, ServiceBusTopic topic)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (namespaceName == null) {
        throw new NullPointerException("namespaceName");
    }
    if (topic == null) {
        throw new NullPointerException("topic");
    }

    // 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("namespaceName", namespaceName);
        tracingParameters.put("topic", topic);
        CloudTracing.enter(invocationId, this, "updateAsync", 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/servicebus/namespaces/";
    url = url + URLEncoder.encode(namespaceName, "UTF-8");
    url = url + "/topics/";
    if (topic.getName() != null) {
        url = url + URLEncoder.encode(topic.getName(), "UTF-8");
    }
    url = url + "/";
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

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

    // Set Headers
    httpRequest.setHeader("Content-Type", "application/atom+xml");
    httpRequest.setHeader("if-match", "*");
    httpRequest.setHeader("type", "entry");
    httpRequest.setHeader("x-ms-version", "2013-08-01");
    httpRequest.setHeader("x-process-at", "ServiceBus");

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

    Element entryElement = requestDoc.createElementNS("http://www.w3.org/2005/Atom", "entry");
    requestDoc.appendChild(entryElement);

    Element contentElement = requestDoc.createElementNS("http://www.w3.org/2005/Atom", "content");
    entryElement.appendChild(contentElement);

    Attr typeAttribute = requestDoc.createAttribute("type");
    typeAttribute.setValue("application/atom+xml;type=entry;charset=utf-8");
    contentElement.setAttributeNode(typeAttribute);

    Element topicDescriptionElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "TopicDescription");
    contentElement.appendChild(topicDescriptionElement);

    if (topic.getDefaultMessageTimeToLive() != null) {
        Element defaultMessageTimeToLiveElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                "DefaultMessageTimeToLive");
        defaultMessageTimeToLiveElement
                .appendChild(requestDoc.createTextNode(topic.getDefaultMessageTimeToLive()));
        topicDescriptionElement.appendChild(defaultMessageTimeToLiveElement);
    }

    Element maxSizeInMegabytesElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "MaxSizeInMegabytes");
    maxSizeInMegabytesElement
            .appendChild(requestDoc.createTextNode(Integer.toString(topic.getMaxSizeInMegabytes())));
    topicDescriptionElement.appendChild(maxSizeInMegabytesElement);

    Element requiresDuplicateDetectionElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
            "RequiresDuplicateDetection");
    requiresDuplicateDetectionElement.appendChild(
            requestDoc.createTextNode(Boolean.toString(topic.isRequiresDuplicateDetection()).toLowerCase()));
    topicDescriptionElement.appendChild(requiresDuplicateDetectionElement);

    if (topic.getDuplicateDetectionHistoryTimeWindow() != null) {
        Element duplicateDetectionHistoryTimeWindowElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                "DuplicateDetectionHistoryTimeWindow");
        duplicateDetectionHistoryTimeWindowElement
                .appendChild(requestDoc.createTextNode(topic.getDuplicateDetectionHistoryTimeWindow()));
        topicDescriptionElement.appendChild(duplicateDetectionHistoryTimeWindowElement);
    }

    Element enableBatchedOperationsElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "EnableBatchedOperations");
    enableBatchedOperationsElement.appendChild(
            requestDoc.createTextNode(Boolean.toString(topic.isEnableBatchedOperations()).toLowerCase()));
    topicDescriptionElement.appendChild(enableBatchedOperationsElement);

    Element sizeInBytesElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "SizeInBytes");
    sizeInBytesElement.appendChild(requestDoc.createTextNode(Integer.toString(topic.getSizeInBytes())));
    topicDescriptionElement.appendChild(sizeInBytesElement);

    Element filteringMessagesBeforePublishingElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
            "FilteringMessagesBeforePublishing");
    filteringMessagesBeforePublishingElement.appendChild(requestDoc
            .createTextNode(Boolean.toString(topic.isFilteringMessagesBeforePublishing()).toLowerCase()));
    topicDescriptionElement.appendChild(filteringMessagesBeforePublishingElement);

    Element isAnonymousAccessibleElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "IsAnonymousAccessible");
    isAnonymousAccessibleElement.appendChild(
            requestDoc.createTextNode(Boolean.toString(topic.isAnonymousAccessible()).toLowerCase()));
    topicDescriptionElement.appendChild(isAnonymousAccessibleElement);

    if (topic.getAuthorizationRules() != null) {
        if (topic.getAuthorizationRules() instanceof LazyCollection == false
                || ((LazyCollection) topic.getAuthorizationRules()).isInitialized()) {
            Element authorizationRulesSequenceElement = requestDoc.createElementNS(
                    "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                    "AuthorizationRules");
            for (ServiceBusSharedAccessAuthorizationRule authorizationRulesItem : topic
                    .getAuthorizationRules()) {
                Element authorizationRuleElement = requestDoc.createElementNS(
                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                        "AuthorizationRule");
                authorizationRulesSequenceElement.appendChild(authorizationRuleElement);

                Attr typeAttribute2 = requestDoc.createAttributeNS("http://www.w3.org/2001/XMLSchema-instance",
                        "type");
                typeAttribute2.setValue("SharedAccessAuthorizationRule");
                authorizationRuleElement.setAttributeNode(typeAttribute2);

                if (authorizationRulesItem.getClaimType() != null) {
                    Element claimTypeElement = requestDoc.createElementNS(
                            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "ClaimType");
                    claimTypeElement
                            .appendChild(requestDoc.createTextNode(authorizationRulesItem.getClaimType()));
                    authorizationRuleElement.appendChild(claimTypeElement);
                }

                if (authorizationRulesItem.getClaimValue() != null) {
                    Element claimValueElement = requestDoc.createElementNS(
                            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                            "ClaimValue");
                    claimValueElement
                            .appendChild(requestDoc.createTextNode(authorizationRulesItem.getClaimValue()));
                    authorizationRuleElement.appendChild(claimValueElement);
                }

                if (authorizationRulesItem.getRights() != null) {
                    if (authorizationRulesItem.getRights() instanceof LazyCollection == false
                            || ((LazyCollection) authorizationRulesItem.getRights()).isInitialized()) {
                        Element rightsSequenceElement = requestDoc.createElementNS(
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "Rights");
                        for (AccessRight rightsItem : authorizationRulesItem.getRights()) {
                            Element rightsItemElement = requestDoc.createElementNS(
                                    "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                    "AccessRights");
                            rightsItemElement.appendChild(requestDoc.createTextNode(rightsItem.toString()));
                            rightsSequenceElement.appendChild(rightsItemElement);
                        }
                        authorizationRuleElement.appendChild(rightsSequenceElement);
                    }
                }

                Element createdTimeElement = requestDoc.createElementNS(
                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "CreatedTime");
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
                simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
                createdTimeElement.appendChild(requestDoc.createTextNode(
                        simpleDateFormat.format(authorizationRulesItem.getCreatedTime().getTime())));
                authorizationRuleElement.appendChild(createdTimeElement);

                if (authorizationRulesItem.getKeyName() != null) {
                    Element keyNameElement = requestDoc.createElementNS(
                            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "KeyName");
                    keyNameElement.appendChild(requestDoc.createTextNode(authorizationRulesItem.getKeyName()));
                    authorizationRuleElement.appendChild(keyNameElement);
                }

                Element modifiedTimeElement = requestDoc.createElementNS(
                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "ModifiedTime");
                SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
                simpleDateFormat2.setTimeZone(TimeZone.getTimeZone("UTC"));
                modifiedTimeElement.appendChild(requestDoc.createTextNode(
                        simpleDateFormat2.format(authorizationRulesItem.getModifiedTime().getTime())));
                authorizationRuleElement.appendChild(modifiedTimeElement);

                if (authorizationRulesItem.getPrimaryKey() != null) {
                    Element primaryKeyElement = requestDoc.createElementNS(
                            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                            "PrimaryKey");
                    primaryKeyElement
                            .appendChild(requestDoc.createTextNode(authorizationRulesItem.getPrimaryKey()));
                    authorizationRuleElement.appendChild(primaryKeyElement);
                }

                if (authorizationRulesItem.getSecondaryKey() != null) {
                    Element secondaryKeyElement = requestDoc.createElementNS(
                            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                            "SecondaryKey");
                    secondaryKeyElement
                            .appendChild(requestDoc.createTextNode(authorizationRulesItem.getSecondaryKey()));
                    authorizationRuleElement.appendChild(secondaryKeyElement);
                }
            }
            topicDescriptionElement.appendChild(authorizationRulesSequenceElement);
        }
    }

    if (topic.getStatus() != null) {
        Element statusElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "Status");
        statusElement.appendChild(requestDoc.createTextNode(topic.getStatus()));
        topicDescriptionElement.appendChild(statusElement);
    }

    Element createdAtElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "CreatedAt");
    SimpleDateFormat simpleDateFormat3 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
    simpleDateFormat3.setTimeZone(TimeZone.getTimeZone("UTC"));
    createdAtElement
            .appendChild(requestDoc.createTextNode(simpleDateFormat3.format(topic.getCreatedAt().getTime())));
    topicDescriptionElement.appendChild(createdAtElement);

    Element updatedAtElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "UpdatedAt");
    SimpleDateFormat simpleDateFormat4 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
    simpleDateFormat4.setTimeZone(TimeZone.getTimeZone("UTC"));
    updatedAtElement
            .appendChild(requestDoc.createTextNode(simpleDateFormat4.format(topic.getUpdatedAt().getTime())));
    topicDescriptionElement.appendChild(updatedAtElement);

    Element accessedAtElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "AccessedAt");
    SimpleDateFormat simpleDateFormat5 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
    simpleDateFormat5.setTimeZone(TimeZone.getTimeZone("UTC"));
    accessedAtElement
            .appendChild(requestDoc.createTextNode(simpleDateFormat5.format(topic.getAccessedAt().getTime())));
    topicDescriptionElement.appendChild(accessedAtElement);

    Element supportOrderingElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "SupportOrdering");
    supportOrderingElement
            .appendChild(requestDoc.createTextNode(Boolean.toString(topic.isSupportOrdering()).toLowerCase()));
    topicDescriptionElement.appendChild(supportOrderingElement);

    if (topic.getCountDetails() != null) {
        Element countDetailsElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "CountDetails");
        topicDescriptionElement.appendChild(countDetailsElement);

        Element activeMessageCountElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2011/06/servicebus", "ActiveMessageCount");
        activeMessageCountElement.appendChild(
                requestDoc.createTextNode(Integer.toString(topic.getCountDetails().getActiveMessageCount())));
        countDetailsElement.appendChild(activeMessageCountElement);

        Element deadLetterMessageCountElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2011/06/servicebus", "DeadLetterMessageCount");
        deadLetterMessageCountElement.appendChild(requestDoc
                .createTextNode(Integer.toString(topic.getCountDetails().getDeadLetterMessageCount())));
        countDetailsElement.appendChild(deadLetterMessageCountElement);

        Element scheduledMessageCountElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2011/06/servicebus", "ScheduledMessageCount");
        scheduledMessageCountElement.appendChild(requestDoc
                .createTextNode(Integer.toString(topic.getCountDetails().getScheduledMessageCount())));
        countDetailsElement.appendChild(scheduledMessageCountElement);

        Element transferDeadLetterMessageCountElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2011/06/servicebus",
                "TransferDeadLetterMessageCount");
        transferDeadLetterMessageCountElement.appendChild(requestDoc
                .createTextNode(Integer.toString(topic.getCountDetails().getTransferDeadLetterMessageCount())));
        countDetailsElement.appendChild(transferDeadLetterMessageCountElement);

        Element transferMessageCountElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2011/06/servicebus", "TransferMessageCount");
        transferMessageCountElement.appendChild(
                requestDoc.createTextNode(Integer.toString(topic.getCountDetails().getTransferMessageCount())));
        countDetailsElement.appendChild(transferMessageCountElement);
    }

    Element subscriptionCountElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "SubscriptionCount");
    subscriptionCountElement
            .appendChild(requestDoc.createTextNode(Integer.toString(topic.getSubscriptionCount())));
    topicDescriptionElement.appendChild(subscriptionCountElement);

    if (topic.getAutoDeleteOnIdle() != null) {
        Element autoDeleteOnIdleElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "AutoDeleteOnIdle");
        autoDeleteOnIdleElement.appendChild(requestDoc.createTextNode(topic.getAutoDeleteOnIdle()));
        topicDescriptionElement.appendChild(autoDeleteOnIdleElement);
    }

    if (topic.getEntityAvailabilityStatus() != null) {
        Element entityAvailabilityStatusElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                "EntityAvailabilityStatus");
        entityAvailabilityStatusElement
                .appendChild(requestDoc.createTextNode(topic.getEntityAvailabilityStatus()));
        topicDescriptionElement.appendChild(entityAvailabilityStatusElement);
    }

    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/atom+xml");

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

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

            Element entryElement2 = XmlUtility.getElementByTagNameNS(responseDoc, "http://www.w3.org/2005/Atom",
                    "entry");
            if (entryElement2 != null) {
                Element titleElement = XmlUtility.getElementByTagNameNS(entryElement2,
                        "http://www.w3.org/2005/Atom", "title");
                if (titleElement != null) {
                }

                Element contentElement2 = XmlUtility.getElementByTagNameNS(entryElement2,
                        "http://www.w3.org/2005/Atom", "content");
                if (contentElement2 != null) {
                    Element topicDescriptionElement2 = XmlUtility.getElementByTagNameNS(contentElement2,
                            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                            "TopicDescription");
                    if (topicDescriptionElement2 != null) {
                        ServiceBusTopic topicDescriptionInstance = new ServiceBusTopic();
                        result.setTopic(topicDescriptionInstance);

                        Element defaultMessageTimeToLiveElement2 = XmlUtility.getElementByTagNameNS(
                                topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "DefaultMessageTimeToLive");
                        if (defaultMessageTimeToLiveElement2 != null) {
                            String defaultMessageTimeToLiveInstance;
                            defaultMessageTimeToLiveInstance = defaultMessageTimeToLiveElement2
                                    .getTextContent();
                            topicDescriptionInstance
                                    .setDefaultMessageTimeToLive(defaultMessageTimeToLiveInstance);
                        }

                        Element maxSizeInMegabytesElement2 = XmlUtility.getElementByTagNameNS(
                                topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "MaxSizeInMegabytes");
                        if (maxSizeInMegabytesElement2 != null) {
                            int maxSizeInMegabytesInstance;
                            maxSizeInMegabytesInstance = DatatypeConverter
                                    .parseInt(maxSizeInMegabytesElement2.getTextContent());
                            topicDescriptionInstance.setMaxSizeInMegabytes(maxSizeInMegabytesInstance);
                        }

                        Element requiresDuplicateDetectionElement2 = XmlUtility.getElementByTagNameNS(
                                topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "RequiresDuplicateDetection");
                        if (requiresDuplicateDetectionElement2 != null) {
                            boolean requiresDuplicateDetectionInstance;
                            requiresDuplicateDetectionInstance = DatatypeConverter.parseBoolean(
                                    requiresDuplicateDetectionElement2.getTextContent().toLowerCase());
                            topicDescriptionInstance
                                    .setRequiresDuplicateDetection(requiresDuplicateDetectionInstance);
                        }

                        Element duplicateDetectionHistoryTimeWindowElement2 = XmlUtility.getElementByTagNameNS(
                                topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "DuplicateDetectionHistoryTimeWindow");
                        if (duplicateDetectionHistoryTimeWindowElement2 != null) {
                            String duplicateDetectionHistoryTimeWindowInstance;
                            duplicateDetectionHistoryTimeWindowInstance = duplicateDetectionHistoryTimeWindowElement2
                                    .getTextContent();
                            topicDescriptionInstance.setDuplicateDetectionHistoryTimeWindow(
                                    duplicateDetectionHistoryTimeWindowInstance);
                        }

                        Element enableBatchedOperationsElement2 = XmlUtility.getElementByTagNameNS(
                                topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "EnableBatchedOperations");
                        if (enableBatchedOperationsElement2 != null) {
                            boolean enableBatchedOperationsInstance;
                            enableBatchedOperationsInstance = DatatypeConverter.parseBoolean(
                                    enableBatchedOperationsElement2.getTextContent().toLowerCase());
                            topicDescriptionInstance
                                    .setEnableBatchedOperations(enableBatchedOperationsInstance);
                        }

                        Element sizeInBytesElement2 = XmlUtility.getElementByTagNameNS(topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "SizeInBytes");
                        if (sizeInBytesElement2 != null) {
                            int sizeInBytesInstance;
                            sizeInBytesInstance = DatatypeConverter
                                    .parseInt(sizeInBytesElement2.getTextContent());
                            topicDescriptionInstance.setSizeInBytes(sizeInBytesInstance);
                        }

                        Element filteringMessagesBeforePublishingElement2 = XmlUtility.getElementByTagNameNS(
                                topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "FilteringMessagesBeforePublishing");
                        if (filteringMessagesBeforePublishingElement2 != null) {
                            boolean filteringMessagesBeforePublishingInstance;
                            filteringMessagesBeforePublishingInstance = DatatypeConverter.parseBoolean(
                                    filteringMessagesBeforePublishingElement2.getTextContent().toLowerCase());
                            topicDescriptionInstance.setFilteringMessagesBeforePublishing(
                                    filteringMessagesBeforePublishingInstance);
                        }

                        Element isAnonymousAccessibleElement2 = XmlUtility.getElementByTagNameNS(
                                topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "IsAnonymousAccessible");
                        if (isAnonymousAccessibleElement2 != null) {
                            boolean isAnonymousAccessibleInstance;
                            isAnonymousAccessibleInstance = DatatypeConverter
                                    .parseBoolean(isAnonymousAccessibleElement2.getTextContent().toLowerCase());
                            topicDescriptionInstance.setIsAnonymousAccessible(isAnonymousAccessibleInstance);
                        }

                        Element authorizationRulesSequenceElement2 = XmlUtility.getElementByTagNameNS(
                                topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "AuthorizationRules");
                        if (authorizationRulesSequenceElement2 != null) {
                            for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(authorizationRulesSequenceElement2,
                                            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                            "AuthorizationRule")
                                    .size(); i1 = i1 + 1) {
                                org.w3c.dom.Element authorizationRulesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                        .getElementsByTagNameNS(authorizationRulesSequenceElement2,
                                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                                "AuthorizationRule")
                                        .get(i1));
                                ServiceBusSharedAccessAuthorizationRule authorizationRuleInstance = new ServiceBusSharedAccessAuthorizationRule();
                                topicDescriptionInstance.getAuthorizationRules().add(authorizationRuleInstance);

                                Element claimTypeElement2 = XmlUtility.getElementByTagNameNS(
                                        authorizationRulesElement,
                                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                        "ClaimType");
                                if (claimTypeElement2 != null) {
                                    String claimTypeInstance;
                                    claimTypeInstance = claimTypeElement2.getTextContent();
                                    authorizationRuleInstance.setClaimType(claimTypeInstance);
                                }

                                Element claimValueElement2 = XmlUtility.getElementByTagNameNS(
                                        authorizationRulesElement,
                                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                        "ClaimValue");
                                if (claimValueElement2 != null) {
                                    String claimValueInstance;
                                    claimValueInstance = claimValueElement2.getTextContent();
                                    authorizationRuleInstance.setClaimValue(claimValueInstance);
                                }

                                Element rightsSequenceElement2 = XmlUtility.getElementByTagNameNS(
                                        authorizationRulesElement,
                                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                        "Rights");
                                if (rightsSequenceElement2 != null) {
                                    for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility
                                            .getElementsByTagNameNS(rightsSequenceElement2,
                                                    "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                                    "AccessRights")
                                            .size(); i2 = i2 + 1) {
                                        org.w3c.dom.Element rightsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                                .getElementsByTagNameNS(rightsSequenceElement2,
                                                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                                        "AccessRights")
                                                .get(i2));
                                        authorizationRuleInstance.getRights()
                                                .add(AccessRight.valueOf(rightsElement.getTextContent()));
                                    }
                                }

                                Element createdTimeElement2 = XmlUtility.getElementByTagNameNS(
                                        authorizationRulesElement,
                                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                        "CreatedTime");
                                if (createdTimeElement2 != null) {
                                    Calendar createdTimeInstance;
                                    createdTimeInstance = DatatypeConverter
                                            .parseDateTime(createdTimeElement2.getTextContent());
                                    authorizationRuleInstance.setCreatedTime(createdTimeInstance);
                                }

                                Element keyNameElement2 = XmlUtility.getElementByTagNameNS(
                                        authorizationRulesElement,
                                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                        "KeyName");
                                if (keyNameElement2 != null) {
                                    String keyNameInstance;
                                    keyNameInstance = keyNameElement2.getTextContent();
                                    authorizationRuleInstance.setKeyName(keyNameInstance);
                                }

                                Element modifiedTimeElement2 = XmlUtility.getElementByTagNameNS(
                                        authorizationRulesElement,
                                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                        "ModifiedTime");
                                if (modifiedTimeElement2 != null) {
                                    Calendar modifiedTimeInstance;
                                    modifiedTimeInstance = DatatypeConverter
                                            .parseDateTime(modifiedTimeElement2.getTextContent());
                                    authorizationRuleInstance.setModifiedTime(modifiedTimeInstance);
                                }

                                Element primaryKeyElement2 = XmlUtility.getElementByTagNameNS(
                                        authorizationRulesElement,
                                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                        "PrimaryKey");
                                if (primaryKeyElement2 != null) {
                                    String primaryKeyInstance;
                                    primaryKeyInstance = primaryKeyElement2.getTextContent();
                                    authorizationRuleInstance.setPrimaryKey(primaryKeyInstance);
                                }

                                Element secondaryKeyElement2 = XmlUtility.getElementByTagNameNS(
                                        authorizationRulesElement,
                                        "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                        "SecondaryKey");
                                if (secondaryKeyElement2 != null) {
                                    String secondaryKeyInstance;
                                    secondaryKeyInstance = secondaryKeyElement2.getTextContent();
                                    authorizationRuleInstance.setSecondaryKey(secondaryKeyInstance);
                                }
                            }
                        }

                        Element statusElement2 = XmlUtility.getElementByTagNameNS(topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "Status");
                        if (statusElement2 != null) {
                            String statusInstance;
                            statusInstance = statusElement2.getTextContent();
                            topicDescriptionInstance.setStatus(statusInstance);
                        }

                        Element createdAtElement2 = XmlUtility.getElementByTagNameNS(topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "CreatedAt");
                        if (createdAtElement2 != null) {
                            Calendar createdAtInstance;
                            createdAtInstance = DatatypeConverter
                                    .parseDateTime(createdAtElement2.getTextContent());
                            topicDescriptionInstance.setCreatedAt(createdAtInstance);
                        }

                        Element updatedAtElement2 = XmlUtility.getElementByTagNameNS(topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "UpdatedAt");
                        if (updatedAtElement2 != null) {
                            Calendar updatedAtInstance;
                            updatedAtInstance = DatatypeConverter
                                    .parseDateTime(updatedAtElement2.getTextContent());
                            topicDescriptionInstance.setUpdatedAt(updatedAtInstance);
                        }

                        Element accessedAtElement2 = XmlUtility.getElementByTagNameNS(topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "AccessedAt");
                        if (accessedAtElement2 != null) {
                            Calendar accessedAtInstance;
                            accessedAtInstance = DatatypeConverter
                                    .parseDateTime(accessedAtElement2.getTextContent());
                            topicDescriptionInstance.setAccessedAt(accessedAtInstance);
                        }

                        Element supportOrderingElement2 = XmlUtility.getElementByTagNameNS(
                                topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "SupportOrdering");
                        if (supportOrderingElement2 != null) {
                            boolean supportOrderingInstance;
                            supportOrderingInstance = DatatypeConverter
                                    .parseBoolean(supportOrderingElement2.getTextContent().toLowerCase());
                            topicDescriptionInstance.setSupportOrdering(supportOrderingInstance);
                        }

                        Element countDetailsElement2 = XmlUtility.getElementByTagNameNS(
                                topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "CountDetails");
                        if (countDetailsElement2 != null) {
                            CountDetails countDetailsInstance = new CountDetails();
                            topicDescriptionInstance.setCountDetails(countDetailsInstance);
                        }

                        Element subscriptionCountElement2 = XmlUtility.getElementByTagNameNS(
                                topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "SubscriptionCount");
                        if (subscriptionCountElement2 != null) {
                            int subscriptionCountInstance;
                            subscriptionCountInstance = DatatypeConverter
                                    .parseInt(subscriptionCountElement2.getTextContent());
                            topicDescriptionInstance.setSubscriptionCount(subscriptionCountInstance);
                        }

                        Element autoDeleteOnIdleElement2 = XmlUtility.getElementByTagNameNS(
                                topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "AutoDeleteOnIdle");
                        if (autoDeleteOnIdleElement2 != null) {
                            String autoDeleteOnIdleInstance;
                            autoDeleteOnIdleInstance = autoDeleteOnIdleElement2.getTextContent();
                            topicDescriptionInstance.setAutoDeleteOnIdle(autoDeleteOnIdleInstance);
                        }

                        Element entityAvailabilityStatusElement2 = XmlUtility.getElementByTagNameNS(
                                topicDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "EntityAvailabilityStatus");
                        if (entityAvailabilityStatusElement2 != null) {
                            String entityAvailabilityStatusInstance;
                            entityAvailabilityStatusInstance = entityAvailabilityStatusElement2
                                    .getTextContent();
                            topicDescriptionInstance
                                    .setEntityAvailabilityStatus(entityAvailabilityStatusInstance);
                        }
                    }
                }
            }

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

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

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

/**
* Returns information about Azure SQL Database Elastic Pool Activity.
*
* @param resourceGroupName Required. The name of the Resource Group to
* which the Azure SQL Database Serve belongs.
* @param serverName Required. The name of the Azure SQL Database Server in
* which Azure SQL Database Elastic Pools are hosted.
* @param elasticPoolName Required. The name of the Azure SQL Database
* Elastic Pool for which to get the current activity.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations./* w w  w .  jav a 2s.c  om*/
* @throws ServiceException Thrown if an unexpected response is found.
* @return Represents the response to a List Azure Sql Elastic Pool Activity
* request.
*/
@Override
public ElasticPoolActivityListResponse listActivity(String resourceGroupName, String serverName,
        String elasticPoolName) throws IOException, ServiceException {
    // Validate
    if (resourceGroupName == null) {
        throw new NullPointerException("resourceGroupName");
    }
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }
    if (elasticPoolName == null) {
        throw new NullPointerException("elasticPoolName");
    }

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

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

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

    // Set Headers

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

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

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

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

                            JsonNode endTimeValue = propertiesValue.get("endTime");
                            if (endTimeValue != null && endTimeValue instanceof NullNode == false) {
                                Calendar endTimeInstance;
                                endTimeInstance = DatatypeConverter.parseDateTime(endTimeValue.getTextValue());
                                propertiesInstance.setEndTime(endTimeInstance);
                            }

                            JsonNode errorCodeValue = propertiesValue.get("errorCode");
                            if (errorCodeValue != null && errorCodeValue instanceof NullNode == false) {
                                int errorCodeInstance;
                                errorCodeInstance = errorCodeValue.getIntValue();
                                propertiesInstance.setErrorCode(errorCodeInstance);
                            }

                            JsonNode errorMessageValue = propertiesValue.get("errorMessage");
                            if (errorMessageValue != null && errorMessageValue instanceof NullNode == false) {
                                String errorMessageInstance;
                                errorMessageInstance = errorMessageValue.getTextValue();
                                propertiesInstance.setErrorMessage(errorMessageInstance);
                            }

                            JsonNode errorSeverityValue = propertiesValue.get("errorSeverity");
                            if (errorSeverityValue != null && errorSeverityValue instanceof NullNode == false) {
                                int errorSeverityInstance;
                                errorSeverityInstance = errorSeverityValue.getIntValue();
                                propertiesInstance.setErrorSeverity(errorSeverityInstance);
                            }

                            JsonNode operationValue = propertiesValue.get("operation");
                            if (operationValue != null && operationValue instanceof NullNode == false) {
                                String operationInstance;
                                operationInstance = operationValue.getTextValue();
                                propertiesInstance.setOperation(operationInstance);
                            }

                            JsonNode operationIdValue = propertiesValue.get("operationId");
                            if (operationIdValue != null && operationIdValue instanceof NullNode == false) {
                                String operationIdInstance;
                                operationIdInstance = operationIdValue.getTextValue();
                                propertiesInstance.setOperationId(operationIdInstance);
                            }

                            JsonNode percentCompleteValue = propertiesValue.get("percentComplete");
                            if (percentCompleteValue != null
                                    && percentCompleteValue instanceof NullNode == false) {
                                int percentCompleteInstance;
                                percentCompleteInstance = percentCompleteValue.getIntValue();
                                propertiesInstance.setPercentComplete(percentCompleteInstance);
                            }

                            JsonNode requestedDatabaseDtuMaxValue = propertiesValue
                                    .get("requestedDatabaseDtuMax");
                            if (requestedDatabaseDtuMaxValue != null
                                    && requestedDatabaseDtuMaxValue instanceof NullNode == false) {
                                int requestedDatabaseDtuMaxInstance;
                                requestedDatabaseDtuMaxInstance = requestedDatabaseDtuMaxValue.getIntValue();
                                propertiesInstance.setRequestedDatabaseDtuMax(requestedDatabaseDtuMaxInstance);
                            }

                            JsonNode requestedDatabaseDtuMinValue = propertiesValue
                                    .get("requestedDatabaseDtuMin");
                            if (requestedDatabaseDtuMinValue != null
                                    && requestedDatabaseDtuMinValue instanceof NullNode == false) {
                                int requestedDatabaseDtuMinInstance;
                                requestedDatabaseDtuMinInstance = requestedDatabaseDtuMinValue.getIntValue();
                                propertiesInstance.setRequestedDatabaseDtuMin(requestedDatabaseDtuMinInstance);
                            }

                            JsonNode requestedDtuValue = propertiesValue.get("requestedDtu");
                            if (requestedDtuValue != null && requestedDtuValue instanceof NullNode == false) {
                                int requestedDtuInstance;
                                requestedDtuInstance = requestedDtuValue.getIntValue();
                                propertiesInstance.setRequestedDtu(requestedDtuInstance);
                            }

                            JsonNode requestedElasticPoolNameValue = propertiesValue
                                    .get("requestedElasticPoolName");
                            if (requestedElasticPoolNameValue != null
                                    && requestedElasticPoolNameValue instanceof NullNode == false) {
                                String requestedElasticPoolNameInstance;
                                requestedElasticPoolNameInstance = requestedElasticPoolNameValue.getTextValue();
                                propertiesInstance
                                        .setRequestedElasticPoolName(requestedElasticPoolNameInstance);
                            }

                            JsonNode requestedStorageLimitInGBValue = propertiesValue
                                    .get("requestedStorageLimitInGB");
                            if (requestedStorageLimitInGBValue != null
                                    && requestedStorageLimitInGBValue instanceof NullNode == false) {
                                long requestedStorageLimitInGBInstance;
                                requestedStorageLimitInGBInstance = requestedStorageLimitInGBValue
                                        .getLongValue();
                                propertiesInstance
                                        .setRequestedStorageLimitInGB(requestedStorageLimitInGBInstance);
                            }

                            JsonNode elasticPoolNameValue = propertiesValue.get("elasticPoolName");
                            if (elasticPoolNameValue != null
                                    && elasticPoolNameValue instanceof NullNode == false) {
                                String elasticPoolNameInstance;
                                elasticPoolNameInstance = elasticPoolNameValue.getTextValue();
                                propertiesInstance.setElasticPoolName(elasticPoolNameInstance);
                            }

                            JsonNode serverNameValue = propertiesValue.get("serverName");
                            if (serverNameValue != null && serverNameValue instanceof NullNode == false) {
                                String serverNameInstance;
                                serverNameInstance = serverNameValue.getTextValue();
                                propertiesInstance.setServerName(serverNameInstance);
                            }

                            JsonNode startTimeValue = propertiesValue.get("startTime");
                            if (startTimeValue != null && startTimeValue instanceof NullNode == false) {
                                Calendar startTimeInstance;
                                startTimeInstance = DatatypeConverter
                                        .parseDateTime(startTimeValue.getTextValue());
                                propertiesInstance.setStartTime(startTimeInstance);
                            }

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

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

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

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

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

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

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

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

From source file:i5.las2peer.services.mobsos.SurveyService.java

/**
 * Stores a new survey described with JSON into the MobSOS database.
 * The MobSOS database thereby generates a new id returned by this method.
 * @throws ParseException //from w  w  w  . ja va 2  s  .c o  m
 */
private int storeNewSurvey(JSONObject survey) throws IllegalArgumentException, SQLException, ParseException {

    Connection conn = null;
    PreparedStatement stmt = null;
    ResultSet rset = null;

    String sub = (String) getActiveUserInfo().get("sub");

    try {
        conn = dataSource.getConnection();
        stmt = conn.prepareStatement("insert into " + jdbcSchema
                + ".survey(owner, organization, logo, name, description, resource, start, end, lang ) values (?,?,?,?,?,?,?,?,?)",
                Statement.RETURN_GENERATED_KEYS);

        stmt.clearParameters();
        stmt.setString(1, sub); // active agent becomes owner automatically
        stmt.setString(2, (String) survey.get("organization"));
        stmt.setString(3, (String) survey.get("logo"));
        stmt.setString(4, (String) survey.get("name"));
        stmt.setString(5, (String) survey.get("description"));
        stmt.setString(6, (String) survey.get("resource"));
        stmt.setTimestamp(7,
                new Timestamp(DatatypeConverter.parseDateTime((String) survey.get("start")).getTimeInMillis()));
        stmt.setTimestamp(8,
                new Timestamp(DatatypeConverter.parseDateTime((String) survey.get("end")).getTimeInMillis()));
        stmt.setString(9, (String) survey.get("lang"));

        stmt.executeUpdate();
        ResultSet rs = stmt.getGeneratedKeys();

        if (rs.next()) {
            return rs.getInt(1);
        } else {
            throw new NoSuchElementException("No new survey was created!");
        }

    } catch (UnsupportedOperationException e) {
        e.printStackTrace();
    } finally {
        try {
            if (rset != null)
                rset.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            if (stmt != null)
                stmt.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            if (conn != null)
                conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    throw new NoSuchElementException("No new survey was created!");
}

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

/**
* You can retrieve details for a web site by issuing an HTTP GET request.
* (see http://msdn.microsoft.com/en-us/library/windowsazure/dn167007.aspx
* for more information)/*from ww  w . j av  a2s .  com*/
*
* @param resourceGroupName Required. The name of the resource group.
* @param webSiteName Required. The name of the web site.
* @param slotName Optional. The name of the slot.
* @param parameters Optional. Additional parameters.
* @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 Get Web Site Details operation response.
*/
@Override
public WebSiteGetResponse get(String resourceGroupName, String webSiteName, String slotName,
        WebSiteGetParameters parameters) throws IOException, ServiceException, URISyntaxException {
    // Validate
    if (resourceGroupName == null) {
        throw new NullPointerException("resourceGroupName");
    }
    if (webSiteName == null) {
        throw new NullPointerException("webSiteName");
    }

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

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

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

    // Set Headers

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

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

            if (responseDoc != null && responseDoc instanceof NullNode == false) {
                WebSite webSiteInstance = new WebSite();
                result.setWebSite(webSiteInstance);

                JsonNode propertiesValue = responseDoc.get("properties");
                if (propertiesValue != null && propertiesValue instanceof NullNode == false) {
                    WebSiteProperties propertiesInstance = new WebSiteProperties();
                    webSiteInstance.setProperties(propertiesInstance);

                    JsonNode adminEnabledValue = propertiesValue.get("adminEnabled");
                    if (adminEnabledValue != null && adminEnabledValue instanceof NullNode == false) {
                        boolean adminEnabledInstance;
                        adminEnabledInstance = adminEnabledValue.getBooleanValue();
                        propertiesInstance.setAdminEnabled(adminEnabledInstance);
                    }

                    JsonNode availabilityStateValue = propertiesValue.get("availabilityState");
                    if (availabilityStateValue != null && availabilityStateValue instanceof NullNode == false) {
                        WebSpaceAvailabilityState availabilityStateInstance;
                        availabilityStateInstance = Enum.valueOf(WebSpaceAvailabilityState.class,
                                availabilityStateValue.getTextValue());
                        propertiesInstance.setAvailabilityState(availabilityStateInstance);
                    }

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

                    JsonNode enabledHostNamesArray = propertiesValue.get("enabledHostNames");
                    if (enabledHostNamesArray != null && enabledHostNamesArray instanceof NullNode == false) {
                        for (JsonNode enabledHostNamesValue : ((ArrayNode) enabledHostNamesArray)) {
                            propertiesInstance.getEnabledHostNames().add(enabledHostNamesValue.getTextValue());
                        }
                    }

                    JsonNode hostNameSslStatesArray = propertiesValue.get("hostNameSslStates");
                    if (hostNameSslStatesArray != null && hostNameSslStatesArray instanceof NullNode == false) {
                        for (JsonNode hostNameSslStatesValue : ((ArrayNode) hostNameSslStatesArray)) {
                            WebSiteProperties.WebSiteHostNameSslState webSiteHostNameSslStateInstance = new WebSiteProperties.WebSiteHostNameSslState();
                            propertiesInstance.getHostNameSslStates().add(webSiteHostNameSslStateInstance);

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

                            JsonNode sslStateValue = hostNameSslStatesValue.get("sslState");
                            if (sslStateValue != null && sslStateValue instanceof NullNode == false) {
                                WebSiteSslState sslStateInstance;
                                sslStateInstance = Enum.valueOf(WebSiteSslState.class,
                                        sslStateValue.getTextValue());
                                webSiteHostNameSslStateInstance.setSslState(sslStateInstance);
                            }

                            JsonNode thumbprintValue = hostNameSslStatesValue.get("thumbprint");
                            if (thumbprintValue != null && thumbprintValue instanceof NullNode == false) {
                                String thumbprintInstance;
                                thumbprintInstance = thumbprintValue.getTextValue();
                                webSiteHostNameSslStateInstance.setThumbprint(thumbprintInstance);
                            }

                            JsonNode virtualIPValue = hostNameSslStatesValue.get("virtualIP");
                            if (virtualIPValue != null && virtualIPValue instanceof NullNode == false) {
                                InetAddress virtualIPInstance;
                                virtualIPInstance = InetAddress.getByName(virtualIPValue.getTextValue());
                                webSiteHostNameSslStateInstance.setVirtualIP(virtualIPInstance);
                            }

                            JsonNode ipBasedSslResultValue = hostNameSslStatesValue.get("ipBasedSslResult");
                            if (ipBasedSslResultValue != null
                                    && ipBasedSslResultValue instanceof NullNode == false) {
                                String ipBasedSslResultInstance;
                                ipBasedSslResultInstance = ipBasedSslResultValue.getTextValue();
                                webSiteHostNameSslStateInstance.setIpBasedSslResult(ipBasedSslResultInstance);
                            }

                            JsonNode toUpdateValue = hostNameSslStatesValue.get("toUpdate");
                            if (toUpdateValue != null && toUpdateValue instanceof NullNode == false) {
                                boolean toUpdateInstance;
                                toUpdateInstance = toUpdateValue.getBooleanValue();
                                webSiteHostNameSslStateInstance.setToUpdate(toUpdateInstance);
                            }

                            JsonNode toUpdateIpBasedSslValue = hostNameSslStatesValue.get("toUpdateIpBasedSsl");
                            if (toUpdateIpBasedSslValue != null
                                    && toUpdateIpBasedSslValue instanceof NullNode == false) {
                                boolean toUpdateIpBasedSslInstance;
                                toUpdateIpBasedSslInstance = toUpdateIpBasedSslValue.getBooleanValue();
                                webSiteHostNameSslStateInstance
                                        .setToUpdateIpBasedSsl(toUpdateIpBasedSslInstance);
                            }

                            JsonNode hostTypeValue = hostNameSslStatesValue.get("hostType");
                            if (hostTypeValue != null && hostTypeValue instanceof NullNode == false) {
                                HostType hostTypeInstance;
                                hostTypeInstance = Enum.valueOf(HostType.class, hostTypeValue.getTextValue());
                                webSiteHostNameSslStateInstance.setHostType(hostTypeInstance);
                            }
                        }
                    }

                    JsonNode hostNamesArray = propertiesValue.get("hostNames");
                    if (hostNamesArray != null && hostNamesArray instanceof NullNode == false) {
                        for (JsonNode hostNamesValue : ((ArrayNode) hostNamesArray)) {
                            propertiesInstance.getHostNames().add(hostNamesValue.getTextValue());
                        }
                    }

                    JsonNode lastModifiedTimeUtcValue = propertiesValue.get("lastModifiedTimeUtc");
                    if (lastModifiedTimeUtcValue != null
                            && lastModifiedTimeUtcValue instanceof NullNode == false) {
                        Calendar lastModifiedTimeUtcInstance;
                        lastModifiedTimeUtcInstance = DatatypeConverter
                                .parseDateTime(lastModifiedTimeUtcValue.getTextValue());
                        propertiesInstance.setLastModifiedTimeUtc(lastModifiedTimeUtcInstance);
                    }

                    JsonNode repositorySiteNameValue = propertiesValue.get("repositorySiteName");
                    if (repositorySiteNameValue != null
                            && repositorySiteNameValue instanceof NullNode == false) {
                        String repositorySiteNameInstance;
                        repositorySiteNameInstance = repositorySiteNameValue.getTextValue();
                        propertiesInstance.setRepositorySiteName(repositorySiteNameInstance);
                    }

                    JsonNode runtimeAvailabilityStateValue = propertiesValue.get("runtimeAvailabilityState");
                    if (runtimeAvailabilityStateValue != null
                            && runtimeAvailabilityStateValue instanceof NullNode == false) {
                        WebSiteRuntimeAvailabilityState runtimeAvailabilityStateInstance;
                        runtimeAvailabilityStateInstance = Enum.valueOf(WebSiteRuntimeAvailabilityState.class,
                                runtimeAvailabilityStateValue.getTextValue());
                        propertiesInstance.setRuntimeAvailabilityState(runtimeAvailabilityStateInstance);
                    }

                    JsonNode trafficManagerHostNamesArray = propertiesValue.get("trafficManagerHostNames");
                    if (trafficManagerHostNamesArray != null
                            && trafficManagerHostNamesArray instanceof NullNode == false) {
                        for (JsonNode trafficManagerHostNamesValue : ((ArrayNode) trafficManagerHostNamesArray)) {
                            propertiesInstance.getTrafficManagerHostNames()
                                    .add(trafficManagerHostNamesValue.getTextValue());
                        }
                    }

                    JsonNode selfLinkValue = propertiesValue.get("selfLink");
                    if (selfLinkValue != null && selfLinkValue instanceof NullNode == false) {
                        URI selfLinkInstance;
                        selfLinkInstance = new URI(selfLinkValue.getTextValue());
                        propertiesInstance.setUri(selfLinkInstance);
                    }

                    JsonNode serverFarmValue = propertiesValue.get("serverFarm");
                    if (serverFarmValue != null && serverFarmValue instanceof NullNode == false) {
                        String serverFarmInstance;
                        serverFarmInstance = serverFarmValue.getTextValue();
                        propertiesInstance.setServerFarm(serverFarmInstance);
                    }

                    JsonNode serverFarmIdValue = propertiesValue.get("serverFarmId");
                    if (serverFarmIdValue != null && serverFarmIdValue instanceof NullNode == false) {
                        String serverFarmIdInstance;
                        serverFarmIdInstance = serverFarmIdValue.getTextValue();
                        propertiesInstance.setServerFarmId(serverFarmIdInstance);
                    }

                    JsonNode skuValue = propertiesValue.get("sku");
                    if (skuValue != null && skuValue instanceof NullNode == false) {
                        SkuOptions skuInstance;
                        skuInstance = Enum.valueOf(SkuOptions.class, skuValue.getTextValue());
                        propertiesInstance.setSku(skuInstance);
                    }

                    JsonNode sitePropertiesValue = propertiesValue.get("siteProperties");
                    if (sitePropertiesValue != null && sitePropertiesValue instanceof NullNode == false) {
                        WebSiteProperties.SiteProperties sitePropertiesInstance = new WebSiteProperties.SiteProperties();
                        propertiesInstance.setProperties(sitePropertiesInstance);

                        JsonNode appSettingsSequenceElement = ((JsonNode) sitePropertiesValue
                                .get("appSettings"));
                        if (appSettingsSequenceElement != null
                                && appSettingsSequenceElement instanceof NullNode == false) {
                            Iterator<Map.Entry<String, JsonNode>> itr = appSettingsSequenceElement.getFields();
                            while (itr.hasNext()) {
                                Map.Entry<String, JsonNode> property = itr.next();
                                String appSettingsKey = property.getKey();
                                String appSettingsValue = property.getValue().getTextValue();
                                sitePropertiesInstance.getAppSettings().put(appSettingsKey, appSettingsValue);
                            }
                        }

                        JsonNode metadataSequenceElement = ((JsonNode) sitePropertiesValue.get("metadata"));
                        if (metadataSequenceElement != null
                                && metadataSequenceElement instanceof NullNode == false) {
                            Iterator<Map.Entry<String, JsonNode>> itr2 = metadataSequenceElement.getFields();
                            while (itr2.hasNext()) {
                                Map.Entry<String, JsonNode> property2 = itr2.next();
                                String metadataKey = property2.getKey();
                                String metadataValue = property2.getValue().getTextValue();
                                sitePropertiesInstance.getMetadata().put(metadataKey, metadataValue);
                            }
                        }

                        JsonNode propertiesSequenceElement = ((JsonNode) sitePropertiesValue.get("properties"));
                        if (propertiesSequenceElement != null
                                && propertiesSequenceElement instanceof NullNode == false) {
                            Iterator<Map.Entry<String, JsonNode>> itr3 = propertiesSequenceElement.getFields();
                            while (itr3.hasNext()) {
                                Map.Entry<String, JsonNode> property3 = itr3.next();
                                String propertiesKey = property3.getKey();
                                String propertiesValue2 = property3.getValue().getTextValue();
                                sitePropertiesInstance.getProperties().put(propertiesKey, propertiesValue2);
                            }
                        }
                    }

                    JsonNode siteConfigValue = propertiesValue.get("siteConfig");
                    if (siteConfigValue != null && siteConfigValue instanceof NullNode == false) {
                        WebSiteConfiguration siteConfigInstance = new WebSiteConfiguration();
                        propertiesInstance.setSiteConfig(siteConfigInstance);

                        JsonNode appSettingsSequenceElement2 = ((JsonNode) siteConfigValue.get("appSettings"));
                        if (appSettingsSequenceElement2 != null
                                && appSettingsSequenceElement2 instanceof NullNode == false) {
                            Iterator<Map.Entry<String, JsonNode>> itr4 = appSettingsSequenceElement2
                                    .getFields();
                            while (itr4.hasNext()) {
                                Map.Entry<String, JsonNode> property4 = itr4.next();
                                String appSettingsKey2 = property4.getKey();
                                String appSettingsValue2 = property4.getValue().getTextValue();
                                siteConfigInstance.getAppSettings().put(appSettingsKey2, appSettingsValue2);
                            }
                        }

                        JsonNode connectionStringsArray = siteConfigValue.get("connectionStrings");
                        if (connectionStringsArray != null
                                && connectionStringsArray instanceof NullNode == false) {
                            for (JsonNode connectionStringsValue : ((ArrayNode) connectionStringsArray)) {
                                ConnectionStringInfo connStringInfoInstance = new ConnectionStringInfo();
                                siteConfigInstance.getConnectionStrings().add(connStringInfoInstance);

                                JsonNode connectionStringValue = connectionStringsValue.get("connectionString");
                                if (connectionStringValue != null
                                        && connectionStringValue instanceof NullNode == false) {
                                    String connectionStringInstance;
                                    connectionStringInstance = connectionStringValue.getTextValue();
                                    connStringInfoInstance.setConnectionString(connectionStringInstance);
                                }

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

                                JsonNode typeValue = connectionStringsValue.get("type");
                                if (typeValue != null && typeValue instanceof NullNode == false) {
                                    DatabaseServerType typeInstance;
                                    typeInstance = Enum.valueOf(DatabaseServerType.class,
                                            typeValue.getTextValue());
                                    connStringInfoInstance.setType(typeInstance);
                                }
                            }
                        }

                        JsonNode defaultDocumentsArray = siteConfigValue.get("defaultDocuments");
                        if (defaultDocumentsArray != null
                                && defaultDocumentsArray instanceof NullNode == false) {
                            for (JsonNode defaultDocumentsValue : ((ArrayNode) defaultDocumentsArray)) {
                                siteConfigInstance.getDefaultDocuments()
                                        .add(defaultDocumentsValue.getTextValue());
                            }
                        }

                        JsonNode detailedErrorLoggingEnabledValue = siteConfigValue
                                .get("detailedErrorLoggingEnabled");
                        if (detailedErrorLoggingEnabledValue != null
                                && detailedErrorLoggingEnabledValue instanceof NullNode == false) {
                            boolean detailedErrorLoggingEnabledInstance;
                            detailedErrorLoggingEnabledInstance = detailedErrorLoggingEnabledValue
                                    .getBooleanValue();
                            siteConfigInstance
                                    .setDetailedErrorLoggingEnabled(detailedErrorLoggingEnabledInstance);
                        }

                        JsonNode documentRootValue = siteConfigValue.get("documentRoot");
                        if (documentRootValue != null && documentRootValue instanceof NullNode == false) {
                            String documentRootInstance;
                            documentRootInstance = documentRootValue.getTextValue();
                            siteConfigInstance.setDocumentRoot(documentRootInstance);
                        }

                        JsonNode handlerMappingsArray = siteConfigValue.get("handlerMappings");
                        if (handlerMappingsArray != null && handlerMappingsArray instanceof NullNode == false) {
                            for (JsonNode handlerMappingsValue : ((ArrayNode) handlerMappingsArray)) {
                                WebSiteConfiguration.HandlerMapping handlerMappingInstance = new WebSiteConfiguration.HandlerMapping();
                                siteConfigInstance.getHandlerMappings().add(handlerMappingInstance);

                                JsonNode argumentsValue = handlerMappingsValue.get("arguments");
                                if (argumentsValue != null && argumentsValue instanceof NullNode == false) {
                                    String argumentsInstance;
                                    argumentsInstance = argumentsValue.getTextValue();
                                    handlerMappingInstance.setArguments(argumentsInstance);
                                }

                                JsonNode extensionValue = handlerMappingsValue.get("extension");
                                if (extensionValue != null && extensionValue instanceof NullNode == false) {
                                    String extensionInstance;
                                    extensionInstance = extensionValue.getTextValue();
                                    handlerMappingInstance.setExtension(extensionInstance);
                                }

                                JsonNode scriptProcessorValue = handlerMappingsValue.get("scriptProcessor");
                                if (scriptProcessorValue != null
                                        && scriptProcessorValue instanceof NullNode == false) {
                                    String scriptProcessorInstance;
                                    scriptProcessorInstance = scriptProcessorValue.getTextValue();
                                    handlerMappingInstance.setScriptProcessor(scriptProcessorInstance);
                                }
                            }
                        }

                        JsonNode httpLoggingEnabledValue = siteConfigValue.get("httpLoggingEnabled");
                        if (httpLoggingEnabledValue != null
                                && httpLoggingEnabledValue instanceof NullNode == false) {
                            boolean httpLoggingEnabledInstance;
                            httpLoggingEnabledInstance = httpLoggingEnabledValue.getBooleanValue();
                            siteConfigInstance.setHttpLoggingEnabled(httpLoggingEnabledInstance);
                        }

                        JsonNode logsDirectorySizeLimitValue = siteConfigValue.get("logsDirectorySizeLimit");
                        if (logsDirectorySizeLimitValue != null
                                && logsDirectorySizeLimitValue instanceof NullNode == false) {
                            int logsDirectorySizeLimitInstance;
                            logsDirectorySizeLimitInstance = logsDirectorySizeLimitValue.getIntValue();
                            siteConfigInstance.setLogsDirectorySizeLimit(logsDirectorySizeLimitInstance);
                        }

                        JsonNode managedPipelineModeValue = siteConfigValue.get("managedPipelineMode");
                        if (managedPipelineModeValue != null
                                && managedPipelineModeValue instanceof NullNode == false) {
                            ManagedPipelineMode managedPipelineModeInstance;
                            managedPipelineModeInstance = Enum.valueOf(ManagedPipelineMode.class,
                                    managedPipelineModeValue.getTextValue());
                            siteConfigInstance.setManagedPipelineMode(managedPipelineModeInstance);
                        }

                        JsonNode metadataSequenceElement2 = ((JsonNode) siteConfigValue.get("metadata"));
                        if (metadataSequenceElement2 != null
                                && metadataSequenceElement2 instanceof NullNode == false) {
                            Iterator<Map.Entry<String, JsonNode>> itr5 = metadataSequenceElement2.getFields();
                            while (itr5.hasNext()) {
                                Map.Entry<String, JsonNode> property5 = itr5.next();
                                String metadataKey2 = property5.getKey();
                                String metadataValue2 = property5.getValue().getTextValue();
                                siteConfigInstance.getMetadata().put(metadataKey2, metadataValue2);
                            }
                        }

                        JsonNode netFrameworkVersionValue = siteConfigValue.get("netFrameworkVersion");
                        if (netFrameworkVersionValue != null
                                && netFrameworkVersionValue instanceof NullNode == false) {
                            String netFrameworkVersionInstance;
                            netFrameworkVersionInstance = netFrameworkVersionValue.getTextValue();
                            siteConfigInstance.setNetFrameworkVersion(netFrameworkVersionInstance);
                        }

                        JsonNode numberOfWorkersValue = siteConfigValue.get("numberOfWorkers");
                        if (numberOfWorkersValue != null && numberOfWorkersValue instanceof NullNode == false) {
                            int numberOfWorkersInstance;
                            numberOfWorkersInstance = numberOfWorkersValue.getIntValue();
                            siteConfigInstance.setNumberOfWorkers(numberOfWorkersInstance);
                        }

                        JsonNode phpVersionValue = siteConfigValue.get("phpVersion");
                        if (phpVersionValue != null && phpVersionValue instanceof NullNode == false) {
                            String phpVersionInstance;
                            phpVersionInstance = phpVersionValue.getTextValue();
                            siteConfigInstance.setPhpVersion(phpVersionInstance);
                        }

                        JsonNode pythonVersionValue = siteConfigValue.get("pythonVersion");
                        if (pythonVersionValue != null && pythonVersionValue instanceof NullNode == false) {
                            String pythonVersionInstance;
                            pythonVersionInstance = pythonVersionValue.getTextValue();
                            siteConfigInstance.setPythonVersion(pythonVersionInstance);
                        }

                        JsonNode publishingPasswordValue = siteConfigValue.get("publishingPassword");
                        if (publishingPasswordValue != null
                                && publishingPasswordValue instanceof NullNode == false) {
                            String publishingPasswordInstance;
                            publishingPasswordInstance = publishingPasswordValue.getTextValue();
                            siteConfigInstance.setPublishingPassword(publishingPasswordInstance);
                        }

                        JsonNode publishingUsernameValue = siteConfigValue.get("publishingUsername");
                        if (publishingUsernameValue != null
                                && publishingUsernameValue instanceof NullNode == false) {
                            String publishingUsernameInstance;
                            publishingUsernameInstance = publishingUsernameValue.getTextValue();
                            siteConfigInstance.setPublishingUserName(publishingUsernameInstance);
                        }

                        JsonNode remoteDebuggingEnabledValue = siteConfigValue.get("RemoteDebuggingEnabled");
                        if (remoteDebuggingEnabledValue != null
                                && remoteDebuggingEnabledValue instanceof NullNode == false) {
                            boolean remoteDebuggingEnabledInstance;
                            remoteDebuggingEnabledInstance = remoteDebuggingEnabledValue.getBooleanValue();
                            siteConfigInstance.setRemoteDebuggingEnabled(remoteDebuggingEnabledInstance);
                        }

                        JsonNode remoteDebuggingVersionValue = siteConfigValue.get("remoteDebuggingVersion");
                        if (remoteDebuggingVersionValue != null
                                && remoteDebuggingVersionValue instanceof NullNode == false) {
                            RemoteDebuggingVersion remoteDebuggingVersionInstance;
                            remoteDebuggingVersionInstance = Enum.valueOf(RemoteDebuggingVersion.class,
                                    remoteDebuggingVersionValue.getTextValue());
                            siteConfigInstance.setRemoteDebuggingVersion(remoteDebuggingVersionInstance);
                        }

                        JsonNode requestTracingEnabledValue = siteConfigValue.get("requestTracingEnabled");
                        if (requestTracingEnabledValue != null
                                && requestTracingEnabledValue instanceof NullNode == false) {
                            boolean requestTracingEnabledInstance;
                            requestTracingEnabledInstance = requestTracingEnabledValue.getBooleanValue();
                            siteConfigInstance.setRequestTracingEnabled(requestTracingEnabledInstance);
                        }

                        JsonNode requestTracingExpirationTimeValue = siteConfigValue
                                .get("requestTracingExpirationTime");
                        if (requestTracingExpirationTimeValue != null
                                && requestTracingExpirationTimeValue instanceof NullNode == false) {
                            Calendar requestTracingExpirationTimeInstance;
                            requestTracingExpirationTimeInstance = DatatypeConverter
                                    .parseDateTime(requestTracingExpirationTimeValue.getTextValue());
                            siteConfigInstance
                                    .setRequestTracingExpirationTime(requestTracingExpirationTimeInstance);
                        }

                        JsonNode scmTypeValue = siteConfigValue.get("scmType");
                        if (scmTypeValue != null && scmTypeValue instanceof NullNode == false) {
                            String scmTypeInstance;
                            scmTypeInstance = scmTypeValue.getTextValue();
                            siteConfigInstance.setScmType(scmTypeInstance);
                        }

                        JsonNode autoSwapSlotNameValue = siteConfigValue.get("autoSwapSlotName");
                        if (autoSwapSlotNameValue != null
                                && autoSwapSlotNameValue instanceof NullNode == false) {
                            String autoSwapSlotNameInstance;
                            autoSwapSlotNameInstance = autoSwapSlotNameValue.getTextValue();
                            siteConfigInstance.setAutoSwapSlotName(autoSwapSlotNameInstance);
                        }

                        JsonNode use32BitWorkerProcessValue = siteConfigValue.get("use32BitWorkerProcess");
                        if (use32BitWorkerProcessValue != null
                                && use32BitWorkerProcessValue instanceof NullNode == false) {
                            boolean use32BitWorkerProcessInstance;
                            use32BitWorkerProcessInstance = use32BitWorkerProcessValue.getBooleanValue();
                            siteConfigInstance.setUse32BitWorkerProcess(use32BitWorkerProcessInstance);
                        }

                        JsonNode webSocketsEnabledValue = siteConfigValue.get("webSocketsEnabled");
                        if (webSocketsEnabledValue != null
                                && webSocketsEnabledValue instanceof NullNode == false) {
                            boolean webSocketsEnabledInstance;
                            webSocketsEnabledInstance = webSocketsEnabledValue.getBooleanValue();
                            siteConfigInstance.setWebSocketsEnabled(webSocketsEnabledInstance);
                        }

                        JsonNode limitsValue = siteConfigValue.get("limits");
                        if (limitsValue != null && limitsValue instanceof NullNode == false) {
                            SiteLimits limitsInstance = new SiteLimits();
                            siteConfigInstance.setLimits(limitsInstance);

                            JsonNode maxPercentageCpuValue = limitsValue.get("maxPercentageCpu");
                            if (maxPercentageCpuValue != null
                                    && maxPercentageCpuValue instanceof NullNode == false) {
                                double maxPercentageCpuInstance;
                                maxPercentageCpuInstance = maxPercentageCpuValue.getDoubleValue();
                                limitsInstance.setMaxPercentageCpu(maxPercentageCpuInstance);
                            }

                            JsonNode maxMemoryInMbValue = limitsValue.get("maxMemoryInMb");
                            if (maxMemoryInMbValue != null && maxMemoryInMbValue instanceof NullNode == false) {
                                long maxMemoryInMbInstance;
                                maxMemoryInMbInstance = maxMemoryInMbValue.getLongValue();
                                limitsInstance.setMaxMemoryInMb(maxMemoryInMbInstance);
                            }

                            JsonNode maxDiskSizeInMbValue = limitsValue.get("maxDiskSizeInMb");
                            if (maxDiskSizeInMbValue != null
                                    && maxDiskSizeInMbValue instanceof NullNode == false) {
                                long maxDiskSizeInMbInstance;
                                maxDiskSizeInMbInstance = maxDiskSizeInMbValue.getLongValue();
                                limitsInstance.setMaxDiskSizeInMb(maxDiskSizeInMbInstance);
                            }
                        }
                    }

                    JsonNode stateValue = propertiesValue.get("state");
                    if (stateValue != null && stateValue instanceof NullNode == false) {
                        WebSiteState stateInstance;
                        stateInstance = Enum.valueOf(WebSiteState.class, stateValue.getTextValue());
                        propertiesInstance.setState(stateInstance);
                    }

                    JsonNode usageStateValue = propertiesValue.get("usageState");
                    if (usageStateValue != null && usageStateValue instanceof NullNode == false) {
                        WebSiteUsageState usageStateInstance;
                        usageStateInstance = Enum.valueOf(WebSiteUsageState.class,
                                usageStateValue.getTextValue());
                        propertiesInstance.setUsageState(usageStateInstance);
                    }

                    JsonNode webSpaceValue = propertiesValue.get("webSpace");
                    if (webSpaceValue != null && webSpaceValue instanceof NullNode == false) {
                        String webSpaceInstance;
                        webSpaceInstance = webSpaceValue.getTextValue();
                        propertiesInstance.setWebSpace(webSpaceInstance);
                    }

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

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

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

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

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

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

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

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

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

/**
* You can retrieve details for a web site by issuing an HTTP GET request.
* (see http://msdn.microsoft.com/en-us/library/windowsazure/dn167007.aspx
* for more information)/*from w  ww.  ja va 2s . c  om*/
*
* @param webSpaceName Required. The name of the web space.
* @param webSiteName Required. The name of the web site.
* @param parameters Optional. Parameters supplied to the Get Web Site
* Operation.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @throws ParserConfigurationException Thrown if there was a serious
* configuration error with the document parser.
* @throws SAXException Thrown if there was an error parsing the XML
* response.
* @throws URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return The Get Web Site operation response.
*/
@Override
public WebSiteGetResponse get(String webSpaceName, String webSiteName, WebSiteGetParameters parameters)
        throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException {
    // Validate
    if (webSpaceName == null) {
        throw new NullPointerException("webSpaceName");
    }
    if (webSiteName == null) {
        throw new NullPointerException("webSiteName");
    }

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

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/services/WebSpaces/";
    url = url + URLEncoder.encode(webSpaceName, "UTF-8");
    url = url + "/sites/";
    url = url + URLEncoder.encode(webSiteName, "UTF-8");
    ArrayList<String> queryParameters = new ArrayList<String>();
    if (parameters != null && parameters.getPropertiesToInclude() != null
            && parameters.getPropertiesToInclude().size() > 0) {
        queryParameters.add("propertiesToInclude=" + URLEncoder
                .encode(CollectionStringBuilder.join(parameters.getPropertiesToInclude(), ","), "UTF-8"));
    }
    if (queryParameters.size() > 0) {
        url = url + "?" + CollectionStringBuilder.join(queryParameters, "&");
    }
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

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

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

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

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

            Element siteElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "Site");
            if (siteElement != null) {
                WebSite webSiteInstance = new WebSite();
                result.setWebSite(webSiteInstance);

                Element adminEnabledElement = XmlUtility.getElementByTagNameNS(siteElement,
                        "http://schemas.microsoft.com/windowsazure", "AdminEnabled");
                if (adminEnabledElement != null && adminEnabledElement.getTextContent() != null
                        && !adminEnabledElement.getTextContent().isEmpty()) {
                    boolean adminEnabledInstance;
                    adminEnabledInstance = DatatypeConverter
                            .parseBoolean(adminEnabledElement.getTextContent().toLowerCase());
                    webSiteInstance.setAdminEnabled(adminEnabledInstance);
                }

                Element availabilityStateElement = XmlUtility.getElementByTagNameNS(siteElement,
                        "http://schemas.microsoft.com/windowsazure", "AvailabilityState");
                if (availabilityStateElement != null && availabilityStateElement.getTextContent() != null
                        && !availabilityStateElement.getTextContent().isEmpty()) {
                    WebSpaceAvailabilityState availabilityStateInstance;
                    availabilityStateInstance = WebSpaceAvailabilityState
                            .valueOf(availabilityStateElement.getTextContent());
                    webSiteInstance.setAvailabilityState(availabilityStateInstance);
                }

                Element sKUElement = XmlUtility.getElementByTagNameNS(siteElement,
                        "http://schemas.microsoft.com/windowsazure", "SKU");
                if (sKUElement != null && sKUElement.getTextContent() != null
                        && !sKUElement.getTextContent().isEmpty()) {
                    SkuOptions sKUInstance;
                    sKUInstance = SkuOptions.valueOf(sKUElement.getTextContent());
                    webSiteInstance.setSku(sKUInstance);
                }

                Element enabledElement = XmlUtility.getElementByTagNameNS(siteElement,
                        "http://schemas.microsoft.com/windowsazure", "Enabled");
                if (enabledElement != null && enabledElement.getTextContent() != null
                        && !enabledElement.getTextContent().isEmpty()) {
                    boolean enabledInstance;
                    enabledInstance = DatatypeConverter
                            .parseBoolean(enabledElement.getTextContent().toLowerCase());
                    webSiteInstance.setEnabled(enabledInstance);
                }

                Element enabledHostNamesSequenceElement = XmlUtility.getElementByTagNameNS(siteElement,
                        "http://schemas.microsoft.com/windowsazure", "EnabledHostNames");
                if (enabledHostNamesSequenceElement != null) {
                    for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(enabledHostNamesSequenceElement,
                                    "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string")
                            .size(); i1 = i1 + 1) {
                        org.w3c.dom.Element enabledHostNamesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(enabledHostNamesSequenceElement,
                                        "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string")
                                .get(i1));
                        webSiteInstance.getEnabledHostNames().add(enabledHostNamesElement.getTextContent());
                    }
                }

                Element hostNameSslStatesSequenceElement = XmlUtility.getElementByTagNameNS(siteElement,
                        "http://schemas.microsoft.com/windowsazure", "HostNameSslStates");
                if (hostNameSslStatesSequenceElement != null) {
                    for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(hostNameSslStatesSequenceElement,
                                    "http://schemas.microsoft.com/windowsazure", "HostNameSslState")
                            .size(); i2 = i2 + 1) {
                        org.w3c.dom.Element hostNameSslStatesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(hostNameSslStatesSequenceElement,
                                        "http://schemas.microsoft.com/windowsazure", "HostNameSslState")
                                .get(i2));
                        WebSite.WebSiteHostNameSslState hostNameSslStateInstance = new WebSite.WebSiteHostNameSslState();
                        webSiteInstance.getHostNameSslStates().add(hostNameSslStateInstance);

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

                        Element sslStateElement = XmlUtility.getElementByTagNameNS(hostNameSslStatesElement,
                                "http://schemas.microsoft.com/windowsazure", "SslState");
                        if (sslStateElement != null && sslStateElement.getTextContent() != null
                                && !sslStateElement.getTextContent().isEmpty()) {
                            WebSiteSslState sslStateInstance;
                            sslStateInstance = WebSiteSslState.valueOf(sslStateElement.getTextContent());
                            hostNameSslStateInstance.setSslState(sslStateInstance);
                        }

                        Element thumbprintElement = XmlUtility.getElementByTagNameNS(hostNameSslStatesElement,
                                "http://schemas.microsoft.com/windowsazure", "Thumbprint");
                        if (thumbprintElement != null) {
                            boolean isNil = false;
                            Attr nilAttribute = thumbprintElement
                                    .getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil");
                            if (nilAttribute != null) {
                                isNil = "true".equals(nilAttribute.getValue());
                            }
                            if (isNil == false) {
                                String thumbprintInstance;
                                thumbprintInstance = thumbprintElement.getTextContent();
                                hostNameSslStateInstance.setThumbprint(thumbprintInstance);
                            }
                        }

                        Element virtualIPElement = XmlUtility.getElementByTagNameNS(hostNameSslStatesElement,
                                "http://schemas.microsoft.com/windowsazure", "VirtualIP");
                        if (virtualIPElement != null) {
                            boolean isNil2 = false;
                            Attr nilAttribute2 = virtualIPElement
                                    .getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil");
                            if (nilAttribute2 != null) {
                                isNil2 = "true".equals(nilAttribute2.getValue());
                            }
                            if (isNil2 == false) {
                                InetAddress virtualIPInstance;
                                virtualIPInstance = InetAddress.getByName(virtualIPElement.getTextContent());
                                hostNameSslStateInstance.setVirtualIP(virtualIPInstance);
                            }
                        }
                    }
                }

                Element hostNamesSequenceElement = XmlUtility.getElementByTagNameNS(siteElement,
                        "http://schemas.microsoft.com/windowsazure", "HostNames");
                if (hostNamesSequenceElement != null) {
                    for (int i3 = 0; i3 < com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(hostNamesSequenceElement,
                                    "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string")
                            .size(); i3 = i3 + 1) {
                        org.w3c.dom.Element hostNamesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(hostNamesSequenceElement,
                                        "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string")
                                .get(i3));
                        webSiteInstance.getHostNames().add(hostNamesElement.getTextContent());
                    }
                }

                Element lastModifiedTimeUtcElement = XmlUtility.getElementByTagNameNS(siteElement,
                        "http://schemas.microsoft.com/windowsazure", "LastModifiedTimeUtc");
                if (lastModifiedTimeUtcElement != null && lastModifiedTimeUtcElement.getTextContent() != null
                        && !lastModifiedTimeUtcElement.getTextContent().isEmpty()) {
                    Calendar lastModifiedTimeUtcInstance;
                    lastModifiedTimeUtcInstance = DatatypeConverter
                            .parseDateTime(lastModifiedTimeUtcElement.getTextContent());
                    webSiteInstance.setLastModifiedTimeUtc(lastModifiedTimeUtcInstance);
                }

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

                Element repositorySiteNameElement = XmlUtility.getElementByTagNameNS(siteElement,
                        "http://schemas.microsoft.com/windowsazure", "RepositorySiteName");
                if (repositorySiteNameElement != null) {
                    String repositorySiteNameInstance;
                    repositorySiteNameInstance = repositorySiteNameElement.getTextContent();
                    webSiteInstance.setRepositorySiteName(repositorySiteNameInstance);
                }

                Element runtimeAvailabilityStateElement = XmlUtility.getElementByTagNameNS(siteElement,
                        "http://schemas.microsoft.com/windowsazure", "RuntimeAvailabilityState");
                if (runtimeAvailabilityStateElement != null
                        && runtimeAvailabilityStateElement.getTextContent() != null
                        && !runtimeAvailabilityStateElement.getTextContent().isEmpty()) {
                    WebSiteRuntimeAvailabilityState runtimeAvailabilityStateInstance;
                    runtimeAvailabilityStateInstance = WebSiteRuntimeAvailabilityState
                            .valueOf(runtimeAvailabilityStateElement.getTextContent());
                    webSiteInstance.setRuntimeAvailabilityState(runtimeAvailabilityStateInstance);
                }

                Element selfLinkElement = XmlUtility.getElementByTagNameNS(siteElement,
                        "http://schemas.microsoft.com/windowsazure", "SelfLink");
                if (selfLinkElement != null) {
                    URI selfLinkInstance;
                    selfLinkInstance = new URI(selfLinkElement.getTextContent());
                    webSiteInstance.setUri(selfLinkInstance);
                }

                Element serverFarmElement = XmlUtility.getElementByTagNameNS(siteElement,
                        "http://schemas.microsoft.com/windowsazure", "ServerFarm");
                if (serverFarmElement != null) {
                    String serverFarmInstance;
                    serverFarmInstance = serverFarmElement.getTextContent();
                    webSiteInstance.setServerFarm(serverFarmInstance);
                }

                Element sitePropertiesElement = XmlUtility.getElementByTagNameNS(siteElement,
                        "http://schemas.microsoft.com/windowsazure", "SiteProperties");
                if (sitePropertiesElement != null) {
                    WebSite.WebSiteProperties sitePropertiesInstance = new WebSite.WebSiteProperties();
                    webSiteInstance.setSiteProperties(sitePropertiesInstance);

                    Element appSettingsSequenceElement = XmlUtility.getElementByTagNameNS(sitePropertiesElement,
                            "http://schemas.microsoft.com/windowsazure", "AppSettings");
                    if (appSettingsSequenceElement != null) {
                        for (int i4 = 0; i4 < com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(appSettingsSequenceElement,
                                        "http://schemas.microsoft.com/windowsazure", "NameValuePair")
                                .size(); i4 = i4 + 1) {
                            org.w3c.dom.Element appSettingsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(appSettingsSequenceElement,
                                            "http://schemas.microsoft.com/windowsazure", "NameValuePair")
                                    .get(i4));
                            String appSettingsKey = XmlUtility
                                    .getElementByTagNameNS(appSettingsElement,
                                            "http://schemas.microsoft.com/windowsazure", "Name")
                                    .getTextContent();
                            String appSettingsValue = XmlUtility
                                    .getElementByTagNameNS(appSettingsElement,
                                            "http://schemas.microsoft.com/windowsazure", "Value")
                                    .getTextContent();
                            sitePropertiesInstance.getAppSettings().put(appSettingsKey, appSettingsValue);
                        }
                    }

                    Element metadataSequenceElement = XmlUtility.getElementByTagNameNS(sitePropertiesElement,
                            "http://schemas.microsoft.com/windowsazure", "Metadata");
                    if (metadataSequenceElement != null) {
                        for (int i5 = 0; i5 < com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(metadataSequenceElement,
                                        "http://schemas.microsoft.com/windowsazure", "NameValuePair")
                                .size(); i5 = i5 + 1) {
                            org.w3c.dom.Element metadataElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(metadataSequenceElement,
                                            "http://schemas.microsoft.com/windowsazure", "NameValuePair")
                                    .get(i5));
                            String metadataKey = XmlUtility
                                    .getElementByTagNameNS(metadataElement,
                                            "http://schemas.microsoft.com/windowsazure", "Name")
                                    .getTextContent();
                            String metadataValue = XmlUtility
                                    .getElementByTagNameNS(metadataElement,
                                            "http://schemas.microsoft.com/windowsazure", "Value")
                                    .getTextContent();
                            sitePropertiesInstance.getMetadata().put(metadataKey, metadataValue);
                        }
                    }

                    Element propertiesSequenceElement = XmlUtility.getElementByTagNameNS(sitePropertiesElement,
                            "http://schemas.microsoft.com/windowsazure", "Properties");
                    if (propertiesSequenceElement != null) {
                        for (int i6 = 0; i6 < com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(propertiesSequenceElement,
                                        "http://schemas.microsoft.com/windowsazure", "NameValuePair")
                                .size(); i6 = i6 + 1) {
                            org.w3c.dom.Element propertiesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(propertiesSequenceElement,
                                            "http://schemas.microsoft.com/windowsazure", "NameValuePair")
                                    .get(i6));
                            String propertiesKey = XmlUtility
                                    .getElementByTagNameNS(propertiesElement,
                                            "http://schemas.microsoft.com/windowsazure", "Name")
                                    .getTextContent();
                            String propertiesValue = XmlUtility
                                    .getElementByTagNameNS(propertiesElement,
                                            "http://schemas.microsoft.com/windowsazure", "Value")
                                    .getTextContent();
                            sitePropertiesInstance.getProperties().put(propertiesKey, propertiesValue);
                        }
                    }
                }

                Element stateElement = XmlUtility.getElementByTagNameNS(siteElement,
                        "http://schemas.microsoft.com/windowsazure", "State");
                if (stateElement != null) {
                    String stateInstance;
                    stateInstance = stateElement.getTextContent();
                    webSiteInstance.setState(stateInstance);
                }

                Element usageStateElement = XmlUtility.getElementByTagNameNS(siteElement,
                        "http://schemas.microsoft.com/windowsazure", "UsageState");
                if (usageStateElement != null && usageStateElement.getTextContent() != null
                        && !usageStateElement.getTextContent().isEmpty()) {
                    WebSiteUsageState usageStateInstance;
                    usageStateInstance = WebSiteUsageState.valueOf(usageStateElement.getTextContent());
                    webSiteInstance.setUsageState(usageStateInstance);
                }

                Element webSpaceElement = XmlUtility.getElementByTagNameNS(siteElement,
                        "http://schemas.microsoft.com/windowsazure", "WebSpace");
                if (webSpaceElement != null) {
                    String webSpaceInstance;
                    webSpaceInstance = webSpaceElement.getTextContent();
                    webSiteInstance.setWebSpace(webSpaceInstance);
                }
            }

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