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.marklogic.client.functionaltest.TestBiTemporal.java

@Test
// Test bitemporal create, update and delete works with a JSON document while passing
// system time. The temporal collection needs to be enabled for lsqt and we have enabled
// automation for lsqt (lsqt will be advanced every second and system time will be set with 
// a lag of 1 second)
public void testSystemTime() throws Exception {

    System.out.println("Inside testSystemTime");
    ConnectedRESTQA.updateTemporalCollectionForLSQT(dbName, temporalLsqtCollectionName, true);

    String docId = "javaSingleJSONDoc.json";

    Calendar firstInsertTime = DatatypeConverter.parseDateTime("2010-01-01T00:00:01");
    insertJSONSingleDocument(temporalLsqtCollectionName, docId, null, null, firstInsertTime);

    // Verify that the document was inserted
    JSONDocumentManager docMgr = readerClient.newJSONDocumentManager();
    JacksonDatabindHandle<ObjectNode> recordHandle = new JacksonDatabindHandle<ObjectNode>(ObjectNode.class);
    DocumentMetadataHandle metadataHandle = new DocumentMetadataHandle();
    docMgr.read(docId, metadataHandle, recordHandle);
    DocumentPage readResults = docMgr.read(docId);

    System.out.println("Number of results = " + readResults.size());
    assertEquals("Wrong number of results", 1, readResults.size());

    DocumentRecord record = readResults.next();
    System.out.println("URI after insert = " + record.getUri());
    assertEquals("Document uri wrong after insert", docId, record.getUri());
    System.out.println("Content = " + recordHandle.toString());

    // Make sure System start time was what was set ("2010-01-01T00:00:01")
    if (record.getFormat() != Format.JSON) {
        assertFalse("Invalid document format: " + record.getFormat(), true);
    } else {/*from   w ww. j a v a  2  s. co  m*/
        JsonFactory factory = new JsonFactory();
        ObjectMapper mapper = new ObjectMapper(factory);
        TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>() {
        };

        HashMap<String, Object> docObject = mapper.readValue(recordHandle.toString(), typeRef);

        @SuppressWarnings("unchecked")
        HashMap<String, Object> validNode = (HashMap<String, Object>) (docObject.get(systemNodeName));

        String systemStartDate = (String) validNode.get(systemStartERIName);
        String systemEndDate = (String) validNode.get(systemEndERIName);
        System.out.println("systemStartDate = " + systemStartDate);
        System.out.println("systemEndDate = " + systemEndDate);

        assertTrue("System start date check failed", (systemStartDate.contains("2010-01-01T00:00:01")));
        assertTrue("System end date check failed", (systemEndDate.contains("9999-12-31T23:59:59")));

        // Validate collections
        Iterator<String> resCollections = metadataHandle.getCollections().iterator();
        while (resCollections.hasNext()) {
            String collection = resCollections.next();
            System.out.println("Collection = " + collection);

            if (!collection.equals(docId) && !collection.equals(insertCollectionName)
                    && !collection.equals(temporalLsqtCollectionName)
                    && !collection.equals(latestCollectionName)) {
                assertFalse("Collection not what is expected: " + collection, true);
            }
        }

        // Validate permissions
        DocumentPermissions permissions = metadataHandle.getPermissions();
        System.out.println("Permissions: " + permissions);

        String actualPermissions = getDocumentPermissionsString(permissions);
        System.out.println("actualPermissions: " + actualPermissions);

        assertTrue("Document permissions difference in size value", actualPermissions.contains("size:3"));

        assertTrue("Document permissions difference in rest-reader permission",
                actualPermissions.contains("rest-reader:[READ]"));
        assertTrue("Document permissions difference in rest-writer permission",
                actualPermissions.contains("rest-writer:[UPDATE]"));
        assertTrue("Document permissions difference in app-user permission",
                (actualPermissions.contains("app-user:[") && actualPermissions.contains("READ")
                        && actualPermissions.contains("UPDATE") && actualPermissions.contains("EXECUTE")));

        // Validate quality
        int quality = metadataHandle.getQuality();
        System.out.println("Quality: " + quality);
        assertEquals(quality, 11);

        validateMetadata(metadataHandle);
    }

    // =============================================================================
    // Check update works
    // =============================================================================
    Calendar updateTime = DatatypeConverter.parseDateTime("2011-01-01T00:00:01");
    updateJSONSingleDocument(temporalLsqtCollectionName, docId, null, updateTime);

    // Verify that the document was updated
    // Make sure there is 1 document in latest collection
    QueryManager queryMgr = readerClient.newQueryManager();
    StructuredQueryBuilder sqb = queryMgr.newStructuredQueryBuilder();
    StructuredQueryDefinition termQuery = sqb.collection(latestCollectionName);
    long start = 1;
    DocumentPage termQueryResults = docMgr.search(termQuery, start);
    System.out.println("Number of results = " + termQueryResults.getTotalSize());
    assertEquals("Wrong number of results", 1, termQueryResults.getTotalSize());

    // Document URIs in latest collection must be the same as the one as the
    // original document
    while (termQueryResults.hasNext()) {
        record = termQueryResults.next();

        String uri = record.getUri();
        System.out.println("URI = " + uri);

        if (!uri.equals(docId)) {
            assertFalse("URIs are not what is expected", true);
        }
    }

    // Make sure there are 4 documents in jsonDocId collection
    queryMgr = readerClient.newQueryManager();
    sqb = queryMgr.newStructuredQueryBuilder();
    termQuery = sqb.collection(docId);

    start = 1;
    termQueryResults = docMgr.search(termQuery, start);
    System.out.println("Number of results = " + termQueryResults.getTotalSize());
    assertEquals("Wrong number of results", 4, termQueryResults.getTotalSize());

    // Make sure there are 4 documents in temporal collection
    queryMgr = readerClient.newQueryManager();
    sqb = queryMgr.newStructuredQueryBuilder();
    termQuery = sqb.collection(temporalLsqtCollectionName);

    start = 1;
    termQueryResults = docMgr.search(termQuery, start);
    System.out.println("Number of results = " + termQueryResults.getTotalSize());
    assertEquals("Wrong number of results", 4, termQueryResults.getTotalSize());

    // Make sure there are 4 documents in total. Use string search for this
    queryMgr = readerClient.newQueryManager();
    StringQueryDefinition stringQD = queryMgr.newStringDefinition();
    stringQD.setCriteria("");

    start = 1;
    docMgr.setMetadataCategories(Metadata.ALL);
    termQueryResults = docMgr.search(stringQD, start);
    System.out.println("Number of results = " + termQueryResults.getTotalSize());
    assertEquals("Wrong number of results", 4, termQueryResults.getTotalSize());

    while (termQueryResults.hasNext()) {
        record = termQueryResults.next();
        System.out.println("URI = " + record.getUri());

        metadataHandle = new DocumentMetadataHandle();
        record.getMetadata(metadataHandle);

        if (record.getFormat() != Format.JSON) {
            assertFalse("Format is not JSON: " + Format.JSON, true);
        } else {
            // Make sure that system and valid times are what is expected
            recordHandle = new JacksonDatabindHandle<ObjectNode>(ObjectNode.class);
            record.getContent(recordHandle);
            System.out.println("Content = " + recordHandle.toString());

            JsonFactory factory = new JsonFactory();
            ObjectMapper mapper = new ObjectMapper(factory);
            TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>() {
            };

            HashMap<String, Object> docObject = mapper.readValue(recordHandle.toString(), typeRef);

            @SuppressWarnings("unchecked")
            HashMap<String, Object> systemNode = (HashMap<String, Object>) (docObject.get(systemNodeName));

            String systemStartDate = (String) systemNode.get(systemStartERIName);
            String systemEndDate = (String) systemNode.get(systemEndERIName);
            System.out.println("systemStartDate = " + systemStartDate);
            System.out.println("systemEndDate = " + systemEndDate);

            @SuppressWarnings("unchecked")
            HashMap<String, Object> validNode = (HashMap<String, Object>) (docObject.get(validNodeName));

            String validStartDate = (String) validNode.get(validStartERIName);
            String validEndDate = (String) validNode.get(validEndERIName);
            System.out.println("validStartDate = " + validStartDate);
            System.out.println("validEndDate = " + validEndDate);

            // Permissions
            DocumentPermissions permissions = metadataHandle.getPermissions();
            System.out.println("Permissions: " + permissions);

            String actualPermissions = getDocumentPermissionsString(permissions);
            System.out.println("actualPermissions: " + actualPermissions);

            int quality = metadataHandle.getQuality();
            System.out.println("Quality: " + quality);

            if (validStartDate.contains("2003-01-01T00:00:00")
                    && validEndDate.contains("2008-12-31T23:59:59")) {
                assertTrue("System start date check failed", (systemStartDate.contains("2011-01-01T00:00:01")));
                assertTrue("System start date check failed", (systemEndDate.contains("9999-12-31T23:59:59")));

                Iterator<String> resCollections = metadataHandle.getCollections().iterator();
                while (resCollections.hasNext()) {
                    String collection = resCollections.next();
                    System.out.println("Collection = " + collection);

                    if (!collection.equals(docId) && !collection.equals(updateCollectionName)
                            && !collection.equals(temporalLsqtCollectionName)) {
                        assertFalse("Collection not what is expected: " + collection, true);
                    }
                }

                assertTrue("Properties should be empty", metadataHandle.getProperties().isEmpty());

                assertTrue("Document permissions difference in size value",
                        actualPermissions.contains("size:3"));

                assertTrue("Document permissions difference in rest-reader permission",
                        actualPermissions.contains("rest-reader:[READ]"));
                assertTrue("Document permissions difference in rest-writer permission",
                        actualPermissions.contains("rest-writer:[UPDATE]"));
                assertTrue("Document permissions difference in app-user permission",
                        (actualPermissions.contains("app-user:[") && actualPermissions.contains("READ")
                                && actualPermissions.contains("UPDATE")));
                assertFalse("Document permissions difference in app-user permission",
                        actualPermissions.contains("EXECUTE"));

                assertEquals(quality, 99);
            }

            if (validStartDate.contains("2001-01-01T00:00:00")
                    && validEndDate.contains("2003-01-01T00:00:00")) {
                assertTrue("System start date check failed", (systemStartDate.contains("2011-01-01T00:00:01")));
                assertTrue("System start date check failed", (systemEndDate.contains("9999-12-31T23:59:59")));

                Iterator<String> resCollections = metadataHandle.getCollections().iterator();
                while (resCollections.hasNext()) {
                    String collection = resCollections.next();
                    System.out.println("Collection = " + collection);

                    if (!collection.equals(docId) && !collection.equals(insertCollectionName)
                            && !collection.equals(temporalLsqtCollectionName)) {
                        assertFalse("Collection not what is expected: " + collection, true);
                    }
                }

                assertTrue("Properties should be empty", metadataHandle.getProperties().isEmpty());

                assertTrue("Document permissions difference in size value",
                        actualPermissions.contains("size:3"));

                assertTrue("Document permissions difference in rest-reader permission",
                        actualPermissions.contains("rest-reader:[READ]"));
                assertTrue("Document permissions difference in rest-writer permission",
                        actualPermissions.contains("rest-writer:[UPDATE]"));
                assertTrue("Document permissions difference in app-user permission",
                        (actualPermissions.contains("app-user:[") && actualPermissions.contains("READ")
                                && actualPermissions.contains("UPDATE")
                                && actualPermissions.contains("EXECUTE")));

                assertEquals(quality, 11);
            }

            if (validStartDate.contains("2008-12-31T23:59:59")
                    && validEndDate.contains("2011-12-31T23:59:59")) {
                // This is the latest document
                assertTrue("System start date check failed", (systemStartDate.contains("2011-01-01T00:00:01")));
                assertTrue("System start date check failed", (systemEndDate.contains("9999-12-31T23:59:59")));
                assertTrue("URI should be the doc uri ", record.getUri().equals(docId));

                Iterator<String> resCollections = metadataHandle.getCollections().iterator();
                while (resCollections.hasNext()) {
                    String collection = resCollections.next();
                    System.out.println("Collection = " + collection);

                    if (!collection.equals(docId) && !collection.equals(insertCollectionName)
                            && !collection.equals(temporalLsqtCollectionName)
                            && !collection.equals(latestCollectionName)) {
                        assertFalse("Collection not what is expected: " + collection, true);
                    }
                }

                assertTrue("Document permissions difference in size value",
                        actualPermissions.contains("size:3"));

                assertTrue("Document permissions difference in rest-reader permission",
                        actualPermissions.contains("rest-reader:[READ]"));
                assertTrue("Document permissions difference in rest-writer permission",
                        actualPermissions.contains("rest-writer:[UPDATE]"));
                assertTrue("Document permissions difference in app-user permission",
                        (actualPermissions.contains("app-user:[") && actualPermissions.contains("READ")
                                && actualPermissions.contains("UPDATE")
                                && actualPermissions.contains("EXECUTE")));

                assertEquals(quality, 11);

                validateMetadata(metadataHandle);
            }

            if (validStartDate.contains("2001-01-01T00:00:00")
                    && validEndDate.contains("2011-12-31T23:59:59")) {
                assertTrue("System start date check failed", (systemStartDate.contains("2010-01-01T00:00:01")));
                assertTrue("System start date check failed", (systemEndDate.contains("2011-01-01T00:00:01")));

                Iterator<String> resCollections = metadataHandle.getCollections().iterator();
                while (resCollections.hasNext()) {
                    String collection = resCollections.next();
                    System.out.println("Collection = " + collection);

                    if (!collection.equals(docId) && !collection.equals(insertCollectionName)
                            && !collection.equals(temporalLsqtCollectionName)) {
                        assertFalse("Collection not what is expected: " + collection, true);
                    }
                }

                assertTrue("Properties should be empty", metadataHandle.getProperties().isEmpty());

                assertTrue("Document permissions difference in size value",
                        actualPermissions.contains("size:3"));

                assertTrue("Document permissions difference in rest-reader permission",
                        actualPermissions.contains("rest-reader:[READ]"));
                assertTrue("Document permissions difference in rest-writer permission",
                        actualPermissions.contains("rest-writer:[UPDATE]"));
                assertTrue("Document permissions difference in app-user permission",
                        (actualPermissions.contains("app-user:[") && actualPermissions.contains("READ")
                                && actualPermissions.contains("UPDATE")
                                && actualPermissions.contains("EXECUTE")));

                assertEquals(quality, 11);
            }
        }
    }

    // =============================================================================
    // Check delete works
    // =============================================================================
    // Delete one of the document
    Calendar deleteTime = DatatypeConverter.parseDateTime("2012-01-01T00:00:01");
    deleteJSONSingleDocument(temporalLsqtCollectionName, docId, null, deleteTime);

    // Make sure there are still 4 documents in docId collection
    queryMgr = readerClient.newQueryManager();
    sqb = queryMgr.newStructuredQueryBuilder();
    termQuery = sqb.collection(docId);

    start = 1;
    termQueryResults = docMgr.search(termQuery, start);
    System.out.println("Number of results = " + termQueryResults.getTotalSize());
    assertEquals("Wrong number of results", 4, termQueryResults.getTotalSize());

    // Make sure there is one document with docId uri
    docMgr = readerClient.newJSONDocumentManager();
    readResults = docMgr.read(docId);

    System.out.println("Number of results = " + readResults.size());
    assertEquals("Wrong number of results", 1, readResults.size());

    // Make sure there are no documents in latest collection
    queryMgr = readerClient.newQueryManager();
    sqb = queryMgr.newStructuredQueryBuilder();
    termQuery = sqb.collection(latestCollectionName);

    start = 1;
    termQueryResults = docMgr.search(termQuery, start);
    System.out.println("Number of results = " + termQueryResults.getTotalSize());
    assertEquals("Wrong number of results", 0, termQueryResults.getTotalSize());

    // Make sure there are 4 documents in temporal collection
    queryMgr = readerClient.newQueryManager();
    sqb = queryMgr.newStructuredQueryBuilder();
    termQuery = sqb.collection(temporalLsqtCollectionName);

    start = 1;
    docMgr.setMetadataCategories(Metadata.ALL);
    termQueryResults = docMgr.search(termQuery, start);
    System.out.println("Number of results = " + termQueryResults.getTotalSize());
    assertEquals("Wrong number of results", 4, termQueryResults.getTotalSize());

    while (termQueryResults.hasNext()) {
        record = termQueryResults.next();
        System.out.println("URI = " + record.getUri());

        metadataHandle = new DocumentMetadataHandle();
        record.getMetadata(metadataHandle);

        if (record.getFormat() != Format.JSON) {
            assertFalse("Format is not JSON: " + Format.JSON, true);
        } else {
            // Make sure that system and valid times are what is expected
            recordHandle = new JacksonDatabindHandle<ObjectNode>(ObjectNode.class);
            record.getContent(recordHandle);
            System.out.println("Content = " + recordHandle.toString());

            JsonFactory factory = new JsonFactory();
            ObjectMapper mapper = new ObjectMapper(factory);
            TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>() {
            };

            HashMap<String, Object> docObject = mapper.readValue(recordHandle.toString(), typeRef);

            @SuppressWarnings("unchecked")
            HashMap<String, Object> systemNode = (HashMap<String, Object>) (docObject.get(systemNodeName));

            String systemStartDate = (String) systemNode.get(systemStartERIName);
            String systemEndDate = (String) systemNode.get(systemEndERIName);
            System.out.println("systemStartDate = " + systemStartDate);
            System.out.println("systemEndDate = " + systemEndDate);

            @SuppressWarnings("unchecked")
            HashMap<String, Object> validNode = (HashMap<String, Object>) (docObject.get(validNodeName));

            String validStartDate = (String) validNode.get(validStartERIName);
            String validEndDate = (String) validNode.get(validEndERIName);
            System.out.println("validStartDate = " + validStartDate);
            System.out.println("validEndDate = " + validEndDate);

            // Permissions
            DocumentPermissions permissions = metadataHandle.getPermissions();
            System.out.println("Permissions: " + permissions);

            String actualPermissions = getDocumentPermissionsString(permissions);
            System.out.println("actualPermissions: " + actualPermissions);

            int quality = metadataHandle.getQuality();
            System.out.println("Quality: " + quality);

            if (validStartDate.contains("2003-01-01T00:00:00")
                    && validEndDate.contains("2008-12-31T23:59:59")) {
                assertTrue("System start date check failed", (systemStartDate.contains("2011-01-01T00:00:01")));
                assertTrue("System start date check failed", (systemEndDate.contains("2012-01-01T00:00:01")));

                Iterator<String> resCollections = metadataHandle.getCollections().iterator();
                while (resCollections.hasNext()) {
                    String collection = resCollections.next();
                    System.out.println("Collection = " + collection);

                    if (!collection.equals(docId) && !collection.equals(updateCollectionName)
                            && !collection.equals(temporalLsqtCollectionName)) {
                        assertFalse("Collection not what is expected: " + collection, true);
                    }
                }

                assertTrue("Properties should be empty", metadataHandle.getProperties().isEmpty());

                assertTrue("Document permissions difference in size value",
                        actualPermissions.contains("size:3"));

                assertTrue("Document permissions difference in rest-reader permission",
                        actualPermissions.contains("rest-reader:[READ]"));
                assertTrue("Document permissions difference in rest-writer permission",
                        actualPermissions.contains("rest-writer:[UPDATE]"));
                assertTrue("Document permissions difference in app-user permission",
                        (actualPermissions.contains("app-user:[") && actualPermissions.contains("READ")
                                && actualPermissions.contains("UPDATE")));
                assertFalse("Document permissions difference in app-user permission",
                        actualPermissions.contains("EXECUTE"));

                assertEquals(quality, 99);
            }

            if (validStartDate.contains("2001-01-01T00:00:00")
                    && validEndDate.contains("2003-01-01T00:00:00")) {
                assertTrue("System start date check failed", (systemStartDate.contains("2011-01-01T00:00:01")));
                assertTrue("System start date check failed", (systemEndDate.contains("2012-01-01T00:00:01")));

                Iterator<String> resCollections = metadataHandle.getCollections().iterator();
                while (resCollections.hasNext()) {
                    String collection = resCollections.next();
                    System.out.println("Collection = " + collection);

                    if (!collection.equals(docId) && !collection.equals(insertCollectionName)
                            && !collection.equals(temporalLsqtCollectionName)) {
                        assertFalse("Collection not what is expected: " + collection, true);
                    }
                }

                assertTrue("Properties should be empty", metadataHandle.getProperties().isEmpty());

                assertTrue("Document permissions difference in size value",
                        actualPermissions.contains("size:3"));

                assertTrue("Document permissions difference in rest-reader permission",
                        actualPermissions.contains("rest-reader:[READ]"));
                assertTrue("Document permissions difference in rest-writer permission",
                        actualPermissions.contains("rest-writer:[UPDATE]"));
                assertTrue("Document permissions difference in app-user permission",
                        (actualPermissions.contains("app-user:[") && actualPermissions.contains("READ")
                                && actualPermissions.contains("UPDATE")
                                && actualPermissions.contains("EXECUTE")));

                assertEquals(quality, 11);
            }

            if (validStartDate.contains("2008-12-31T23:59:59")
                    && validEndDate.contains("2011-12-31T23:59:59")) {
                assertTrue("System start date check failed", (systemStartDate.contains("2011-01-01T00:00:01")));
                assertTrue("System start date check failed", (systemEndDate.contains("2012-01-01T00:00:01")));

                assertTrue("URI should be the doc uri ", record.getUri().equals(docId));

                // Document should not be in latest collection
                Iterator<String> resCollections = metadataHandle.getCollections().iterator();
                while (resCollections.hasNext()) {
                    String collection = resCollections.next();
                    System.out.println("Collection = " + collection);

                    if (!collection.equals(docId) && !collection.equals(insertCollectionName)
                            && !collection.equals(temporalLsqtCollectionName)) {
                        assertFalse("Collection not what is expected: " + collection, true);
                    }
                }

                assertTrue("Document permissions difference in size value",
                        actualPermissions.contains("size:3"));

                assertTrue("Document permissions difference in rest-reader permission",
                        actualPermissions.contains("rest-reader:[READ]"));
                assertTrue("Document permissions difference in rest-writer permission",
                        actualPermissions.contains("rest-writer:[UPDATE]"));
                assertTrue("Document permissions difference in app-user permission",
                        (actualPermissions.contains("app-user:[") && actualPermissions.contains("READ")
                                && actualPermissions.contains("UPDATE")
                                && actualPermissions.contains("EXECUTE")));

                assertEquals(quality, 11);

                validateMetadata(metadataHandle);
            }

            if (validStartDate.contains("2001-01-01T00:00:00")
                    && validEndDate.contains("2011-12-31T23:59:59")) {
                assertTrue("System start date check failed", (systemStartDate.contains("2010-01-01T00:00:01")));
                assertTrue("System start date check failed", (systemEndDate.contains("2011-01-01T00:00:01")));
                Iterator<String> resCollections = metadataHandle.getCollections().iterator();
                while (resCollections.hasNext()) {
                    String collection = resCollections.next();
                    System.out.println("Collection = " + collection);

                    if (!collection.equals(docId) && !collection.equals(insertCollectionName)
                            && !collection.equals(temporalLsqtCollectionName)) {
                        assertFalse("Collection not what is expected: " + collection, true);
                    }
                }

                assertTrue("Properties should be empty", metadataHandle.getProperties().isEmpty());

                assertTrue("Document permissions difference in size value",
                        actualPermissions.contains("size:3"));

                assertTrue("Document permissions difference in rest-reader permission",
                        actualPermissions.contains("rest-reader:[READ]"));
                assertTrue("Document permissions difference in rest-writer permission",
                        actualPermissions.contains("rest-writer:[UPDATE]"));
                assertTrue("Document permissions difference in app-user permission",
                        (actualPermissions.contains("app-user:[") && actualPermissions.contains("READ")
                                && actualPermissions.contains("UPDATE")
                                && actualPermissions.contains("EXECUTE")));

                assertEquals(quality, 11);
            }
        }
    }

    // Make sure there are 4 documents in total. Use string search for this
    queryMgr = readerClient.newQueryManager();

    start = 1;
    termQueryResults = docMgr.search(stringQD, start);
    System.out.println("Number of results = " + termQueryResults.getTotalSize());
    assertEquals("Wrong number of results", 4, termQueryResults.getTotalSize());
}

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

