List of usage examples for javax.xml.bind DatatypeConverter parseBoolean
public static boolean parseBoolean(String lexicalXSDBoolean)
Converts the string argument into a boolean value.
From source file:com.microsoft.windowsazure.management.sql.DatabaseCopyOperationsImpl.java
/** * Retrieves information about a SQL Server database copy. * * @param serverName Required. The name of the source or destination SQL * Server instance./*from ww w. ja va 2 s . c om*/ * @param databaseName Required. The name of the database. * @param databaseCopyName Required. The unique identifier for the database * copy to retrieve. * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations. * @throws ServiceException Thrown if an unexpected response is found. * @throws ParserConfigurationException Thrown if there was a serious * configuration error with the document parser. * @throws SAXException Thrown if there was an error parsing the XML * response. * @return Represents a response to the get request. */ @Override public DatabaseCopyGetResponse get(String serverName, String databaseName, String databaseCopyName) throws IOException, ServiceException, ParserConfigurationException, SAXException { // Validate if (serverName == null) { throw new NullPointerException("serverName"); } if (databaseName == null) { throw new NullPointerException("databaseName"); } if (databaseCopyName == null) { throw new NullPointerException("databaseCopyName"); } // Tracing boolean shouldTrace = CloudTracing.getIsEnabled(); String invocationId = null; if (shouldTrace) { invocationId = Long.toString(CloudTracing.getNextInvocationId()); HashMap<String, Object> tracingParameters = new HashMap<String, Object>(); tracingParameters.put("serverName", serverName); tracingParameters.put("databaseName", databaseName); tracingParameters.put("databaseCopyName", databaseCopyName); CloudTracing.enter(invocationId, this, "getAsync", tracingParameters); } // Construct URL String url = ""; url = url + "/"; if (this.getClient().getCredentials().getSubscriptionId() != null) { url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8"); } url = url + "/services/sqlservers/servers/"; url = url + URLEncoder.encode(serverName, "UTF-8"); url = url + "/databases/"; url = url + URLEncoder.encode(databaseName, "UTF-8"); url = url + "/databasecopies/"; url = url + URLEncoder.encode(databaseCopyName, "UTF-8"); String baseUrl = this.getClient().getBaseUri().toString(); // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl.charAt(baseUrl.length() - 1) == '/') { baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); } if (url.charAt(0) == '/') { url = url.substring(1); } url = baseUrl + "/" + url; url = url.replace(" ", "%20"); // Create HTTP transport objects HttpGet httpRequest = new HttpGet(url); // Set Headers httpRequest.setHeader("x-ms-version", "2012-03-01"); // Send Request HttpResponse httpResponse = null; try { if (shouldTrace) { CloudTracing.sendRequest(invocationId, httpRequest); } httpResponse = this.getClient().getHttpClient().execute(httpRequest); if (shouldTrace) { CloudTracing.receiveResponse(invocationId, httpResponse); } int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result DatabaseCopyGetResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_OK) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new DatabaseCopyGetResponse(); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); Element serviceResourceElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "ServiceResource"); if (serviceResourceElement != null) { DatabaseCopy serviceResourceInstance = new DatabaseCopy(); result.setDatabaseCopy(serviceResourceInstance); Element sourceServerNameElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "SourceServerName"); if (sourceServerNameElement != null) { String sourceServerNameInstance; sourceServerNameInstance = sourceServerNameElement.getTextContent(); serviceResourceInstance.setSourceServerName(sourceServerNameInstance); } Element sourceDatabaseNameElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "SourceDatabaseName"); if (sourceDatabaseNameElement != null) { String sourceDatabaseNameInstance; sourceDatabaseNameInstance = sourceDatabaseNameElement.getTextContent(); serviceResourceInstance.setSourceDatabaseName(sourceDatabaseNameInstance); } Element destinationServerNameElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "DestinationServerName"); if (destinationServerNameElement != null) { String destinationServerNameInstance; destinationServerNameInstance = destinationServerNameElement.getTextContent(); serviceResourceInstance.setDestinationServerName(destinationServerNameInstance); } Element destinationDatabaseNameElement = XmlUtility.getElementByTagNameNS( serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "DestinationDatabaseName"); if (destinationDatabaseNameElement != null) { String destinationDatabaseNameInstance; destinationDatabaseNameInstance = destinationDatabaseNameElement.getTextContent(); serviceResourceInstance.setDestinationDatabaseName(destinationDatabaseNameInstance); } Element isContinuousElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "IsContinuous"); if (isContinuousElement != null) { boolean isContinuousInstance; isContinuousInstance = DatatypeConverter .parseBoolean(isContinuousElement.getTextContent().toLowerCase()); serviceResourceInstance.setIsContinuous(isContinuousInstance); } Element replicationStateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "ReplicationState"); if (replicationStateElement != null) { byte replicationStateInstance; replicationStateInstance = DatatypeConverter .parseByte(replicationStateElement.getTextContent()); serviceResourceInstance.setReplicationState(replicationStateInstance); } Element replicationStateDescriptionElement = XmlUtility.getElementByTagNameNS( serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "ReplicationStateDescription"); if (replicationStateDescriptionElement != null) { String replicationStateDescriptionInstance; replicationStateDescriptionInstance = replicationStateDescriptionElement.getTextContent(); serviceResourceInstance.setReplicationStateDescription(replicationStateDescriptionInstance); } Element localDatabaseIdElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "LocalDatabaseId"); if (localDatabaseIdElement != null) { int localDatabaseIdInstance; localDatabaseIdInstance = DatatypeConverter .parseInt(localDatabaseIdElement.getTextContent()); serviceResourceInstance.setLocalDatabaseId(localDatabaseIdInstance); } Element isLocalDatabaseReplicationTargetElement = XmlUtility.getElementByTagNameNS( serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "IsLocalDatabaseReplicationTarget"); if (isLocalDatabaseReplicationTargetElement != null) { boolean isLocalDatabaseReplicationTargetInstance; isLocalDatabaseReplicationTargetInstance = DatatypeConverter.parseBoolean( isLocalDatabaseReplicationTargetElement.getTextContent().toLowerCase()); serviceResourceInstance .setIsLocalDatabaseReplicationTarget(isLocalDatabaseReplicationTargetInstance); } Element isInterlinkConnectedElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "IsInterlinkConnected"); if (isInterlinkConnectedElement != null) { boolean isInterlinkConnectedInstance; isInterlinkConnectedInstance = DatatypeConverter .parseBoolean(isInterlinkConnectedElement.getTextContent().toLowerCase()); serviceResourceInstance.setIsInterlinkConnected(isInterlinkConnectedInstance); } Element startDateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "StartDate"); if (startDateElement != null) { String startDateInstance; startDateInstance = startDateElement.getTextContent(); serviceResourceInstance.setStartDate(startDateInstance); } Element modifyDateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "ModifyDate"); if (modifyDateElement != null) { String modifyDateInstance; modifyDateInstance = modifyDateElement.getTextContent(); serviceResourceInstance.setModifyDate(modifyDateInstance); } Element percentCompleteElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "PercentComplete"); if (percentCompleteElement != null) { float percentCompleteInstance; percentCompleteInstance = DatatypeConverter .parseFloat(percentCompleteElement.getTextContent()); serviceResourceInstance.setPercentComplete(percentCompleteInstance); } Element isOfflineSecondaryElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "IsOfflineSecondary"); if (isOfflineSecondaryElement != null) { boolean isOfflineSecondaryInstance; isOfflineSecondaryInstance = DatatypeConverter .parseBoolean(isOfflineSecondaryElement.getTextContent().toLowerCase()); serviceResourceInstance.setIsOfflineSecondary(isOfflineSecondaryInstance); } Element isTerminationAllowedElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "IsTerminationAllowed"); if (isTerminationAllowedElement != null) { boolean isTerminationAllowedInstance; isTerminationAllowedInstance = DatatypeConverter .parseBoolean(isTerminationAllowedElement.getTextContent().toLowerCase()); serviceResourceInstance.setIsTerminationAllowed(isTerminationAllowedInstance); } Element nameElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "Name"); if (nameElement != null) { String nameInstance; nameInstance = nameElement.getTextContent(); serviceResourceInstance.setName(nameInstance); } Element typeElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "Type"); if (typeElement != null) { String typeInstance; typeInstance = typeElement.getTextContent(); serviceResourceInstance.setType(typeInstance); } Element stateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "State"); if (stateElement != null) { String stateInstance; stateInstance = stateElement.getTextContent(); serviceResourceInstance.setState(stateInstance); } } } result.setStatusCode(statusCode); if (httpResponse.getHeaders("x-ms-request-id").length > 0) { result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); } if (shouldTrace) { CloudTracing.exit(invocationId, result); } return result; } finally { if (httpResponse != null && httpResponse.getEntity() != null) { httpResponse.getEntity().getContent().close(); } } }
From source file:com.microsoft.windowsazure.management.sql.DatabaseOperationsImpl.java
/** * Returns information about an Azure SQL Database. * * @param serverName Required. The name of the Azure SQL Database Server on * which the database is hosted./*from w w w.ja va 2s. c o m*/ * @param databaseName Required. The name of the Azure SQL Database to be * retrieved. * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations. * @throws ServiceException Thrown if an unexpected response is found. * @throws ParserConfigurationException Thrown if there was a serious * configuration error with the document parser. * @throws SAXException Thrown if there was an error parsing the XML * response. * @return Contains the response to a Get Database request. */ @Override public DatabaseGetResponse get(String serverName, String databaseName) throws IOException, ServiceException, ParserConfigurationException, SAXException { // Validate if (serverName == null) { throw new NullPointerException("serverName"); } if (databaseName == null) { throw new NullPointerException("databaseName"); } // Tracing boolean shouldTrace = CloudTracing.getIsEnabled(); String invocationId = null; if (shouldTrace) { invocationId = Long.toString(CloudTracing.getNextInvocationId()); HashMap<String, Object> tracingParameters = new HashMap<String, Object>(); tracingParameters.put("serverName", serverName); tracingParameters.put("databaseName", databaseName); CloudTracing.enter(invocationId, this, "getAsync", tracingParameters); } // Construct URL String url = ""; url = url + "/"; if (this.getClient().getCredentials().getSubscriptionId() != null) { url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8"); } url = url + "/services/sqlservers/servers/"; url = url + URLEncoder.encode(serverName, "UTF-8"); url = url + "/databases/"; url = url + URLEncoder.encode(databaseName, "UTF-8"); String baseUrl = this.getClient().getBaseUri().toString(); // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl.charAt(baseUrl.length() - 1) == '/') { baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); } if (url.charAt(0) == '/') { url = url.substring(1); } url = baseUrl + "/" + url; url = url.replace(" ", "%20"); // Create HTTP transport objects HttpGet httpRequest = new HttpGet(url); // Set Headers httpRequest.setHeader("x-ms-version", "2012-03-01"); // Send Request HttpResponse httpResponse = null; try { if (shouldTrace) { CloudTracing.sendRequest(invocationId, httpRequest); } httpResponse = this.getClient().getHttpClient().execute(httpRequest); if (shouldTrace) { CloudTracing.receiveResponse(invocationId, httpResponse); } int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result DatabaseGetResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_OK) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new DatabaseGetResponse(); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); Element serviceResourceElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "ServiceResource"); if (serviceResourceElement != null) { Database serviceResourceInstance = new Database(); result.setDatabase(serviceResourceInstance); Element idElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "Id"); if (idElement != null) { int idInstance; idInstance = DatatypeConverter.parseInt(idElement.getTextContent()); serviceResourceInstance.setId(idInstance); } Element editionElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "Edition"); if (editionElement != null) { String editionInstance; editionInstance = editionElement.getTextContent(); serviceResourceInstance.setEdition(editionInstance); } Element maxSizeGBElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "MaxSizeGB"); if (maxSizeGBElement != null) { int maxSizeGBInstance; maxSizeGBInstance = DatatypeConverter.parseInt(maxSizeGBElement.getTextContent()); serviceResourceInstance.setMaximumDatabaseSizeInGB(maxSizeGBInstance); } Element maxSizeBytesElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "MaxSizeBytes"); if (maxSizeBytesElement != null) { long maxSizeBytesInstance; maxSizeBytesInstance = DatatypeConverter.parseLong(maxSizeBytesElement.getTextContent()); serviceResourceInstance.setMaximumDatabaseSizeInBytes(maxSizeBytesInstance); } Element collationNameElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "CollationName"); if (collationNameElement != null) { String collationNameInstance; collationNameInstance = collationNameElement.getTextContent(); serviceResourceInstance.setCollationName(collationNameInstance); } Element creationDateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "CreationDate"); if (creationDateElement != null) { Calendar creationDateInstance; creationDateInstance = DatatypeConverter .parseDateTime(creationDateElement.getTextContent()); serviceResourceInstance.setCreationDate(creationDateInstance); } Element isFederationRootElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "IsFederationRoot"); if (isFederationRootElement != null) { boolean isFederationRootInstance; isFederationRootInstance = DatatypeConverter .parseBoolean(isFederationRootElement.getTextContent().toLowerCase()); serviceResourceInstance.setIsFederationRoot(isFederationRootInstance); } Element isSystemObjectElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "IsSystemObject"); if (isSystemObjectElement != null) { boolean isSystemObjectInstance; isSystemObjectInstance = DatatypeConverter .parseBoolean(isSystemObjectElement.getTextContent().toLowerCase()); serviceResourceInstance.setIsSystemObject(isSystemObjectInstance); } Element sizeMBElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "SizeMB"); if (sizeMBElement != null) { String sizeMBInstance; sizeMBInstance = sizeMBElement.getTextContent(); serviceResourceInstance.setSizeMB(sizeMBInstance); } Element serviceObjectiveAssignmentErrorCodeElement = XmlUtility.getElementByTagNameNS( serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "ServiceObjectiveAssignmentErrorCode"); if (serviceObjectiveAssignmentErrorCodeElement != null) { String serviceObjectiveAssignmentErrorCodeInstance; serviceObjectiveAssignmentErrorCodeInstance = serviceObjectiveAssignmentErrorCodeElement .getTextContent(); serviceResourceInstance.setServiceObjectiveAssignmentErrorCode( serviceObjectiveAssignmentErrorCodeInstance); } Element serviceObjectiveAssignmentErrorDescriptionElement = XmlUtility.getElementByTagNameNS( serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "ServiceObjectiveAssignmentErrorDescription"); if (serviceObjectiveAssignmentErrorDescriptionElement != null) { String serviceObjectiveAssignmentErrorDescriptionInstance; serviceObjectiveAssignmentErrorDescriptionInstance = serviceObjectiveAssignmentErrorDescriptionElement .getTextContent(); serviceResourceInstance.setServiceObjectiveAssignmentErrorDescription( serviceObjectiveAssignmentErrorDescriptionInstance); } Element serviceObjectiveAssignmentStateElement = XmlUtility.getElementByTagNameNS( serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "ServiceObjectiveAssignmentState"); if (serviceObjectiveAssignmentStateElement != null) { String serviceObjectiveAssignmentStateInstance; serviceObjectiveAssignmentStateInstance = serviceObjectiveAssignmentStateElement .getTextContent(); serviceResourceInstance .setServiceObjectiveAssignmentState(serviceObjectiveAssignmentStateInstance); } Element serviceObjectiveAssignmentStateDescriptionElement = XmlUtility.getElementByTagNameNS( serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "ServiceObjectiveAssignmentStateDescription"); if (serviceObjectiveAssignmentStateDescriptionElement != null) { String serviceObjectiveAssignmentStateDescriptionInstance; serviceObjectiveAssignmentStateDescriptionInstance = serviceObjectiveAssignmentStateDescriptionElement .getTextContent(); serviceResourceInstance.setServiceObjectiveAssignmentStateDescription( serviceObjectiveAssignmentStateDescriptionInstance); } Element serviceObjectiveAssignmentSuccessDateElement = XmlUtility.getElementByTagNameNS( serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "ServiceObjectiveAssignmentSuccessDate"); if (serviceObjectiveAssignmentSuccessDateElement != null) { String serviceObjectiveAssignmentSuccessDateInstance; serviceObjectiveAssignmentSuccessDateInstance = serviceObjectiveAssignmentSuccessDateElement .getTextContent(); serviceResourceInstance.setServiceObjectiveAssignmentSuccessDate( serviceObjectiveAssignmentSuccessDateInstance); } Element serviceObjectiveIdElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "ServiceObjectiveId"); if (serviceObjectiveIdElement != null) { String serviceObjectiveIdInstance; serviceObjectiveIdInstance = serviceObjectiveIdElement.getTextContent(); serviceResourceInstance.setServiceObjectiveId(serviceObjectiveIdInstance); } Element assignedServiceObjectiveIdElement = XmlUtility.getElementByTagNameNS( serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "AssignedServiceObjectiveId"); if (assignedServiceObjectiveIdElement != null) { String assignedServiceObjectiveIdInstance; assignedServiceObjectiveIdInstance = assignedServiceObjectiveIdElement.getTextContent(); serviceResourceInstance.setAssignedServiceObjectiveId(assignedServiceObjectiveIdInstance); } Element recoveryPeriodStartDateElement = XmlUtility.getElementByTagNameNS( serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "RecoveryPeriodStartDate"); if (recoveryPeriodStartDateElement != null && recoveryPeriodStartDateElement.getTextContent() != null && !recoveryPeriodStartDateElement.getTextContent().isEmpty()) { Calendar recoveryPeriodStartDateInstance; recoveryPeriodStartDateInstance = DatatypeConverter .parseDateTime(recoveryPeriodStartDateElement.getTextContent()); serviceResourceInstance.setRecoveryPeriodStartDate(recoveryPeriodStartDateInstance); } Element nameElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "Name"); if (nameElement != null) { String nameInstance; nameInstance = nameElement.getTextContent(); serviceResourceInstance.setName(nameInstance); } Element typeElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "Type"); if (typeElement != null) { String typeInstance; typeInstance = typeElement.getTextContent(); serviceResourceInstance.setType(typeInstance); } Element stateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "State"); if (stateElement != null) { String stateInstance; stateInstance = stateElement.getTextContent(); serviceResourceInstance.setState(stateInstance); } } } result.setStatusCode(statusCode); if (httpResponse.getHeaders("x-ms-request-id").length > 0) { result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); } if (shouldTrace) { CloudTracing.exit(invocationId, result); } return result; } finally { if (httpResponse != null && httpResponse.getEntity() != null) { httpResponse.getEntity().getContent().close(); } } }
From source file:com.microsoft.windowsazure.management.scheduler.JobCollectionOperationsImpl.java
/** * Determine if the JobCollection name is available to be used. * JobCollection names must be unique within a cloud-service. * * @param cloudServiceName Required. The name of the cloud service. * @param jobCollectionName Required. A name for the JobCollection. The name * must be unique as scoped within the CloudService. The name can be up to * 100 characters in length./*from ww w . j a 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. * @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 Check Name Availability operation response. */ @Override public JobCollectionCheckNameAvailabilityResponse checkNameAvailability(String cloudServiceName, String jobCollectionName) throws IOException, ServiceException, ParserConfigurationException, SAXException { // Validate if (cloudServiceName == null) { throw new NullPointerException("cloudServiceName"); } if (jobCollectionName == null) { throw new NullPointerException("jobCollectionName"); } if (jobCollectionName.length() > 100) { throw new IllegalArgumentException("jobCollectionName"); } // 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("cloudServiceName", cloudServiceName); tracingParameters.put("jobCollectionName", jobCollectionName); CloudTracing.enter(invocationId, this, "checkNameAvailabilityAsync", tracingParameters); } // Construct URL String url = ""; if (this.getClient().getCredentials().getSubscriptionId() != null) { url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8"); } url = url + "/cloudservices/"; url = url + URLEncoder.encode(cloudServiceName, "UTF-8"); url = url + "/resources/"; url = url + "scheduler"; url = url + "/"; url = url + "JobCollections"; url = url + "/"; ArrayList<String> queryParameters = new ArrayList<String>(); queryParameters.add("op=checknameavailability"); queryParameters.add("resourceName=" + URLEncoder.encode(jobCollectionName, "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", "2013-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 JobCollectionCheckNameAvailabilityResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_OK) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new JobCollectionCheckNameAvailabilityResponse(); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); Element resourceNameAvailabilityResponseElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "ResourceNameAvailabilityResponse"); if (resourceNameAvailabilityResponseElement != null) { Element isAvailableElement = XmlUtility.getElementByTagNameNS( resourceNameAvailabilityResponseElement, "http://schemas.microsoft.com/windowsazure", "IsAvailable"); if (isAvailableElement != null) { boolean isAvailableInstance; isAvailableInstance = DatatypeConverter .parseBoolean(isAvailableElement.getTextContent().toLowerCase()); result.setIsAvailable(isAvailableInstance); } } } result.setStatusCode(statusCode); if (httpResponse.getHeaders("x-ms-request-id").length > 0) { result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); } if (shouldTrace) { CloudTracing.exit(invocationId, result); } return result; } finally { if (httpResponse != null && httpResponse.getEntity() != null) { httpResponse.getEntity().getContent().close(); } } }
From source file:com.microsoft.windowsazure.management.websites.WebSiteOperationsImpl.java
/** * Backups a site on-demand./*from ww w. j a v a2s . co m*/ * * @param webSpaceName Required. The name of the web space. * @param webSiteName Required. The name of the web site. * @param backupRequest Required. A backup specification. * @throws ParserConfigurationException Thrown if there was an error * configuring the parser for the response body. * @throws SAXException Thrown if there was an error parsing the response * body. * @throws TransformerException Thrown if there was an error creating the * DOM transformer. * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations. * @throws ServiceException Thrown if an unexpected response is found. * @return The backup record created based on the backup request. */ @Override public WebSiteBackupResponse backup(String webSpaceName, String webSiteName, BackupRequest backupRequest) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { // Validate if (webSpaceName == null) { throw new NullPointerException("webSpaceName"); } if (webSiteName == null) { throw new NullPointerException("webSiteName"); } if (backupRequest == null) { throw new NullPointerException("backupRequest"); } // Tracing boolean shouldTrace = CloudTracing.getIsEnabled(); String invocationId = null; if (shouldTrace) { invocationId = Long.toString(CloudTracing.getNextInvocationId()); HashMap<String, Object> tracingParameters = new HashMap<String, Object>(); tracingParameters.put("webSpaceName", webSpaceName); tracingParameters.put("webSiteName", webSiteName); tracingParameters.put("backupRequest", backupRequest); CloudTracing.enter(invocationId, this, "backupAsync", tracingParameters); } // Construct URL String url = ""; url = url + "/"; if (this.getClient().getCredentials().getSubscriptionId() != null) { url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8"); } url = url + "/services/WebSpaces/"; url = url + URLEncoder.encode(webSpaceName, "UTF-8"); url = url + "/sites/"; url = url + URLEncoder.encode(webSiteName, "UTF-8"); url = url + "/backup"; String baseUrl = this.getClient().getBaseUri().toString(); // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl.charAt(baseUrl.length() - 1) == '/') { baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); } if (url.charAt(0) == '/') { url = url.substring(1); } url = baseUrl + "/" + url; url = url.replace(" ", "%20"); // Create HTTP transport objects HttpPut httpRequest = new HttpPut(url); // Set Headers httpRequest.setHeader("Content-Type", "application/xml"); httpRequest.setHeader("x-ms-version", "2014-04-01"); // Serialize Request String requestContent = null; DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document requestDoc = documentBuilder.newDocument(); Element backupRequestElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "BackupRequest"); requestDoc.appendChild(backupRequestElement); if (backupRequest.getBackupSchedule() != null) { Element backupScheduleElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "BackupSchedule"); backupRequestElement.appendChild(backupScheduleElement); Element frequencyIntervalElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "FrequencyInterval"); frequencyIntervalElement.appendChild(requestDoc .createTextNode(Integer.toString(backupRequest.getBackupSchedule().getFrequencyInterval()))); backupScheduleElement.appendChild(frequencyIntervalElement); if (backupRequest.getBackupSchedule().getFrequencyUnit() != null) { Element frequencyUnitElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "FrequencyUnit"); frequencyUnitElement.appendChild( requestDoc.createTextNode(backupRequest.getBackupSchedule().getFrequencyUnit().toString())); backupScheduleElement.appendChild(frequencyUnitElement); } Element keepAtLeastOneBackupElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "KeepAtLeastOneBackup"); keepAtLeastOneBackupElement.appendChild(requestDoc.createTextNode( Boolean.toString(backupRequest.getBackupSchedule().isKeepAtLeastOneBackup()).toLowerCase())); backupScheduleElement.appendChild(keepAtLeastOneBackupElement); if (backupRequest.getBackupSchedule().getLastExecutionTime() != null) { Element lastExecutionTimeElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "LastExecutionTime"); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'"); simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); lastExecutionTimeElement.appendChild(requestDoc.createTextNode(simpleDateFormat .format(backupRequest.getBackupSchedule().getLastExecutionTime().getTime()))); backupScheduleElement.appendChild(lastExecutionTimeElement); } Element retentionPeriodInDaysElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "RetentionPeriodInDays"); retentionPeriodInDaysElement.appendChild(requestDoc.createTextNode( Integer.toString(backupRequest.getBackupSchedule().getRetentionPeriodInDays()))); backupScheduleElement.appendChild(retentionPeriodInDaysElement); if (backupRequest.getBackupSchedule().getStartTime() != null) { Element startTimeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "StartTime"); SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'"); simpleDateFormat2.setTimeZone(TimeZone.getTimeZone("UTC")); startTimeElement.appendChild(requestDoc.createTextNode( simpleDateFormat2.format(backupRequest.getBackupSchedule().getStartTime().getTime()))); backupScheduleElement.appendChild(startTimeElement); } } if (backupRequest.getDatabases() != null) { if (backupRequest.getDatabases() instanceof LazyCollection == false || ((LazyCollection) backupRequest.getDatabases()).isInitialized()) { Element databasesSequenceElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "Databases"); for (DatabaseBackupSetting databasesItem : backupRequest.getDatabases()) { Element databaseBackupSettingElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "DatabaseBackupSetting"); databasesSequenceElement.appendChild(databaseBackupSettingElement); if (databasesItem.getConnectionString() != null) { Element connectionStringElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "ConnectionString"); connectionStringElement .appendChild(requestDoc.createTextNode(databasesItem.getConnectionString())); databaseBackupSettingElement.appendChild(connectionStringElement); } if (databasesItem.getConnectionStringName() != null) { Element connectionStringNameElement = requestDoc.createElementNS( "http://schemas.microsoft.com/windowsazure", "ConnectionStringName"); connectionStringNameElement .appendChild(requestDoc.createTextNode(databasesItem.getConnectionStringName())); databaseBackupSettingElement.appendChild(connectionStringNameElement); } if (databasesItem.getDatabaseType() != null) { Element databaseTypeElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "DatabaseType"); databaseTypeElement.appendChild(requestDoc.createTextNode(databasesItem.getDatabaseType())); databaseBackupSettingElement.appendChild(databaseTypeElement); } if (databasesItem.getName() != null) { Element nameElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); nameElement.appendChild(requestDoc.createTextNode(databasesItem.getName())); databaseBackupSettingElement.appendChild(nameElement); } } backupRequestElement.appendChild(databasesSequenceElement); } } if (backupRequest.isEnabled() != null) { Element enabledElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Enabled"); enabledElement.appendChild( requestDoc.createTextNode(Boolean.toString(backupRequest.isEnabled()).toLowerCase())); backupRequestElement.appendChild(enabledElement); } if (backupRequest.getName() != null) { Element nameElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); nameElement2.appendChild(requestDoc.createTextNode(backupRequest.getName())); backupRequestElement.appendChild(nameElement2); } if (backupRequest.getStorageAccountUrl() != null) { Element storageAccountUrlElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "StorageAccountUrl"); storageAccountUrlElement.appendChild(requestDoc.createTextNode(backupRequest.getStorageAccountUrl())); backupRequestElement.appendChild(storageAccountUrlElement); } DOMSource domSource = new DOMSource(requestDoc); StringWriter stringWriter = new StringWriter(); StreamResult streamResult = new StreamResult(stringWriter); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.transform(domSource, streamResult); requestContent = stringWriter.toString(); StringEntity entity = new StringEntity(requestContent); httpRequest.setEntity(entity); httpRequest.setHeader("Content-Type", "application/xml"); // Send Request HttpResponse httpResponse = null; try { if (shouldTrace) { CloudTracing.sendRequest(invocationId, httpRequest); } httpResponse = this.getClient().getHttpClient().execute(httpRequest); if (shouldTrace) { CloudTracing.receiveResponse(invocationId, httpResponse); } int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result WebSiteBackupResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_OK) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new WebSiteBackupResponse(); DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance(); documentBuilderFactory2.setNamespaceAware(true); DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder(); Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent)); Element backupItemElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "BackupItem"); if (backupItemElement != null) { BackupItem backupItemInstance = new BackupItem(); result.setBackupItem(backupItemInstance); Element storageAccountUrlElement2 = XmlUtility.getElementByTagNameNS(backupItemElement, "http://schemas.microsoft.com/windowsazure", "StorageAccountUrl"); if (storageAccountUrlElement2 != null) { String storageAccountUrlInstance; storageAccountUrlInstance = storageAccountUrlElement2.getTextContent(); backupItemInstance.setStorageAccountUrl(storageAccountUrlInstance); } Element blobNameElement = XmlUtility.getElementByTagNameNS(backupItemElement, "http://schemas.microsoft.com/windowsazure", "BlobName"); if (blobNameElement != null) { String blobNameInstance; blobNameInstance = blobNameElement.getTextContent(); backupItemInstance.setBlobName(blobNameInstance); } Element nameElement3 = XmlUtility.getElementByTagNameNS(backupItemElement, "http://schemas.microsoft.com/windowsazure", "Name"); if (nameElement3 != null) { String nameInstance; nameInstance = nameElement3.getTextContent(); backupItemInstance.setName(nameInstance); } Element statusElement = XmlUtility.getElementByTagNameNS(backupItemElement, "http://schemas.microsoft.com/windowsazure", "Status"); if (statusElement != null && statusElement.getTextContent() != null && !statusElement.getTextContent().isEmpty()) { BackupItemStatus statusInstance; statusInstance = BackupItemStatus.valueOf(statusElement.getTextContent()); backupItemInstance.setStatus(statusInstance); } Element sizeInBytesElement = XmlUtility.getElementByTagNameNS(backupItemElement, "http://schemas.microsoft.com/windowsazure", "SizeInBytes"); if (sizeInBytesElement != null) { long sizeInBytesInstance; sizeInBytesInstance = DatatypeConverter.parseLong(sizeInBytesElement.getTextContent()); backupItemInstance.setSizeInBytes(sizeInBytesInstance); } Element createdElement = XmlUtility.getElementByTagNameNS(backupItemElement, "http://schemas.microsoft.com/windowsazure", "Created"); if (createdElement != null && createdElement.getTextContent() != null && !createdElement.getTextContent().isEmpty()) { Calendar createdInstance; createdInstance = DatatypeConverter.parseDateTime(createdElement.getTextContent()); backupItemInstance.setCreated(createdInstance); } Element logElement = XmlUtility.getElementByTagNameNS(backupItemElement, "http://schemas.microsoft.com/windowsazure", "Log"); if (logElement != null) { String logInstance; logInstance = logElement.getTextContent(); backupItemInstance.setLog(logInstance); } Element databasesSequenceElement2 = XmlUtility.getElementByTagNameNS(backupItemElement, "http://schemas.microsoft.com/windowsazure", "Databases"); if (databasesSequenceElement2 != null) { for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility .getElementsByTagNameNS(databasesSequenceElement2, "http://schemas.microsoft.com/windowsazure", "DatabaseBackupSetting") .size(); i1 = i1 + 1) { org.w3c.dom.Element databasesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility .getElementsByTagNameNS(databasesSequenceElement2, "http://schemas.microsoft.com/windowsazure", "DatabaseBackupSetting") .get(i1)); DatabaseBackupSetting databaseBackupSettingInstance = new DatabaseBackupSetting(); backupItemInstance.getDatabases().add(databaseBackupSettingInstance); Element connectionStringElement2 = XmlUtility.getElementByTagNameNS(databasesElement, "http://schemas.microsoft.com/windowsazure", "ConnectionString"); if (connectionStringElement2 != null) { String connectionStringInstance; connectionStringInstance = connectionStringElement2.getTextContent(); databaseBackupSettingInstance.setConnectionString(connectionStringInstance); } Element connectionStringNameElement2 = XmlUtility.getElementByTagNameNS( databasesElement, "http://schemas.microsoft.com/windowsazure", "ConnectionStringName"); if (connectionStringNameElement2 != null) { String connectionStringNameInstance; connectionStringNameInstance = connectionStringNameElement2.getTextContent(); databaseBackupSettingInstance.setConnectionStringName(connectionStringNameInstance); } Element databaseTypeElement2 = XmlUtility.getElementByTagNameNS(databasesElement, "http://schemas.microsoft.com/windowsazure", "DatabaseType"); if (databaseTypeElement2 != null) { String databaseTypeInstance; databaseTypeInstance = databaseTypeElement2.getTextContent(); databaseBackupSettingInstance.setDatabaseType(databaseTypeInstance); } Element nameElement4 = XmlUtility.getElementByTagNameNS(databasesElement, "http://schemas.microsoft.com/windowsazure", "Name"); if (nameElement4 != null) { String nameInstance2; nameInstance2 = nameElement4.getTextContent(); databaseBackupSettingInstance.setName(nameInstance2); } } } Element scheduledElement = XmlUtility.getElementByTagNameNS(backupItemElement, "http://schemas.microsoft.com/windowsazure", "Scheduled"); if (scheduledElement != null) { boolean scheduledInstance; scheduledInstance = DatatypeConverter .parseBoolean(scheduledElement.getTextContent().toLowerCase()); backupItemInstance.setScheduled(scheduledInstance); } Element lastRestoreTimeStampElement = XmlUtility.getElementByTagNameNS(backupItemElement, "http://schemas.microsoft.com/windowsazure", "LastRestoreTimeStamp"); if (lastRestoreTimeStampElement != null && lastRestoreTimeStampElement.getTextContent() != null && !lastRestoreTimeStampElement.getTextContent().isEmpty()) { Calendar lastRestoreTimeStampInstance; lastRestoreTimeStampInstance = DatatypeConverter .parseDateTime(lastRestoreTimeStampElement.getTextContent()); backupItemInstance.setLastRestoreTimeStamp(lastRestoreTimeStampInstance); } Element finishedTimeStampElement = XmlUtility.getElementByTagNameNS(backupItemElement, "http://schemas.microsoft.com/windowsazure", "FinishedTimeStamp"); if (finishedTimeStampElement != null && finishedTimeStampElement.getTextContent() != null && !finishedTimeStampElement.getTextContent().isEmpty()) { Calendar finishedTimeStampInstance; finishedTimeStampInstance = DatatypeConverter .parseDateTime(finishedTimeStampElement.getTextContent()); backupItemInstance.setFinishedTimeStamp(finishedTimeStampInstance); } Element correlationIdElement = XmlUtility.getElementByTagNameNS(backupItemElement, "http://schemas.microsoft.com/windowsazure", "CorrelationId"); if (correlationIdElement != null) { String correlationIdInstance; correlationIdInstance = correlationIdElement.getTextContent(); backupItemInstance.setCorrelationId(correlationIdInstance); } } } result.setStatusCode(statusCode); if (httpResponse.getHeaders("x-ms-request-id").length > 0) { result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); } if (shouldTrace) { CloudTracing.exit(invocationId, result); } return result; } finally { if (httpResponse != null && httpResponse.getEntity() != null) { httpResponse.getEntity().getContent().close(); } } }
From source file:com.microsoft.windowsazure.management.compute.HostedServiceOperationsImpl.java
/** * The Check Hosted Service Name Availability operation checks for the * availability of the specified cloud service name. (see * http://msdn.microsoft.com/en-us/library/windowsazure/jj154116.aspx for * more information)/* w w w .j ava 2 s. c o m*/ * * @param serviceName Required. The cloud service name that you would like * to use. * @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 Check Hosted Service Name Availability operation response. */ @Override public HostedServiceCheckNameAvailabilityResponse checkNameAvailability(String serviceName) throws IOException, ServiceException, ParserConfigurationException, SAXException { // Validate if (serviceName == null) { throw new NullPointerException("serviceName"); } // TODO: Validate serviceName is a valid DNS name. // Tracing boolean shouldTrace = CloudTracing.getIsEnabled(); String invocationId = null; if (shouldTrace) { invocationId = Long.toString(CloudTracing.getNextInvocationId()); HashMap<String, Object> tracingParameters = new HashMap<String, Object>(); tracingParameters.put("serviceName", serviceName); CloudTracing.enter(invocationId, this, "checkNameAvailabilityAsync", 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/hostedservices/operations/isavailable/"; url = url + URLEncoder.encode(serviceName, "UTF-8"); String baseUrl = this.getClient().getBaseUri().toString(); // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl.charAt(baseUrl.length() - 1) == '/') { baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); } if (url.charAt(0) == '/') { url = url.substring(1); } url = baseUrl + "/" + url; url = url.replace(" ", "%20"); // Create HTTP transport objects HttpGet httpRequest = new HttpGet(url); // Set Headers httpRequest.setHeader("x-ms-version", "2015-04-01"); // Send Request HttpResponse httpResponse = null; try { if (shouldTrace) { CloudTracing.sendRequest(invocationId, httpRequest); } httpResponse = this.getClient().getHttpClient().execute(httpRequest); if (shouldTrace) { CloudTracing.receiveResponse(invocationId, httpResponse); } int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result HostedServiceCheckNameAvailabilityResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_OK) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new HostedServiceCheckNameAvailabilityResponse(); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); Element availabilityResponseElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "AvailabilityResponse"); if (availabilityResponseElement != null) { Element resultElement = XmlUtility.getElementByTagNameNS(availabilityResponseElement, "http://schemas.microsoft.com/windowsazure", "Result"); if (resultElement != null) { boolean resultInstance; resultInstance = DatatypeConverter .parseBoolean(resultElement.getTextContent().toLowerCase()); result.setIsAvailable(resultInstance); } Element reasonElement = XmlUtility.getElementByTagNameNS(availabilityResponseElement, "http://schemas.microsoft.com/windowsazure", "Reason"); if (reasonElement != null) { String reasonInstance; reasonInstance = reasonElement.getTextContent(); result.setReason(reasonInstance); } } } result.setStatusCode(statusCode); if (httpResponse.getHeaders("x-ms-request-id").length > 0) { result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); } if (shouldTrace) { CloudTracing.exit(invocationId, result); } return result; } finally { if (httpResponse != null && httpResponse.getEntity() != null) { httpResponse.getEntity().getContent().close(); } } }
From source file:com.microsoft.windowsazure.management.sql.DatabaseCopyOperationsImpl.java
/** * Retrieves the list of SQL Server database copies for a database. * * @param serverName Required. The name of the database server to be queried. * @param databaseName Required. The name of the database to be queried. * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations.//from w w w . j av a2 s .co m * @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 copies * for a given database. */ @Override public DatabaseCopyListResponse list(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, "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/sqlservers/servers/"; url = url + URLEncoder.encode(serverName, "UTF-8"); url = url + "/databases/"; url = url + URLEncoder.encode(databaseName, "UTF-8"); url = url + "/databasecopies"; 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 DatabaseCopyListResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_OK) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new DatabaseCopyListResponse(); 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)); DatabaseCopy serviceResourceInstance = new DatabaseCopy(); result.getDatabaseCopies().add(serviceResourceInstance); Element sourceServerNameElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "SourceServerName"); if (sourceServerNameElement != null) { String sourceServerNameInstance; sourceServerNameInstance = sourceServerNameElement.getTextContent(); serviceResourceInstance.setSourceServerName(sourceServerNameInstance); } Element sourceDatabaseNameElement = XmlUtility.getElementByTagNameNS( serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "SourceDatabaseName"); if (sourceDatabaseNameElement != null) { String sourceDatabaseNameInstance; sourceDatabaseNameInstance = sourceDatabaseNameElement.getTextContent(); serviceResourceInstance.setSourceDatabaseName(sourceDatabaseNameInstance); } Element destinationServerNameElement = XmlUtility.getElementByTagNameNS( serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "DestinationServerName"); if (destinationServerNameElement != null) { String destinationServerNameInstance; destinationServerNameInstance = destinationServerNameElement.getTextContent(); serviceResourceInstance.setDestinationServerName(destinationServerNameInstance); } Element destinationDatabaseNameElement = XmlUtility.getElementByTagNameNS( serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "DestinationDatabaseName"); if (destinationDatabaseNameElement != null) { String destinationDatabaseNameInstance; destinationDatabaseNameInstance = destinationDatabaseNameElement.getTextContent(); serviceResourceInstance.setDestinationDatabaseName(destinationDatabaseNameInstance); } Element isContinuousElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "IsContinuous"); if (isContinuousElement != null) { boolean isContinuousInstance; isContinuousInstance = DatatypeConverter .parseBoolean(isContinuousElement.getTextContent().toLowerCase()); serviceResourceInstance.setIsContinuous(isContinuousInstance); } Element replicationStateElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "ReplicationState"); if (replicationStateElement != null) { byte replicationStateInstance; replicationStateInstance = DatatypeConverter .parseByte(replicationStateElement.getTextContent()); serviceResourceInstance.setReplicationState(replicationStateInstance); } Element replicationStateDescriptionElement = XmlUtility.getElementByTagNameNS( serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "ReplicationStateDescription"); if (replicationStateDescriptionElement != null) { String replicationStateDescriptionInstance; replicationStateDescriptionInstance = replicationStateDescriptionElement .getTextContent(); serviceResourceInstance .setReplicationStateDescription(replicationStateDescriptionInstance); } Element localDatabaseIdElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "LocalDatabaseId"); if (localDatabaseIdElement != null) { int localDatabaseIdInstance; localDatabaseIdInstance = DatatypeConverter .parseInt(localDatabaseIdElement.getTextContent()); serviceResourceInstance.setLocalDatabaseId(localDatabaseIdInstance); } Element isLocalDatabaseReplicationTargetElement = XmlUtility.getElementByTagNameNS( serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "IsLocalDatabaseReplicationTarget"); if (isLocalDatabaseReplicationTargetElement != null) { boolean isLocalDatabaseReplicationTargetInstance; isLocalDatabaseReplicationTargetInstance = DatatypeConverter.parseBoolean( isLocalDatabaseReplicationTargetElement.getTextContent().toLowerCase()); serviceResourceInstance .setIsLocalDatabaseReplicationTarget(isLocalDatabaseReplicationTargetInstance); } Element isInterlinkConnectedElement = XmlUtility.getElementByTagNameNS( serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "IsInterlinkConnected"); if (isInterlinkConnectedElement != null) { boolean isInterlinkConnectedInstance; isInterlinkConnectedInstance = DatatypeConverter .parseBoolean(isInterlinkConnectedElement.getTextContent().toLowerCase()); serviceResourceInstance.setIsInterlinkConnected(isInterlinkConnectedInstance); } Element startDateElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "StartDate"); if (startDateElement != null) { String startDateInstance; startDateInstance = startDateElement.getTextContent(); serviceResourceInstance.setStartDate(startDateInstance); } Element modifyDateElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "ModifyDate"); if (modifyDateElement != null) { String modifyDateInstance; modifyDateInstance = modifyDateElement.getTextContent(); serviceResourceInstance.setModifyDate(modifyDateInstance); } Element percentCompleteElement = XmlUtility.getElementByTagNameNS(serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "PercentComplete"); if (percentCompleteElement != null) { float percentCompleteInstance; percentCompleteInstance = DatatypeConverter .parseFloat(percentCompleteElement.getTextContent()); serviceResourceInstance.setPercentComplete(percentCompleteInstance); } Element isOfflineSecondaryElement = XmlUtility.getElementByTagNameNS( serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "IsOfflineSecondary"); if (isOfflineSecondaryElement != null) { boolean isOfflineSecondaryInstance; isOfflineSecondaryInstance = DatatypeConverter .parseBoolean(isOfflineSecondaryElement.getTextContent().toLowerCase()); serviceResourceInstance.setIsOfflineSecondary(isOfflineSecondaryInstance); } Element isTerminationAllowedElement = XmlUtility.getElementByTagNameNS( serviceResourcesElement, "http://schemas.microsoft.com/windowsazure", "IsTerminationAllowed"); if (isTerminationAllowedElement != null) { boolean isTerminationAllowedInstance; isTerminationAllowedInstance = DatatypeConverter .parseBoolean(isTerminationAllowedElement.getTextContent().toLowerCase()); serviceResourceInstance.setIsTerminationAllowed(isTerminationAllowedInstance); } 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.windowsazure.management.compute.VirtualMachineOSImageOperationsImpl.java
/** * The Get OS Image operation retrieves the details for an operating system * image from the image repository. (see * http://msdn.microsoft.com/en-us/library/windowsazure/jj157191.aspx for * more information)/*from w w w . j av a 2s. com*/ * * @param imageName Required. The name of the OS image to retrieve. * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations. * @throws ServiceException Thrown if an unexpected response is found. * @throws ParserConfigurationException Thrown if there was a serious * configuration error with the document parser. * @throws SAXException Thrown if there was an error parsing the XML * response. * @throws URISyntaxException Thrown if there was an error parsing a URI in * the response. * @return A virtual machine image associated with your subscription. */ @Override public VirtualMachineOSImageGetResponse get(String imageName) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException { // Validate if (imageName == null) { throw new NullPointerException("imageName"); } // Tracing boolean shouldTrace = CloudTracing.getIsEnabled(); String invocationId = null; if (shouldTrace) { invocationId = Long.toString(CloudTracing.getNextInvocationId()); HashMap<String, Object> tracingParameters = new HashMap<String, Object>(); tracingParameters.put("imageName", imageName); CloudTracing.enter(invocationId, this, "getAsync", tracingParameters); } // Construct URL String url = ""; url = url + "/"; if (this.getClient().getCredentials().getSubscriptionId() != null) { url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8"); } url = url + "/services/images/"; url = url + URLEncoder.encode(imageName, "UTF-8"); String baseUrl = this.getClient().getBaseUri().toString(); // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl.charAt(baseUrl.length() - 1) == '/') { baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); } if (url.charAt(0) == '/') { url = url.substring(1); } url = baseUrl + "/" + url; url = url.replace(" ", "%20"); // Create HTTP transport objects HttpGet httpRequest = new HttpGet(url); // Set Headers httpRequest.setHeader("x-ms-version", "2015-04-01"); // Send Request HttpResponse httpResponse = null; try { if (shouldTrace) { CloudTracing.sendRequest(invocationId, httpRequest); } httpResponse = this.getClient().getHttpClient().execute(httpRequest); if (shouldTrace) { CloudTracing.receiveResponse(invocationId, httpResponse); } int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result VirtualMachineOSImageGetResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_OK) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new VirtualMachineOSImageGetResponse(); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); Element oSImageElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "OSImage"); if (oSImageElement != null) { Element affinityGroupElement = XmlUtility.getElementByTagNameNS(oSImageElement, "http://schemas.microsoft.com/windowsazure", "AffinityGroup"); if (affinityGroupElement != null) { String affinityGroupInstance; affinityGroupInstance = affinityGroupElement.getTextContent(); result.setAffinityGroup(affinityGroupInstance); } Element categoryElement = XmlUtility.getElementByTagNameNS(oSImageElement, "http://schemas.microsoft.com/windowsazure", "Category"); if (categoryElement != null) { String categoryInstance; categoryInstance = categoryElement.getTextContent(); result.setCategory(categoryInstance); } Element labelElement = XmlUtility.getElementByTagNameNS(oSImageElement, "http://schemas.microsoft.com/windowsazure", "Label"); if (labelElement != null) { String labelInstance; labelInstance = labelElement.getTextContent(); result.setLabel(labelInstance); } Element locationElement = XmlUtility.getElementByTagNameNS(oSImageElement, "http://schemas.microsoft.com/windowsazure", "Location"); if (locationElement != null) { String locationInstance; locationInstance = locationElement.getTextContent(); result.setLocation(locationInstance); } Element logicalSizeInGBElement = XmlUtility.getElementByTagNameNS(oSImageElement, "http://schemas.microsoft.com/windowsazure", "LogicalSizeInGB"); if (logicalSizeInGBElement != null) { double logicalSizeInGBInstance; logicalSizeInGBInstance = DatatypeConverter .parseDouble(logicalSizeInGBElement.getTextContent()); result.setLogicalSizeInGB(logicalSizeInGBInstance); } Element mediaLinkElement = XmlUtility.getElementByTagNameNS(oSImageElement, "http://schemas.microsoft.com/windowsazure", "MediaLink"); if (mediaLinkElement != null) { URI mediaLinkInstance; mediaLinkInstance = new URI(mediaLinkElement.getTextContent()); result.setMediaLinkUri(mediaLinkInstance); } Element nameElement = XmlUtility.getElementByTagNameNS(oSImageElement, "http://schemas.microsoft.com/windowsazure", "Name"); if (nameElement != null) { String nameInstance; nameInstance = nameElement.getTextContent(); result.setName(nameInstance); } Element osElement = XmlUtility.getElementByTagNameNS(oSImageElement, "http://schemas.microsoft.com/windowsazure", "OS"); if (osElement != null) { String osInstance; osInstance = osElement.getTextContent(); result.setOperatingSystemType(osInstance); } Element eulaElement = XmlUtility.getElementByTagNameNS(oSImageElement, "http://schemas.microsoft.com/windowsazure", "Eula"); if (eulaElement != null) { String eulaInstance; eulaInstance = eulaElement.getTextContent(); result.setEula(eulaInstance); } Element descriptionElement = XmlUtility.getElementByTagNameNS(oSImageElement, "http://schemas.microsoft.com/windowsazure", "Description"); if (descriptionElement != null) { String descriptionInstance; descriptionInstance = descriptionElement.getTextContent(); result.setDescription(descriptionInstance); } Element imageFamilyElement = XmlUtility.getElementByTagNameNS(oSImageElement, "http://schemas.microsoft.com/windowsazure", "ImageFamily"); if (imageFamilyElement != null) { String imageFamilyInstance; imageFamilyInstance = imageFamilyElement.getTextContent(); result.setImageFamily(imageFamilyInstance); } Element showInGuiElement = XmlUtility.getElementByTagNameNS(oSImageElement, "http://schemas.microsoft.com/windowsazure", "ShowInGui"); if (showInGuiElement != null && showInGuiElement.getTextContent() != null && !showInGuiElement.getTextContent().isEmpty()) { boolean showInGuiInstance; showInGuiInstance = DatatypeConverter .parseBoolean(showInGuiElement.getTextContent().toLowerCase()); result.setShowInGui(showInGuiInstance); } Element publishedDateElement = XmlUtility.getElementByTagNameNS(oSImageElement, "http://schemas.microsoft.com/windowsazure", "PublishedDate"); if (publishedDateElement != null) { Calendar publishedDateInstance; publishedDateInstance = DatatypeConverter .parseDateTime(publishedDateElement.getTextContent()); result.setPublishedDate(publishedDateInstance); } Element isPremiumElement = XmlUtility.getElementByTagNameNS(oSImageElement, "http://schemas.microsoft.com/windowsazure", "IsPremium"); if (isPremiumElement != null && isPremiumElement.getTextContent() != null && !isPremiumElement.getTextContent().isEmpty()) { boolean isPremiumInstance; isPremiumInstance = DatatypeConverter .parseBoolean(isPremiumElement.getTextContent().toLowerCase()); result.setIsPremium(isPremiumInstance); } Element iconUriElement = XmlUtility.getElementByTagNameNS(oSImageElement, "http://schemas.microsoft.com/windowsazure", "IconUri"); if (iconUriElement != null) { String iconUriInstance; iconUriInstance = iconUriElement.getTextContent(); result.setIconUri(iconUriInstance); } Element privacyUriElement = XmlUtility.getElementByTagNameNS(oSImageElement, "http://schemas.microsoft.com/windowsazure", "PrivacyUri"); if (privacyUriElement != null) { URI privacyUriInstance; privacyUriInstance = new URI(privacyUriElement.getTextContent()); result.setPrivacyUri(privacyUriInstance); } Element recommendedVMSizeElement = XmlUtility.getElementByTagNameNS(oSImageElement, "http://schemas.microsoft.com/windowsazure", "RecommendedVMSize"); if (recommendedVMSizeElement != null) { String recommendedVMSizeInstance; recommendedVMSizeInstance = recommendedVMSizeElement.getTextContent(); result.setRecommendedVMSize(recommendedVMSizeInstance); } Element publisherNameElement = XmlUtility.getElementByTagNameNS(oSImageElement, "http://schemas.microsoft.com/windowsazure", "PublisherName"); if (publisherNameElement != null) { String publisherNameInstance; publisherNameInstance = publisherNameElement.getTextContent(); result.setPublisherName(publisherNameInstance); } Element smallIconUriElement = XmlUtility.getElementByTagNameNS(oSImageElement, "http://schemas.microsoft.com/windowsazure", "SmallIconUri"); if (smallIconUriElement != null) { String smallIconUriInstance; smallIconUriInstance = smallIconUriElement.getTextContent(); result.setSmallIconUri(smallIconUriInstance); } Element languageElement = XmlUtility.getElementByTagNameNS(oSImageElement, "http://schemas.microsoft.com/windowsazure", "Language"); if (languageElement != null) { String languageInstance; languageInstance = languageElement.getTextContent(); result.setLanguage(languageInstance); } Element iOTypeElement = XmlUtility.getElementByTagNameNS(oSImageElement, "http://schemas.microsoft.com/windowsazure", "IOType"); if (iOTypeElement != null) { String iOTypeInstance; iOTypeInstance = iOTypeElement.getTextContent(); result.setIOType(iOTypeInstance); } } } result.setStatusCode(statusCode); if (httpResponse.getHeaders("x-ms-request-id").length > 0) { result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); } if (shouldTrace) { CloudTracing.exit(invocationId, result); } return result; } finally { if (httpResponse != null && httpResponse.getEntity() != null) { httpResponse.getEntity().getContent().close(); } } }
From source file:com.microsoft.windowsazure.management.compute.VirtualMachineDiskOperationsImpl.java
/** * The Create Disk operation adds a disk to the user image repository. The * disk can be an operating system disk or a data disk. (see * http://msdn.microsoft.com/en-us/library/windowsazure/jj157178.aspx for * more information)/* w ww . j a v a 2 s. c o m*/ * * @param parameters Required. Parameters supplied to the Create Virtual * Machine Disk operation. * @throws ParserConfigurationException Thrown if there was an error * configuring the parser for the response body. * @throws SAXException Thrown if there was an error parsing the response * body. * @throws TransformerException Thrown if there was an error creating the * DOM transformer. * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations. * @throws ServiceException Thrown if an unexpected response is found. * @throws URISyntaxException Thrown if there was an error parsing a URI in * the response. * @return A virtual machine disk associated with your subscription. */ @Override public VirtualMachineDiskCreateResponse createDisk(VirtualMachineDiskCreateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException, URISyntaxException { // Validate if (parameters == null) { throw new NullPointerException("parameters"); } if (parameters.getLabel() == null) { throw new NullPointerException("parameters.Label"); } if (parameters.getMediaLinkUri() == null) { throw new NullPointerException("parameters.MediaLinkUri"); } if (parameters.getName() == null) { throw new NullPointerException("parameters.Name"); } // Tracing boolean shouldTrace = CloudTracing.getIsEnabled(); String invocationId = null; if (shouldTrace) { invocationId = Long.toString(CloudTracing.getNextInvocationId()); HashMap<String, Object> tracingParameters = new HashMap<String, Object>(); tracingParameters.put("parameters", parameters); CloudTracing.enter(invocationId, this, "createDiskAsync", 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/disks"; String baseUrl = this.getClient().getBaseUri().toString(); // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl.charAt(baseUrl.length() - 1) == '/') { baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); } if (url.charAt(0) == '/') { url = url.substring(1); } url = baseUrl + "/" + url; url = url.replace(" ", "%20"); // Create HTTP transport objects HttpPost httpRequest = new HttpPost(url); // Set Headers httpRequest.setHeader("Content-Type", "application/xml"); httpRequest.setHeader("x-ms-version", "2015-04-01"); // Serialize Request String requestContent = null; DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document requestDoc = documentBuilder.newDocument(); Element diskElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Disk"); requestDoc.appendChild(diskElement); if (parameters.getOperatingSystemType() != null) { Element osElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "OS"); osElement.appendChild(requestDoc.createTextNode(parameters.getOperatingSystemType())); diskElement.appendChild(osElement); } Element labelElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Label"); labelElement.appendChild(requestDoc.createTextNode(parameters.getLabel())); diskElement.appendChild(labelElement); Element mediaLinkElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "MediaLink"); mediaLinkElement.appendChild(requestDoc.createTextNode(parameters.getMediaLinkUri().toString())); diskElement.appendChild(mediaLinkElement); Element nameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); nameElement.appendChild(requestDoc.createTextNode(parameters.getName())); diskElement.appendChild(nameElement); DOMSource domSource = new DOMSource(requestDoc); StringWriter stringWriter = new StringWriter(); StreamResult streamResult = new StreamResult(stringWriter); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.transform(domSource, streamResult); requestContent = stringWriter.toString(); StringEntity entity = new StringEntity(requestContent); httpRequest.setEntity(entity); httpRequest.setHeader("Content-Type", "application/xml"); // Send Request HttpResponse httpResponse = null; try { if (shouldTrace) { CloudTracing.sendRequest(invocationId, httpRequest); } httpResponse = this.getClient().getHttpClient().execute(httpRequest); if (shouldTrace) { CloudTracing.receiveResponse(invocationId, httpResponse); } int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result VirtualMachineDiskCreateResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_OK) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new VirtualMachineDiskCreateResponse(); DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance(); documentBuilderFactory2.setNamespaceAware(true); DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder(); Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent)); Element diskElement2 = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "Disk"); if (diskElement2 != null) { Element osElement2 = XmlUtility.getElementByTagNameNS(diskElement2, "http://schemas.microsoft.com/windowsazure", "OS"); if (osElement2 != null) { String osInstance; osInstance = osElement2.getTextContent(); result.setOperatingSystem(osInstance); } Element labelElement2 = XmlUtility.getElementByTagNameNS(diskElement2, "http://schemas.microsoft.com/windowsazure", "Label"); if (labelElement2 != null) { String labelInstance; labelInstance = labelElement2.getTextContent(); result.setLabel(labelInstance); } Element affinityGroupElement = XmlUtility.getElementByTagNameNS(diskElement2, "http://schemas.microsoft.com/windowsazure", "AffinityGroup"); if (affinityGroupElement != null) { String affinityGroupInstance; affinityGroupInstance = affinityGroupElement.getTextContent(); result.setAffinityGroup(affinityGroupInstance); } Element locationElement = XmlUtility.getElementByTagNameNS(diskElement2, "http://schemas.microsoft.com/windowsazure", "Location"); if (locationElement != null) { String locationInstance; locationInstance = locationElement.getTextContent(); result.setLocation(locationInstance); } Element logicalDiskSizeInGBElement = XmlUtility.getElementByTagNameNS(diskElement2, "http://schemas.microsoft.com/windowsazure", "LogicalDiskSizeInGB"); if (logicalDiskSizeInGBElement != null) { int logicalDiskSizeInGBInstance; logicalDiskSizeInGBInstance = DatatypeConverter .parseInt(logicalDiskSizeInGBElement.getTextContent()); result.setLogicalSizeInGB(logicalDiskSizeInGBInstance); } Element mediaLinkElement2 = XmlUtility.getElementByTagNameNS(diskElement2, "http://schemas.microsoft.com/windowsazure", "MediaLink"); if (mediaLinkElement2 != null) { URI mediaLinkInstance; mediaLinkInstance = new URI(mediaLinkElement2.getTextContent()); result.setMediaLinkUri(mediaLinkInstance); } Element nameElement2 = XmlUtility.getElementByTagNameNS(diskElement2, "http://schemas.microsoft.com/windowsazure", "Name"); if (nameElement2 != null) { String nameInstance; nameInstance = nameElement2.getTextContent(); result.setName(nameInstance); } Element sourceImageNameElement = XmlUtility.getElementByTagNameNS(diskElement2, "http://schemas.microsoft.com/windowsazure", "SourceImageName"); if (sourceImageNameElement != null) { String sourceImageNameInstance; sourceImageNameInstance = sourceImageNameElement.getTextContent(); result.setSourceImageName(sourceImageNameInstance); } Element attachedToElement = XmlUtility.getElementByTagNameNS(diskElement2, "http://schemas.microsoft.com/windowsazure", "AttachedTo"); if (attachedToElement != null) { VirtualMachineDiskCreateResponse.VirtualMachineDiskUsageDetails attachedToInstance = new VirtualMachineDiskCreateResponse.VirtualMachineDiskUsageDetails(); result.setUsageDetails(attachedToInstance); Element hostedServiceNameElement = XmlUtility.getElementByTagNameNS(attachedToElement, "http://schemas.microsoft.com/windowsazure", "HostedServiceName"); if (hostedServiceNameElement != null) { String hostedServiceNameInstance; hostedServiceNameInstance = hostedServiceNameElement.getTextContent(); attachedToInstance.setHostedServiceName(hostedServiceNameInstance); } Element deploymentNameElement = XmlUtility.getElementByTagNameNS(attachedToElement, "http://schemas.microsoft.com/windowsazure", "DeploymentName"); if (deploymentNameElement != null) { String deploymentNameInstance; deploymentNameInstance = deploymentNameElement.getTextContent(); attachedToInstance.setDeploymentName(deploymentNameInstance); } Element roleNameElement = XmlUtility.getElementByTagNameNS(attachedToElement, "http://schemas.microsoft.com/windowsazure", "RoleName"); if (roleNameElement != null) { String roleNameInstance; roleNameInstance = roleNameElement.getTextContent(); attachedToInstance.setRoleName(roleNameInstance); } } Element isPremiumElement = XmlUtility.getElementByTagNameNS(diskElement2, "http://schemas.microsoft.com/windowsazure", "IsPremium"); if (isPremiumElement != null && isPremiumElement.getTextContent() != null && !isPremiumElement.getTextContent().isEmpty()) { boolean isPremiumInstance; isPremiumInstance = DatatypeConverter .parseBoolean(isPremiumElement.getTextContent().toLowerCase()); result.setIsPremium(isPremiumInstance); } Element iOTypeElement = XmlUtility.getElementByTagNameNS(diskElement2, "http://schemas.microsoft.com/windowsazure", "IOType"); if (iOTypeElement != null) { String iOTypeInstance; iOTypeInstance = iOTypeElement.getTextContent(); result.setIOType(iOTypeInstance); } } } result.setStatusCode(statusCode); if (httpResponse.getHeaders("x-ms-request-id").length > 0) { result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); } if (shouldTrace) { CloudTracing.exit(invocationId, result); } return result; } finally { if (httpResponse != null && httpResponse.getEntity() != null) { httpResponse.getEntity().getContent().close(); } } }
From source file:com.microsoft.windowsazure.management.servicebus.NamespaceOperationsImpl.java
/** * Creates a new service namespace. Once created, this namespace's resource * manifest is immutable. This operation is idempotent. (see * http://msdn.microsoft.com/en-us/library/windowsazure/jj856303.aspx for * more information)// www .ja v a 2 s . c om * * @param namespaceName Required. The namespace name. * @param namespaceEntity Required. The service bus namespace. * @throws ParserConfigurationException Thrown if there was an error * configuring the parser for the response body. * @throws SAXException Thrown if there was an error parsing the response * body. * @throws TransformerException Thrown if there was an error creating the * DOM transformer. * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations. * @throws ServiceException Thrown if an unexpected response is found. * @throws URISyntaxException Thrown if there was an error parsing a URI in * the response. * @return The response to a request for a particular namespace. */ @Override public ServiceBusNamespaceResponse createNamespace(String namespaceName, ServiceBusNamespaceCreateParameters namespaceEntity) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException, URISyntaxException { // Validate if (namespaceName == null) { throw new NullPointerException("namespaceName"); } if (namespaceEntity == null) { throw new NullPointerException("namespaceEntity"); } if (namespaceEntity.getNamespaceType() == null) { throw new NullPointerException("namespaceEntity.NamespaceType"); } if (namespaceEntity.getRegion() == null) { throw new NullPointerException("namespaceEntity.Region"); } // Tracing boolean shouldTrace = CloudTracing.getIsEnabled(); String invocationId = null; if (shouldTrace) { invocationId = Long.toString(CloudTracing.getNextInvocationId()); HashMap<String, Object> tracingParameters = new HashMap<String, Object>(); tracingParameters.put("namespaceName", namespaceName); tracingParameters.put("namespaceEntity", namespaceEntity); CloudTracing.enter(invocationId, this, "createNamespaceAsync", tracingParameters); } // Construct URL String url = ""; url = url + "/"; if (this.getClient().getCredentials().getSubscriptionId() != null) { url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8"); } url = url + "/services/servicebus/namespaces/"; url = url + URLEncoder.encode(namespaceName, "UTF-8"); String baseUrl = this.getClient().getBaseUri().toString(); // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl.charAt(baseUrl.length() - 1) == '/') { baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); } if (url.charAt(0) == '/') { url = url.substring(1); } url = baseUrl + "/" + url; url = url.replace(" ", "%20"); // Create HTTP transport objects HttpPut httpRequest = new HttpPut(url); // Set Headers httpRequest.setHeader("Accept", "application/atom+xml"); httpRequest.setHeader("Content-Type", "application/atom+xml"); httpRequest.setHeader("type", "entry"); httpRequest.setHeader("x-ms-version", "2014-06-01"); // Serialize Request String requestContent = null; DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document requestDoc = documentBuilder.newDocument(); Element entryElement = requestDoc.createElementNS("http://www.w3.org/2005/Atom", "entry"); requestDoc.appendChild(entryElement); Element contentElement = requestDoc.createElementNS("http://www.w3.org/2005/Atom", "content"); entryElement.appendChild(contentElement); Attr typeAttribute = requestDoc.createAttribute("type"); typeAttribute.setValue("application/atom+xml;type=entry;charset=utf-8"); contentElement.setAttributeNode(typeAttribute); Element namespaceDescriptionElement = requestDoc.createElementNS( "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "NamespaceDescription"); contentElement.appendChild(namespaceDescriptionElement); if (namespaceEntity.getRegion() != null) { Element regionElement = requestDoc.createElementNS( "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "Region"); regionElement.appendChild(requestDoc.createTextNode(namespaceEntity.getRegion())); namespaceDescriptionElement.appendChild(regionElement); } Element createACSNamespaceElement = requestDoc.createElementNS( "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "CreateACSNamespace"); createACSNamespaceElement.appendChild( requestDoc.createTextNode(Boolean.toString(namespaceEntity.isCreateACSNamespace()).toLowerCase())); namespaceDescriptionElement.appendChild(createACSNamespaceElement); if (namespaceEntity.getNamespaceType() != null) { Element namespaceTypeElement = requestDoc.createElementNS( "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "NamespaceType"); namespaceTypeElement .appendChild(requestDoc.createTextNode(namespaceEntity.getNamespaceType().toString())); namespaceDescriptionElement.appendChild(namespaceTypeElement); } DOMSource domSource = new DOMSource(requestDoc); StringWriter stringWriter = new StringWriter(); StreamResult streamResult = new StreamResult(stringWriter); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.transform(domSource, streamResult); requestContent = stringWriter.toString(); StringEntity entity = new StringEntity(requestContent); httpRequest.setEntity(entity); httpRequest.setHeader("Content-Type", "application/atom+xml"); // Send Request HttpResponse httpResponse = null; try { if (shouldTrace) { CloudTracing.sendRequest(invocationId, httpRequest); } httpResponse = this.getClient().getHttpClient().execute(httpRequest); if (shouldTrace) { CloudTracing.receiveResponse(invocationId, httpResponse); } int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result ServiceBusNamespaceResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_OK) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new ServiceBusNamespaceResponse(); DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance(); documentBuilderFactory2.setNamespaceAware(true); DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder(); Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent)); Element entryElement2 = XmlUtility.getElementByTagNameNS(responseDoc, "http://www.w3.org/2005/Atom", "entry"); if (entryElement2 != null) { Element contentElement2 = XmlUtility.getElementByTagNameNS(entryElement2, "http://www.w3.org/2005/Atom", "content"); if (contentElement2 != null) { Element namespaceDescriptionElement2 = XmlUtility.getElementByTagNameNS(contentElement2, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "NamespaceDescription"); if (namespaceDescriptionElement2 != null) { ServiceBusNamespace namespaceDescriptionInstance = new ServiceBusNamespace(); result.setNamespace(namespaceDescriptionInstance); Element nameElement = XmlUtility.getElementByTagNameNS(namespaceDescriptionElement2, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "Name"); if (nameElement != null) { String nameInstance; nameInstance = nameElement.getTextContent(); namespaceDescriptionInstance.setName(nameInstance); } Element regionElement2 = XmlUtility.getElementByTagNameNS(namespaceDescriptionElement2, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "Region"); if (regionElement2 != null) { String regionInstance; regionInstance = regionElement2.getTextContent(); namespaceDescriptionInstance.setRegion(regionInstance); } Element statusElement = XmlUtility.getElementByTagNameNS(namespaceDescriptionElement2, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "Status"); if (statusElement != null) { String statusInstance; statusInstance = statusElement.getTextContent(); namespaceDescriptionInstance.setStatus(statusInstance); } Element createdAtElement = XmlUtility.getElementByTagNameNS( namespaceDescriptionElement2, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "CreatedAt"); if (createdAtElement != null) { Calendar createdAtInstance; createdAtInstance = DatatypeConverter .parseDateTime(createdAtElement.getTextContent()); namespaceDescriptionInstance.setCreatedAt(createdAtInstance); } Element acsManagementEndpointElement = XmlUtility.getElementByTagNameNS( namespaceDescriptionElement2, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "AcsManagementEndpoint"); if (acsManagementEndpointElement != null) { URI acsManagementEndpointInstance; acsManagementEndpointInstance = new URI( acsManagementEndpointElement.getTextContent()); namespaceDescriptionInstance .setAcsManagementEndpoint(acsManagementEndpointInstance); } Element serviceBusEndpointElement = XmlUtility.getElementByTagNameNS( namespaceDescriptionElement2, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "ServiceBusEndpoint"); if (serviceBusEndpointElement != null) { URI serviceBusEndpointInstance; serviceBusEndpointInstance = new URI(serviceBusEndpointElement.getTextContent()); namespaceDescriptionInstance.setServiceBusEndpoint(serviceBusEndpointInstance); } Element subscriptionIdElement = XmlUtility.getElementByTagNameNS( namespaceDescriptionElement2, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "SubscriptionId"); if (subscriptionIdElement != null) { String subscriptionIdInstance; subscriptionIdInstance = subscriptionIdElement.getTextContent(); namespaceDescriptionInstance.setSubscriptionId(subscriptionIdInstance); } Element enabledElement = XmlUtility.getElementByTagNameNS(namespaceDescriptionElement2, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "Enabled"); if (enabledElement != null) { boolean enabledInstance; enabledInstance = DatatypeConverter .parseBoolean(enabledElement.getTextContent().toLowerCase()); namespaceDescriptionInstance.setEnabled(enabledInstance); } Element createACSNamespaceElement2 = XmlUtility.getElementByTagNameNS( namespaceDescriptionElement2, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "CreateACSNamespace"); if (createACSNamespaceElement2 != null) { boolean createACSNamespaceInstance; createACSNamespaceInstance = DatatypeConverter .parseBoolean(createACSNamespaceElement2.getTextContent().toLowerCase()); namespaceDescriptionInstance.setCreateACSNamespace(createACSNamespaceInstance); } Element namespaceTypeElement2 = XmlUtility.getElementByTagNameNS( namespaceDescriptionElement2, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "NamespaceType"); if (namespaceTypeElement2 != null && namespaceTypeElement2.getTextContent() != null && !namespaceTypeElement2.getTextContent().isEmpty()) { NamespaceType namespaceTypeInstance; namespaceTypeInstance = NamespaceType .valueOf(namespaceTypeElement2.getTextContent()); namespaceDescriptionInstance.setNamespaceType(namespaceTypeInstance); } } } } } result.setStatusCode(statusCode); if (httpResponse.getHeaders("x-ms-request-id").length > 0) { result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); } if (shouldTrace) { CloudTracing.exit(invocationId, result); } return result; } finally { if (httpResponse != null && httpResponse.getEntity() != null) { httpResponse.getEntity().getContent().close(); } } }
From source file:com.microsoft.windowsazure.management.servicebus.TopicOperationsImpl.java
/** * The topic description is an XML AtomPub document that defines the desired * semantics for a topic. The topic description contains the following * properties. For more information, see the TopicDescription Properties * topic. (see//from w w w. ja v a2 s . c om * http://msdn.microsoft.com/en-us/library/windowsazure/hh780749.aspx for * more information) * * @param namespaceName Required. The namespace name. * @param topicName Required. The topic. * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations. * @throws ServiceException Thrown if an unexpected response is found. * @throws ParserConfigurationException Thrown if there was a serious * configuration error with the document parser. * @throws SAXException Thrown if there was an error parsing the XML * response. * @throws URISyntaxException Thrown if there was an error parsing a URI in * the response. * @return A response to a request for a particular topic. */ @Override public ServiceBusTopicResponse get(String namespaceName, String topicName) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException { // Validate if (namespaceName == null) { throw new NullPointerException("namespaceName"); } if (topicName == null) { throw new NullPointerException("topicName"); } // Tracing boolean shouldTrace = CloudTracing.getIsEnabled(); String invocationId = null; if (shouldTrace) { invocationId = Long.toString(CloudTracing.getNextInvocationId()); HashMap<String, Object> tracingParameters = new HashMap<String, Object>(); tracingParameters.put("namespaceName", namespaceName); tracingParameters.put("topicName", topicName); CloudTracing.enter(invocationId, this, "getAsync", tracingParameters); } // Construct URL String url = ""; url = url + "/"; if (this.getClient().getCredentials().getSubscriptionId() != null) { url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8"); } url = url + "/services/servicebus/namespaces/"; url = url + URLEncoder.encode(namespaceName, "UTF-8"); url = url + "/topics/"; url = url + URLEncoder.encode(topicName, "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("Content-Type", "application/xml; charset=utf-8"); httpRequest.setHeader("x-ms-version", "2013-08-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 ServiceBusTopicResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_OK) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new ServiceBusTopicResponse(); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); Element entryElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://www.w3.org/2005/Atom", "entry"); if (entryElement != null) { Element titleElement = XmlUtility.getElementByTagNameNS(entryElement, "http://www.w3.org/2005/Atom", "title"); if (titleElement != null) { } Element contentElement = XmlUtility.getElementByTagNameNS(entryElement, "http://www.w3.org/2005/Atom", "content"); if (contentElement != null) { Element topicDescriptionElement = XmlUtility.getElementByTagNameNS(contentElement, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "TopicDescription"); if (topicDescriptionElement != null) { ServiceBusTopic topicDescriptionInstance = new ServiceBusTopic(); result.setTopic(topicDescriptionInstance); Element defaultMessageTimeToLiveElement = XmlUtility.getElementByTagNameNS( topicDescriptionElement, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "DefaultMessageTimeToLive"); if (defaultMessageTimeToLiveElement != null) { String defaultMessageTimeToLiveInstance; defaultMessageTimeToLiveInstance = defaultMessageTimeToLiveElement.getTextContent(); topicDescriptionInstance .setDefaultMessageTimeToLive(defaultMessageTimeToLiveInstance); } Element maxSizeInMegabytesElement = XmlUtility.getElementByTagNameNS( topicDescriptionElement, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "MaxSizeInMegabytes"); if (maxSizeInMegabytesElement != null) { int maxSizeInMegabytesInstance; maxSizeInMegabytesInstance = DatatypeConverter .parseInt(maxSizeInMegabytesElement.getTextContent()); topicDescriptionInstance.setMaxSizeInMegabytes(maxSizeInMegabytesInstance); } Element requiresDuplicateDetectionElement = XmlUtility.getElementByTagNameNS( topicDescriptionElement, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "RequiresDuplicateDetection"); if (requiresDuplicateDetectionElement != null) { boolean requiresDuplicateDetectionInstance; requiresDuplicateDetectionInstance = DatatypeConverter.parseBoolean( requiresDuplicateDetectionElement.getTextContent().toLowerCase()); topicDescriptionInstance .setRequiresDuplicateDetection(requiresDuplicateDetectionInstance); } Element duplicateDetectionHistoryTimeWindowElement = XmlUtility.getElementByTagNameNS( topicDescriptionElement, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "DuplicateDetectionHistoryTimeWindow"); if (duplicateDetectionHistoryTimeWindowElement != null) { String duplicateDetectionHistoryTimeWindowInstance; duplicateDetectionHistoryTimeWindowInstance = duplicateDetectionHistoryTimeWindowElement .getTextContent(); topicDescriptionInstance.setDuplicateDetectionHistoryTimeWindow( duplicateDetectionHistoryTimeWindowInstance); } Element enableBatchedOperationsElement = XmlUtility.getElementByTagNameNS( topicDescriptionElement, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "EnableBatchedOperations"); if (enableBatchedOperationsElement != null) { boolean enableBatchedOperationsInstance; enableBatchedOperationsInstance = DatatypeConverter.parseBoolean( enableBatchedOperationsElement.getTextContent().toLowerCase()); topicDescriptionInstance .setEnableBatchedOperations(enableBatchedOperationsInstance); } Element sizeInBytesElement = XmlUtility.getElementByTagNameNS(topicDescriptionElement, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "SizeInBytes"); if (sizeInBytesElement != null) { int sizeInBytesInstance; sizeInBytesInstance = DatatypeConverter .parseInt(sizeInBytesElement.getTextContent()); topicDescriptionInstance.setSizeInBytes(sizeInBytesInstance); } Element filteringMessagesBeforePublishingElement = XmlUtility.getElementByTagNameNS( topicDescriptionElement, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "FilteringMessagesBeforePublishing"); if (filteringMessagesBeforePublishingElement != null) { boolean filteringMessagesBeforePublishingInstance; filteringMessagesBeforePublishingInstance = DatatypeConverter.parseBoolean( filteringMessagesBeforePublishingElement.getTextContent().toLowerCase()); topicDescriptionInstance.setFilteringMessagesBeforePublishing( filteringMessagesBeforePublishingInstance); } Element isAnonymousAccessibleElement = XmlUtility.getElementByTagNameNS( topicDescriptionElement, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "IsAnonymousAccessible"); if (isAnonymousAccessibleElement != null) { boolean isAnonymousAccessibleInstance; isAnonymousAccessibleInstance = DatatypeConverter .parseBoolean(isAnonymousAccessibleElement.getTextContent().toLowerCase()); topicDescriptionInstance.setIsAnonymousAccessible(isAnonymousAccessibleInstance); } Element authorizationRulesSequenceElement = XmlUtility.getElementByTagNameNS( topicDescriptionElement, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "AuthorizationRules"); if (authorizationRulesSequenceElement != null) { for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility .getElementsByTagNameNS(authorizationRulesSequenceElement, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "AuthorizationRule") .size(); i1 = i1 + 1) { org.w3c.dom.Element authorizationRulesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility .getElementsByTagNameNS(authorizationRulesSequenceElement, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "AuthorizationRule") .get(i1)); ServiceBusSharedAccessAuthorizationRule authorizationRuleInstance = new ServiceBusSharedAccessAuthorizationRule(); topicDescriptionInstance.getAuthorizationRules().add(authorizationRuleInstance); Element claimTypeElement = XmlUtility.getElementByTagNameNS( authorizationRulesElement, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "ClaimType"); if (claimTypeElement != null) { String claimTypeInstance; claimTypeInstance = claimTypeElement.getTextContent(); authorizationRuleInstance.setClaimType(claimTypeInstance); } Element claimValueElement = XmlUtility.getElementByTagNameNS( authorizationRulesElement, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "ClaimValue"); if (claimValueElement != null) { String claimValueInstance; claimValueInstance = claimValueElement.getTextContent(); authorizationRuleInstance.setClaimValue(claimValueInstance); } Element rightsSequenceElement = XmlUtility.getElementByTagNameNS( authorizationRulesElement, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "Rights"); if (rightsSequenceElement != null) { for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility .getElementsByTagNameNS(rightsSequenceElement, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "AccessRights") .size(); i2 = i2 + 1) { org.w3c.dom.Element rightsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility .getElementsByTagNameNS(rightsSequenceElement, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "AccessRights") .get(i2)); authorizationRuleInstance.getRights() .add(AccessRight.valueOf(rightsElement.getTextContent())); } } Element createdTimeElement = XmlUtility.getElementByTagNameNS( authorizationRulesElement, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "CreatedTime"); if (createdTimeElement != null) { Calendar createdTimeInstance; createdTimeInstance = DatatypeConverter .parseDateTime(createdTimeElement.getTextContent()); authorizationRuleInstance.setCreatedTime(createdTimeInstance); } Element keyNameElement = XmlUtility.getElementByTagNameNS( authorizationRulesElement, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "KeyName"); if (keyNameElement != null) { String keyNameInstance; keyNameInstance = keyNameElement.getTextContent(); authorizationRuleInstance.setKeyName(keyNameInstance); } Element modifiedTimeElement = XmlUtility.getElementByTagNameNS( authorizationRulesElement, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "ModifiedTime"); if (modifiedTimeElement != null) { Calendar modifiedTimeInstance; modifiedTimeInstance = DatatypeConverter .parseDateTime(modifiedTimeElement.getTextContent()); authorizationRuleInstance.setModifiedTime(modifiedTimeInstance); } Element primaryKeyElement = XmlUtility.getElementByTagNameNS( authorizationRulesElement, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "PrimaryKey"); if (primaryKeyElement != null) { String primaryKeyInstance; primaryKeyInstance = primaryKeyElement.getTextContent(); authorizationRuleInstance.setPrimaryKey(primaryKeyInstance); } Element secondaryKeyElement = XmlUtility.getElementByTagNameNS( authorizationRulesElement, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "SecondaryKey"); if (secondaryKeyElement != null) { String secondaryKeyInstance; secondaryKeyInstance = secondaryKeyElement.getTextContent(); authorizationRuleInstance.setSecondaryKey(secondaryKeyInstance); } } } Element statusElement = XmlUtility.getElementByTagNameNS(topicDescriptionElement, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "Status"); if (statusElement != null) { String statusInstance; statusInstance = statusElement.getTextContent(); topicDescriptionInstance.setStatus(statusInstance); } Element createdAtElement = XmlUtility.getElementByTagNameNS(topicDescriptionElement, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "CreatedAt"); if (createdAtElement != null) { Calendar createdAtInstance; createdAtInstance = DatatypeConverter .parseDateTime(createdAtElement.getTextContent()); topicDescriptionInstance.setCreatedAt(createdAtInstance); } Element updatedAtElement = XmlUtility.getElementByTagNameNS(topicDescriptionElement, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "UpdatedAt"); if (updatedAtElement != null) { Calendar updatedAtInstance; updatedAtInstance = DatatypeConverter .parseDateTime(updatedAtElement.getTextContent()); topicDescriptionInstance.setUpdatedAt(updatedAtInstance); } Element accessedAtElement = XmlUtility.getElementByTagNameNS(topicDescriptionElement, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "AccessedAt"); if (accessedAtElement != null) { Calendar accessedAtInstance; accessedAtInstance = DatatypeConverter .parseDateTime(accessedAtElement.getTextContent()); topicDescriptionInstance.setAccessedAt(accessedAtInstance); } Element supportOrderingElement = XmlUtility.getElementByTagNameNS( topicDescriptionElement, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "SupportOrdering"); if (supportOrderingElement != null) { boolean supportOrderingInstance; supportOrderingInstance = DatatypeConverter .parseBoolean(supportOrderingElement.getTextContent().toLowerCase()); topicDescriptionInstance.setSupportOrdering(supportOrderingInstance); } Element countDetailsElement = XmlUtility.getElementByTagNameNS(topicDescriptionElement, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "CountDetails"); if (countDetailsElement != null) { CountDetails countDetailsInstance = new CountDetails(); topicDescriptionInstance.setCountDetails(countDetailsInstance); } Element subscriptionCountElement = XmlUtility.getElementByTagNameNS( topicDescriptionElement, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "SubscriptionCount"); if (subscriptionCountElement != null) { int subscriptionCountInstance; subscriptionCountInstance = DatatypeConverter .parseInt(subscriptionCountElement.getTextContent()); topicDescriptionInstance.setSubscriptionCount(subscriptionCountInstance); } Element autoDeleteOnIdleElement = XmlUtility.getElementByTagNameNS( topicDescriptionElement, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "AutoDeleteOnIdle"); if (autoDeleteOnIdleElement != null) { String autoDeleteOnIdleInstance; autoDeleteOnIdleInstance = autoDeleteOnIdleElement.getTextContent(); topicDescriptionInstance.setAutoDeleteOnIdle(autoDeleteOnIdleInstance); } Element entityAvailabilityStatusElement = XmlUtility.getElementByTagNameNS( topicDescriptionElement, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "EntityAvailabilityStatus"); if (entityAvailabilityStatusElement != null) { String entityAvailabilityStatusInstance; entityAvailabilityStatusInstance = entityAvailabilityStatusElement.getTextContent(); topicDescriptionInstance .setEntityAvailabilityStatus(entityAvailabilityStatusInstance); } } } } } result.setStatusCode(statusCode); if (httpResponse.getHeaders("x-ms-request-id").length > 0) { result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); } if (shouldTrace) { CloudTracing.exit(invocationId, result); } return result; } finally { if (httpResponse != null && httpResponse.getEntity() != null) { httpResponse.getEntity().getContent().close(); } } }