List of usage examples for javax.xml.bind DatatypeConverter parseDateTime
public static java.util.Calendar parseDateTime(String lexicalXSDDateTime)
Converts the string argument into a Calendar value.
From source file:com.verisign.epp.codec.gen.EPPUtil.java
/** * Decode an XML Schema timeInstant data type to a Java Date object. * // w ww. java 2 s. c o m * @param aTimeInstant * XML Schema timeInstant data type string. * @return Java Date object if <code>aTimeInstant</code> format is valid; * <code>null</code> otherwise */ public static Date decodeTimeInstant(String aTimeInstant) { Date theDate = null; try { theDate = DatatypeConverter.parseDateTime(aTimeInstant).getTime(); } catch (IllegalArgumentException ex) { cat.error("Exception decoding dataTime: " + ex); theDate = null; } return theDate; }
From source file:com.microsoft.windowsazure.management.sql.DatabaseOperationOperationsImpl.java
/** * Retrieves all of the operations that took place on a specific database. * * @param serverName Required. The name of the Azure SQL Database Server * that hosts the database./*from w w w . jav a2 s . c o m*/ * @param databaseName Required. The name of the database for which the * operations should be retrieved. * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations. * @throws ServiceException Thrown if an unexpected response is found. * @throws ParserConfigurationException Thrown if there was a serious * configuration error with the document parser. * @throws SAXException Thrown if there was an error parsing the XML * response. * @return Represents the response containing the list of database * operations for a given server or database. */ @Override public DatabaseOperationListResponse listByDatabase(String serverName, String databaseName) throws IOException, ServiceException, ParserConfigurationException, SAXException { // Validate if (serverName == null) { throw new NullPointerException("serverName"); } if (databaseName == null) { throw new NullPointerException("databaseName"); } // Tracing boolean shouldTrace = CloudTracing.getIsEnabled(); String invocationId = null; if (shouldTrace) { invocationId = Long.toString(CloudTracing.getNextInvocationId()); HashMap<String, Object> tracingParameters = new HashMap<String, Object>(); tracingParameters.put("serverName", serverName); tracingParameters.put("databaseName", databaseName); CloudTracing.enter(invocationId, this, "listByDatabaseAsync", tracingParameters); } // Construct URL String 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 + "/databaseoperations"; ArrayList<String> queryParameters = new ArrayList<String>(); queryParameters.add("databaseName=" + URLEncoder.encode(databaseName, "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 DatabaseOperationListResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_OK) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new DatabaseOperationListResponse(); 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)); DatabaseOperation serviceResourceInstance = new DatabaseOperation(); result.getDatabaseOperations().add(serviceResourceInstance); Element idElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "Id"); if (idElement != null) { String idInstance; idInstance = idElement.getTextContent(); serviceResourceInstance.setId(idInstance); } Element stateIdElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "StateId"); if (stateIdElement != null) { int stateIdInstance; stateIdInstance = DatatypeConverter.parseInt(stateIdElement.getTextContent()); serviceResourceInstance.setStateId(stateIdInstance); } Element sessionActivityIdElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "SessionActivityId"); if (sessionActivityIdElement != null) { String sessionActivityIdInstance; sessionActivityIdInstance = sessionActivityIdElement.getTextContent(); serviceResourceInstance.setSessionActivityId(sessionActivityIdInstance); } Element databaseNameElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "DatabaseName"); if (databaseNameElement != null) { String databaseNameInstance; databaseNameInstance = databaseNameElement.getTextContent(); serviceResourceInstance.setDatabaseName(databaseNameInstance); } Element percentCompleteElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "PercentComplete"); if (percentCompleteElement != null) { int percentCompleteInstance; percentCompleteInstance = DatatypeConverter .parseInt(percentCompleteElement.getTextContent()); serviceResourceInstance.setPercentComplete(percentCompleteInstance); } Element errorCodeElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "ErrorCode"); if (errorCodeElement != null) { int errorCodeInstance; errorCodeInstance = DatatypeConverter.parseInt(errorCodeElement.getTextContent()); serviceResourceInstance.setErrorCode(errorCodeInstance); } Element errorElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "Error"); if (errorElement != null) { String errorInstance; errorInstance = errorElement.getTextContent(); serviceResourceInstance.setError(errorInstance); } Element errorSeverityElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "ErrorSeverity"); if (errorSeverityElement != null) { int errorSeverityInstance; errorSeverityInstance = DatatypeConverter .parseInt(errorSeverityElement.getTextContent()); serviceResourceInstance.setErrorSeverity(errorSeverityInstance); } Element errorStateElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "ErrorState"); if (errorStateElement != null) { int errorStateInstance; errorStateInstance = DatatypeConverter.parseInt(errorStateElement.getTextContent()); serviceResourceInstance.setErrorState(errorStateInstance); } Element startTimeElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "StartTime"); if (startTimeElement != null) { Calendar startTimeInstance; startTimeInstance = DatatypeConverter.parseDateTime(startTimeElement.getTextContent()); serviceResourceInstance.setStartTime(startTimeInstance); } Element lastModifyTimeElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "LastModifyTime"); if (lastModifyTimeElement != null) { Calendar lastModifyTimeInstance; lastModifyTimeInstance = DatatypeConverter .parseDateTime(lastModifyTimeElement.getTextContent()); serviceResourceInstance.setLastModifyTime(lastModifyTimeInstance); } 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.compute.VirtualMachineExtensionOperationsImpl.java
/** * The operation to create or update the extension. * * @param resourceGroupName Required. The name of the resource group. * @param vmName Required. The name of the virtual machine where the * extension should be create or updated. * @param extensionParameters Required. Parameters supplied to the Create * Virtual Machine Extension operation./*from ww w . j a va 2 s. c o m*/ * @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 compute long running operation response. */ @Override public VirtualMachineExtensionCreateOrUpdateResponse beginCreatingOrUpdating(String resourceGroupName, String vmName, VirtualMachineExtension extensionParameters) throws IOException, ServiceException, URISyntaxException { // Validate if (resourceGroupName == null) { throw new NullPointerException("resourceGroupName"); } if (vmName == null) { throw new NullPointerException("vmName"); } if (extensionParameters == null) { throw new NullPointerException("extensionParameters"); } if (extensionParameters.getLocation() == null) { throw new NullPointerException("extensionParameters.Location"); } // Tracing boolean shouldTrace = CloudTracing.getIsEnabled(); String invocationId = null; if (shouldTrace) { invocationId = Long.toString(CloudTracing.getNextInvocationId()); HashMap<String, Object> tracingParameters = new HashMap<String, Object>(); tracingParameters.put("resourceGroupName", resourceGroupName); tracingParameters.put("vmName", vmName); tracingParameters.put("extensionParameters", extensionParameters); CloudTracing.enter(invocationId, this, "beginCreatingOrUpdatingAsync", tracingParameters); } // Construct URL String url = ""; url = url + "/subscriptions/"; if (this.getClient().getCredentials().getSubscriptionId() != null) { url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8"); } url = url + "/resourceGroups/"; url = url + URLEncoder.encode(resourceGroupName, "UTF-8"); url = url + "/providers/"; url = url + "Microsoft.Compute"; url = url + "/"; url = url + "virtualMachines"; url = url + "/"; url = url + URLEncoder.encode(vmName, "UTF-8"); url = url + "/extensions/"; if (extensionParameters.getName() != null) { url = url + URLEncoder.encode(extensionParameters.getName(), "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 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 virtualMachineExtensionJsonValue = objectMapper.createObjectNode(); requestDoc = virtualMachineExtensionJsonValue; ObjectNode propertiesValue = objectMapper.createObjectNode(); ((ObjectNode) virtualMachineExtensionJsonValue).put("properties", propertiesValue); if (extensionParameters.getPublisher() != null) { ((ObjectNode) propertiesValue).put("publisher", extensionParameters.getPublisher()); } if (extensionParameters.getExtensionType() != null) { ((ObjectNode) propertiesValue).put("type", extensionParameters.getExtensionType()); } if (extensionParameters.getTypeHandlerVersion() != null) { ((ObjectNode) propertiesValue).put("typeHandlerVersion", extensionParameters.getTypeHandlerVersion()); } ((ObjectNode) propertiesValue).put("autoUpgradeMinorVersion", extensionParameters.isAutoUpgradeMinorVersion()); if (extensionParameters.getSettings() != null) { ((ObjectNode) propertiesValue).put("settings", objectMapper.readTree(extensionParameters.getSettings())); } if (extensionParameters.getProtectedSettings() != null) { ((ObjectNode) propertiesValue).put("protectedSettings", objectMapper.readTree(extensionParameters.getProtectedSettings())); } if (extensionParameters.getProvisioningState() != null) { ((ObjectNode) propertiesValue).put("provisioningState", extensionParameters.getProvisioningState()); } if (extensionParameters.getInstanceView() != null) { ObjectNode instanceViewValue = objectMapper.createObjectNode(); ((ObjectNode) propertiesValue).put("instanceView", instanceViewValue); if (extensionParameters.getInstanceView().getName() != null) { ((ObjectNode) instanceViewValue).put("name", extensionParameters.getInstanceView().getName()); } if (extensionParameters.getInstanceView().getExtensionType() != null) { ((ObjectNode) instanceViewValue).put("type", extensionParameters.getInstanceView().getExtensionType()); } if (extensionParameters.getInstanceView().getTypeHandlerVersion() != null) { ((ObjectNode) instanceViewValue).put("typeHandlerVersion", extensionParameters.getInstanceView().getTypeHandlerVersion()); } if (extensionParameters.getInstanceView().getSubStatuses() != null) { if (extensionParameters.getInstanceView().getSubStatuses() instanceof LazyCollection == false || ((LazyCollection) extensionParameters.getInstanceView().getSubStatuses()) .isInitialized()) { ArrayNode substatusesArray = objectMapper.createArrayNode(); for (InstanceViewStatus substatusesItem : extensionParameters.getInstanceView() .getSubStatuses()) { ObjectNode instanceViewStatusValue = objectMapper.createObjectNode(); substatusesArray.add(instanceViewStatusValue); if (substatusesItem.getCode() != null) { ((ObjectNode) instanceViewStatusValue).put("code", substatusesItem.getCode()); } if (substatusesItem.getLevel() != null) { ((ObjectNode) instanceViewStatusValue).put("level", substatusesItem.getLevel()); } if (substatusesItem.getDisplayStatus() != null) { ((ObjectNode) instanceViewStatusValue).put("displayStatus", substatusesItem.getDisplayStatus()); } if (substatusesItem.getMessage() != null) { ((ObjectNode) instanceViewStatusValue).put("message", substatusesItem.getMessage()); } if (substatusesItem.getTime() != null) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'"); simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); ((ObjectNode) instanceViewStatusValue).put("time", simpleDateFormat.format(substatusesItem.getTime().getTime())); } } ((ObjectNode) instanceViewValue).put("substatuses", substatusesArray); } } if (extensionParameters.getInstanceView().getStatuses() != null) { ArrayNode statusesArray = objectMapper.createArrayNode(); for (InstanceViewStatus statusesItem : extensionParameters.getInstanceView().getStatuses()) { ObjectNode instanceViewStatusValue2 = objectMapper.createObjectNode(); statusesArray.add(instanceViewStatusValue2); if (statusesItem.getCode() != null) { ((ObjectNode) instanceViewStatusValue2).put("code", statusesItem.getCode()); } if (statusesItem.getLevel() != null) { ((ObjectNode) instanceViewStatusValue2).put("level", statusesItem.getLevel()); } if (statusesItem.getDisplayStatus() != null) { ((ObjectNode) instanceViewStatusValue2).put("displayStatus", statusesItem.getDisplayStatus()); } if (statusesItem.getMessage() != null) { ((ObjectNode) instanceViewStatusValue2).put("message", statusesItem.getMessage()); } if (statusesItem.getTime() != null) { SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'"); simpleDateFormat2.setTimeZone(TimeZone.getTimeZone("UTC")); ((ObjectNode) instanceViewStatusValue2).put("time", simpleDateFormat2.format(statusesItem.getTime().getTime())); } } ((ObjectNode) instanceViewValue).put("statuses", statusesArray); } } if (extensionParameters.getId() != null) { ((ObjectNode) virtualMachineExtensionJsonValue).put("id", extensionParameters.getId()); } if (extensionParameters.getName() != null) { ((ObjectNode) virtualMachineExtensionJsonValue).put("name", extensionParameters.getName()); } if (extensionParameters.getType() != null) { ((ObjectNode) virtualMachineExtensionJsonValue).put("type", extensionParameters.getType()); } ((ObjectNode) virtualMachineExtensionJsonValue).put("location", extensionParameters.getLocation()); if (extensionParameters.getTags() != null) { ObjectNode tagsDictionary = objectMapper.createObjectNode(); for (Map.Entry<String, String> entry : extensionParameters.getTags().entrySet()) { String tagsKey = entry.getKey(); String tagsValue = entry.getValue(); ((ObjectNode) tagsDictionary).put(tagsKey, tagsValue); } ((ObjectNode) virtualMachineExtensionJsonValue).put("tags", tagsDictionary); } StringWriter stringWriter = new StringWriter(); objectMapper.writeValue(stringWriter, requestDoc); requestContent = stringWriter.toString(); StringEntity entity = new StringEntity(requestContent); httpRequest.setEntity(entity); httpRequest.setHeader("Content-Type", "application/json"); // Send Request HttpResponse httpResponse = null; try { if (shouldTrace) { CloudTracing.sendRequest(invocationId, httpRequest); } httpResponse = this.getClient().getHttpClient().execute(httpRequest); if (shouldTrace) { CloudTracing.receiveResponse(invocationId, httpResponse); } int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED) { ServiceException ex = ServiceException.createFromJson(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result VirtualMachineExtensionCreateOrUpdateResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new VirtualMachineExtensionCreateOrUpdateResponse(); 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) { VirtualMachineExtension virtualMachineExtensionInstance = new VirtualMachineExtension(); result.setVirtualMachineExtension(virtualMachineExtensionInstance); JsonNode propertiesValue2 = responseDoc.get("properties"); if (propertiesValue2 != null && propertiesValue2 instanceof NullNode == false) { JsonNode publisherValue = propertiesValue2.get("publisher"); if (publisherValue != null && publisherValue instanceof NullNode == false) { String publisherInstance; publisherInstance = publisherValue.getTextValue(); virtualMachineExtensionInstance.setPublisher(publisherInstance); } JsonNode typeValue = propertiesValue2.get("type"); if (typeValue != null && typeValue instanceof NullNode == false) { String typeInstance; typeInstance = typeValue.getTextValue(); virtualMachineExtensionInstance.setExtensionType(typeInstance); } JsonNode typeHandlerVersionValue = propertiesValue2.get("typeHandlerVersion"); if (typeHandlerVersionValue != null && typeHandlerVersionValue instanceof NullNode == false) { String typeHandlerVersionInstance; typeHandlerVersionInstance = typeHandlerVersionValue.getTextValue(); virtualMachineExtensionInstance.setTypeHandlerVersion(typeHandlerVersionInstance); } JsonNode autoUpgradeMinorVersionValue = propertiesValue2.get("autoUpgradeMinorVersion"); if (autoUpgradeMinorVersionValue != null && autoUpgradeMinorVersionValue instanceof NullNode == false) { boolean autoUpgradeMinorVersionInstance; autoUpgradeMinorVersionInstance = autoUpgradeMinorVersionValue.getBooleanValue(); virtualMachineExtensionInstance .setAutoUpgradeMinorVersion(autoUpgradeMinorVersionInstance); } JsonNode settingsValue = propertiesValue2.get("settings"); if (settingsValue != null && settingsValue instanceof NullNode == false) { String settingsInstance; settingsInstance = settingsValue.getTextValue(); virtualMachineExtensionInstance.setSettings(settingsInstance); } JsonNode protectedSettingsValue = propertiesValue2.get("protectedSettings"); if (protectedSettingsValue != null && protectedSettingsValue instanceof NullNode == false) { String protectedSettingsInstance; protectedSettingsInstance = protectedSettingsValue.getTextValue(); virtualMachineExtensionInstance.setProtectedSettings(protectedSettingsInstance); } JsonNode provisioningStateValue = propertiesValue2.get("provisioningState"); if (provisioningStateValue != null && provisioningStateValue instanceof NullNode == false) { String provisioningStateInstance; provisioningStateInstance = provisioningStateValue.getTextValue(); virtualMachineExtensionInstance.setProvisioningState(provisioningStateInstance); } JsonNode instanceViewValue2 = propertiesValue2.get("instanceView"); if (instanceViewValue2 != null && instanceViewValue2 instanceof NullNode == false) { VirtualMachineExtensionInstanceView instanceViewInstance = new VirtualMachineExtensionInstanceView(); virtualMachineExtensionInstance.setInstanceView(instanceViewInstance); JsonNode nameValue = instanceViewValue2.get("name"); if (nameValue != null && nameValue instanceof NullNode == false) { String nameInstance; nameInstance = nameValue.getTextValue(); instanceViewInstance.setName(nameInstance); } JsonNode typeValue2 = instanceViewValue2.get("type"); if (typeValue2 != null && typeValue2 instanceof NullNode == false) { String typeInstance2; typeInstance2 = typeValue2.getTextValue(); instanceViewInstance.setExtensionType(typeInstance2); } JsonNode typeHandlerVersionValue2 = instanceViewValue2.get("typeHandlerVersion"); if (typeHandlerVersionValue2 != null && typeHandlerVersionValue2 instanceof NullNode == false) { String typeHandlerVersionInstance2; typeHandlerVersionInstance2 = typeHandlerVersionValue2.getTextValue(); instanceViewInstance.setTypeHandlerVersion(typeHandlerVersionInstance2); } JsonNode substatusesArray2 = instanceViewValue2.get("substatuses"); if (substatusesArray2 != null && substatusesArray2 instanceof NullNode == false) { for (JsonNode substatusesValue : ((ArrayNode) substatusesArray2)) { InstanceViewStatus instanceViewStatusInstance = new InstanceViewStatus(); instanceViewInstance.getSubStatuses().add(instanceViewStatusInstance); JsonNode codeValue = substatusesValue.get("code"); if (codeValue != null && codeValue instanceof NullNode == false) { String codeInstance; codeInstance = codeValue.getTextValue(); instanceViewStatusInstance.setCode(codeInstance); } JsonNode levelValue = substatusesValue.get("level"); if (levelValue != null && levelValue instanceof NullNode == false) { String levelInstance; levelInstance = levelValue.getTextValue(); instanceViewStatusInstance.setLevel(levelInstance); } JsonNode displayStatusValue = substatusesValue.get("displayStatus"); if (displayStatusValue != null && displayStatusValue instanceof NullNode == false) { String displayStatusInstance; displayStatusInstance = displayStatusValue.getTextValue(); instanceViewStatusInstance.setDisplayStatus(displayStatusInstance); } JsonNode messageValue = substatusesValue.get("message"); if (messageValue != null && messageValue instanceof NullNode == false) { String messageInstance; messageInstance = messageValue.getTextValue(); instanceViewStatusInstance.setMessage(messageInstance); } JsonNode timeValue = substatusesValue.get("time"); if (timeValue != null && timeValue instanceof NullNode == false) { Calendar timeInstance; timeInstance = DatatypeConverter.parseDateTime(timeValue.getTextValue()); instanceViewStatusInstance.setTime(timeInstance); } } } JsonNode statusesArray2 = instanceViewValue2.get("statuses"); if (statusesArray2 != null && statusesArray2 instanceof NullNode == false) { for (JsonNode statusesValue : ((ArrayNode) statusesArray2)) { InstanceViewStatus instanceViewStatusInstance2 = new InstanceViewStatus(); instanceViewInstance.getStatuses().add(instanceViewStatusInstance2); JsonNode codeValue2 = statusesValue.get("code"); if (codeValue2 != null && codeValue2 instanceof NullNode == false) { String codeInstance2; codeInstance2 = codeValue2.getTextValue(); instanceViewStatusInstance2.setCode(codeInstance2); } JsonNode levelValue2 = statusesValue.get("level"); if (levelValue2 != null && levelValue2 instanceof NullNode == false) { String levelInstance2; levelInstance2 = levelValue2.getTextValue(); instanceViewStatusInstance2.setLevel(levelInstance2); } JsonNode displayStatusValue2 = statusesValue.get("displayStatus"); if (displayStatusValue2 != null && displayStatusValue2 instanceof NullNode == false) { String displayStatusInstance2; displayStatusInstance2 = displayStatusValue2.getTextValue(); instanceViewStatusInstance2.setDisplayStatus(displayStatusInstance2); } JsonNode messageValue2 = statusesValue.get("message"); if (messageValue2 != null && messageValue2 instanceof NullNode == false) { String messageInstance2; messageInstance2 = messageValue2.getTextValue(); instanceViewStatusInstance2.setMessage(messageInstance2); } JsonNode timeValue2 = statusesValue.get("time"); if (timeValue2 != null && timeValue2 instanceof NullNode == false) { Calendar timeInstance2; timeInstance2 = DatatypeConverter.parseDateTime(timeValue2.getTextValue()); instanceViewStatusInstance2.setTime(timeInstance2); } } } } } JsonNode idValue = responseDoc.get("id"); if (idValue != null && idValue instanceof NullNode == false) { String idInstance; idInstance = idValue.getTextValue(); virtualMachineExtensionInstance.setId(idInstance); } JsonNode nameValue2 = responseDoc.get("name"); if (nameValue2 != null && nameValue2 instanceof NullNode == false) { String nameInstance2; nameInstance2 = nameValue2.getTextValue(); virtualMachineExtensionInstance.setName(nameInstance2); } JsonNode typeValue3 = responseDoc.get("type"); if (typeValue3 != null && typeValue3 instanceof NullNode == false) { String typeInstance3; typeInstance3 = typeValue3.getTextValue(); virtualMachineExtensionInstance.setType(typeInstance3); } JsonNode locationValue = responseDoc.get("location"); if (locationValue != null && locationValue instanceof NullNode == false) { String locationInstance; locationInstance = locationValue.getTextValue(); virtualMachineExtensionInstance.setLocation(locationInstance); } JsonNode tagsSequenceElement = ((JsonNode) responseDoc.get("tags")); if (tagsSequenceElement != null && tagsSequenceElement instanceof NullNode == false) { Iterator<Map.Entry<String, JsonNode>> itr = tagsSequenceElement.getFields(); while (itr.hasNext()) { Map.Entry<String, JsonNode> property = itr.next(); String tagsKey2 = property.getKey(); String tagsValue2 = property.getValue().getTextValue(); virtualMachineExtensionInstance.getTags().put(tagsKey2, tagsValue2); } } } } result.setStatusCode(statusCode); if (httpResponse.getHeaders("Azure-AsyncOperation").length > 0) { result.setAzureAsyncOperation(httpResponse.getFirstHeader("Azure-AsyncOperation").getValue()); } 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.DacOperationsImpl.java
/** * Gets the status of the import or export operation in the specified server * with the corresponding request ID. The request ID is provided in the * responses of the import or export operation. * * @param serverName Required. The name of the server in which the import or * export operation is taking place./*from w w w . j av a 2 s. c o m*/ * @param fullyQualifiedServerName Required. The fully qualified domain name * of the Azure SQL Database Server where the operation is taking place. * Example: a9s7f7s9d3.database.windows.net * @param username Required. The administrator username for the Azure SQL * Database Server. * @param password Required. The administrator password for the Azure SQL * Database Server. * @param requestId Required. The request ID of the operation being queried. * The request ID is obtained from the responses of the import and export * operations. * @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 Represents a list of import or export status values returned from * GetStatus. */ @Override public DacGetStatusResponse getStatus(String serverName, String fullyQualifiedServerName, String username, String password, String requestId) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException { // Validate if (serverName == null) { throw new NullPointerException("serverName"); } if (fullyQualifiedServerName == null) { throw new NullPointerException("fullyQualifiedServerName"); } if (username == null) { throw new NullPointerException("username"); } if (password == null) { throw new NullPointerException("password"); } if (requestId == null) { throw new NullPointerException("requestId"); } // 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("fullyQualifiedServerName", fullyQualifiedServerName); tracingParameters.put("username", username); tracingParameters.put("password", password); tracingParameters.put("requestId", requestId); CloudTracing.enter(invocationId, this, "getStatusAsync", 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 + "/DacOperations/Status"; ArrayList<String> queryParameters = new ArrayList<String>(); queryParameters.add("servername=" + URLEncoder.encode(fullyQualifiedServerName, "UTF-8")); queryParameters.add("username=" + URLEncoder.encode(username, "UTF-8")); queryParameters.add("password=" + URLEncoder.encode(password, "UTF-8")); queryParameters.add("reqId=" + URLEncoder.encode(requestId, "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 DacGetStatusResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_OK) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new DacGetStatusResponse(); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); Element arrayOfStatusInfoElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "ArrayOfStatusInfo"); if (arrayOfStatusInfoElement != null) { if (arrayOfStatusInfoElement != null) { for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility .getElementsByTagNameNS(arrayOfStatusInfoElement, "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "StatusInfo") .size(); i1 = i1 + 1) { org.w3c.dom.Element statusInfoElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility .getElementsByTagNameNS(arrayOfStatusInfoElement, "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "StatusInfo") .get(i1)); StatusInfo statusInfoInstance = new StatusInfo(); result.getStatusInfoList().add(statusInfoInstance); Element blobUriElement = XmlUtility.getElementByTagNameNS(statusInfoElement, "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "BlobUri"); if (blobUriElement != null) { URI blobUriInstance; blobUriInstance = new URI(blobUriElement.getTextContent()); statusInfoInstance.setBlobUri(blobUriInstance); } Element databaseNameElement = XmlUtility.getElementByTagNameNS(statusInfoElement, "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "DatabaseName"); if (databaseNameElement != null) { String databaseNameInstance; databaseNameInstance = databaseNameElement.getTextContent(); statusInfoInstance.setDatabaseName(databaseNameInstance); } Element errorMessageElement = XmlUtility.getElementByTagNameNS(statusInfoElement, "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "ErrorMessage"); if (errorMessageElement != null) { boolean isNil = false; Attr nilAttribute = errorMessageElement .getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); if (nilAttribute != null) { isNil = "true".equals(nilAttribute.getValue()); } if (isNil == false) { String errorMessageInstance; errorMessageInstance = errorMessageElement.getTextContent(); statusInfoInstance.setErrorMessage(errorMessageInstance); } } Element lastModifiedTimeElement = XmlUtility.getElementByTagNameNS(statusInfoElement, "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "LastModifiedTime"); if (lastModifiedTimeElement != null) { Calendar lastModifiedTimeInstance; lastModifiedTimeInstance = DatatypeConverter .parseDateTime(lastModifiedTimeElement.getTextContent()); statusInfoInstance.setLastModifiedTime(lastModifiedTimeInstance); } Element queuedTimeElement = XmlUtility.getElementByTagNameNS(statusInfoElement, "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "QueuedTime"); if (queuedTimeElement != null) { Calendar queuedTimeInstance; queuedTimeInstance = DatatypeConverter .parseDateTime(queuedTimeElement.getTextContent()); statusInfoInstance.setQueuedTime(queuedTimeInstance); } Element requestIdElement = XmlUtility.getElementByTagNameNS(statusInfoElement, "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "RequestId"); if (requestIdElement != null) { String requestIdInstance; requestIdInstance = requestIdElement.getTextContent(); statusInfoInstance.setRequestId(requestIdInstance); } Element requestTypeElement = XmlUtility.getElementByTagNameNS(statusInfoElement, "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "RequestType"); if (requestTypeElement != null) { String requestTypeInstance; requestTypeInstance = requestTypeElement.getTextContent(); statusInfoInstance.setRequestType(requestTypeInstance); } Element serverNameElement = XmlUtility.getElementByTagNameNS(statusInfoElement, "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "ServerName"); if (serverNameElement != null) { String serverNameInstance; serverNameInstance = serverNameElement.getTextContent(); statusInfoInstance.setServerName(serverNameInstance); } Element statusElement = XmlUtility.getElementByTagNameNS(statusInfoElement, "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "Status"); if (statusElement != null) { String statusInstance; statusInstance = statusElement.getTextContent(); statusInfoInstance.setStatus(statusInstance); } } } } } result.setStatusCode(statusCode); if (httpResponse.getHeaders("x-ms-request-id").length > 0) { result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); } if (shouldTrace) { CloudTracing.exit(invocationId, result); } return result; } finally { if (httpResponse != null && httpResponse.getEntity() != null) { httpResponse.getEntity().getContent().close(); } } }
From source file:com.microsoft.azure.management.compute.ComputeManagementClientImpl.java
/** * The Get Operation Status operation returns the status of the specified * operation. After calling an asynchronous operation, you can call * GetLongRunningOperationStatus to determine whether the operation has * succeeded, failed, or is still in progress. * * @param operationStatusLink Required. Location value returned by the Begin * operation.// ww w . ja v a 2 s . c o m * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations. * @throws ServiceException Thrown if an unexpected response is found. * @return The Compute service response for long-running operations. */ @Override public ComputeLongRunningOperationResponse getLongRunningOperationStatus(String operationStatusLink) throws IOException, ServiceException { // Validate if (operationStatusLink == null) { throw new NullPointerException("operationStatusLink"); } // 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("operationStatusLink", operationStatusLink); CloudTracing.enter(invocationId, this, "getLongRunningOperationStatusAsync", tracingParameters); } // Construct URL String url = ""; url = url + operationStatusLink; 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.getHttpClient().execute(httpRequest); if (shouldTrace) { CloudTracing.receiveResponse(invocationId, httpResponse); } int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_ACCEPTED) { ServiceException ex = ServiceException.createFromJson(httpRequest, null, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result ComputeLongRunningOperationResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_ACCEPTED) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new ComputeLongRunningOperationResponse(); 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 operationIdValue = responseDoc.get("operationId"); if (operationIdValue != null && operationIdValue instanceof NullNode == false) { String operationIdInstance; operationIdInstance = operationIdValue.getTextValue(); result.setTrackingOperationId(operationIdInstance); } JsonNode statusValue = responseDoc.get("status"); if (statusValue != null && statusValue instanceof NullNode == false) { ComputeOperationStatus statusInstance; statusInstance = Enum.valueOf(ComputeOperationStatus.class, statusValue.getTextValue()); result.setStatus(statusInstance); } JsonNode startTimeValue = responseDoc.get("startTime"); if (startTimeValue != null && startTimeValue instanceof NullNode == false) { Calendar startTimeInstance; startTimeInstance = DatatypeConverter.parseDateTime(startTimeValue.getTextValue()); result.setStartTime(startTimeInstance); } JsonNode endTimeValue = responseDoc.get("endTime"); if (endTimeValue != null && endTimeValue instanceof NullNode == false) { Calendar endTimeInstance; endTimeInstance = DatatypeConverter.parseDateTime(endTimeValue.getTextValue()); result.setEndTime(endTimeInstance); } JsonNode propertiesValue = responseDoc.get("properties"); if (propertiesValue != null && propertiesValue instanceof NullNode == false) { JsonNode outputValue = propertiesValue.get("output"); if (outputValue != null && outputValue instanceof NullNode == false) { String outputInstance; outputInstance = outputValue.getTextValue(); result.setOutput(outputInstance); } } JsonNode errorValue = responseDoc.get("error"); if (errorValue != null && errorValue instanceof NullNode == false) { ApiError errorInstance = new ApiError(); result.setError(errorInstance); JsonNode detailsArray = errorValue.get("details"); if (detailsArray != null && detailsArray instanceof NullNode == false) { for (JsonNode detailsValue : ((ArrayNode) detailsArray)) { ApiErrorBase apiErrorBaseInstance = new ApiErrorBase(); errorInstance.getDetails().add(apiErrorBaseInstance); JsonNode codeValue = detailsValue.get("code"); if (codeValue != null && codeValue instanceof NullNode == false) { String codeInstance; codeInstance = codeValue.getTextValue(); apiErrorBaseInstance.setCode(codeInstance); } JsonNode targetValue = detailsValue.get("target"); if (targetValue != null && targetValue instanceof NullNode == false) { String targetInstance; targetInstance = targetValue.getTextValue(); apiErrorBaseInstance.setTarget(targetInstance); } JsonNode messageValue = detailsValue.get("message"); if (messageValue != null && messageValue instanceof NullNode == false) { String messageInstance; messageInstance = messageValue.getTextValue(); apiErrorBaseInstance.setMessage(messageInstance); } } } JsonNode innererrorValue = errorValue.get("innererror"); if (innererrorValue != null && innererrorValue instanceof NullNode == false) { InnerError innererrorInstance = new InnerError(); errorInstance.setInnerError(innererrorInstance); JsonNode exceptiontypeValue = innererrorValue.get("exceptiontype"); if (exceptiontypeValue != null && exceptiontypeValue instanceof NullNode == false) { String exceptiontypeInstance; exceptiontypeInstance = exceptiontypeValue.getTextValue(); innererrorInstance.setExceptionType(exceptiontypeInstance); } JsonNode errordetailValue = innererrorValue.get("errordetail"); if (errordetailValue != null && errordetailValue instanceof NullNode == false) { String errordetailInstance; errordetailInstance = errordetailValue.getTextValue(); innererrorInstance.setErrorDetail(errordetailInstance); } } JsonNode codeValue2 = errorValue.get("code"); if (codeValue2 != null && codeValue2 instanceof NullNode == false) { String codeInstance2; codeInstance2 = codeValue2.getTextValue(); errorInstance.setCode(codeInstance2); } JsonNode targetValue2 = errorValue.get("target"); if (targetValue2 != null && targetValue2 instanceof NullNode == false) { String targetInstance2; targetInstance2 = targetValue2.getTextValue(); errorInstance.setTarget(targetInstance2); } JsonNode messageValue2 = errorValue.get("message"); if (messageValue2 != null && messageValue2 instanceof NullNode == false) { String messageInstance2; messageInstance2 = messageValue2.getTextValue(); errorInstance.setMessage(messageInstance2); } } } } 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.AffinityGroupOperationsImpl.java
/** * The Get Affinity Group Properties operation returns the system properties * associated with the specified affinity group. (see * http://msdn.microsoft.com/en-us/library/windowsazure/ee460789.aspx for * more information)/* ww w . j a v a 2 s. c om*/ * * @param affinityGroupName Required. The name of the desired affinity group * as returned by the name element of the List Affinity Groups operation. * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations. * @throws ServiceException Thrown if an unexpected response is found. * @throws ParserConfigurationException Thrown if there was a serious * configuration error with the document parser. * @throws SAXException Thrown if there was an error parsing the XML * response. * @throws URISyntaxException Thrown if there was an error parsing a URI in * the response. * @return The Get Affinity Group operation response. */ @Override public AffinityGroupGetResponse get(String affinityGroupName) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException { // Validate if (affinityGroupName == null) { throw new NullPointerException("affinityGroupName"); } // 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("affinityGroupName", affinityGroupName); 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 + "/affinitygroups/"; url = url + URLEncoder.encode(affinityGroupName, "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", "2014-10-01"); // Send Request HttpResponse httpResponse = null; try { if (shouldTrace) { CloudTracing.sendRequest(invocationId, httpRequest); } httpResponse = this.getClient().getHttpClient().execute(httpRequest); if (shouldTrace) { CloudTracing.receiveResponse(invocationId, httpResponse); } int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result AffinityGroupGetResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_OK) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new AffinityGroupGetResponse(); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); Element affinityGroupElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "AffinityGroup"); if (affinityGroupElement != null) { Element nameElement = XmlUtility.getElementByTagNameNS(affinityGroupElement, "http://schemas.microsoft.com/windowsazure", "Name"); if (nameElement != null) { String nameInstance; nameInstance = nameElement.getTextContent(); result.setName(nameInstance); } Element labelElement = XmlUtility.getElementByTagNameNS(affinityGroupElement, "http://schemas.microsoft.com/windowsazure", "Label"); if (labelElement != null) { String labelInstance; labelInstance = labelElement.getTextContent() != null ? new String(Base64.decode(labelElement.getTextContent())) : null; result.setLabel(labelInstance); } Element descriptionElement = XmlUtility.getElementByTagNameNS(affinityGroupElement, "http://schemas.microsoft.com/windowsazure", "Description"); if (descriptionElement != null) { String descriptionInstance; descriptionInstance = descriptionElement.getTextContent(); result.setDescription(descriptionInstance); } Element locationElement = XmlUtility.getElementByTagNameNS(affinityGroupElement, "http://schemas.microsoft.com/windowsazure", "Location"); if (locationElement != null) { String locationInstance; locationInstance = locationElement.getTextContent(); result.setLocation(locationInstance); } Element hostedServicesSequenceElement = XmlUtility.getElementByTagNameNS(affinityGroupElement, "http://schemas.microsoft.com/windowsazure", "HostedServices"); if (hostedServicesSequenceElement != null) { for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility .getElementsByTagNameNS(hostedServicesSequenceElement, "http://schemas.microsoft.com/windowsazure", "HostedService") .size(); i1 = i1 + 1) { org.w3c.dom.Element hostedServicesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility .getElementsByTagNameNS(hostedServicesSequenceElement, "http://schemas.microsoft.com/windowsazure", "HostedService") .get(i1)); AffinityGroupGetResponse.HostedServiceReference hostedServiceInstance = new AffinityGroupGetResponse.HostedServiceReference(); result.getHostedServices().add(hostedServiceInstance); Element urlElement = XmlUtility.getElementByTagNameNS(hostedServicesElement, "http://schemas.microsoft.com/windowsazure", "Url"); if (urlElement != null) { URI urlInstance; urlInstance = new URI(urlElement.getTextContent()); hostedServiceInstance.setUri(urlInstance); } Element serviceNameElement = XmlUtility.getElementByTagNameNS(hostedServicesElement, "http://schemas.microsoft.com/windowsazure", "ServiceName"); if (serviceNameElement != null) { String serviceNameInstance; serviceNameInstance = serviceNameElement.getTextContent(); hostedServiceInstance.setServiceName(serviceNameInstance); } } } Element storageServicesSequenceElement = XmlUtility.getElementByTagNameNS(affinityGroupElement, "http://schemas.microsoft.com/windowsazure", "StorageServices"); if (storageServicesSequenceElement != null) { for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility .getElementsByTagNameNS(storageServicesSequenceElement, "http://schemas.microsoft.com/windowsazure", "StorageService") .size(); i2 = i2 + 1) { org.w3c.dom.Element storageServicesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility .getElementsByTagNameNS(storageServicesSequenceElement, "http://schemas.microsoft.com/windowsazure", "StorageService") .get(i2)); AffinityGroupGetResponse.StorageServiceReference storageServiceInstance = new AffinityGroupGetResponse.StorageServiceReference(); result.getStorageServices().add(storageServiceInstance); Element urlElement2 = XmlUtility.getElementByTagNameNS(storageServicesElement, "http://schemas.microsoft.com/windowsazure", "Url"); if (urlElement2 != null) { URI urlInstance2; urlInstance2 = new URI(urlElement2.getTextContent()); storageServiceInstance.setUri(urlInstance2); } Element serviceNameElement2 = XmlUtility.getElementByTagNameNS(storageServicesElement, "http://schemas.microsoft.com/windowsazure", "ServiceName"); if (serviceNameElement2 != null) { String serviceNameInstance2; serviceNameInstance2 = serviceNameElement2.getTextContent(); storageServiceInstance.setServiceName(serviceNameInstance2); } } } Element capabilitiesSequenceElement = XmlUtility.getElementByTagNameNS(affinityGroupElement, "http://schemas.microsoft.com/windowsazure", "Capabilities"); if (capabilitiesSequenceElement != null) { for (int i3 = 0; i3 < com.microsoft.windowsazure.core.utils.XmlUtility .getElementsByTagNameNS(capabilitiesSequenceElement, "http://schemas.microsoft.com/windowsazure", "Capability") .size(); i3 = i3 + 1) { org.w3c.dom.Element capabilitiesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility .getElementsByTagNameNS(capabilitiesSequenceElement, "http://schemas.microsoft.com/windowsazure", "Capability") .get(i3)); result.getCapabilities().add(capabilitiesElement.getTextContent()); } } Element createdTimeElement = XmlUtility.getElementByTagNameNS(affinityGroupElement, "http://schemas.microsoft.com/windowsazure", "CreatedTime"); if (createdTimeElement != null && createdTimeElement.getTextContent() != null && !createdTimeElement.getTextContent().isEmpty()) { Calendar createdTimeInstance; createdTimeInstance = DatatypeConverter.parseDateTime(createdTimeElement.getTextContent()); result.setCreatedTime(createdTimeInstance); } Element computeCapabilitiesElement = XmlUtility.getElementByTagNameNS(affinityGroupElement, "http://schemas.microsoft.com/windowsazure", "ComputeCapabilities"); if (computeCapabilitiesElement != null) { ComputeCapabilities computeCapabilitiesInstance = new ComputeCapabilities(); result.setComputeCapabilities(computeCapabilitiesInstance); Element virtualMachinesRoleSizesSequenceElement = XmlUtility.getElementByTagNameNS( computeCapabilitiesElement, "http://schemas.microsoft.com/windowsazure", "VirtualMachinesRoleSizes"); if (virtualMachinesRoleSizesSequenceElement != null) { for (int i4 = 0; i4 < com.microsoft.windowsazure.core.utils.XmlUtility .getElementsByTagNameNS(virtualMachinesRoleSizesSequenceElement, "http://schemas.microsoft.com/windowsazure", "RoleSize") .size(); i4 = i4 + 1) { org.w3c.dom.Element virtualMachinesRoleSizesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility .getElementsByTagNameNS(virtualMachinesRoleSizesSequenceElement, "http://schemas.microsoft.com/windowsazure", "RoleSize") .get(i4)); computeCapabilitiesInstance.getVirtualMachinesRoleSizes() .add(virtualMachinesRoleSizesElement.getTextContent()); } } Element webWorkerRoleSizesSequenceElement = XmlUtility.getElementByTagNameNS( computeCapabilitiesElement, "http://schemas.microsoft.com/windowsazure", "WebWorkerRoleSizes"); if (webWorkerRoleSizesSequenceElement != null) { for (int i5 = 0; i5 < com.microsoft.windowsazure.core.utils.XmlUtility .getElementsByTagNameNS(webWorkerRoleSizesSequenceElement, "http://schemas.microsoft.com/windowsazure", "RoleSize") .size(); i5 = i5 + 1) { org.w3c.dom.Element webWorkerRoleSizesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility .getElementsByTagNameNS(webWorkerRoleSizesSequenceElement, "http://schemas.microsoft.com/windowsazure", "RoleSize") .get(i5)); computeCapabilitiesInstance.getWebWorkerRoleSizes() .add(webWorkerRoleSizesElement.getTextContent()); } } } } } result.setStatusCode(statusCode); if (httpResponse.getHeaders("x-ms-request-id").length > 0) { result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); } if (shouldTrace) { CloudTracing.exit(invocationId, result); } return result; } finally { if (httpResponse != null && httpResponse.getEntity() != null) { httpResponse.getEntity().getContent().close(); } } }
From source file:com.microsoft.windowsazure.management.network.ClientRootCertificateOperationsImpl.java
/** * The List Client Root Certificates operation returns a list of all the * client root certificates that are associated with the specified virtual * network in Azure. (see/* w ww . ja v a 2 s . co m*/ * http://msdn.microsoft.com/en-us/library/windowsazure/dn205130.aspx for * more information) * * @param networkName Required. The name of the virtual network for this * gateway. * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations. * @throws ServiceException Thrown if an unexpected response is found. * @throws ParserConfigurationException Thrown if there was a serious * configuration error with the document parser. * @throws SAXException Thrown if there was an error parsing the XML * response. * @return The response for the List Client Root Certificates operation. */ @Override public ClientRootCertificateListResponse list(String networkName) throws IOException, ServiceException, ParserConfigurationException, SAXException { // Validate if (networkName == null) { throw new NullPointerException("networkName"); } // Tracing boolean shouldTrace = CloudTracing.getIsEnabled(); String invocationId = null; if (shouldTrace) { invocationId = Long.toString(CloudTracing.getNextInvocationId()); HashMap<String, Object> tracingParameters = new HashMap<String, Object>(); tracingParameters.put("networkName", networkName); CloudTracing.enter(invocationId, this, "listAsync", tracingParameters); } // Construct URL String url = ""; url = url + "/"; if (this.getClient().getCredentials().getSubscriptionId() != null) { url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8"); } url = url + "/services/networking/"; url = url + URLEncoder.encode(networkName, "UTF-8"); url = url + "/gateway/clientrootcertificates"; 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/xml"); 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 ClientRootCertificateListResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_OK) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new ClientRootCertificateListResponse(); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); Element clientRootCertificatesSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "ClientRootCertificates"); if (clientRootCertificatesSequenceElement != null) { for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility .getElementsByTagNameNS(clientRootCertificatesSequenceElement, "http://schemas.microsoft.com/windowsazure", "ClientRootCertificate") .size(); i1 = i1 + 1) { org.w3c.dom.Element clientRootCertificatesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility .getElementsByTagNameNS(clientRootCertificatesSequenceElement, "http://schemas.microsoft.com/windowsazure", "ClientRootCertificate") .get(i1)); ClientRootCertificateListResponse.ClientRootCertificate clientRootCertificateInstance = new ClientRootCertificateListResponse.ClientRootCertificate(); result.getClientRootCertificates().add(clientRootCertificateInstance); Element expirationTimeElement = XmlUtility.getElementByTagNameNS( clientRootCertificatesElement, "http://schemas.microsoft.com/windowsazure", "ExpirationTime"); if (expirationTimeElement != null) { Calendar expirationTimeInstance; expirationTimeInstance = DatatypeConverter .parseDateTime(expirationTimeElement.getTextContent()); clientRootCertificateInstance.setExpirationTime(expirationTimeInstance); } Element subjectElement = XmlUtility.getElementByTagNameNS(clientRootCertificatesElement, "http://schemas.microsoft.com/windowsazure", "Subject"); if (subjectElement != null) { String subjectInstance; subjectInstance = subjectElement.getTextContent(); clientRootCertificateInstance.setSubject(subjectInstance); } Element thumbprintElement = XmlUtility.getElementByTagNameNS(clientRootCertificatesElement, "http://schemas.microsoft.com/windowsazure", "Thumbprint"); if (thumbprintElement != null) { String thumbprintInstance; thumbprintInstance = thumbprintElement.getTextContent(); clientRootCertificateInstance.setThumbprint(thumbprintInstance); } } } } 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.DeploymentOperationOperationsImpl.java
/** * Gets a next list of deployments operations. * * @param nextLink Required. NextLink from the previous successful call to * List operation.//from ww w. j av a 2s . c o m * @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 List of deployment operations. */ @Override public DeploymentOperationsListResult listNext(String nextLink) throws IOException, ServiceException, URISyntaxException { // Validate if (nextLink == null) { throw new NullPointerException("nextLink"); } // 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("nextLink", nextLink); CloudTracing.enter(invocationId, this, "listNextAsync", tracingParameters); } // Construct URL String url = ""; url = url + nextLink; 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 DeploymentOperationsListResult result = null; // Deserialize Response if (statusCode == HttpStatus.SC_OK) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new DeploymentOperationsListResult(); 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)) { DeploymentOperation deploymentOperationInstance = new DeploymentOperation(); result.getOperations().add(deploymentOperationInstance); JsonNode idValue = valueValue.get("id"); if (idValue != null && idValue instanceof NullNode == false) { String idInstance; idInstance = idValue.getTextValue(); deploymentOperationInstance.setId(idInstance); } JsonNode operationIdValue = valueValue.get("operationId"); if (operationIdValue != null && operationIdValue instanceof NullNode == false) { String operationIdInstance; operationIdInstance = operationIdValue.getTextValue(); deploymentOperationInstance.setOperationId(operationIdInstance); } JsonNode propertiesValue = valueValue.get("properties"); if (propertiesValue != null && propertiesValue instanceof NullNode == false) { DeploymentOperationProperties propertiesInstance = new DeploymentOperationProperties(); deploymentOperationInstance.setProperties(propertiesInstance); JsonNode provisioningStateValue = propertiesValue.get("provisioningState"); if (provisioningStateValue != null && provisioningStateValue instanceof NullNode == false) { String provisioningStateInstance; provisioningStateInstance = provisioningStateValue.getTextValue(); propertiesInstance.setProvisioningState(provisioningStateInstance); } JsonNode timestampValue = propertiesValue.get("timestamp"); if (timestampValue != null && timestampValue instanceof NullNode == false) { Calendar timestampInstance; timestampInstance = DatatypeConverter .parseDateTime(timestampValue.getTextValue()); propertiesInstance.setTimestamp(timestampInstance); } JsonNode statusCodeValue = propertiesValue.get("statusCode"); if (statusCodeValue != null && statusCodeValue instanceof NullNode == false) { String statusCodeInstance; statusCodeInstance = statusCodeValue.getTextValue(); propertiesInstance.setStatusCode(statusCodeInstance); } JsonNode statusMessageValue = propertiesValue.get("statusMessage"); if (statusMessageValue != null && statusMessageValue instanceof NullNode == false) { String statusMessageInstance; statusMessageInstance = statusMessageValue.getTextValue(); propertiesInstance.setStatusMessage(statusMessageInstance); } JsonNode targetResourceValue = propertiesValue.get("targetResource"); if (targetResourceValue != null && targetResourceValue instanceof NullNode == false) { TargetResource targetResourceInstance = new TargetResource(); propertiesInstance.setTargetResource(targetResourceInstance); JsonNode idValue2 = targetResourceValue.get("id"); if (idValue2 != null && idValue2 instanceof NullNode == false) { String idInstance2; idInstance2 = idValue2.getTextValue(); targetResourceInstance.setId(idInstance2); } JsonNode resourceNameValue = targetResourceValue.get("resourceName"); if (resourceNameValue != null && resourceNameValue instanceof NullNode == false) { String resourceNameInstance; resourceNameInstance = resourceNameValue.getTextValue(); targetResourceInstance.setResourceName(resourceNameInstance); } JsonNode resourceTypeValue = targetResourceValue.get("resourceType"); if (resourceTypeValue != null && resourceTypeValue instanceof NullNode == false) { String resourceTypeInstance; resourceTypeInstance = resourceTypeValue.getTextValue(); targetResourceInstance.setResourceType(resourceTypeInstance); } } } } } JsonNode nextLinkValue = responseDoc.get("nextLink"); if (nextLinkValue != null && nextLinkValue instanceof NullNode == false) { String nextLinkInstance; nextLinkInstance = nextLinkValue.getTextValue(); result.setNextLink(nextLinkInstance); } } } result.setStatusCode(statusCode); if (httpResponse.getHeaders("x-ms-request-id").length > 0) { result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); } if (shouldTrace) { CloudTracing.exit(invocationId, result); } return result; } finally { if (httpResponse != null && httpResponse.getEntity() != null) { httpResponse.getEntity().getContent().close(); } } }
From source file:com.microsoft.azure.management.websites.WebSiteOperationsImpl.java
/** * Backups a site on-demand./*from w ww . j av a 2 s . c o m*/ * * @param resourceGroupName Required. The name of the web space. * @param webSiteName Required. The name of the web site. * @param slotName Optional. The name of the slot. * @param backupRequestEnvelope Required. A backup specification. * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations. * @throws ServiceException Thrown if an unexpected response is found. * @return The backup record created based on the backup request. */ @Override public WebSiteBackupResponse backup(String resourceGroupName, String webSiteName, String slotName, BackupRequestEnvelope backupRequestEnvelope) throws IOException, ServiceException { // Validate if (resourceGroupName == null) { throw new NullPointerException("resourceGroupName"); } if (webSiteName == null) { throw new NullPointerException("webSiteName"); } if (backupRequestEnvelope == null) { throw new NullPointerException("backupRequestEnvelope"); } if (backupRequestEnvelope.getLocation() == null) { throw new NullPointerException("backupRequestEnvelope.Location"); } // Tracing boolean shouldTrace = CloudTracing.getIsEnabled(); String invocationId = null; if (shouldTrace) { invocationId = Long.toString(CloudTracing.getNextInvocationId()); HashMap<String, Object> tracingParameters = new HashMap<String, Object>(); tracingParameters.put("resourceGroupName", resourceGroupName); tracingParameters.put("webSiteName", webSiteName); tracingParameters.put("slotName", slotName); tracingParameters.put("backupRequestEnvelope", backupRequestEnvelope); CloudTracing.enter(invocationId, this, "backupAsync", tracingParameters); } // Construct URL String url = ""; url = url + "/subscriptions/"; if (this.getClient().getCredentials().getSubscriptionId() != null) { url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8"); } url = url + "/resourceGroups/"; url = url + URLEncoder.encode(resourceGroupName, "UTF-8"); url = url + "/providers/"; url = url + "Microsoft.Web"; url = url + "/"; url = url + "sites"; url = url + "/"; url = url + URLEncoder.encode(webSiteName, "UTF-8"); if (slotName != null) { url = url + "/slots/" + URLEncoder.encode(slotName, "UTF-8"); } url = url + "/backup"; ArrayList<String> queryParameters = new ArrayList<String>(); queryParameters.add("api-version=" + "2014-06-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"); httpRequest.setHeader("x-ms-version", "2014-06-01"); // Serialize Request String requestContent = null; JsonNode requestDoc = null; ObjectMapper objectMapper = new ObjectMapper(); ObjectNode backupRequestEnvelopeValue = objectMapper.createObjectNode(); requestDoc = backupRequestEnvelopeValue; if (backupRequestEnvelope.getRequest() != null) { ObjectNode propertiesValue = objectMapper.createObjectNode(); ((ObjectNode) backupRequestEnvelopeValue).put("properties", propertiesValue); if (backupRequestEnvelope.getRequest().getBackupSchedule() != null) { ObjectNode backupScheduleValue = objectMapper.createObjectNode(); ((ObjectNode) propertiesValue).put("backupSchedule", backupScheduleValue); ((ObjectNode) backupScheduleValue).put("frequencyInterval", backupRequestEnvelope.getRequest().getBackupSchedule().getFrequencyInterval()); if (backupRequestEnvelope.getRequest().getBackupSchedule().getFrequencyUnit() != null) { ((ObjectNode) backupScheduleValue).put("frequencyUnit", backupRequestEnvelope.getRequest().getBackupSchedule().getFrequencyUnit().toString()); } ((ObjectNode) backupScheduleValue).put("keepAtLeastOneBackup", backupRequestEnvelope.getRequest().getBackupSchedule().isKeepAtLeastOneBackup()); if (backupRequestEnvelope.getRequest().getBackupSchedule().getLastExecutionTime() != null) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'"); simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); ((ObjectNode) backupScheduleValue).put("lastExecutionTime", simpleDateFormat.format(backupRequestEnvelope.getRequest().getBackupSchedule() .getLastExecutionTime().getTime())); } ((ObjectNode) backupScheduleValue).put("retentionPeriodInDays", backupRequestEnvelope.getRequest().getBackupSchedule().getRetentionPeriodInDays()); if (backupRequestEnvelope.getRequest().getBackupSchedule().getStartTime() != null) { SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'"); simpleDateFormat2.setTimeZone(TimeZone.getTimeZone("UTC")); ((ObjectNode) backupScheduleValue).put("startTime", simpleDateFormat2.format( backupRequestEnvelope.getRequest().getBackupSchedule().getStartTime().getTime())); } } if (backupRequestEnvelope.getRequest().getDatabases() != null) { if (backupRequestEnvelope.getRequest().getDatabases() instanceof LazyCollection == false || ((LazyCollection) backupRequestEnvelope.getRequest().getDatabases()).isInitialized()) { ArrayNode databasesArray = objectMapper.createArrayNode(); for (DatabaseBackupSetting databasesItem : backupRequestEnvelope.getRequest().getDatabases()) { ObjectNode databaseBackupSettingValue = objectMapper.createObjectNode(); databasesArray.add(databaseBackupSettingValue); if (databasesItem.getConnectionString() != null) { ((ObjectNode) databaseBackupSettingValue).put("connectionString", databasesItem.getConnectionString()); } if (databasesItem.getConnectionStringName() != null) { ((ObjectNode) databaseBackupSettingValue).put("connectionStringName", databasesItem.getConnectionStringName()); } if (databasesItem.getDatabaseType() != null) { ((ObjectNode) databaseBackupSettingValue).put("databaseType", databasesItem.getDatabaseType()); } if (databasesItem.getName() != null) { ((ObjectNode) databaseBackupSettingValue).put("name", databasesItem.getName()); } } ((ObjectNode) propertiesValue).put("databases", databasesArray); } } if (backupRequestEnvelope.getRequest().isEnabled() != null) { ((ObjectNode) propertiesValue).put("enabled", backupRequestEnvelope.getRequest().isEnabled()); } if (backupRequestEnvelope.getRequest().getName() != null) { ((ObjectNode) propertiesValue).put("name", backupRequestEnvelope.getRequest().getName()); } if (backupRequestEnvelope.getRequest().getStorageAccountUrl() != null) { ((ObjectNode) propertiesValue).put("storageAccountUrl", backupRequestEnvelope.getRequest().getStorageAccountUrl()); } } if (backupRequestEnvelope.getId() != null) { ((ObjectNode) backupRequestEnvelopeValue).put("id", backupRequestEnvelope.getId()); } if (backupRequestEnvelope.getName() != null) { ((ObjectNode) backupRequestEnvelopeValue).put("name", backupRequestEnvelope.getName()); } ((ObjectNode) backupRequestEnvelopeValue).put("location", backupRequestEnvelope.getLocation()); if (backupRequestEnvelope.getTags() != null) { ObjectNode tagsDictionary = objectMapper.createObjectNode(); for (Map.Entry<String, String> entry : backupRequestEnvelope.getTags().entrySet()) { String tagsKey = entry.getKey(); String tagsValue = entry.getValue(); ((ObjectNode) tagsDictionary).put(tagsKey, tagsValue); } ((ObjectNode) backupRequestEnvelopeValue).put("tags", tagsDictionary); } if (backupRequestEnvelope.getType() != null) { ((ObjectNode) backupRequestEnvelopeValue).put("type", backupRequestEnvelope.getType()); } 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 WebSiteBackupResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_OK) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new WebSiteBackupResponse(); 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) { BackupItemEnvelope backupItemInstance = new BackupItemEnvelope(); result.setBackupItem(backupItemInstance); JsonNode propertiesValue2 = responseDoc.get("properties"); if (propertiesValue2 != null && propertiesValue2 instanceof NullNode == false) { BackupItem propertiesInstance = new BackupItem(); backupItemInstance.setProperties(propertiesInstance); JsonNode storageAccountUrlValue = propertiesValue2.get("storageAccountUrl"); if (storageAccountUrlValue != null && storageAccountUrlValue instanceof NullNode == false) { String storageAccountUrlInstance; storageAccountUrlInstance = storageAccountUrlValue.getTextValue(); propertiesInstance.setStorageAccountUrl(storageAccountUrlInstance); } JsonNode blobNameValue = propertiesValue2.get("blobName"); if (blobNameValue != null && blobNameValue instanceof NullNode == false) { String blobNameInstance; blobNameInstance = blobNameValue.getTextValue(); propertiesInstance.setBlobName(blobNameInstance); } JsonNode nameValue = propertiesValue2.get("name"); if (nameValue != null && nameValue instanceof NullNode == false) { String nameInstance; nameInstance = nameValue.getTextValue(); propertiesInstance.setName(nameInstance); } JsonNode statusValue = propertiesValue2.get("status"); if (statusValue != null && statusValue instanceof NullNode == false) { BackupItemStatus statusInstance; statusInstance = Enum.valueOf(BackupItemStatus.class, statusValue.getTextValue()); propertiesInstance.setStatus(statusInstance); } JsonNode sizeInBytesValue = propertiesValue2.get("sizeInBytes"); if (sizeInBytesValue != null && sizeInBytesValue instanceof NullNode == false) { long sizeInBytesInstance; sizeInBytesInstance = sizeInBytesValue.getLongValue(); propertiesInstance.setSizeInBytes(sizeInBytesInstance); } JsonNode createdValue = propertiesValue2.get("created"); if (createdValue != null && createdValue instanceof NullNode == false) { Calendar createdInstance; createdInstance = DatatypeConverter.parseDateTime(createdValue.getTextValue()); propertiesInstance.setCreated(createdInstance); } JsonNode logValue = propertiesValue2.get("log"); if (logValue != null && logValue instanceof NullNode == false) { String logInstance; logInstance = logValue.getTextValue(); propertiesInstance.setLog(logInstance); } JsonNode databasesArray2 = propertiesValue2.get("databases"); if (databasesArray2 != null && databasesArray2 instanceof NullNode == false) { for (JsonNode databasesValue : ((ArrayNode) databasesArray2)) { DatabaseBackupSetting databaseBackupSettingInstance = new DatabaseBackupSetting(); propertiesInstance.getDatabases().add(databaseBackupSettingInstance); JsonNode connectionStringValue = databasesValue.get("connectionString"); if (connectionStringValue != null && connectionStringValue instanceof NullNode == false) { String connectionStringInstance; connectionStringInstance = connectionStringValue.getTextValue(); databaseBackupSettingInstance.setConnectionString(connectionStringInstance); } JsonNode connectionStringNameValue = databasesValue.get("connectionStringName"); if (connectionStringNameValue != null && connectionStringNameValue instanceof NullNode == false) { String connectionStringNameInstance; connectionStringNameInstance = connectionStringNameValue.getTextValue(); databaseBackupSettingInstance .setConnectionStringName(connectionStringNameInstance); } JsonNode databaseTypeValue = databasesValue.get("databaseType"); if (databaseTypeValue != null && databaseTypeValue instanceof NullNode == false) { String databaseTypeInstance; databaseTypeInstance = databaseTypeValue.getTextValue(); databaseBackupSettingInstance.setDatabaseType(databaseTypeInstance); } JsonNode nameValue2 = databasesValue.get("name"); if (nameValue2 != null && nameValue2 instanceof NullNode == false) { String nameInstance2; nameInstance2 = nameValue2.getTextValue(); databaseBackupSettingInstance.setName(nameInstance2); } } } JsonNode scheduledValue = propertiesValue2.get("scheduled"); if (scheduledValue != null && scheduledValue instanceof NullNode == false) { boolean scheduledInstance; scheduledInstance = scheduledValue.getBooleanValue(); propertiesInstance.setScheduled(scheduledInstance); } JsonNode lastRestoreTimeStampValue = propertiesValue2.get("lastRestoreTimeStamp"); if (lastRestoreTimeStampValue != null && lastRestoreTimeStampValue instanceof NullNode == false) { Calendar lastRestoreTimeStampInstance; lastRestoreTimeStampInstance = DatatypeConverter .parseDateTime(lastRestoreTimeStampValue.getTextValue()); propertiesInstance.setLastRestoreTimeStamp(lastRestoreTimeStampInstance); } JsonNode finishedTimeStampValue = propertiesValue2.get("finishedTimeStamp"); if (finishedTimeStampValue != null && finishedTimeStampValue instanceof NullNode == false) { Calendar finishedTimeStampInstance; finishedTimeStampInstance = DatatypeConverter .parseDateTime(finishedTimeStampValue.getTextValue()); propertiesInstance.setFinishedTimeStamp(finishedTimeStampInstance); } JsonNode correlationIdValue = propertiesValue2.get("correlationId"); if (correlationIdValue != null && correlationIdValue instanceof NullNode == false) { String correlationIdInstance; correlationIdInstance = correlationIdValue.getTextValue(); propertiesInstance.setCorrelationId(correlationIdInstance); } } JsonNode idValue = responseDoc.get("id"); if (idValue != null && idValue instanceof NullNode == false) { String idInstance; idInstance = idValue.getTextValue(); backupItemInstance.setId(idInstance); } JsonNode nameValue3 = responseDoc.get("name"); if (nameValue3 != null && nameValue3 instanceof NullNode == false) { String nameInstance3; nameInstance3 = nameValue3.getTextValue(); backupItemInstance.setName(nameInstance3); } JsonNode locationValue = responseDoc.get("location"); if (locationValue != null && locationValue instanceof NullNode == false) { String locationInstance; locationInstance = locationValue.getTextValue(); backupItemInstance.setLocation(locationInstance); } JsonNode tagsSequenceElement = ((JsonNode) responseDoc.get("tags")); if (tagsSequenceElement != null && tagsSequenceElement instanceof NullNode == false) { Iterator<Map.Entry<String, JsonNode>> itr = tagsSequenceElement.getFields(); while (itr.hasNext()) { Map.Entry<String, JsonNode> property = itr.next(); String tagsKey2 = property.getKey(); String tagsValue2 = property.getValue().getTextValue(); backupItemInstance.getTags().put(tagsKey2, tagsValue2); } } JsonNode typeValue = responseDoc.get("type"); if (typeValue != null && typeValue instanceof NullNode == false) { String typeInstance; typeInstance = typeValue.getTextValue(); backupItemInstance.setType(typeInstance); } } } 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.ManagementCertificateOperationsImpl.java
/** * The List Management Certificates operation lists and returns basic * information about all of the management certificates associated with the * specified subscription. Management certificates, which are also known as * subscription certificates, authenticate clients attempting to connect to * resources associated with your Azure subscription. (see * http://msdn.microsoft.com/en-us/library/windowsazure/jj154105.aspx for * more information)/*from w ww .jav a 2s .c o m*/ * * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations. * @throws ServiceException Thrown if an unexpected response is found. * @throws ParserConfigurationException Thrown if there was a serious * configuration error with the document parser. * @throws SAXException Thrown if there was an error parsing the XML * response. * @return The List Management Certificates operation response. */ @Override public ManagementCertificateListResponse list() throws IOException, ServiceException, ParserConfigurationException, SAXException { // Validate // Tracing boolean shouldTrace = CloudTracing.getIsEnabled(); String invocationId = null; if (shouldTrace) { invocationId = Long.toString(CloudTracing.getNextInvocationId()); HashMap<String, Object> tracingParameters = new HashMap<String, Object>(); CloudTracing.enter(invocationId, this, "listAsync", 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 + "/certificates"; String baseUrl = this.getClient().getBaseUri().toString(); // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl.charAt(baseUrl.length() - 1) == '/') { baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); } if (url.charAt(0) == '/') { url = url.substring(1); } url = baseUrl + "/" + url; url = url.replace(" ", "%20"); // Create HTTP transport objects HttpGet httpRequest = new HttpGet(url); // Set Headers httpRequest.setHeader("x-ms-version", "2014-10-01"); // Send Request HttpResponse httpResponse = null; try { if (shouldTrace) { CloudTracing.sendRequest(invocationId, httpRequest); } httpResponse = this.getClient().getHttpClient().execute(httpRequest); if (shouldTrace) { CloudTracing.receiveResponse(invocationId, httpResponse); } int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result ManagementCertificateListResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_OK) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new ManagementCertificateListResponse(); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); Element subscriptionCertificatesSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "SubscriptionCertificates"); if (subscriptionCertificatesSequenceElement != null) { for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility .getElementsByTagNameNS(subscriptionCertificatesSequenceElement, "http://schemas.microsoft.com/windowsazure", "SubscriptionCertificate") .size(); i1 = i1 + 1) { org.w3c.dom.Element subscriptionCertificatesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility .getElementsByTagNameNS(subscriptionCertificatesSequenceElement, "http://schemas.microsoft.com/windowsazure", "SubscriptionCertificate") .get(i1)); ManagementCertificateListResponse.SubscriptionCertificate subscriptionCertificateInstance = new ManagementCertificateListResponse.SubscriptionCertificate(); result.getSubscriptionCertificates().add(subscriptionCertificateInstance); Element subscriptionCertificatePublicKeyElement = XmlUtility.getElementByTagNameNS( subscriptionCertificatesElement, "http://schemas.microsoft.com/windowsazure", "SubscriptionCertificatePublicKey"); if (subscriptionCertificatePublicKeyElement != null) { byte[] subscriptionCertificatePublicKeyInstance; subscriptionCertificatePublicKeyInstance = subscriptionCertificatePublicKeyElement .getTextContent() != null ? Base64.decode( subscriptionCertificatePublicKeyElement.getTextContent()) : null; subscriptionCertificateInstance.setPublicKey(subscriptionCertificatePublicKeyInstance); } Element subscriptionCertificateThumbprintElement = XmlUtility.getElementByTagNameNS( subscriptionCertificatesElement, "http://schemas.microsoft.com/windowsazure", "SubscriptionCertificateThumbprint"); if (subscriptionCertificateThumbprintElement != null) { String subscriptionCertificateThumbprintInstance; subscriptionCertificateThumbprintInstance = subscriptionCertificateThumbprintElement .getTextContent(); subscriptionCertificateInstance .setThumbprint(subscriptionCertificateThumbprintInstance); } Element subscriptionCertificateDataElement = XmlUtility.getElementByTagNameNS( subscriptionCertificatesElement, "http://schemas.microsoft.com/windowsazure", "SubscriptionCertificateData"); if (subscriptionCertificateDataElement != null) { byte[] subscriptionCertificateDataInstance; subscriptionCertificateDataInstance = subscriptionCertificateDataElement .getTextContent() != null ? Base64.decode(subscriptionCertificateDataElement.getTextContent()) : null; subscriptionCertificateInstance.setData(subscriptionCertificateDataInstance); } Element createdElement = XmlUtility.getElementByTagNameNS(subscriptionCertificatesElement, "http://schemas.microsoft.com/windowsazure", "Created"); if (createdElement != null) { Calendar createdInstance; createdInstance = DatatypeConverter.parseDateTime(createdElement.getTextContent()); subscriptionCertificateInstance.setCreated(createdInstance); } } } } 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(); } } }