/**
* The Get OS Image operation retrieves the details for an operating system
* image from the image repository.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/jj157191.aspx for
* more information)/*from   w w w  .  j  a  v  a 2  s  .  c om*/
*
* @param imageName Required. The name of the OS image to retrieve.
* @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 A virtual machine image associated with your subscription.
*/
@Override
public VirtualMachineOSImageGetResponse get(String imageName)
        throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException {
    // Validate
    if (imageName == null) {
        throw new NullPointerException("imageName");
    }

    // 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("imageName", imageName);
        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/images/";
    url = url + URLEncoder.encode(imageName, "UTF-8");
    String baseUrl = this.getClient().getBaseUri().toString();
    // Trim '/' character from the end of baseUrl and beginning of url.
    if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
        baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
    }
    if (url.charAt(0) == '/') {
        url = url.substring(1);
    }
    url = baseUrl + "/" + url;
    url = url.replace(" ", "%20");

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

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

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

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

            Element oSImageElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "OSImage");
            if (oSImageElement != null) {
                Element affinityGroupElement = XmlUtility.getElementByTagNameNS(oSImageElement,
                        "http://schemas.microsoft.com/windowsazure", "AffinityGroup");
                if (affinityGroupElement != null) {
                    String affinityGroupInstance;
                    affinityGroupInstance = affinityGroupElement.getTextContent();
                    result.setAffinityGroup(affinityGroupInstance);
                }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

/**
* The create namespace authorization rule operation creates an
* authorization rule for a namespace/* w ww . j  av  a2 s .  c  o m*/
*
* @param resourceGroupName Required. The name of the resource group.
* @param namespaceName Required. The namespace name.
* @param authorizationRuleName Required. The namespace
* authorizationRuleName name.
* @param parameters Required. The shared access authorization rule.
* @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 Response of the CreateOrUpdate operation on the AuthorizationRules
*/
@Override
public SharedAccessAuthorizationRuleCreateOrUpdateResponse createOrUpdateAuthorizationRule(
        String resourceGroupName, String namespaceName, String authorizationRuleName,
        SharedAccessAuthorizationRuleCreateOrUpdateParameters parameters) throws IOException, ServiceException {
    // Validate
    if (resourceGroupName == null) {
        throw new NullPointerException("resourceGroupName");
    }
    if (namespaceName == null) {
        throw new NullPointerException("namespaceName");
    }
    if (authorizationRuleName == null) {
        throw new NullPointerException("authorizationRuleName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getProperties() == null) {
        throw new NullPointerException("parameters.Properties");
    }

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

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

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

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

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

    if (parameters.getLocation() != null) {
        ((ObjectNode) sharedAccessAuthorizationRuleCreateOrUpdateParametersValue).put("location",
                parameters.getLocation());
    }

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

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

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

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

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

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

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

    if (parameters.getProperties().getRights() != null) {
        ArrayNode rightsArray = objectMapper.createArrayNode();
        for (AccessRights rightsItem : parameters.getProperties().getRights()) {
            rightsArray.add(rightsItem.toString());
        }
        ((ObjectNode) propertiesValue).put("rights", rightsArray);
    }

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

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

    ((ObjectNode) propertiesValue).put("revision", parameters.getProperties().getRevision());

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

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

        // Create Result
        SharedAccessAuthorizationRuleCreateOrUpdateResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new SharedAccessAuthorizationRuleCreateOrUpdateResponse();
            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) {
                SharedAccessAuthorizationRuleResource valueInstance = new SharedAccessAuthorizationRuleResource();
                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 propertiesValue2 = responseDoc.get("properties");
                if (propertiesValue2 != null && propertiesValue2 instanceof NullNode == false) {
                    SharedAccessAuthorizationRuleProperties propertiesInstance = new SharedAccessAuthorizationRuleProperties();
                    valueInstance.setProperties(propertiesInstance);

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

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

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

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

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

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

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

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

                    JsonNode revisionValue = propertiesValue2.get("revision");
                    if (revisionValue != null && revisionValue instanceof NullNode == false) {
                        int revisionInstance;
                        revisionInstance = revisionValue.getIntValue();
                        propertiesInstance.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.sql.DatabaseOperationsImpl.java

/**
* Returns information about an Azure SQL Database event logs.
*
* @param serverName Required. The name of the Azure SQL Database Server on
* which the database is hosted.//from  w  ww  . jav a2 s .  co m
* @param databaseName Required. The name of the Azure SQL Database to be
* retrieved.
* @param parameters Required. The parameters for the Get Database Event
* Logs operation.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @throws ParserConfigurationException Thrown if there was a serious
* configuration error with the document parser.
* @throws SAXException Thrown if there was an error parsing the XML
* response.
* @return Contains the response to a Get Database Event Logs request.
*/
@Override
public DatabaseGetEventLogsResponse getEventLogs(String serverName, String databaseName,
        DatabaseGetEventLogsParameters parameters)
        throws IOException, ServiceException, ParserConfigurationException, SAXException {
    // Validate
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }
    if (databaseName == null) {
        throw new NullPointerException("databaseName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getEventTypes() == null) {
        throw new NullPointerException("parameters.EventTypes");
    }

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

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/services/sqlservers/servers/";
    url = url + URLEncoder.encode(serverName, "UTF-8");
    url = url + "/databases/";
    url = url + URLEncoder.encode(databaseName, "UTF-8");
    url = url + "/events";
    ArrayList<String> queryParameters = new ArrayList<String>();
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
    simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    queryParameters.add("startDate="
            + URLEncoder.encode(simpleDateFormat.format(parameters.getStartDate().getTime()), "UTF-8"));
    queryParameters.add("intervalSizeInMinutes="
            + URLEncoder.encode(Integer.toString(parameters.getIntervalSizeInMinutes()), "UTF-8"));
    queryParameters.add("eventTypes=" + URLEncoder.encode(parameters.getEventTypes(), "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", "2012-03-01");

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

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

            Element serviceResourcesSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "ServiceResources");
            if (serviceResourcesSequenceElement != null) {
                for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                        .getElementsByTagNameNS(serviceResourcesSequenceElement,
                                "http://schemas.microsoft.com/windowsazure", "ServiceResource")
                        .size(); i1 = i1 + 1) {
                    org.w3c.dom.Element serviceResourcesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(serviceResourcesSequenceElement,
                                    "http://schemas.microsoft.com/windowsazure", "ServiceResource")
                            .get(i1));
                    DatabaseEventLog serviceResourceInstance = new DatabaseEventLog();
                    result.getEventLogs().add(serviceResourceInstance);

                    Element databaseNameElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                            "http://schemas.microsoft.com/windowsazure", "DatabaseName");
                    if (databaseNameElement != null) {
                        String databaseNameInstance;
                        databaseNameInstance = databaseNameElement.getTextContent();
                        serviceResourceInstance.setDatabaseName(databaseNameInstance);
                    }

                    Element startTimeUtcElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                            "http://schemas.microsoft.com/windowsazure", "StartTimeUtc");
                    if (startTimeUtcElement != null) {
                        Calendar startTimeUtcInstance;
                        startTimeUtcInstance = DatatypeConverter
                                .parseDateTime(startTimeUtcElement.getTextContent());
                        serviceResourceInstance.setStartTimeUtc(startTimeUtcInstance);
                    }

                    Element intervalSizeInMinutesElement = XmlUtility.getElementByTagNameNS(
                            serviceResourcesElement, "http://schemas.microsoft.com/windowsazure",
                            "IntervalSizeInMinutes");
                    if (intervalSizeInMinutesElement != null) {
                        int intervalSizeInMinutesInstance;
                        intervalSizeInMinutesInstance = DatatypeConverter
                                .parseInt(intervalSizeInMinutesElement.getTextContent());
                        serviceResourceInstance.setIntervalSizeInMinutes(intervalSizeInMinutesInstance);
                    }

                    Element eventCategoryElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                            "http://schemas.microsoft.com/windowsazure", "EventCategory");
                    if (eventCategoryElement != null) {
                        String eventCategoryInstance;
                        eventCategoryInstance = eventCategoryElement.getTextContent();
                        serviceResourceInstance.setEventCategory(eventCategoryInstance);
                    }

                    Element eventTypeElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                            "http://schemas.microsoft.com/windowsazure", "EventType");
                    if (eventTypeElement != null) {
                        String eventTypeInstance;
                        eventTypeInstance = eventTypeElement.getTextContent();
                        serviceResourceInstance.setEventType(eventTypeInstance);
                    }

                    Element eventSubtypeElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                            "http://schemas.microsoft.com/windowsazure", "EventSubtype");
                    if (eventSubtypeElement != null) {
                        String eventSubtypeInstance;
                        eventSubtypeInstance = eventSubtypeElement.getTextContent();
                        serviceResourceInstance.setEventSubtype(eventSubtypeInstance);
                    }

                    Element eventSubtypeDescriptionElement = XmlUtility.getElementByTagNameNS(
                            serviceResourcesElement, "http://schemas.microsoft.com/windowsazure",
                            "EventSubtypeDescription");
                    if (eventSubtypeDescriptionElement != null) {
                        String eventSubtypeDescriptionInstance;
                        eventSubtypeDescriptionInstance = eventSubtypeDescriptionElement.getTextContent();
                        serviceResourceInstance.setEventSubtypeDescription(eventSubtypeDescriptionInstance);
                    }

                    Element numberOfEventsElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                            "http://schemas.microsoft.com/windowsazure", "NumberOfEvents");
                    if (numberOfEventsElement != null) {
                        int numberOfEventsInstance;
                        numberOfEventsInstance = DatatypeConverter
                                .parseInt(numberOfEventsElement.getTextContent());
                        serviceResourceInstance.setNumberOfEvents(numberOfEventsInstance);
                    }

                    Element severityElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                            "http://schemas.microsoft.com/windowsazure", "Severity");
                    if (severityElement != null) {
                        int severityInstance;
                        severityInstance = DatatypeConverter.parseInt(severityElement.getTextContent());
                        serviceResourceInstance.setSeverity(severityInstance);
                    }

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

                    Element additionalDataElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                            "http://schemas.microsoft.com/windowsazure", "AdditionalData");
                    if (additionalDataElement != null) {
                        boolean isNil = false;
                        Attr nilAttribute = additionalDataElement
                                .getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil");
                        if (nilAttribute != null) {
                            isNil = "true".equals(nilAttribute.getValue());
                        }
                        if (isNil == false) {
                            String additionalDataInstance;
                            additionalDataInstance = additionalDataElement.getTextContent();
                            serviceResourceInstance.setAdditionalData(additionalDataInstance);
                        }
                    }

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

                    Element typeElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement,
                            "http://schemas.microsoft.com/windowsazure", "Type");
                    if (typeElement != null) {
                        String typeInstance;
                        typeInstance = typeElement.getTextContent();
                        serviceResourceInstance.setType(typeInstance);
                    }

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

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

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

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

/**
* Returns information about an Azure SQL Database inside of an Azure Sql
* Database Elastic Pool./*from   w  w w. j av a 2  s .c om*/
*
* @param resourceGroupName Required. The name of the Resource Group to
* which the server belongs.
* @param serverName Required. The name of the Azure SQL Database Server on
* which the database is hosted.
* @param elasticPoolName Required. The name of the Azure SQL Database
* Elastic Pool to be retrieved.
* @param databaseName Required. The name of the Azure SQL Database to be
* retrieved.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return Represents the response to a Get Azure Sql Database request.
*/
@Override
public DatabaseGetResponse getDatabases(String resourceGroupName, String serverName, String elasticPoolName,
        String databaseName) 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");
    }
    if (databaseName == null) {
        throw new NullPointerException("databaseName");
    }

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

    // Create HTTP transport objects
    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
        DatabaseGetResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new DatabaseGetResponse();
            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) {
                Database databaseInstance = new Database();
                result.setDatabase(databaseInstance);

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

                    JsonNode collationValue = propertiesValue.get("collation");
                    if (collationValue != null && collationValue instanceof NullNode == false) {
                        String collationInstance;
                        collationInstance = collationValue.getTextValue();
                        propertiesInstance.setCollation(collationInstance);
                    }

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

                    JsonNode currentServiceObjectiveIdValue = propertiesValue.get("currentServiceObjectiveId");
                    if (currentServiceObjectiveIdValue != null
                            && currentServiceObjectiveIdValue instanceof NullNode == false) {
                        String currentServiceObjectiveIdInstance;
                        currentServiceObjectiveIdInstance = currentServiceObjectiveIdValue.getTextValue();
                        propertiesInstance.setCurrentServiceObjectiveId(currentServiceObjectiveIdInstance);
                    }

                    JsonNode databaseIdValue = propertiesValue.get("databaseId");
                    if (databaseIdValue != null && databaseIdValue instanceof NullNode == false) {
                        String databaseIdInstance;
                        databaseIdInstance = databaseIdValue.getTextValue();
                        propertiesInstance.setDatabaseId(databaseIdInstance);
                    }

                    JsonNode earliestRestoreDateValue = propertiesValue.get("earliestRestoreDate");
                    if (earliestRestoreDateValue != null
                            && earliestRestoreDateValue instanceof NullNode == false) {
                        Calendar earliestRestoreDateInstance;
                        earliestRestoreDateInstance = DatatypeConverter
                                .parseDateTime(earliestRestoreDateValue.getTextValue());
                        propertiesInstance.setEarliestRestoreDate(earliestRestoreDateInstance);
                    }

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

                    JsonNode maxSizeBytesValue = propertiesValue.get("maxSizeBytes");
                    if (maxSizeBytesValue != null && maxSizeBytesValue instanceof NullNode == false) {
                        long maxSizeBytesInstance;
                        maxSizeBytesInstance = maxSizeBytesValue.getLongValue();
                        propertiesInstance.setMaxSizeBytes(maxSizeBytesInstance);
                    }

                    JsonNode requestedServiceObjectiveIdValue = propertiesValue
                            .get("requestedServiceObjectiveId");
                    if (requestedServiceObjectiveIdValue != null
                            && requestedServiceObjectiveIdValue instanceof NullNode == false) {
                        String requestedServiceObjectiveIdInstance;
                        requestedServiceObjectiveIdInstance = requestedServiceObjectiveIdValue.getTextValue();
                        propertiesInstance.setRequestedServiceObjectiveId(requestedServiceObjectiveIdInstance);
                    }

                    JsonNode requestedServiceObjectiveNameValue = propertiesValue
                            .get("requestedServiceObjectiveName");
                    if (requestedServiceObjectiveNameValue != null
                            && requestedServiceObjectiveNameValue instanceof NullNode == false) {
                        String requestedServiceObjectiveNameInstance;
                        requestedServiceObjectiveNameInstance = requestedServiceObjectiveNameValue
                                .getTextValue();
                        propertiesInstance
                                .setRequestedServiceObjectiveName(requestedServiceObjectiveNameInstance);
                    }

                    JsonNode serviceLevelObjectiveValue = propertiesValue.get("serviceLevelObjective");
                    if (serviceLevelObjectiveValue != null
                            && serviceLevelObjectiveValue instanceof NullNode == false) {
                        String serviceLevelObjectiveInstance;
                        serviceLevelObjectiveInstance = serviceLevelObjectiveValue.getTextValue();
                        propertiesInstance.setServiceObjective(serviceLevelObjectiveInstance);
                    }

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

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

                    JsonNode serviceTierAdvisorsArray = propertiesValue.get("serviceTierAdvisors");
                    if (serviceTierAdvisorsArray != null
                            && serviceTierAdvisorsArray instanceof NullNode == false) {
                        for (JsonNode serviceTierAdvisorsValue : ((ArrayNode) serviceTierAdvisorsArray)) {
                            ServiceTierAdvisor serviceTierAdvisorInstance = new ServiceTierAdvisor();
                            propertiesInstance.getServiceTierAdvisors().add(serviceTierAdvisorInstance);

                            JsonNode propertiesValue2 = serviceTierAdvisorsValue.get("properties");
                            if (propertiesValue2 != null && propertiesValue2 instanceof NullNode == false) {
                                ServiceTierAdvisorProperties propertiesInstance2 = new ServiceTierAdvisorProperties();
                                serviceTierAdvisorInstance.setProperties(propertiesInstance2);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                    JsonNode upgradeHintValue = propertiesValue.get("upgradeHint");
                    if (upgradeHintValue != null && upgradeHintValue instanceof NullNode == false) {
                        UpgradeHint upgradeHintInstance = new UpgradeHint();
                        propertiesInstance.setUpgradeHint(upgradeHintInstance);

                        JsonNode targetServiceLevelObjectiveValue = upgradeHintValue
                                .get("targetServiceLevelObjective");
                        if (targetServiceLevelObjectiveValue != null
                                && targetServiceLevelObjectiveValue instanceof NullNode == false) {
                            String targetServiceLevelObjectiveInstance;
                            targetServiceLevelObjectiveInstance = targetServiceLevelObjectiveValue
                                    .getTextValue();
                            upgradeHintInstance
                                    .setTargetServiceLevelObjective(targetServiceLevelObjectiveInstance);
                        }

                        JsonNode targetServiceLevelObjectiveIdValue = upgradeHintValue
                                .get("targetServiceLevelObjectiveId");
                        if (targetServiceLevelObjectiveIdValue != null
                                && targetServiceLevelObjectiveIdValue instanceof NullNode == false) {
                            String targetServiceLevelObjectiveIdInstance;
                            targetServiceLevelObjectiveIdInstance = targetServiceLevelObjectiveIdValue
                                    .getTextValue();
                            upgradeHintInstance
                                    .setTargetServiceLevelObjectiveId(targetServiceLevelObjectiveIdInstance);
                        }

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

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

                        JsonNode typeValue3 = upgradeHintValue.get("type");
                        if (typeValue3 != null && typeValue3 instanceof NullNode == false) {
                            String typeInstance3;
                            typeInstance3 = typeValue3.getTextValue();
                            upgradeHintInstance.setType(typeInstance3);
                        }

                        JsonNode locationValue3 = upgradeHintValue.get("location");
                        if (locationValue3 != null && locationValue3 instanceof NullNode == false) {
                            String locationInstance3;
                            locationInstance3 = locationValue3.getTextValue();
                            upgradeHintInstance.setLocation(locationInstance3);
                        }

                        JsonNode tagsSequenceElement3 = ((JsonNode) upgradeHintValue.get("tags"));
                        if (tagsSequenceElement3 != null && tagsSequenceElement3 instanceof NullNode == false) {
                            Iterator<Map.Entry<String, JsonNode>> itr3 = tagsSequenceElement3.getFields();
                            while (itr3.hasNext()) {
                                Map.Entry<String, JsonNode> property3 = itr3.next();
                                String tagsKey3 = property3.getKey();
                                String tagsValue3 = property3.getValue().getTextValue();
                                upgradeHintInstance.getTags().put(tagsKey3, tagsValue3);
                            }
                        }
                    }

                    JsonNode schemasArray = propertiesValue.get("schemas");
                    if (schemasArray != null && schemasArray instanceof NullNode == false) {
                        for (JsonNode schemasValue : ((ArrayNode) schemasArray)) {
                            Schema schemaInstance = new Schema();
                            propertiesInstance.getSchemas().add(schemaInstance);

                            JsonNode propertiesValue3 = schemasValue.get("properties");
                            if (propertiesValue3 != null && propertiesValue3 instanceof NullNode == false) {
                                SchemaProperties propertiesInstance3 = new SchemaProperties();
                                schemaInstance.setProperties(propertiesInstance3);

                                JsonNode tablesArray = propertiesValue3.get("tables");
                                if (tablesArray != null && tablesArray instanceof NullNode == false) {
                                    for (JsonNode tablesValue : ((ArrayNode) tablesArray)) {
                                        Table tableInstance = new Table();
                                        propertiesInstance3.getTables().add(tableInstance);

                                        JsonNode propertiesValue4 = tablesValue.get("properties");
                                        if (propertiesValue4 != null
                                                && propertiesValue4 instanceof NullNode == false) {
                                            TableProperties propertiesInstance4 = new TableProperties();
                                            tableInstance.setProperties(propertiesInstance4);

                                            JsonNode tableTypeValue = propertiesValue4.get("tableType");
                                            if (tableTypeValue != null
                                                    && tableTypeValue instanceof NullNode == false) {
                                                String tableTypeInstance;
                                                tableTypeInstance = tableTypeValue.getTextValue();
                                                propertiesInstance4.setTableType(tableTypeInstance);
                                            }

                                            JsonNode columnsArray = propertiesValue4.get("columns");
                                            if (columnsArray != null
                                                    && columnsArray instanceof NullNode == false) {
                                                for (JsonNode columnsValue : ((ArrayNode) columnsArray)) {
                                                    Column columnInstance = new Column();
                                                    propertiesInstance4.getColumns().add(columnInstance);

                                                    JsonNode propertiesValue5 = columnsValue.get("properties");
                                                    if (propertiesValue5 != null
                                                            && propertiesValue5 instanceof NullNode == false) {
                                                        ColumnProperties propertiesInstance5 = new ColumnProperties();
                                                        columnInstance.setProperties(propertiesInstance5);

                                                        JsonNode columnTypeValue = propertiesValue5
                                                                .get("columnType");
                                                        if (columnTypeValue != null
                                                                && columnTypeValue instanceof NullNode == false) {
                                                            String columnTypeInstance;
                                                            columnTypeInstance = columnTypeValue.getTextValue();
                                                            propertiesInstance5
                                                                    .setColumnType(columnTypeInstance);
                                                        }
                                                    }

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

                                                    JsonNode nameValue4 = columnsValue.get("name");
                                                    if (nameValue4 != null
                                                            && nameValue4 instanceof NullNode == false) {
                                                        String nameInstance4;
                                                        nameInstance4 = nameValue4.getTextValue();
                                                        columnInstance.setName(nameInstance4);
                                                    }

                                                    JsonNode typeValue4 = columnsValue.get("type");
                                                    if (typeValue4 != null
                                                            && typeValue4 instanceof NullNode == false) {
                                                        String typeInstance4;
                                                        typeInstance4 = typeValue4.getTextValue();
                                                        columnInstance.setType(typeInstance4);
                                                    }

                                                    JsonNode locationValue4 = columnsValue.get("location");
                                                    if (locationValue4 != null
                                                            && locationValue4 instanceof NullNode == false) {
                                                        String locationInstance4;
                                                        locationInstance4 = locationValue4.getTextValue();
                                                        columnInstance.setLocation(locationInstance4);
                                                    }

                                                    JsonNode tagsSequenceElement4 = ((JsonNode) columnsValue
                                                            .get("tags"));
                                                    if (tagsSequenceElement4 != null
                                                            && tagsSequenceElement4 instanceof NullNode == false) {
                                                        Iterator<Map.Entry<String, JsonNode>> itr4 = tagsSequenceElement4
                                                                .getFields();
                                                        while (itr4.hasNext()) {
                                                            Map.Entry<String, JsonNode> property4 = itr4.next();
                                                            String tagsKey4 = property4.getKey();
                                                            String tagsValue4 = property4.getValue()
                                                                    .getTextValue();
                                                            columnInstance.getTags().put(tagsKey4, tagsValue4);
                                                        }
                                                    }
                                                }
                                            }

                                            JsonNode recommendedIndexesArray = propertiesValue4
                                                    .get("recommendedIndexes");
                                            if (recommendedIndexesArray != null
                                                    && recommendedIndexesArray instanceof NullNode == false) {
                                                for (JsonNode recommendedIndexesValue : ((ArrayNode) recommendedIndexesArray)) {
                                                    RecommendedIndex recommendedIndexInstance = new RecommendedIndex();
                                                    propertiesInstance4.getRecommendedIndexes()
                                                            .add(recommendedIndexInstance);

                                                    JsonNode propertiesValue6 = recommendedIndexesValue
                                                            .get("properties");
                                                    if (propertiesValue6 != null
                                                            && propertiesValue6 instanceof NullNode == false) {
                                                        RecommendedIndexProperties propertiesInstance6 = new RecommendedIndexProperties();
                                                        recommendedIndexInstance
                                                                .setProperties(propertiesInstance6);

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

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

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

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

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

                                                        JsonNode schemaValue = propertiesValue6.get("schema");
                                                        if (schemaValue != null
                                                                && schemaValue instanceof NullNode == false) {
                                                            String schemaInstance2;
                                                            schemaInstance2 = schemaValue.getTextValue();
                                                            propertiesInstance6.setSchema(schemaInstance2);
                                                        }

                                                        JsonNode tableValue = propertiesValue6.get("table");
                                                        if (tableValue != null
                                                                && tableValue instanceof NullNode == false) {
                                                            String tableInstance2;
                                                            tableInstance2 = tableValue.getTextValue();
                                                            propertiesInstance6.setTable(tableInstance2);
                                                        }

                                                        JsonNode columnsArray2 = propertiesValue6
                                                                .get("columns");
                                                        if (columnsArray2 != null
                                                                && columnsArray2 instanceof NullNode == false) {
                                                            for (JsonNode columnsValue2 : ((ArrayNode) columnsArray2)) {
                                                                propertiesInstance6.getColumns()
                                                                        .add(columnsValue2.getTextValue());
                                                            }
                                                        }

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

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

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

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

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

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

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

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

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

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

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

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

                                                    JsonNode idValue5 = recommendedIndexesValue.get("id");
                                                    if (idValue5 != null
                                                            && idValue5 instanceof NullNode == false) {
                                                        String idInstance5;
                                                        idInstance5 = idValue5.getTextValue();
                                                        recommendedIndexInstance.setId(idInstance5);
                                                    }

                                                    JsonNode nameValue7 = recommendedIndexesValue.get("name");
                                                    if (nameValue7 != null
                                                            && nameValue7 instanceof NullNode == false) {
                                                        String nameInstance7;
                                                        nameInstance7 = nameValue7.getTextValue();
                                                        recommendedIndexInstance.setName(nameInstance7);
                                                    }

                                                    JsonNode typeValue5 = recommendedIndexesValue.get("type");
                                                    if (typeValue5 != null
                                                            && typeValue5 instanceof NullNode == false) {
                                                        String typeInstance5;
                                                        typeInstance5 = typeValue5.getTextValue();
                                                        recommendedIndexInstance.setType(typeInstance5);
                                                    }

                                                    JsonNode locationValue5 = recommendedIndexesValue
                                                            .get("location");
                                                    if (locationValue5 != null
                                                            && locationValue5 instanceof NullNode == false) {
                                                        String locationInstance5;
                                                        locationInstance5 = locationValue5.getTextValue();
                                                        recommendedIndexInstance.setLocation(locationInstance5);
                                                    }

                                                    JsonNode tagsSequenceElement5 = ((JsonNode) recommendedIndexesValue
                                                            .get("tags"));
                                                    if (tagsSequenceElement5 != null
                                                            && tagsSequenceElement5 instanceof NullNode == false) {
                                                        Iterator<Map.Entry<String, JsonNode>> itr5 = tagsSequenceElement5
                                                                .getFields();
                                                        while (itr5.hasNext()) {
                                                            Map.Entry<String, JsonNode> property5 = itr5.next();
                                                            String tagsKey5 = property5.getKey();
                                                            String tagsValue5 = property5.getValue()
                                                                    .getTextValue();
                                                            recommendedIndexInstance.getTags().put(tagsKey5,
                                                                    tagsValue5);
                                                        }
                                                    }
                                                }
                                            }
                                        }

                                        JsonNode idValue6 = tablesValue.get("id");
                                        if (idValue6 != null && idValue6 instanceof NullNode == false) {
                                            String idInstance6;
                                            idInstance6 = idValue6.getTextValue();
                                            tableInstance.setId(idInstance6);
                                        }

                                        JsonNode nameValue8 = tablesValue.get("name");
                                        if (nameValue8 != null && nameValue8 instanceof NullNode == false) {
                                            String nameInstance8;
                                            nameInstance8 = nameValue8.getTextValue();
                                            tableInstance.setName(nameInstance8);
                                        }

                                        JsonNode typeValue6 = tablesValue.get("type");
                                        if (typeValue6 != null && typeValue6 instanceof NullNode == false) {
                                            String typeInstance6;
                                            typeInstance6 = typeValue6.getTextValue();
                                            tableInstance.setType(typeInstance6);
                                        }

                                        JsonNode locationValue6 = tablesValue.get("location");
                                        if (locationValue6 != null
                                                && locationValue6 instanceof NullNode == false) {
                                            String locationInstance6;
                                            locationInstance6 = locationValue6.getTextValue();
                                            tableInstance.setLocation(locationInstance6);
                                        }

                                        JsonNode tagsSequenceElement6 = ((JsonNode) tablesValue.get("tags"));
                                        if (tagsSequenceElement6 != null
                                                && tagsSequenceElement6 instanceof NullNode == false) {
                                            Iterator<Map.Entry<String, JsonNode>> itr6 = tagsSequenceElement6
                                                    .getFields();
                                            while (itr6.hasNext()) {
                                                Map.Entry<String, JsonNode> property6 = itr6.next();
                                                String tagsKey6 = property6.getKey();
                                                String tagsValue6 = property6.getValue().getTextValue();
                                                tableInstance.getTags().put(tagsKey6, tagsValue6);
                                            }
                                        }
                                    }
                                }
                            }

                            JsonNode idValue7 = schemasValue.get("id");
                            if (idValue7 != null && idValue7 instanceof NullNode == false) {
                                String idInstance7;
                                idInstance7 = idValue7.getTextValue();
                                schemaInstance.setId(idInstance7);
                            }

                            JsonNode nameValue9 = schemasValue.get("name");
                            if (nameValue9 != null && nameValue9 instanceof NullNode == false) {
                                String nameInstance9;
                                nameInstance9 = nameValue9.getTextValue();
                                schemaInstance.setName(nameInstance9);
                            }

                            JsonNode typeValue7 = schemasValue.get("type");
                            if (typeValue7 != null && typeValue7 instanceof NullNode == false) {
                                String typeInstance7;
                                typeInstance7 = typeValue7.getTextValue();
                                schemaInstance.setType(typeInstance7);
                            }

                            JsonNode locationValue7 = schemasValue.get("location");
                            if (locationValue7 != null && locationValue7 instanceof NullNode == false) {
                                String locationInstance7;
                                locationInstance7 = locationValue7.getTextValue();
                                schemaInstance.setLocation(locationInstance7);
                            }

                            JsonNode tagsSequenceElement7 = ((JsonNode) schemasValue.get("tags"));
                            if (tagsSequenceElement7 != null
                                    && tagsSequenceElement7 instanceof NullNode == false) {
                                Iterator<Map.Entry<String, JsonNode>> itr7 = tagsSequenceElement7.getFields();
                                while (itr7.hasNext()) {
                                    Map.Entry<String, JsonNode> property7 = itr7.next();
                                    String tagsKey7 = property7.getKey();
                                    String tagsValue7 = property7.getValue().getTextValue();
                                    schemaInstance.getTags().put(tagsKey7, tagsValue7);
                                }
                            }
                        }
                    }

                    JsonNode defaultSecondaryLocationValue = propertiesValue.get("defaultSecondaryLocation");
                    if (defaultSecondaryLocationValue != null
                            && defaultSecondaryLocationValue instanceof NullNode == false) {
                        String defaultSecondaryLocationInstance;
                        defaultSecondaryLocationInstance = defaultSecondaryLocationValue.getTextValue();
                        propertiesInstance.setDefaultSecondaryLocation(defaultSecondaryLocationInstance);
                    }
                }

                JsonNode idValue8 = responseDoc.get("id");
                if (idValue8 != null && idValue8 instanceof NullNode == false) {
                    String idInstance8;
                    idInstance8 = idValue8.getTextValue();
                    databaseInstance.setId(idInstance8);
                }

                JsonNode nameValue10 = responseDoc.get("name");
                if (nameValue10 != null && nameValue10 instanceof NullNode == false) {
                    String nameInstance10;
                    nameInstance10 = nameValue10.getTextValue();
                    databaseInstance.setName(nameInstance10);
                }

                JsonNode typeValue8 = responseDoc.get("type");
                if (typeValue8 != null && typeValue8 instanceof NullNode == false) {
                    String typeInstance8;
                    typeInstance8 = typeValue8.getTextValue();
                    databaseInstance.setType(typeInstance8);
                }

                JsonNode locationValue8 = responseDoc.get("location");
                if (locationValue8 != null && locationValue8 instanceof NullNode == false) {
                    String locationInstance8;
                    locationInstance8 = locationValue8.getTextValue();
                    databaseInstance.setLocation(locationInstance8);
                }

                JsonNode tagsSequenceElement8 = ((JsonNode) responseDoc.get("tags"));
                if (tagsSequenceElement8 != null && tagsSequenceElement8 instanceof NullNode == false) {
                    Iterator<Map.Entry<String, JsonNode>> itr8 = tagsSequenceElement8.getFields();
                    while (itr8.hasNext()) {
                        Map.Entry<String, JsonNode> property8 = itr8.next();
                        String tagsKey8 = property8.getKey();
                        String tagsValue8 = property8.getValue().getTextValue();
                        databaseInstance.getTags().put(tagsKey8, tagsValue8);
                    }
                }
            }

        }
        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

/**
 * TODO: write documentation//  ww w  . j a v a2  s.  co  m
 * Updates a survey with a given id. The respective survey may only be deleted, if the active agent is the survey's owner.
 * 
 * @param id
 * @return
 */
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Path("surveys/{id}")
@Summary("update given survey.")
@Notes("Requires authentication. Use parent resource to retrieve list of existing surveys.")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Survey updated successfully."),
        @ApiResponse(code = 400, message = "Survey data invalid."),
        @ApiResponse(code = 401, message = "Survey may only be updated by its owner."),
        @ApiResponse(code = 404, message = "Survey does not exist.") })
public HttpResponse updateSurvey(@PathParam("id") int id, @ContentParam String content) {

    if (getActiveAgent().getId() == getActiveNode().getAnonymous().getId()) {
        HttpResponse noauth = new HttpResponse("Please authenticate to update survey!");
        noauth.setStatus(401);
    }

    String onAction = "updating survey " + id;

    try {
        Connection c = null;
        PreparedStatement s = null;
        ResultSet rs = null;

        // +++ dsi 
        try {

            int exown;
            // survey may only be updated if survey exists and active agent is owner
            exown = checkExistenceOwnership(id, 0);

            // check if survey exists; if not, return 404.
            if (exown == -1) {
                HttpResponse result = new HttpResponse("Survey " + id + " does not exist.");
                result.setStatus(404);
                return result;
            }
            // if survey exists, check if active agent is owner. if not, return 401.
            else if (exown == 0) {
                HttpResponse result = new HttpResponse("Survey " + id + " may only be deleted by its owner.");
                result.setStatus(401);
                return result;
            }

            // if survey exists and active agent is owner, proceed.

            JSONObject o;
            // parse and validate content. If invalid, return 400 (bad request)
            try {
                o = parseSurvey(content);
            } catch (IllegalArgumentException e) {
                HttpResponse result = new HttpResponse("Invalid survey data! " + e.getMessage());
                result.setStatus(400);
                return result;
            }

            c = dataSource.getConnection();
            s = c.prepareStatement("update " + jdbcSchema
                    + ".survey set organization=?, logo=?, name=?, description=?, resource=?, start=?, end=?, lang=? where id = ?");

            s.setString(1, (String) o.get("organization"));
            s.setString(2, (String) o.get("logo"));
            s.setString(3, (String) o.get("name"));
            s.setString(4, (String) o.get("description"));
            s.setString(5, (String) o.get("resource"));
            s.setTimestamp(6,
                    new Timestamp(DatatypeConverter.parseDateTime((String) o.get("start")).getTimeInMillis()));
            s.setTimestamp(7,
                    new Timestamp(DatatypeConverter.parseDateTime((String) o.get("end")).getTimeInMillis()));
            s.setString(8, (String) o.get("lang"));
            s.setInt(9, id);

            s.executeUpdate();

            HttpResponse result = new HttpResponse("Survey " + id + " updated successfully.");
            result.setStatus(200);
            return result;

        } catch (Exception e) {
            e.printStackTrace();
            return internalError(onAction);
        } finally {
            try {
                if (rs != null)
                    rs.close();
            } catch (Exception e) {
                e.printStackTrace();
                return internalError(onAction);
            }
            try {
                if (s != null)
                    s.close();
            } catch (Exception e) {
                e.printStackTrace();
                return internalError(onAction);
            }
            try {
                if (c != null)
                    c.close();
            } catch (Exception e) {
                e.printStackTrace();
                return internalError(onAction);
            }
        }
        // --- dsi

    } catch (Exception e) {
        e.printStackTrace();
        return internalError(onAction);
    }

}

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

/**
* Creates a new service namespace. Once created, this namespace's resource
* manifest is immutable. This operation is idempotent.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/jj856303.aspx for
* more information)/* ww w  .j a  v a2 s  .co  m*/
*
* @param namespaceName Required. The namespace name.
* @param namespaceEntity Required. The service bus namespace.
* @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.
* @throws URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return The response to a request for a particular namespace.
*/
@Override
public ServiceBusNamespaceResponse createNamespace(String namespaceName,
        ServiceBusNamespaceCreateParameters namespaceEntity) throws ParserConfigurationException, SAXException,
        TransformerException, IOException, ServiceException, URISyntaxException {
    // Validate
    if (namespaceName == null) {
        throw new NullPointerException("namespaceName");
    }
    if (namespaceEntity == null) {
        throw new NullPointerException("namespaceEntity");
    }
    if (namespaceEntity.getNamespaceType() == null) {
        throw new NullPointerException("namespaceEntity.NamespaceType");
    }
    if (namespaceEntity.getRegion() == null) {
        throw new NullPointerException("namespaceEntity.Region");
    }

    // 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("namespaceEntity", namespaceEntity);
        CloudTracing.enter(invocationId, this, "createNamespaceAsync", 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");
    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("type", "entry");
    httpRequest.setHeader("x-ms-version", "2014-06-01");

    // 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 namespaceDescriptionElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "NamespaceDescription");
    contentElement.appendChild(namespaceDescriptionElement);

    if (namespaceEntity.getRegion() != null) {
        Element regionElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "Region");
        regionElement.appendChild(requestDoc.createTextNode(namespaceEntity.getRegion()));
        namespaceDescriptionElement.appendChild(regionElement);
    }

    Element createACSNamespaceElement = requestDoc.createElementNS(
            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "CreateACSNamespace");
    createACSNamespaceElement.appendChild(
            requestDoc.createTextNode(Boolean.toString(namespaceEntity.isCreateACSNamespace()).toLowerCase()));
    namespaceDescriptionElement.appendChild(createACSNamespaceElement);

    if (namespaceEntity.getNamespaceType() != null) {
        Element namespaceTypeElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "NamespaceType");
        namespaceTypeElement
                .appendChild(requestDoc.createTextNode(namespaceEntity.getNamespaceType().toString()));
        namespaceDescriptionElement.appendChild(namespaceTypeElement);
    }

    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
        ServiceBusNamespaceResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new ServiceBusNamespaceResponse();
            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 namespaceDescriptionElement2 = XmlUtility.getElementByTagNameNS(contentElement2,
                            "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                            "NamespaceDescription");
                    if (namespaceDescriptionElement2 != null) {
                        ServiceBusNamespace namespaceDescriptionInstance = new ServiceBusNamespace();
                        result.setNamespace(namespaceDescriptionInstance);

                        Element nameElement = XmlUtility.getElementByTagNameNS(namespaceDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "Name");
                        if (nameElement != null) {
                            String nameInstance;
                            nameInstance = nameElement.getTextContent();
                            namespaceDescriptionInstance.setName(nameInstance);
                        }

                        Element regionElement2 = XmlUtility.getElementByTagNameNS(namespaceDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "Region");
                        if (regionElement2 != null) {
                            String regionInstance;
                            regionInstance = regionElement2.getTextContent();
                            namespaceDescriptionInstance.setRegion(regionInstance);
                        }

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

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

                        Element acsManagementEndpointElement = XmlUtility.getElementByTagNameNS(
                                namespaceDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "AcsManagementEndpoint");
                        if (acsManagementEndpointElement != null) {
                            URI acsManagementEndpointInstance;
                            acsManagementEndpointInstance = new URI(
                                    acsManagementEndpointElement.getTextContent());
                            namespaceDescriptionInstance
                                    .setAcsManagementEndpoint(acsManagementEndpointInstance);
                        }

                        Element serviceBusEndpointElement = XmlUtility.getElementByTagNameNS(
                                namespaceDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "ServiceBusEndpoint");
                        if (serviceBusEndpointElement != null) {
                            URI serviceBusEndpointInstance;
                            serviceBusEndpointInstance = new URI(serviceBusEndpointElement.getTextContent());
                            namespaceDescriptionInstance.setServiceBusEndpoint(serviceBusEndpointInstance);
                        }

                        Element subscriptionIdElement = XmlUtility.getElementByTagNameNS(
                                namespaceDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "SubscriptionId");
                        if (subscriptionIdElement != null) {
                            String subscriptionIdInstance;
                            subscriptionIdInstance = subscriptionIdElement.getTextContent();
                            namespaceDescriptionInstance.setSubscriptionId(subscriptionIdInstance);
                        }

                        Element enabledElement = XmlUtility.getElementByTagNameNS(namespaceDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "Enabled");
                        if (enabledElement != null) {
                            boolean enabledInstance;
                            enabledInstance = DatatypeConverter
                                    .parseBoolean(enabledElement.getTextContent().toLowerCase());
                            namespaceDescriptionInstance.setEnabled(enabledInstance);
                        }

                        Element createACSNamespaceElement2 = XmlUtility.getElementByTagNameNS(
                                namespaceDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "CreateACSNamespace");
                        if (createACSNamespaceElement2 != null) {
                            boolean createACSNamespaceInstance;
                            createACSNamespaceInstance = DatatypeConverter
                                    .parseBoolean(createACSNamespaceElement2.getTextContent().toLowerCase());
                            namespaceDescriptionInstance.setCreateACSNamespace(createACSNamespaceInstance);
                        }

                        Element namespaceTypeElement2 = XmlUtility.getElementByTagNameNS(
                                namespaceDescriptionElement2,
                                "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect",
                                "NamespaceType");
                        if (namespaceTypeElement2 != null && namespaceTypeElement2.getTextContent() != null
                                && !namespaceTypeElement2.getTextContent().isEmpty()) {
                            NamespaceType namespaceTypeInstance;
                            namespaceTypeInstance = NamespaceType
                                    .valueOf(namespaceTypeElement2.getTextContent());
                            namespaceDescriptionInstance.setNamespaceType(namespaceTypeInstance);
                        }
                    }
                }
            }

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

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

From source file:com.microsoft.azure.management.storage.StorageAccountOperationsImpl.java

/**
* Returns the properties for the specified storage account including but
* not limited to name, account type, location, and account status. The
* ListKeys operation should be used to retrieve storage keys.
*
* @param resourceGroupName Required. The name of the resource group within
* the user's subscription.//from www . j  a  v a  2  s . co  m
* @param accountName Required. The name of the storage account within the
* specified resource group. Storage account names must be between 3 and 24
* characters in length and use numbers and lower-case letters only.
* @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 storage account operation response.
*/
@Override
public StorageAccountGetPropertiesResponse getProperties(String resourceGroupName, String accountName)
        throws IOException, ServiceException, URISyntaxException {
    // Validate
    if (resourceGroupName == null) {
        throw new NullPointerException("resourceGroupName");
    }
    if (accountName == null) {
        throw new NullPointerException("accountName");
    }
    if (accountName.length() < 3) {
        throw new IllegalArgumentException("accountName");
    }
    if (accountName.length() > 24) {
        throw new IllegalArgumentException("accountName");
    }
    for (char accountNameChar : accountName.toCharArray()) {
        if (Character.isLowerCase(accountNameChar) == false && Character.isDigit(accountNameChar) == false) {
            throw new IllegalArgumentException("accountName");
        }
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

/**
* Returns information about Azure SQL Database Replication Links.
*
* @param resourceGroupName Required. The name of the Resource Group to
* which the server belongs./* ww  w .j  a v a  2 s.co  m*/
* @param serverName Required. The name of the Azure SQL Server in which the
* Azure SQL Database is hosted.
* @param databaseName Required. The name of the Azure SQL Database to
* retrieve links 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 Represents the response to a List Azure Sql Database Replication
* Link request.
*/
@Override
public ReplicationLinkListResponse list(String resourceGroupName, String serverName, String databaseName)
        throws IOException, ServiceException {
    // Validate
    if (resourceGroupName == null) {
        throw new NullPointerException("resourceGroupName");
    }
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }
    if (databaseName == null) {
        throw new NullPointerException("databaseName");
    }

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

    // Construct URL
    String url = "";
    url = url + "/subscriptions/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/resourceGroups/";
    url = url + URLEncoder.encode(resourceGroupName, "UTF-8");
    url = url + "/providers/";
    url = url + "Microsoft.Sql";
    url = url + "/servers/";
    url = url + URLEncoder.encode(serverName, "UTF-8");
    url = url + "/databases/";
    url = url + URLEncoder.encode(databaseName, "UTF-8");
    url = url + "/replicationLinks";
    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
        ReplicationLinkListResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new ReplicationLinkListResponse();
            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)) {
                        ReplicationLink replicationLinkInstance = new ReplicationLink();
                        result.getReplicationLinks().add(replicationLinkInstance);

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

                            JsonNode partnerServerValue = propertiesValue.get("partnerServer");
                            if (partnerServerValue != null && partnerServerValue instanceof NullNode == false) {
                                String partnerServerInstance;
                                partnerServerInstance = partnerServerValue.getTextValue();
                                propertiesInstance.setPartnerServer(partnerServerInstance);
                            }

                            JsonNode partnerDatabaseValue = propertiesValue.get("partnerDatabase");
                            if (partnerDatabaseValue != null
                                    && partnerDatabaseValue instanceof NullNode == false) {
                                String partnerDatabaseInstance;
                                partnerDatabaseInstance = partnerDatabaseValue.getTextValue();
                                propertiesInstance.setPartnerDatabase(partnerDatabaseInstance);
                            }

                            JsonNode partnerLocationValue = propertiesValue.get("partnerLocation");
                            if (partnerLocationValue != null
                                    && partnerLocationValue instanceof NullNode == false) {
                                String partnerLocationInstance;
                                partnerLocationInstance = partnerLocationValue.getTextValue();
                                propertiesInstance.setPartnerLocation(partnerLocationInstance);
                            }

                            JsonNode roleValue = propertiesValue.get("role");
                            if (roleValue != null && roleValue instanceof NullNode == false) {
                                String roleInstance;
                                roleInstance = roleValue.getTextValue();
                                propertiesInstance.setRole(roleInstance);
                            }

                            JsonNode partnerRoleValue = propertiesValue.get("partnerRole");
                            if (partnerRoleValue != null && partnerRoleValue instanceof NullNode == false) {
                                String partnerRoleInstance;
                                partnerRoleInstance = partnerRoleValue.getTextValue();
                                propertiesInstance.setPartnerRole(partnerRoleInstance);
                            }

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

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

                            JsonNode replicationStateValue = propertiesValue.get("replicationState");
                            if (replicationStateValue != null
                                    && replicationStateValue instanceof NullNode == false) {
                                String replicationStateInstance;
                                replicationStateInstance = replicationStateValue.getTextValue();
                                propertiesInstance.setReplicationState(replicationStateInstance);
                            }
                        }

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

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

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

                        JsonNode locationValue = valueValue.get("location");
                        if (locationValue != null && locationValue instanceof NullNode == false) {
                            String locationInstance;
                            locationInstance = locationValue.getTextValue();
                            replicationLinkInstance.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();
                                replicationLinkInstance.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.resources.DeploymentOperationsImpl.java

/**
* Get a deployment./*w w  w.  j  a  v a 2  s  .  com*/
*
* @param resourceGroupName Required. The name of the resource group to get.
* The name is case insensitive.
* @param deploymentName Required. The name of the deployment.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @throws URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return Template deployment information.
*/
@Override
public DeploymentGetResult get(String resourceGroupName, String deploymentName)
        throws IOException, ServiceException, URISyntaxException {
    // Validate
    if (resourceGroupName == null) {
        throw new NullPointerException("resourceGroupName");
    }
    if (resourceGroupName != null && resourceGroupName.length() > 1000) {
        throw new IllegalArgumentException("resourceGroupName");
    }
    if (Pattern.matches("^[-\\w\\._]+$", resourceGroupName) == false) {
        throw new IllegalArgumentException("resourceGroupName");
    }
    if (deploymentName == null) {
        throw new NullPointerException("deploymentName");
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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