List of usage examples for javax.xml.bind DatatypeConverter parseDateTime
public static java.util.Calendar parseDateTime(String lexicalXSDDateTime)
Converts the string argument into a Calendar value.
From source file:com.microsoft.azure.management.websites.WebHostingPlanOperationsImpl.java
/** * You can retrieve historical usage metrics for a site by issuing an HTTP * GET request. (see/*from w w w .j a va 2s.c o m*/ * http://msdn.microsoft.com/en-us/library/windowsazure/dn166964.aspx for * more information) * * @param resourceGroupName Required. The name of the resource group. * @param webHostingPlanName Required. The name of the web hosting plan. * @param parameters Required. Parameters supplied to the Get Historical * Usage Metrics Web hosting plan operation. * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations. * @throws ServiceException Thrown if an unexpected response is found. * @return The Get Historical Usage Metrics Web hosting plan operation * response. */ @Override public WebHostingPlanGetHistoricalUsageMetricsResponse getHistoricalUsageMetrics(String resourceGroupName, String webHostingPlanName, WebHostingPlanGetHistoricalUsageMetricsParameters parameters) throws IOException, ServiceException { // Validate if (resourceGroupName == null) { throw new NullPointerException("resourceGroupName"); } if (webHostingPlanName == null) { throw new NullPointerException("webHostingPlanName"); } if (parameters == null) { throw new NullPointerException("parameters"); } // Tracing boolean shouldTrace = CloudTracing.getIsEnabled(); String invocationId = null; if (shouldTrace) { invocationId = Long.toString(CloudTracing.getNextInvocationId()); HashMap<String, Object> tracingParameters = new HashMap<String, Object>(); tracingParameters.put("resourceGroupName", resourceGroupName); tracingParameters.put("webHostingPlanName", webHostingPlanName); tracingParameters.put("parameters", parameters); CloudTracing.enter(invocationId, this, "getHistoricalUsageMetricsAsync", tracingParameters); } // Construct URL String url = ""; url = url + "/subscriptions/"; if (this.getClient().getCredentials().getSubscriptionId() != null) { url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8"); } url = url + "/resourceGroups/"; url = url + URLEncoder.encode(resourceGroupName, "UTF-8"); url = url + "/providers/"; url = url + "Microsoft.Web"; url = url + "/serverFarms/"; url = url + URLEncoder.encode(webHostingPlanName, "UTF-8"); url = url + "/metrics"; ArrayList<String> queryParameters = new ArrayList<String>(); queryParameters.add("api-version=" + "2014-06-01"); if (parameters.getMetricNames() != null && parameters.getMetricNames().size() > 0) { queryParameters.add("names=" + URLEncoder.encode(CollectionStringBuilder.join(parameters.getMetricNames(), ","), "UTF-8")); } SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'"); simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); if (parameters.getStartTime() != null) { queryParameters.add("StartTime=" + URLEncoder.encode(simpleDateFormat.format(parameters.getStartTime().getTime()), "UTF-8")); } SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'"); simpleDateFormat2.setTimeZone(TimeZone.getTimeZone("UTC")); if (parameters.getEndTime() != null) { queryParameters.add("EndTime=" + URLEncoder.encode(simpleDateFormat2.format(parameters.getEndTime().getTime()), "UTF-8")); } if (parameters.getTimeGrain() != null) { queryParameters.add("timeGrain=" + URLEncoder.encode(parameters.getTimeGrain(), "UTF-8")); } queryParameters.add("details=" + URLEncoder .encode(Boolean.toString(parameters.isIncludeInstanceBreakdown()).toLowerCase(), "UTF-8")); if (queryParameters.size() > 0) { url = url + "?" + CollectionStringBuilder.join(queryParameters, "&"); } String baseUrl = this.getClient().getBaseUri().toString(); // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl.charAt(baseUrl.length() - 1) == '/') { baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); } if (url.charAt(0) == '/') { url = url.substring(1); } url = baseUrl + "/" + url; url = url.replace(" ", "%20"); // Create HTTP transport objects HttpGet httpRequest = new HttpGet(url); // Set Headers httpRequest.setHeader("x-ms-version", "2014-06-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.createFromJson(httpRequest, null, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result WebHostingPlanGetHistoricalUsageMetricsResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_OK) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new WebHostingPlanGetHistoricalUsageMetricsResponse(); ObjectMapper objectMapper = new ObjectMapper(); JsonNode responseDoc = null; String responseDocContent = IOUtils.toString(responseContent); if (responseDocContent == null == false && responseDocContent.length() > 0) { responseDoc = objectMapper.readTree(responseDocContent); } if (responseDoc != null && responseDoc instanceof NullNode == false) { JsonNode propertiesArray = responseDoc.get("properties"); if (propertiesArray != null && propertiesArray instanceof NullNode == false) { for (JsonNode propertiesValue : ((ArrayNode) propertiesArray)) { HistoricalUsageMetric historicalUsageMetricInstance = new HistoricalUsageMetric(); result.getUsageMetrics().add(historicalUsageMetricInstance); JsonNode codeValue = propertiesValue.get("code"); if (codeValue != null && codeValue instanceof NullNode == false) { String codeInstance; codeInstance = codeValue.getTextValue(); historicalUsageMetricInstance.setCode(codeInstance); } JsonNode dataValue = propertiesValue.get("data"); if (dataValue != null && dataValue instanceof NullNode == false) { HistoricalUsageMetricData dataInstance = new HistoricalUsageMetricData(); historicalUsageMetricInstance.setData(dataInstance); JsonNode displayNameValue = dataValue.get("displayName"); if (displayNameValue != null && displayNameValue instanceof NullNode == false) { String displayNameInstance; displayNameInstance = displayNameValue.getTextValue(); dataInstance.setDisplayName(displayNameInstance); } JsonNode endTimeValue = dataValue.get("EndTime"); if (endTimeValue != null && endTimeValue instanceof NullNode == false) { Calendar endTimeInstance; endTimeInstance = DatatypeConverter.parseDateTime(endTimeValue.getTextValue()); dataInstance.setEndTime(endTimeInstance); } JsonNode nameValue = dataValue.get("name"); if (nameValue != null && nameValue instanceof NullNode == false) { String nameInstance; nameInstance = nameValue.getTextValue(); dataInstance.setName(nameInstance); } JsonNode primaryAggregationTypeValue = dataValue.get("primaryAggregationType"); if (primaryAggregationTypeValue != null && primaryAggregationTypeValue instanceof NullNode == false) { String primaryAggregationTypeInstance; primaryAggregationTypeInstance = primaryAggregationTypeValue.getTextValue(); dataInstance.setPrimaryAggregationType(primaryAggregationTypeInstance); } JsonNode startTimeValue = dataValue.get("startTime"); if (startTimeValue != null && startTimeValue instanceof NullNode == false) { Calendar startTimeInstance; startTimeInstance = DatatypeConverter .parseDateTime(startTimeValue.getTextValue()); dataInstance.setStartTime(startTimeInstance); } JsonNode timeGrainValue = dataValue.get("timeGrain"); if (timeGrainValue != null && timeGrainValue instanceof NullNode == false) { String timeGrainInstance; timeGrainInstance = timeGrainValue.getTextValue(); dataInstance.setTimeGrain(timeGrainInstance); } JsonNode unitValue = dataValue.get("unit"); if (unitValue != null && unitValue instanceof NullNode == false) { String unitInstance; unitInstance = unitValue.getTextValue(); dataInstance.setUnit(unitInstance); } JsonNode valuesArray = dataValue.get("values"); if (valuesArray != null && valuesArray instanceof NullNode == false) { for (JsonNode valuesValue : ((ArrayNode) valuesArray)) { HistoricalUsageMetricSample metricSampleInstance = new HistoricalUsageMetricSample(); dataInstance.getValues().add(metricSampleInstance); JsonNode countValue = valuesValue.get("count"); if (countValue != null && countValue instanceof NullNode == false) { int countInstance; countInstance = countValue.getIntValue(); metricSampleInstance.setCount(countInstance); } JsonNode maximumValue = valuesValue.get("maximum"); if (maximumValue != null && maximumValue instanceof NullNode == false) { String maximumInstance; maximumInstance = maximumValue.getTextValue(); metricSampleInstance.setMaximum(maximumInstance); } JsonNode minimumValue = valuesValue.get("minimum"); if (minimumValue != null && minimumValue instanceof NullNode == false) { String minimumInstance; minimumInstance = minimumValue.getTextValue(); metricSampleInstance.setMinimum(minimumInstance); } JsonNode timeCreatedValue = valuesValue.get("timeCreated"); if (timeCreatedValue != null && timeCreatedValue instanceof NullNode == false) { Calendar timeCreatedInstance; timeCreatedInstance = DatatypeConverter .parseDateTime(timeCreatedValue.getTextValue()); metricSampleInstance.setTimeCreated(timeCreatedInstance); } JsonNode totalValue = valuesValue.get("total"); if (totalValue != null && totalValue instanceof NullNode == false) { String totalInstance; totalInstance = totalValue.getTextValue(); metricSampleInstance.setTotal(totalInstance); } JsonNode instanceNameValue = valuesValue.get("instanceName"); if (instanceNameValue != null && instanceNameValue instanceof NullNode == false) { String instanceNameInstance; instanceNameInstance = instanceNameValue.getTextValue(); metricSampleInstance.setInstanceName(instanceNameInstance); } } } } JsonNode messageValue = propertiesValue.get("message"); if (messageValue != null && messageValue instanceof NullNode == false) { String messageInstance; messageInstance = messageValue.getTextValue(); historicalUsageMetricInstance.setMessage(messageInstance); } } } } } 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.QueueOperationsImpl.java
/** * Creates a new queue. Once created, this queue's resource manifest is * immutable. This operation is idempotent. Repeating the create call, * after a queue with same name has been created successfully, will result * in a 409 Conflict error message. (see * http://msdn.microsoft.com/en-us/library/windowsazure/jj856295.aspx for * more information)//ww w .java 2 s .co m * * @param namespaceName Required. The namespace name. * @param queue Required. The service bus queue. * @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 response to a request for a particular queue. */ @Override public ServiceBusQueueResponse create(String namespaceName, ServiceBusQueueCreateParameters queue) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException, URISyntaxException { // Validate if (namespaceName == null) { throw new NullPointerException("namespaceName"); } if (queue == null) { throw new NullPointerException("queue"); } if (queue.getName() == null) { throw new NullPointerException("queue.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("namespaceName", namespaceName); tracingParameters.put("queue", queue); CloudTracing.enter(invocationId, this, "createAsync", 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 + "/queues/"; url = url + URLEncoder.encode(queue.getName(), "UTF-8"); url = url + "/"; String baseUrl = this.getClient().getBaseUri().toString(); // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl.charAt(baseUrl.length() - 1) == '/') { baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); } if (url.charAt(0) == '/') { url = url.substring(1); } url = baseUrl + "/" + url; url = url.replace(" ", "%20"); // Create HTTP transport objects HttpPut httpRequest = new HttpPut(url); // Set Headers httpRequest.setHeader("Content-Type", "application/atom+xml"); httpRequest.setHeader("type", "entry"); httpRequest.setHeader("x-ms-version", "2013-08-01"); httpRequest.setHeader("x-process-at", "ServiceBus"); // Serialize Request String requestContent = null; DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document requestDoc = documentBuilder.newDocument(); Element entryElement = requestDoc.createElementNS("http://www.w3.org/2005/Atom", "entry"); requestDoc.appendChild(entryElement); Element contentElement = requestDoc.createElementNS("http://www.w3.org/2005/Atom", "content"); entryElement.appendChild(contentElement); Attr typeAttribute = requestDoc.createAttribute("type"); typeAttribute.setValue("application/atom+xml;type=entry;charset=utf-8"); contentElement.setAttributeNode(typeAttribute); Element queueDescriptionElement = requestDoc.createElementNS( "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "QueueDescription"); contentElement.appendChild(queueDescriptionElement); if (queue.getLockDuration() != null) { Element lockDurationElement = requestDoc.createElementNS( "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "LockDuration"); lockDurationElement.appendChild(requestDoc.createTextNode(queue.getLockDuration())); queueDescriptionElement.appendChild(lockDurationElement); } Element maxSizeInMegabytesElement = requestDoc.createElementNS( "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "MaxSizeInMegabytes"); maxSizeInMegabytesElement .appendChild(requestDoc.createTextNode(Integer.toString(queue.getMaxSizeInMegabytes()))); queueDescriptionElement.appendChild(maxSizeInMegabytesElement); Element requiresDuplicateDetectionElement = requestDoc.createElementNS( "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "RequiresDuplicateDetection"); requiresDuplicateDetectionElement.appendChild( requestDoc.createTextNode(Boolean.toString(queue.isRequiresDuplicateDetection()).toLowerCase())); queueDescriptionElement.appendChild(requiresDuplicateDetectionElement); Element requiresSessionElement = requestDoc.createElementNS( "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "RequiresSession"); requiresSessionElement .appendChild(requestDoc.createTextNode(Boolean.toString(queue.isRequiresSession()).toLowerCase())); queueDescriptionElement.appendChild(requiresSessionElement); if (queue.getDefaultMessageTimeToLive() != null) { Element defaultMessageTimeToLiveElement = requestDoc.createElementNS( "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "DefaultMessageTimeToLive"); defaultMessageTimeToLiveElement .appendChild(requestDoc.createTextNode(queue.getDefaultMessageTimeToLive())); queueDescriptionElement.appendChild(defaultMessageTimeToLiveElement); } Element deadLetteringOnMessageExpirationElement = requestDoc.createElementNS( "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "DeadLetteringOnMessageExpiration"); deadLetteringOnMessageExpirationElement.appendChild(requestDoc .createTextNode(Boolean.toString(queue.isDeadLetteringOnMessageExpiration()).toLowerCase())); queueDescriptionElement.appendChild(deadLetteringOnMessageExpirationElement); if (queue.getDuplicateDetectionHistoryTimeWindow() != null) { Element duplicateDetectionHistoryTimeWindowElement = requestDoc.createElementNS( "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "DuplicateDetectionHistoryTimeWindow"); duplicateDetectionHistoryTimeWindowElement .appendChild(requestDoc.createTextNode(queue.getDuplicateDetectionHistoryTimeWindow())); queueDescriptionElement.appendChild(duplicateDetectionHistoryTimeWindowElement); } Element enableBatchedOperationsElement = requestDoc.createElementNS( "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "EnableBatchedOperations"); enableBatchedOperationsElement.appendChild( requestDoc.createTextNode(Boolean.toString(queue.isEnableBatchedOperations()).toLowerCase())); queueDescriptionElement.appendChild(enableBatchedOperationsElement); Element sizeInBytesElement = requestDoc.createElementNS( "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "SizeInBytes"); sizeInBytesElement.appendChild(requestDoc.createTextNode(Integer.toString(queue.getSizeInBytes()))); queueDescriptionElement.appendChild(sizeInBytesElement); Element messageCountElement = requestDoc.createElementNS( "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "MessageCount"); messageCountElement.appendChild(requestDoc.createTextNode(Integer.toString(queue.getMessageCount()))); queueDescriptionElement.appendChild(messageCountElement); Element isAnonymousAccessibleElement = requestDoc.createElementNS( "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "IsAnonymousAccessible"); isAnonymousAccessibleElement.appendChild( requestDoc.createTextNode(Boolean.toString(queue.isAnonymousAccessible()).toLowerCase())); queueDescriptionElement.appendChild(isAnonymousAccessibleElement); if (queue.getAuthorizationRules() != null) { if (queue.getAuthorizationRules() instanceof LazyCollection == false || ((LazyCollection) queue.getAuthorizationRules()).isInitialized()) { Element authorizationRulesSequenceElement = requestDoc.createElementNS( "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "AuthorizationRules"); for (ServiceBusSharedAccessAuthorizationRule authorizationRulesItem : queue .getAuthorizationRules()) { Element authorizationRuleElement = requestDoc.createElementNS( "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "AuthorizationRule"); authorizationRulesSequenceElement.appendChild(authorizationRuleElement); Attr typeAttribute2 = requestDoc.createAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "type"); typeAttribute2.setValue("SharedAccessAuthorizationRule"); authorizationRuleElement.setAttributeNode(typeAttribute2); if (authorizationRulesItem.getClaimType() != null) { Element claimTypeElement = requestDoc.createElementNS( "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "ClaimType"); claimTypeElement .appendChild(requestDoc.createTextNode(authorizationRulesItem.getClaimType())); authorizationRuleElement.appendChild(claimTypeElement); } if (authorizationRulesItem.getClaimValue() != null) { Element claimValueElement = requestDoc.createElementNS( "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "ClaimValue"); claimValueElement .appendChild(requestDoc.createTextNode(authorizationRulesItem.getClaimValue())); authorizationRuleElement.appendChild(claimValueElement); } if (authorizationRulesItem.getRights() != null) { if (authorizationRulesItem.getRights() instanceof LazyCollection == false || ((LazyCollection) authorizationRulesItem.getRights()).isInitialized()) { Element rightsSequenceElement = requestDoc.createElementNS( "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "Rights"); for (AccessRight rightsItem : authorizationRulesItem.getRights()) { Element rightsItemElement = requestDoc.createElementNS( "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "AccessRights"); rightsItemElement.appendChild(requestDoc.createTextNode(rightsItem.toString())); rightsSequenceElement.appendChild(rightsItemElement); } authorizationRuleElement.appendChild(rightsSequenceElement); } } Element createdTimeElement = requestDoc.createElementNS( "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "CreatedTime"); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'"); simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); createdTimeElement.appendChild(requestDoc.createTextNode( simpleDateFormat.format(authorizationRulesItem.getCreatedTime().getTime()))); authorizationRuleElement.appendChild(createdTimeElement); if (authorizationRulesItem.getKeyName() != null) { Element keyNameElement = requestDoc.createElementNS( "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "KeyName"); keyNameElement.appendChild(requestDoc.createTextNode(authorizationRulesItem.getKeyName())); authorizationRuleElement.appendChild(keyNameElement); } Element modifiedTimeElement = requestDoc.createElementNS( "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "ModifiedTime"); SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'"); simpleDateFormat2.setTimeZone(TimeZone.getTimeZone("UTC")); modifiedTimeElement.appendChild(requestDoc.createTextNode( simpleDateFormat2.format(authorizationRulesItem.getModifiedTime().getTime()))); authorizationRuleElement.appendChild(modifiedTimeElement); if (authorizationRulesItem.getPrimaryKey() != null) { Element primaryKeyElement = requestDoc.createElementNS( "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "PrimaryKey"); primaryKeyElement .appendChild(requestDoc.createTextNode(authorizationRulesItem.getPrimaryKey())); authorizationRuleElement.appendChild(primaryKeyElement); } if (authorizationRulesItem.getSecondaryKey() != null) { Element secondaryKeyElement = requestDoc.createElementNS( "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "SecondaryKey"); secondaryKeyElement .appendChild(requestDoc.createTextNode(authorizationRulesItem.getSecondaryKey())); authorizationRuleElement.appendChild(secondaryKeyElement); } } queueDescriptionElement.appendChild(authorizationRulesSequenceElement); } } if (queue.getStatus() != null) { Element statusElement = requestDoc.createElementNS( "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "Status"); statusElement.appendChild(requestDoc.createTextNode(queue.getStatus())); queueDescriptionElement.appendChild(statusElement); } Element supportOrderingElement = requestDoc.createElementNS( "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "SupportOrdering"); supportOrderingElement .appendChild(requestDoc.createTextNode(Boolean.toString(queue.isSupportOrdering()).toLowerCase())); queueDescriptionElement.appendChild(supportOrderingElement); if (queue.getCountDetails() != null) { Element countDetailsElement = requestDoc.createElementNS( "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "CountDetails"); queueDescriptionElement.appendChild(countDetailsElement); Element activeMessageCountElement = requestDoc.createElementNS( "http://schemas.microsoft.com/netservices/2011/06/servicebus", "ActiveMessageCount"); activeMessageCountElement.appendChild( requestDoc.createTextNode(Integer.toString(queue.getCountDetails().getActiveMessageCount()))); countDetailsElement.appendChild(activeMessageCountElement); Element deadLetterMessageCountElement = requestDoc.createElementNS( "http://schemas.microsoft.com/netservices/2011/06/servicebus", "DeadLetterMessageCount"); deadLetterMessageCountElement.appendChild(requestDoc .createTextNode(Integer.toString(queue.getCountDetails().getDeadLetterMessageCount()))); countDetailsElement.appendChild(deadLetterMessageCountElement); Element scheduledMessageCountElement = requestDoc.createElementNS( "http://schemas.microsoft.com/netservices/2011/06/servicebus", "ScheduledMessageCount"); scheduledMessageCountElement.appendChild(requestDoc .createTextNode(Integer.toString(queue.getCountDetails().getScheduledMessageCount()))); countDetailsElement.appendChild(scheduledMessageCountElement); Element transferDeadLetterMessageCountElement = requestDoc.createElementNS( "http://schemas.microsoft.com/netservices/2011/06/servicebus", "TransferDeadLetterMessageCount"); transferDeadLetterMessageCountElement.appendChild(requestDoc .createTextNode(Integer.toString(queue.getCountDetails().getTransferDeadLetterMessageCount()))); countDetailsElement.appendChild(transferDeadLetterMessageCountElement); Element transferMessageCountElement = requestDoc.createElementNS( "http://schemas.microsoft.com/netservices/2011/06/servicebus", "TransferMessageCount"); transferMessageCountElement.appendChild( requestDoc.createTextNode(Integer.toString(queue.getCountDetails().getTransferMessageCount()))); countDetailsElement.appendChild(transferMessageCountElement); } if (queue.getAutoDeleteOnIdle() != null) { Element autoDeleteOnIdleElement = requestDoc.createElementNS( "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "AutoDeleteOnIdle"); autoDeleteOnIdleElement.appendChild(requestDoc.createTextNode(queue.getAutoDeleteOnIdle())); queueDescriptionElement.appendChild(autoDeleteOnIdleElement); } if (queue.getEntityAvailabilityStatus() != null) { Element entityAvailabilityStatusElement = requestDoc.createElementNS( "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "EntityAvailabilityStatus"); entityAvailabilityStatusElement .appendChild(requestDoc.createTextNode(queue.getEntityAvailabilityStatus())); queueDescriptionElement.appendChild(entityAvailabilityStatusElement); } DOMSource domSource = new DOMSource(requestDoc); StringWriter stringWriter = new StringWriter(); StreamResult streamResult = new StreamResult(stringWriter); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.transform(domSource, streamResult); requestContent = stringWriter.toString(); StringEntity entity = new StringEntity(requestContent); httpRequest.setEntity(entity); httpRequest.setHeader("Content-Type", "application/atom+xml"); // Send Request HttpResponse httpResponse = null; try { if (shouldTrace) { CloudTracing.sendRequest(invocationId, httpRequest); } httpResponse = this.getClient().getHttpClient().execute(httpRequest); if (shouldTrace) { CloudTracing.receiveResponse(invocationId, httpResponse); } int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_CREATED) { ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result ServiceBusQueueResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_CREATED) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new ServiceBusQueueResponse(); DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance(); documentBuilderFactory2.setNamespaceAware(true); DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder(); Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent)); Element entryElement2 = XmlUtility.getElementByTagNameNS(responseDoc, "http://www.w3.org/2005/Atom", "entry"); if (entryElement2 != null) { Element titleElement = XmlUtility.getElementByTagNameNS(entryElement2, "http://www.w3.org/2005/Atom", "title"); if (titleElement != null) { } Element contentElement2 = XmlUtility.getElementByTagNameNS(entryElement2, "http://www.w3.org/2005/Atom", "content"); if (contentElement2 != null) { Element queueDescriptionElement2 = XmlUtility.getElementByTagNameNS(contentElement2, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "QueueDescription"); if (queueDescriptionElement2 != null) { ServiceBusQueue queueDescriptionInstance = new ServiceBusQueue(); result.setQueue(queueDescriptionInstance); Element lockDurationElement2 = XmlUtility.getElementByTagNameNS( queueDescriptionElement2, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "LockDuration"); if (lockDurationElement2 != null) { String lockDurationInstance; lockDurationInstance = lockDurationElement2.getTextContent(); queueDescriptionInstance.setLockDuration(lockDurationInstance); } Element maxSizeInMegabytesElement2 = XmlUtility.getElementByTagNameNS( queueDescriptionElement2, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "MaxSizeInMegabytes"); if (maxSizeInMegabytesElement2 != null) { int maxSizeInMegabytesInstance; maxSizeInMegabytesInstance = DatatypeConverter .parseInt(maxSizeInMegabytesElement2.getTextContent()); queueDescriptionInstance.setMaxSizeInMegabytes(maxSizeInMegabytesInstance); } Element requiresDuplicateDetectionElement2 = XmlUtility.getElementByTagNameNS( queueDescriptionElement2, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "RequiresDuplicateDetection"); if (requiresDuplicateDetectionElement2 != null) { boolean requiresDuplicateDetectionInstance; requiresDuplicateDetectionInstance = DatatypeConverter.parseBoolean( requiresDuplicateDetectionElement2.getTextContent().toLowerCase()); queueDescriptionInstance .setRequiresDuplicateDetection(requiresDuplicateDetectionInstance); } Element requiresSessionElement2 = XmlUtility.getElementByTagNameNS( queueDescriptionElement2, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "RequiresSession"); if (requiresSessionElement2 != null) { boolean requiresSessionInstance; requiresSessionInstance = DatatypeConverter .parseBoolean(requiresSessionElement2.getTextContent().toLowerCase()); queueDescriptionInstance.setRequiresSession(requiresSessionInstance); } Element defaultMessageTimeToLiveElement2 = XmlUtility.getElementByTagNameNS( queueDescriptionElement2, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "DefaultMessageTimeToLive"); if (defaultMessageTimeToLiveElement2 != null) { String defaultMessageTimeToLiveInstance; defaultMessageTimeToLiveInstance = defaultMessageTimeToLiveElement2 .getTextContent(); queueDescriptionInstance .setDefaultMessageTimeToLive(defaultMessageTimeToLiveInstance); } Element deadLetteringOnMessageExpirationElement2 = XmlUtility.getElementByTagNameNS( queueDescriptionElement2, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "DeadLetteringOnMessageExpiration"); if (deadLetteringOnMessageExpirationElement2 != null) { boolean deadLetteringOnMessageExpirationInstance; deadLetteringOnMessageExpirationInstance = DatatypeConverter.parseBoolean( deadLetteringOnMessageExpirationElement2.getTextContent().toLowerCase()); queueDescriptionInstance.setDeadLetteringOnMessageExpiration( deadLetteringOnMessageExpirationInstance); } Element duplicateDetectionHistoryTimeWindowElement2 = XmlUtility.getElementByTagNameNS( queueDescriptionElement2, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "DuplicateDetectionHistoryTimeWindow"); if (duplicateDetectionHistoryTimeWindowElement2 != null) { String duplicateDetectionHistoryTimeWindowInstance; duplicateDetectionHistoryTimeWindowInstance = duplicateDetectionHistoryTimeWindowElement2 .getTextContent(); queueDescriptionInstance.setDuplicateDetectionHistoryTimeWindow( duplicateDetectionHistoryTimeWindowInstance); } Element maxDeliveryCountElement = XmlUtility.getElementByTagNameNS( queueDescriptionElement2, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "MaxDeliveryCount"); if (maxDeliveryCountElement != null) { int maxDeliveryCountInstance; maxDeliveryCountInstance = DatatypeConverter .parseInt(maxDeliveryCountElement.getTextContent()); queueDescriptionInstance.setMaxDeliveryCount(maxDeliveryCountInstance); } Element enableBatchedOperationsElement2 = XmlUtility.getElementByTagNameNS( queueDescriptionElement2, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "EnableBatchedOperations"); if (enableBatchedOperationsElement2 != null) { boolean enableBatchedOperationsInstance; enableBatchedOperationsInstance = DatatypeConverter.parseBoolean( enableBatchedOperationsElement2.getTextContent().toLowerCase()); queueDescriptionInstance .setEnableBatchedOperations(enableBatchedOperationsInstance); } Element sizeInBytesElement2 = XmlUtility.getElementByTagNameNS(queueDescriptionElement2, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "SizeInBytes"); if (sizeInBytesElement2 != null) { int sizeInBytesInstance; sizeInBytesInstance = DatatypeConverter .parseInt(sizeInBytesElement2.getTextContent()); queueDescriptionInstance.setSizeInBytes(sizeInBytesInstance); } Element messageCountElement2 = XmlUtility.getElementByTagNameNS( queueDescriptionElement2, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "MessageCount"); if (messageCountElement2 != null) { int messageCountInstance; messageCountInstance = DatatypeConverter .parseInt(messageCountElement2.getTextContent()); queueDescriptionInstance.setMessageCount(messageCountInstance); } Element isAnonymousAccessibleElement2 = XmlUtility.getElementByTagNameNS( queueDescriptionElement2, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "IsAnonymousAccessible"); if (isAnonymousAccessibleElement2 != null) { boolean isAnonymousAccessibleInstance; isAnonymousAccessibleInstance = DatatypeConverter .parseBoolean(isAnonymousAccessibleElement2.getTextContent().toLowerCase()); queueDescriptionInstance.setIsAnonymousAccessible(isAnonymousAccessibleInstance); } Element authorizationRulesSequenceElement2 = XmlUtility.getElementByTagNameNS( queueDescriptionElement2, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "AuthorizationRules"); if (authorizationRulesSequenceElement2 != null) { for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility .getElementsByTagNameNS(authorizationRulesSequenceElement2, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "AuthorizationRule") .size(); i1 = i1 + 1) { org.w3c.dom.Element authorizationRulesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility .getElementsByTagNameNS(authorizationRulesSequenceElement2, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "AuthorizationRule") .get(i1)); ServiceBusSharedAccessAuthorizationRule authorizationRuleInstance = new ServiceBusSharedAccessAuthorizationRule(); queueDescriptionInstance.getAuthorizationRules().add(authorizationRuleInstance); Element claimTypeElement2 = XmlUtility.getElementByTagNameNS( authorizationRulesElement, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "ClaimType"); if (claimTypeElement2 != null) { String claimTypeInstance; claimTypeInstance = claimTypeElement2.getTextContent(); authorizationRuleInstance.setClaimType(claimTypeInstance); } Element claimValueElement2 = XmlUtility.getElementByTagNameNS( authorizationRulesElement, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "ClaimValue"); if (claimValueElement2 != null) { String claimValueInstance; claimValueInstance = claimValueElement2.getTextContent(); authorizationRuleInstance.setClaimValue(claimValueInstance); } Element rightsSequenceElement2 = XmlUtility.getElementByTagNameNS( authorizationRulesElement, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "Rights"); if (rightsSequenceElement2 != null) { for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility .getElementsByTagNameNS(rightsSequenceElement2, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "AccessRights") .size(); i2 = i2 + 1) { org.w3c.dom.Element rightsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility .getElementsByTagNameNS(rightsSequenceElement2, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "AccessRights") .get(i2)); authorizationRuleInstance.getRights() .add(AccessRight.valueOf(rightsElement.getTextContent())); } } Element createdTimeElement2 = XmlUtility.getElementByTagNameNS( authorizationRulesElement, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "CreatedTime"); if (createdTimeElement2 != null) { Calendar createdTimeInstance; createdTimeInstance = DatatypeConverter .parseDateTime(createdTimeElement2.getTextContent()); authorizationRuleInstance.setCreatedTime(createdTimeInstance); } Element keyNameElement2 = XmlUtility.getElementByTagNameNS( authorizationRulesElement, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "KeyName"); if (keyNameElement2 != null) { String keyNameInstance; keyNameInstance = keyNameElement2.getTextContent(); authorizationRuleInstance.setKeyName(keyNameInstance); } Element modifiedTimeElement2 = XmlUtility.getElementByTagNameNS( authorizationRulesElement, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "ModifiedTime"); if (modifiedTimeElement2 != null) { Calendar modifiedTimeInstance; modifiedTimeInstance = DatatypeConverter .parseDateTime(modifiedTimeElement2.getTextContent()); authorizationRuleInstance.setModifiedTime(modifiedTimeInstance); } Element primaryKeyElement2 = XmlUtility.getElementByTagNameNS( authorizationRulesElement, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "PrimaryKey"); if (primaryKeyElement2 != null) { String primaryKeyInstance; primaryKeyInstance = primaryKeyElement2.getTextContent(); authorizationRuleInstance.setPrimaryKey(primaryKeyInstance); } Element secondaryKeyElement2 = XmlUtility.getElementByTagNameNS( authorizationRulesElement, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "SecondaryKey"); if (secondaryKeyElement2 != null) { String secondaryKeyInstance; secondaryKeyInstance = secondaryKeyElement2.getTextContent(); authorizationRuleInstance.setSecondaryKey(secondaryKeyInstance); } } } Element statusElement2 = XmlUtility.getElementByTagNameNS(queueDescriptionElement2, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "Status"); if (statusElement2 != null) { String statusInstance; statusInstance = statusElement2.getTextContent(); queueDescriptionInstance.setStatus(statusInstance); } Element createdAtElement = XmlUtility.getElementByTagNameNS(queueDescriptionElement2, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "CreatedAt"); if (createdAtElement != null) { Calendar createdAtInstance; createdAtInstance = DatatypeConverter .parseDateTime(createdAtElement.getTextContent()); queueDescriptionInstance.setCreatedAt(createdAtInstance); } Element updatedAtElement = XmlUtility.getElementByTagNameNS(queueDescriptionElement2, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "UpdatedAt"); if (updatedAtElement != null) { Calendar updatedAtInstance; updatedAtInstance = DatatypeConverter .parseDateTime(updatedAtElement.getTextContent()); queueDescriptionInstance.setUpdatedAt(updatedAtInstance); } Element accessedAtElement = XmlUtility.getElementByTagNameNS(queueDescriptionElement2, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "AccessedAt"); if (accessedAtElement != null) { Calendar accessedAtInstance; accessedAtInstance = DatatypeConverter .parseDateTime(accessedAtElement.getTextContent()); queueDescriptionInstance.setAccessedAt(accessedAtInstance); } Element supportOrderingElement2 = XmlUtility.getElementByTagNameNS( queueDescriptionElement2, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "SupportOrdering"); if (supportOrderingElement2 != null) { boolean supportOrderingInstance; supportOrderingInstance = DatatypeConverter .parseBoolean(supportOrderingElement2.getTextContent().toLowerCase()); queueDescriptionInstance.setSupportOrdering(supportOrderingInstance); } Element countDetailsElement2 = XmlUtility.getElementByTagNameNS( queueDescriptionElement2, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "CountDetails"); if (countDetailsElement2 != null) { CountDetails countDetailsInstance = new CountDetails(); queueDescriptionInstance.setCountDetails(countDetailsInstance); Element activeMessageCountElement2 = XmlUtility.getElementByTagNameNS( countDetailsElement2, "http://schemas.microsoft.com/netservices/2011/06/servicebus", "ActiveMessageCount"); if (activeMessageCountElement2 != null) { int activeMessageCountInstance; activeMessageCountInstance = DatatypeConverter .parseInt(activeMessageCountElement2.getTextContent()); countDetailsInstance.setActiveMessageCount(activeMessageCountInstance); } Element deadLetterMessageCountElement2 = XmlUtility.getElementByTagNameNS( countDetailsElement2, "http://schemas.microsoft.com/netservices/2011/06/servicebus", "DeadLetterMessageCount"); if (deadLetterMessageCountElement2 != null) { int deadLetterMessageCountInstance; deadLetterMessageCountInstance = DatatypeConverter .parseInt(deadLetterMessageCountElement2.getTextContent()); countDetailsInstance.setDeadLetterMessageCount(deadLetterMessageCountInstance); } Element scheduledMessageCountElement2 = XmlUtility.getElementByTagNameNS( countDetailsElement2, "http://schemas.microsoft.com/netservices/2011/06/servicebus", "ScheduledMessageCount"); if (scheduledMessageCountElement2 != null) { int scheduledMessageCountInstance; scheduledMessageCountInstance = DatatypeConverter .parseInt(scheduledMessageCountElement2.getTextContent()); countDetailsInstance.setScheduledMessageCount(scheduledMessageCountInstance); } Element transferDeadLetterMessageCountElement2 = XmlUtility.getElementByTagNameNS( countDetailsElement2, "http://schemas.microsoft.com/netservices/2011/06/servicebus", "TransferDeadLetterMessageCount"); if (transferDeadLetterMessageCountElement2 != null) { int transferDeadLetterMessageCountInstance; transferDeadLetterMessageCountInstance = DatatypeConverter .parseInt(transferDeadLetterMessageCountElement2.getTextContent()); countDetailsInstance.setTransferDeadLetterMessageCount( transferDeadLetterMessageCountInstance); } Element transferMessageCountElement2 = XmlUtility.getElementByTagNameNS( countDetailsElement2, "http://schemas.microsoft.com/netservices/2011/06/servicebus", "TransferMessageCount"); if (transferMessageCountElement2 != null) { int transferMessageCountInstance; transferMessageCountInstance = DatatypeConverter .parseInt(transferMessageCountElement2.getTextContent()); countDetailsInstance.setTransferMessageCount(transferMessageCountInstance); } } Element autoDeleteOnIdleElement2 = XmlUtility.getElementByTagNameNS( queueDescriptionElement2, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "AutoDeleteOnIdle"); if (autoDeleteOnIdleElement2 != null) { String autoDeleteOnIdleInstance; autoDeleteOnIdleInstance = autoDeleteOnIdleElement2.getTextContent(); queueDescriptionInstance.setAutoDeleteOnIdle(autoDeleteOnIdleInstance); } Element entityAvailabilityStatusElement2 = XmlUtility.getElementByTagNameNS( queueDescriptionElement2, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "EntityAvailabilityStatus"); if (entityAvailabilityStatusElement2 != null) { String entityAvailabilityStatusInstance; entityAvailabilityStatusInstance = entityAvailabilityStatusElement2 .getTextContent(); queueDescriptionInstance .setEntityAvailabilityStatus(entityAvailabilityStatusInstance); } } } } } result.setStatusCode(statusCode); if (httpResponse.getHeaders("x-ms-request-id").length > 0) { result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); } if (shouldTrace) { CloudTracing.exit(invocationId, result); } return result; } finally { if (httpResponse != null && httpResponse.getEntity() != null) { httpResponse.getEntity().getContent().close(); } } }
From source file:com.microsoft.windowsazure.management.servicebus.NamespaceOperationsImpl.java
/** * The create namespace authorization rule operation creates an * authorization rule for a namespace// w ww . ja va 2 s . co m * * @param namespaceName Required. The namespace name. * @param rule Required. The shared access authorization rule. * @throws ParserConfigurationException Thrown if there was an error * configuring the parser for the response body. * @throws SAXException Thrown if there was an error parsing the response * body. * @throws TransformerException Thrown if there was an error creating the * DOM transformer. * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations. * @throws ServiceException Thrown if an unexpected response is found. * @return A response to a request for a particular authorization rule. */ @Override public ServiceBusAuthorizationRuleResponse createAuthorizationRule(String namespaceName, ServiceBusSharedAccessAuthorizationRule rule) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { // Validate if (namespaceName == null) { throw new NullPointerException("namespaceName"); } if (rule == null) { throw new NullPointerException("rule"); } // Tracing boolean shouldTrace = CloudTracing.getIsEnabled(); String invocationId = null; if (shouldTrace) { invocationId = Long.toString(CloudTracing.getNextInvocationId()); HashMap<String, Object> tracingParameters = new HashMap<String, Object>(); tracingParameters.put("namespaceName", namespaceName); tracingParameters.put("rule", rule); CloudTracing.enter(invocationId, this, "createAuthorizationRuleAsync", tracingParameters); } // Construct URL String url = ""; url = url + "/"; if (this.getClient().getCredentials().getSubscriptionId() != null) { url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8"); } url = url + "/services/servicebus/namespaces/"; url = url + URLEncoder.encode(namespaceName, "UTF-8"); url = url + "/AuthorizationRules"; 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("Accept", "application/atom+xml"); httpRequest.setHeader("Content-Type", "application/atom+xml"); httpRequest.setHeader("type", "entry"); httpRequest.setHeader("x-ms-version", "2013-08-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"); contentElement.setAttributeNode(typeAttribute); Element sharedAccessAuthorizationRuleElement = requestDoc.createElementNS( "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "SharedAccessAuthorizationRule"); contentElement.appendChild(sharedAccessAuthorizationRuleElement); if (rule.getClaimType() != null) { Element claimTypeElement = requestDoc.createElementNS( "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "ClaimType"); claimTypeElement.appendChild(requestDoc.createTextNode(rule.getClaimType())); sharedAccessAuthorizationRuleElement.appendChild(claimTypeElement); } if (rule.getClaimValue() != null) { Element claimValueElement = requestDoc.createElementNS( "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "ClaimValue"); claimValueElement.appendChild(requestDoc.createTextNode(rule.getClaimValue())); sharedAccessAuthorizationRuleElement.appendChild(claimValueElement); } if (rule.getRights() != null) { if (rule.getRights() instanceof LazyCollection == false || ((LazyCollection) rule.getRights()).isInitialized()) { Element rightsSequenceElement = requestDoc.createElementNS( "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "Rights"); for (AccessRight rightsItem : rule.getRights()) { Element rightsItemElement = requestDoc.createElementNS( "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "AccessRights"); rightsItemElement.appendChild(requestDoc.createTextNode(rightsItem.toString())); rightsSequenceElement.appendChild(rightsItemElement); } sharedAccessAuthorizationRuleElement.appendChild(rightsSequenceElement); } } Element createdTimeElement = requestDoc.createElementNS( "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "CreatedTime"); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'"); simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); createdTimeElement .appendChild(requestDoc.createTextNode(simpleDateFormat.format(rule.getCreatedTime().getTime()))); sharedAccessAuthorizationRuleElement.appendChild(createdTimeElement); Element modifiedTimeElement = requestDoc.createElementNS( "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "ModifiedTime"); SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'"); simpleDateFormat2.setTimeZone(TimeZone.getTimeZone("UTC")); modifiedTimeElement .appendChild(requestDoc.createTextNode(simpleDateFormat2.format(rule.getModifiedTime().getTime()))); sharedAccessAuthorizationRuleElement.appendChild(modifiedTimeElement); Element revisionElement = requestDoc .createElementNS("http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "Revision"); revisionElement.appendChild(requestDoc.createTextNode(Integer.toString(rule.getRevision()))); sharedAccessAuthorizationRuleElement.appendChild(revisionElement); if (rule.getKeyName() != null) { Element keyNameElement = requestDoc.createElementNS( "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "KeyName"); keyNameElement.appendChild(requestDoc.createTextNode(rule.getKeyName())); sharedAccessAuthorizationRuleElement.appendChild(keyNameElement); } if (rule.getPrimaryKey() != null) { Element primaryKeyElement = requestDoc.createElementNS( "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "PrimaryKey"); primaryKeyElement.appendChild(requestDoc.createTextNode(rule.getPrimaryKey())); sharedAccessAuthorizationRuleElement.appendChild(primaryKeyElement); } DOMSource domSource = new DOMSource(requestDoc); StringWriter stringWriter = new StringWriter(); StreamResult streamResult = new StreamResult(stringWriter); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.transform(domSource, streamResult); requestContent = stringWriter.toString(); StringEntity entity = new StringEntity(requestContent); httpRequest.setEntity(entity); httpRequest.setHeader("Content-Type", "application/atom+xml"); // Send Request HttpResponse httpResponse = null; try { if (shouldTrace) { CloudTracing.sendRequest(invocationId, httpRequest); } httpResponse = this.getClient().getHttpClient().execute(httpRequest); if (shouldTrace) { CloudTracing.receiveResponse(invocationId, httpResponse); } int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_CREATED) { ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result ServiceBusAuthorizationRuleResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_CREATED) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new ServiceBusAuthorizationRuleResponse(); DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance(); documentBuilderFactory2.setNamespaceAware(true); DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder(); Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent)); Element entryElement2 = XmlUtility.getElementByTagNameNS(responseDoc, "http://www.w3.org/2005/Atom", "entry"); if (entryElement2 != null) { Element contentElement2 = XmlUtility.getElementByTagNameNS(entryElement2, "http://www.w3.org/2005/Atom", "content"); if (contentElement2 != null) { Element sharedAccessAuthorizationRuleElement2 = XmlUtility.getElementByTagNameNS( contentElement2, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "SharedAccessAuthorizationRule"); if (sharedAccessAuthorizationRuleElement2 != null) { ServiceBusSharedAccessAuthorizationRule sharedAccessAuthorizationRuleInstance = new ServiceBusSharedAccessAuthorizationRule(); result.setAuthorizationRule(sharedAccessAuthorizationRuleInstance); Element claimTypeElement2 = XmlUtility.getElementByTagNameNS( sharedAccessAuthorizationRuleElement2, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "ClaimType"); if (claimTypeElement2 != null) { String claimTypeInstance; claimTypeInstance = claimTypeElement2.getTextContent(); sharedAccessAuthorizationRuleInstance.setClaimType(claimTypeInstance); } Element claimValueElement2 = XmlUtility.getElementByTagNameNS( sharedAccessAuthorizationRuleElement2, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "ClaimValue"); if (claimValueElement2 != null) { String claimValueInstance; claimValueInstance = claimValueElement2.getTextContent(); sharedAccessAuthorizationRuleInstance.setClaimValue(claimValueInstance); } Element rightsSequenceElement2 = XmlUtility.getElementByTagNameNS( sharedAccessAuthorizationRuleElement2, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "Rights"); if (rightsSequenceElement2 != null) { for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility .getElementsByTagNameNS(rightsSequenceElement2, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "AccessRights") .size(); i1 = i1 + 1) { org.w3c.dom.Element rightsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility .getElementsByTagNameNS(rightsSequenceElement2, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "AccessRights") .get(i1)); sharedAccessAuthorizationRuleInstance.getRights() .add(AccessRight.valueOf(rightsElement.getTextContent())); } } Element createdTimeElement2 = XmlUtility.getElementByTagNameNS( sharedAccessAuthorizationRuleElement2, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "CreatedTime"); if (createdTimeElement2 != null) { Calendar createdTimeInstance; createdTimeInstance = DatatypeConverter .parseDateTime(createdTimeElement2.getTextContent()); sharedAccessAuthorizationRuleInstance.setCreatedTime(createdTimeInstance); } Element modifiedTimeElement2 = XmlUtility.getElementByTagNameNS( sharedAccessAuthorizationRuleElement2, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "ModifiedTime"); if (modifiedTimeElement2 != null) { Calendar modifiedTimeInstance; modifiedTimeInstance = DatatypeConverter .parseDateTime(modifiedTimeElement2.getTextContent()); sharedAccessAuthorizationRuleInstance.setModifiedTime(modifiedTimeInstance); } Element keyNameElement2 = XmlUtility.getElementByTagNameNS( sharedAccessAuthorizationRuleElement2, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "KeyName"); if (keyNameElement2 != null) { String keyNameInstance; keyNameInstance = keyNameElement2.getTextContent(); sharedAccessAuthorizationRuleInstance.setKeyName(keyNameInstance); } Element primaryKeyElement2 = XmlUtility.getElementByTagNameNS( sharedAccessAuthorizationRuleElement2, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "PrimaryKey"); if (primaryKeyElement2 != null) { String primaryKeyInstance; primaryKeyInstance = primaryKeyElement2.getTextContent(); sharedAccessAuthorizationRuleInstance.setPrimaryKey(primaryKeyInstance); } Element secondaryKeyElement = XmlUtility.getElementByTagNameNS( sharedAccessAuthorizationRuleElement2, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "SecondaryKey"); if (secondaryKeyElement != null) { String secondaryKeyInstance; secondaryKeyInstance = secondaryKeyElement.getTextContent(); sharedAccessAuthorizationRuleInstance.setSecondaryKey(secondaryKeyInstance); } Element revisionElement2 = XmlUtility.getElementByTagNameNS( sharedAccessAuthorizationRuleElement2, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "Revision"); if (revisionElement2 != null) { int revisionInstance; revisionInstance = DatatypeConverter.parseInt(revisionElement2.getTextContent()); sharedAccessAuthorizationRuleInstance.setRevision(revisionInstance); } } } } } result.setStatusCode(statusCode); if (httpResponse.getHeaders("x-ms-request-id").length > 0) { result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); } if (shouldTrace) { CloudTracing.exit(invocationId, result); } return result; } finally { if (httpResponse != null && httpResponse.getEntity() != null) { httpResponse.getEntity().getContent().close(); } } }
From source file:com.microsoft.azure.management.notificationhubs.NotificationHubOperationsImpl.java
/** * Creates a new NotificationHub in a namespace. (see * http://msdn.microsoft.com/en-us/library/windowsazure/jj856303.aspx for * more information)/*from w w w . j a v a2s . c o m*/ * * @param resourceGroupName Required. The name of the resource group. * @param namespaceName Required. The namespace name. * @param notificationHubName Required. The notification hub name. * @param parameters Required. Parameters supplied to the create a Namespace * Resource. * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations. * @throws ServiceException Thrown if an unexpected response is found. * @return Response of the CreateOrUpdate operation on the NotificationHub */ @Override public NotificationHubCreateOrUpdateResponse create(String resourceGroupName, String namespaceName, String notificationHubName, NotificationHubCreateOrUpdateParameters parameters) throws IOException, ServiceException { // Validate if (resourceGroupName == null) { throw new NullPointerException("resourceGroupName"); } if (namespaceName == null) { throw new NullPointerException("namespaceName"); } if (notificationHubName == null) { throw new NullPointerException("notificationHubName"); } if (parameters == null) { throw new NullPointerException("parameters"); } if (parameters.getLocation() == null) { throw new NullPointerException("parameters.Location"); } if (parameters.getProperties() == null) { throw new NullPointerException("parameters.Properties"); } // Tracing boolean shouldTrace = CloudTracing.getIsEnabled(); String invocationId = null; if (shouldTrace) { invocationId = Long.toString(CloudTracing.getNextInvocationId()); HashMap<String, Object> tracingParameters = new HashMap<String, Object>(); tracingParameters.put("resourceGroupName", resourceGroupName); tracingParameters.put("namespaceName", namespaceName); tracingParameters.put("notificationHubName", notificationHubName); tracingParameters.put("parameters", parameters); CloudTracing.enter(invocationId, this, "createAsync", tracingParameters); } // Construct URL String url = ""; url = url + "/subscriptions/"; if (this.getClient().getCredentials().getSubscriptionId() != null) { url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8"); } url = url + "/resourceGroups/"; url = url + URLEncoder.encode(resourceGroupName, "UTF-8"); url = url + "/providers/"; url = url + "Microsoft.NotificationHubs"; url = url + "/namespaces/"; url = url + URLEncoder.encode(namespaceName, "UTF-8"); url = url + "/notificationHubs/"; url = url + URLEncoder.encode(notificationHubName, "UTF-8"); ArrayList<String> queryParameters = new ArrayList<String>(); queryParameters.add("api-version=" + "2014-09-01"); if (queryParameters.size() > 0) { url = url + "?" + CollectionStringBuilder.join(queryParameters, "&"); } String baseUrl = this.getClient().getBaseUri().toString(); // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl.charAt(baseUrl.length() - 1) == '/') { baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); } if (url.charAt(0) == '/') { url = url.substring(1); } url = baseUrl + "/" + url; url = url.replace(" ", "%20"); // Create HTTP transport objects HttpPut httpRequest = new HttpPut(url); // Set Headers httpRequest.setHeader("Content-Type", "application/json"); // Serialize Request String requestContent = null; JsonNode requestDoc = null; ObjectMapper objectMapper = new ObjectMapper(); ObjectNode notificationHubCreateOrUpdateParametersValue = objectMapper.createObjectNode(); requestDoc = notificationHubCreateOrUpdateParametersValue; ((ObjectNode) notificationHubCreateOrUpdateParametersValue).put("location", parameters.getLocation()); if (parameters.getTags() != null) { if (parameters.getTags() instanceof LazyCollection == false || ((LazyCollection) parameters.getTags()).isInitialized()) { ObjectNode tagsDictionary = objectMapper.createObjectNode(); for (Map.Entry<String, String> entry : parameters.getTags().entrySet()) { String tagsKey = entry.getKey(); String tagsValue = entry.getValue(); ((ObjectNode) tagsDictionary).put(tagsKey, tagsValue); } ((ObjectNode) notificationHubCreateOrUpdateParametersValue).put("tags", tagsDictionary); } } ObjectNode propertiesValue = objectMapper.createObjectNode(); ((ObjectNode) notificationHubCreateOrUpdateParametersValue).put("properties", propertiesValue); if (parameters.getProperties().getName() != null) { ((ObjectNode) propertiesValue).put("name", parameters.getProperties().getName()); } if (parameters.getProperties().getRegistrationTtl() != null) { ((ObjectNode) propertiesValue).put("registrationTtl", parameters.getProperties().getRegistrationTtl()); } if (parameters.getProperties().getAuthorizationRules() != null) { if (parameters.getProperties().getAuthorizationRules() instanceof LazyCollection == false || ((LazyCollection) parameters.getProperties().getAuthorizationRules()).isInitialized()) { ArrayNode authorizationRulesArray = objectMapper.createArrayNode(); for (SharedAccessAuthorizationRuleProperties authorizationRulesItem : parameters.getProperties() .getAuthorizationRules()) { if (authorizationRulesItem.getPrimaryKey() != null) { requestDoc = authorizationRulesItem.getPrimaryKey(); } if (authorizationRulesItem.getSecondaryKey() != null) { requestDoc = authorizationRulesItem.getSecondaryKey(); } if (authorizationRulesItem.getKeyName() != null) { requestDoc = authorizationRulesItem.getKeyName(); } if (authorizationRulesItem.getClaimType() != null) { requestDoc = authorizationRulesItem.getClaimType(); } if (authorizationRulesItem.getClaimValue() != null) { requestDoc = authorizationRulesItem.getClaimValue(); } if (authorizationRulesItem.getRights() != null) { ArrayNode rightsArray = objectMapper.createArrayNode(); for (AccessRights rightsItem : authorizationRulesItem.getRights()) { rightsArray.add(rightsItem.toString()); } requestDoc = rightsArray; } SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'"); simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); requestDoc = simpleDateFormat.format(authorizationRulesItem.getCreatedTime().getTime()); SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'"); simpleDateFormat2.setTimeZone(TimeZone.getTimeZone("UTC")); requestDoc = simpleDateFormat2.format(authorizationRulesItem.getModifiedTime().getTime()); requestDoc = authorizationRulesItem.getRevision(); } ((ObjectNode) propertiesValue).put("authorizationRules", authorizationRulesArray); } } if (parameters.getProperties().getApnsCredential() != null) { ObjectNode apnsCredentialValue = objectMapper.createObjectNode(); ((ObjectNode) propertiesValue).put("apnsCredential", apnsCredentialValue); if (parameters.getProperties().getApnsCredential().getProperties() != null) { ObjectNode propertiesValue2 = objectMapper.createObjectNode(); ((ObjectNode) apnsCredentialValue).put("properties", propertiesValue2); if (parameters.getProperties().getApnsCredential().getProperties().getApnsCertificate() != null) { ((ObjectNode) propertiesValue2).put("apnsCertificate", parameters.getProperties().getApnsCredential().getProperties().getApnsCertificate()); } if (parameters.getProperties().getApnsCredential().getProperties().getCertificateKey() != null) { ((ObjectNode) propertiesValue2).put("certificateKey", parameters.getProperties().getApnsCredential().getProperties().getCertificateKey()); } if (parameters.getProperties().getApnsCredential().getProperties().getEndpoint() != null) { ((ObjectNode) propertiesValue2).put("endpoint", parameters.getProperties().getApnsCredential().getProperties().getEndpoint()); } if (parameters.getProperties().getApnsCredential().getProperties().getThumbprint() != null) { ((ObjectNode) propertiesValue2).put("thumbprint", parameters.getProperties().getApnsCredential().getProperties().getThumbprint()); } } } if (parameters.getProperties().getWnsCredential() != null) { ObjectNode wnsCredentialValue = objectMapper.createObjectNode(); ((ObjectNode) propertiesValue).put("wnsCredential", wnsCredentialValue); if (parameters.getProperties().getWnsCredential().getProperties() != null) { ObjectNode propertiesValue3 = objectMapper.createObjectNode(); ((ObjectNode) wnsCredentialValue).put("properties", propertiesValue3); if (parameters.getProperties().getWnsCredential().getProperties().getPackageSid() != null) { ((ObjectNode) propertiesValue3).put("packageSid", parameters.getProperties().getWnsCredential().getProperties().getPackageSid()); } if (parameters.getProperties().getWnsCredential().getProperties().getSecretKey() != null) { ((ObjectNode) propertiesValue3).put("secretKey", parameters.getProperties().getWnsCredential().getProperties().getSecretKey()); } if (parameters.getProperties().getWnsCredential().getProperties() .getWindowsLiveEndpoint() != null) { ((ObjectNode) propertiesValue3).put("windowsLiveEndpoint", parameters.getProperties().getWnsCredential().getProperties().getWindowsLiveEndpoint()); } } } if (parameters.getProperties().getGcmCredential() != null) { ObjectNode gcmCredentialValue = objectMapper.createObjectNode(); ((ObjectNode) propertiesValue).put("gcmCredential", gcmCredentialValue); if (parameters.getProperties().getGcmCredential().getProperties() != null) { ObjectNode propertiesValue4 = objectMapper.createObjectNode(); ((ObjectNode) gcmCredentialValue).put("properties", propertiesValue4); if (parameters.getProperties().getGcmCredential().getProperties().getGcmEndpoint() != null) { ((ObjectNode) propertiesValue4).put("gcmEndpoint", parameters.getProperties().getGcmCredential().getProperties().getGcmEndpoint()); } if (parameters.getProperties().getGcmCredential().getProperties().getGoogleApiKey() != null) { ((ObjectNode) propertiesValue4).put("googleApiKey", parameters.getProperties().getGcmCredential().getProperties().getGoogleApiKey()); } } } if (parameters.getProperties().getMpnsCredential() != null) { ObjectNode mpnsCredentialValue = objectMapper.createObjectNode(); ((ObjectNode) propertiesValue).put("mpnsCredential", mpnsCredentialValue); if (parameters.getProperties().getMpnsCredential().getProperties() != null) { ObjectNode propertiesValue5 = objectMapper.createObjectNode(); ((ObjectNode) mpnsCredentialValue).put("properties", propertiesValue5); if (parameters.getProperties().getMpnsCredential().getProperties().getMpnsCertificate() != null) { ((ObjectNode) propertiesValue5).put("mpnsCertificate", parameters.getProperties().getMpnsCredential().getProperties().getMpnsCertificate()); } if (parameters.getProperties().getMpnsCredential().getProperties().getCertificateKey() != null) { ((ObjectNode) propertiesValue5).put("certificateKey", parameters.getProperties().getMpnsCredential().getProperties().getCertificateKey()); } if (parameters.getProperties().getMpnsCredential().getProperties().getThumbprint() != null) { ((ObjectNode) propertiesValue5).put("thumbprint", parameters.getProperties().getMpnsCredential().getProperties().getThumbprint()); } } } if (parameters.getProperties().getAdmCredential() != null) { ObjectNode admCredentialValue = objectMapper.createObjectNode(); ((ObjectNode) propertiesValue).put("admCredential", admCredentialValue); if (parameters.getProperties().getAdmCredential().getProperties() != null) { ObjectNode propertiesValue6 = objectMapper.createObjectNode(); ((ObjectNode) admCredentialValue).put("properties", propertiesValue6); if (parameters.getProperties().getAdmCredential().getProperties().getClientId() != null) { ((ObjectNode) propertiesValue6).put("clientId", parameters.getProperties().getAdmCredential().getProperties().getClientId()); } if (parameters.getProperties().getAdmCredential().getProperties().getClientSecret() != null) { ((ObjectNode) propertiesValue6).put("clientSecret", parameters.getProperties().getAdmCredential().getProperties().getClientSecret()); } if (parameters.getProperties().getAdmCredential().getProperties().getAuthTokenUrl() != null) { ((ObjectNode) propertiesValue6).put("authTokenUrl", parameters.getProperties().getAdmCredential().getProperties().getAuthTokenUrl()); } } } if (parameters.getProperties().getBaiduCredential() != null) { ObjectNode baiduCredentialValue = objectMapper.createObjectNode(); ((ObjectNode) propertiesValue).put("baiduCredential", baiduCredentialValue); if (parameters.getProperties().getBaiduCredential().getProperties() != null) { ObjectNode propertiesValue7 = objectMapper.createObjectNode(); ((ObjectNode) baiduCredentialValue).put("properties", propertiesValue7); if (parameters.getProperties().getBaiduCredential().getProperties().getBaiduApiKey() != null) { ((ObjectNode) propertiesValue7).put("baiduApiKey", parameters.getProperties().getBaiduCredential().getProperties().getBaiduApiKey()); } if (parameters.getProperties().getBaiduCredential().getProperties().getBaiduEndPoint() != null) { ((ObjectNode) propertiesValue7).put("baiduEndPoint", parameters.getProperties().getBaiduCredential().getProperties().getBaiduEndPoint()); } if (parameters.getProperties().getBaiduCredential().getProperties().getBaiduSecretKey() != null) { ((ObjectNode) propertiesValue7).put("baiduSecretKey", parameters.getProperties().getBaiduCredential().getProperties().getBaiduSecretKey()); } } } StringWriter stringWriter = new StringWriter(); objectMapper.writeValue(stringWriter, requestDoc); requestContent = stringWriter.toString(); StringEntity entity = new StringEntity(requestContent); httpRequest.setEntity(entity); httpRequest.setHeader("Content-Type", "application/json"); // Send Request HttpResponse httpResponse = null; try { if (shouldTrace) { CloudTracing.sendRequest(invocationId, httpRequest); } httpResponse = this.getClient().getHttpClient().execute(httpRequest); if (shouldTrace) { CloudTracing.receiveResponse(invocationId, httpResponse); } int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED) { ServiceException ex = ServiceException.createFromJson(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result NotificationHubCreateOrUpdateResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new NotificationHubCreateOrUpdateResponse(); JsonNode responseDoc = null; String responseDocContent = IOUtils.toString(responseContent); if (responseDocContent == null == false && responseDocContent.length() > 0) { responseDoc = objectMapper.readTree(responseDocContent); } if (responseDoc != null && responseDoc instanceof NullNode == false) { NotificationHubResource valueInstance = new NotificationHubResource(); result.setValue(valueInstance); JsonNode idValue = responseDoc.get("id"); if (idValue != null && idValue instanceof NullNode == false) { String idInstance; idInstance = idValue.getTextValue(); valueInstance.setId(idInstance); } JsonNode locationValue = responseDoc.get("location"); if (locationValue != null && locationValue instanceof NullNode == false) { String locationInstance; locationInstance = locationValue.getTextValue(); valueInstance.setLocation(locationInstance); } JsonNode nameValue = responseDoc.get("name"); if (nameValue != null && nameValue instanceof NullNode == false) { String nameInstance; nameInstance = nameValue.getTextValue(); valueInstance.setName(nameInstance); } JsonNode typeValue = responseDoc.get("type"); if (typeValue != null && typeValue instanceof NullNode == false) { String typeInstance; typeInstance = typeValue.getTextValue(); valueInstance.setType(typeInstance); } JsonNode tagsSequenceElement = ((JsonNode) responseDoc.get("tags")); if (tagsSequenceElement != null && tagsSequenceElement instanceof NullNode == false) { Iterator<Map.Entry<String, JsonNode>> itr = tagsSequenceElement.getFields(); while (itr.hasNext()) { Map.Entry<String, JsonNode> property = itr.next(); String tagsKey2 = property.getKey(); String tagsValue2 = property.getValue().getTextValue(); valueInstance.getTags().put(tagsKey2, tagsValue2); } } JsonNode propertiesValue8 = responseDoc.get("properties"); if (propertiesValue8 != null && propertiesValue8 instanceof NullNode == false) { NotificationHubProperties propertiesInstance = new NotificationHubProperties(); valueInstance.setProperties(propertiesInstance); JsonNode nameValue2 = propertiesValue8.get("name"); if (nameValue2 != null && nameValue2 instanceof NullNode == false) { String nameInstance2; nameInstance2 = nameValue2.getTextValue(); propertiesInstance.setName(nameInstance2); } JsonNode registrationTtlValue = propertiesValue8.get("registrationTtl"); if (registrationTtlValue != null && registrationTtlValue instanceof NullNode == false) { String registrationTtlInstance; registrationTtlInstance = registrationTtlValue.getTextValue(); propertiesInstance.setRegistrationTtl(registrationTtlInstance); } JsonNode authorizationRulesArray2 = propertiesValue8.get("authorizationRules"); if (authorizationRulesArray2 != null && authorizationRulesArray2 instanceof NullNode == false) { for (JsonNode authorizationRulesValue : ((ArrayNode) authorizationRulesArray2)) { SharedAccessAuthorizationRuleProperties sharedAccessAuthorizationRulePropertiesInstance = new SharedAccessAuthorizationRuleProperties(); propertiesInstance.getAuthorizationRules() .add(sharedAccessAuthorizationRulePropertiesInstance); JsonNode primaryKeyValue = authorizationRulesValue.get("primaryKey"); if (primaryKeyValue != null && primaryKeyValue instanceof NullNode == false) { String primaryKeyInstance; primaryKeyInstance = primaryKeyValue.getTextValue(); sharedAccessAuthorizationRulePropertiesInstance .setPrimaryKey(primaryKeyInstance); } JsonNode secondaryKeyValue = authorizationRulesValue.get("secondaryKey"); if (secondaryKeyValue != null && secondaryKeyValue instanceof NullNode == false) { String secondaryKeyInstance; secondaryKeyInstance = secondaryKeyValue.getTextValue(); sharedAccessAuthorizationRulePropertiesInstance .setSecondaryKey(secondaryKeyInstance); } JsonNode keyNameValue = authorizationRulesValue.get("keyName"); if (keyNameValue != null && keyNameValue instanceof NullNode == false) { String keyNameInstance; keyNameInstance = keyNameValue.getTextValue(); sharedAccessAuthorizationRulePropertiesInstance.setKeyName(keyNameInstance); } JsonNode claimTypeValue = authorizationRulesValue.get("claimType"); if (claimTypeValue != null && claimTypeValue instanceof NullNode == false) { String claimTypeInstance; claimTypeInstance = claimTypeValue.getTextValue(); sharedAccessAuthorizationRulePropertiesInstance.setClaimType(claimTypeInstance); } JsonNode claimValueValue = authorizationRulesValue.get("claimValue"); if (claimValueValue != null && claimValueValue instanceof NullNode == false) { String claimValueInstance; claimValueInstance = claimValueValue.getTextValue(); sharedAccessAuthorizationRulePropertiesInstance .setClaimValue(claimValueInstance); } JsonNode rightsArray2 = authorizationRulesValue.get("rights"); if (rightsArray2 != null && rightsArray2 instanceof NullNode == false) { for (JsonNode rightsValue : ((ArrayNode) rightsArray2)) { sharedAccessAuthorizationRulePropertiesInstance.getRights() .add(Enum.valueOf(AccessRights.class, rightsValue.getTextValue())); } } JsonNode createdTimeValue = authorizationRulesValue.get("createdTime"); if (createdTimeValue != null && createdTimeValue instanceof NullNode == false) { Calendar createdTimeInstance; createdTimeInstance = DatatypeConverter .parseDateTime(createdTimeValue.getTextValue()); sharedAccessAuthorizationRulePropertiesInstance .setCreatedTime(createdTimeInstance); } JsonNode modifiedTimeValue = authorizationRulesValue.get("modifiedTime"); if (modifiedTimeValue != null && modifiedTimeValue instanceof NullNode == false) { Calendar modifiedTimeInstance; modifiedTimeInstance = DatatypeConverter .parseDateTime(modifiedTimeValue.getTextValue()); sharedAccessAuthorizationRulePropertiesInstance .setModifiedTime(modifiedTimeInstance); } JsonNode revisionValue = authorizationRulesValue.get("revision"); if (revisionValue != null && revisionValue instanceof NullNode == false) { int revisionInstance; revisionInstance = revisionValue.getIntValue(); sharedAccessAuthorizationRulePropertiesInstance.setRevision(revisionInstance); } } } JsonNode apnsCredentialValue2 = propertiesValue8.get("apnsCredential"); if (apnsCredentialValue2 != null && apnsCredentialValue2 instanceof NullNode == false) { ApnsCredential apnsCredentialInstance = new ApnsCredential(); propertiesInstance.setApnsCredential(apnsCredentialInstance); JsonNode propertiesValue9 = apnsCredentialValue2.get("properties"); if (propertiesValue9 != null && propertiesValue9 instanceof NullNode == false) { ApnsCredentialProperties propertiesInstance2 = new ApnsCredentialProperties(); apnsCredentialInstance.setProperties(propertiesInstance2); JsonNode apnsCertificateValue = propertiesValue9.get("apnsCertificate"); if (apnsCertificateValue != null && apnsCertificateValue instanceof NullNode == false) { String apnsCertificateInstance; apnsCertificateInstance = apnsCertificateValue.getTextValue(); propertiesInstance2.setApnsCertificate(apnsCertificateInstance); } JsonNode certificateKeyValue = propertiesValue9.get("certificateKey"); if (certificateKeyValue != null && certificateKeyValue instanceof NullNode == false) { String certificateKeyInstance; certificateKeyInstance = certificateKeyValue.getTextValue(); propertiesInstance2.setCertificateKey(certificateKeyInstance); } JsonNode endpointValue = propertiesValue9.get("endpoint"); if (endpointValue != null && endpointValue instanceof NullNode == false) { String endpointInstance; endpointInstance = endpointValue.getTextValue(); propertiesInstance2.setEndpoint(endpointInstance); } JsonNode thumbprintValue = propertiesValue9.get("thumbprint"); if (thumbprintValue != null && thumbprintValue instanceof NullNode == false) { String thumbprintInstance; thumbprintInstance = thumbprintValue.getTextValue(); propertiesInstance2.setThumbprint(thumbprintInstance); } } } JsonNode wnsCredentialValue2 = propertiesValue8.get("wnsCredential"); if (wnsCredentialValue2 != null && wnsCredentialValue2 instanceof NullNode == false) { WnsCredential wnsCredentialInstance = new WnsCredential(); propertiesInstance.setWnsCredential(wnsCredentialInstance); JsonNode propertiesValue10 = wnsCredentialValue2.get("properties"); if (propertiesValue10 != null && propertiesValue10 instanceof NullNode == false) { WnsCredentialProperties propertiesInstance3 = new WnsCredentialProperties(); wnsCredentialInstance.setProperties(propertiesInstance3); JsonNode packageSidValue = propertiesValue10.get("packageSid"); if (packageSidValue != null && packageSidValue instanceof NullNode == false) { String packageSidInstance; packageSidInstance = packageSidValue.getTextValue(); propertiesInstance3.setPackageSid(packageSidInstance); } JsonNode secretKeyValue = propertiesValue10.get("secretKey"); if (secretKeyValue != null && secretKeyValue instanceof NullNode == false) { String secretKeyInstance; secretKeyInstance = secretKeyValue.getTextValue(); propertiesInstance3.setSecretKey(secretKeyInstance); } JsonNode windowsLiveEndpointValue = propertiesValue10.get("windowsLiveEndpoint"); if (windowsLiveEndpointValue != null && windowsLiveEndpointValue instanceof NullNode == false) { String windowsLiveEndpointInstance; windowsLiveEndpointInstance = windowsLiveEndpointValue.getTextValue(); propertiesInstance3.setWindowsLiveEndpoint(windowsLiveEndpointInstance); } } } JsonNode gcmCredentialValue2 = propertiesValue8.get("gcmCredential"); if (gcmCredentialValue2 != null && gcmCredentialValue2 instanceof NullNode == false) { GcmCredential gcmCredentialInstance = new GcmCredential(); propertiesInstance.setGcmCredential(gcmCredentialInstance); JsonNode propertiesValue11 = gcmCredentialValue2.get("properties"); if (propertiesValue11 != null && propertiesValue11 instanceof NullNode == false) { GcmCredentialProperties propertiesInstance4 = new GcmCredentialProperties(); gcmCredentialInstance.setProperties(propertiesInstance4); JsonNode gcmEndpointValue = propertiesValue11.get("gcmEndpoint"); if (gcmEndpointValue != null && gcmEndpointValue instanceof NullNode == false) { String gcmEndpointInstance; gcmEndpointInstance = gcmEndpointValue.getTextValue(); propertiesInstance4.setGcmEndpoint(gcmEndpointInstance); } JsonNode googleApiKeyValue = propertiesValue11.get("googleApiKey"); if (googleApiKeyValue != null && googleApiKeyValue instanceof NullNode == false) { String googleApiKeyInstance; googleApiKeyInstance = googleApiKeyValue.getTextValue(); propertiesInstance4.setGoogleApiKey(googleApiKeyInstance); } } } JsonNode mpnsCredentialValue2 = propertiesValue8.get("mpnsCredential"); if (mpnsCredentialValue2 != null && mpnsCredentialValue2 instanceof NullNode == false) { MpnsCredential mpnsCredentialInstance = new MpnsCredential(); propertiesInstance.setMpnsCredential(mpnsCredentialInstance); JsonNode propertiesValue12 = mpnsCredentialValue2.get("properties"); if (propertiesValue12 != null && propertiesValue12 instanceof NullNode == false) { MpnsCredentialProperties propertiesInstance5 = new MpnsCredentialProperties(); mpnsCredentialInstance.setProperties(propertiesInstance5); JsonNode mpnsCertificateValue = propertiesValue12.get("mpnsCertificate"); if (mpnsCertificateValue != null && mpnsCertificateValue instanceof NullNode == false) { String mpnsCertificateInstance; mpnsCertificateInstance = mpnsCertificateValue.getTextValue(); propertiesInstance5.setMpnsCertificate(mpnsCertificateInstance); } JsonNode certificateKeyValue2 = propertiesValue12.get("certificateKey"); if (certificateKeyValue2 != null && certificateKeyValue2 instanceof NullNode == false) { String certificateKeyInstance2; certificateKeyInstance2 = certificateKeyValue2.getTextValue(); propertiesInstance5.setCertificateKey(certificateKeyInstance2); } JsonNode thumbprintValue2 = propertiesValue12.get("thumbprint"); if (thumbprintValue2 != null && thumbprintValue2 instanceof NullNode == false) { String thumbprintInstance2; thumbprintInstance2 = thumbprintValue2.getTextValue(); propertiesInstance5.setThumbprint(thumbprintInstance2); } } } JsonNode admCredentialValue2 = propertiesValue8.get("admCredential"); if (admCredentialValue2 != null && admCredentialValue2 instanceof NullNode == false) { AdmCredential admCredentialInstance = new AdmCredential(); propertiesInstance.setAdmCredential(admCredentialInstance); JsonNode propertiesValue13 = admCredentialValue2.get("properties"); if (propertiesValue13 != null && propertiesValue13 instanceof NullNode == false) { AdmCredentialProperties propertiesInstance6 = new AdmCredentialProperties(); admCredentialInstance.setProperties(propertiesInstance6); JsonNode clientIdValue = propertiesValue13.get("clientId"); if (clientIdValue != null && clientIdValue instanceof NullNode == false) { String clientIdInstance; clientIdInstance = clientIdValue.getTextValue(); propertiesInstance6.setClientId(clientIdInstance); } JsonNode clientSecretValue = propertiesValue13.get("clientSecret"); if (clientSecretValue != null && clientSecretValue instanceof NullNode == false) { String clientSecretInstance; clientSecretInstance = clientSecretValue.getTextValue(); propertiesInstance6.setClientSecret(clientSecretInstance); } JsonNode authTokenUrlValue = propertiesValue13.get("authTokenUrl"); if (authTokenUrlValue != null && authTokenUrlValue instanceof NullNode == false) { String authTokenUrlInstance; authTokenUrlInstance = authTokenUrlValue.getTextValue(); propertiesInstance6.setAuthTokenUrl(authTokenUrlInstance); } } } JsonNode baiduCredentialValue2 = propertiesValue8.get("baiduCredential"); if (baiduCredentialValue2 != null && baiduCredentialValue2 instanceof NullNode == false) { BaiduCredential baiduCredentialInstance = new BaiduCredential(); propertiesInstance.setBaiduCredential(baiduCredentialInstance); JsonNode propertiesValue14 = baiduCredentialValue2.get("properties"); if (propertiesValue14 != null && propertiesValue14 instanceof NullNode == false) { BaiduCredentialProperties propertiesInstance7 = new BaiduCredentialProperties(); baiduCredentialInstance.setProperties(propertiesInstance7); JsonNode baiduApiKeyValue = propertiesValue14.get("baiduApiKey"); if (baiduApiKeyValue != null && baiduApiKeyValue instanceof NullNode == false) { String baiduApiKeyInstance; baiduApiKeyInstance = baiduApiKeyValue.getTextValue(); propertiesInstance7.setBaiduApiKey(baiduApiKeyInstance); } JsonNode baiduEndPointValue = propertiesValue14.get("baiduEndPoint"); if (baiduEndPointValue != null && baiduEndPointValue instanceof NullNode == false) { String baiduEndPointInstance; baiduEndPointInstance = baiduEndPointValue.getTextValue(); propertiesInstance7.setBaiduEndPoint(baiduEndPointInstance); } JsonNode baiduSecretKeyValue = propertiesValue14.get("baiduSecretKey"); if (baiduSecretKeyValue != null && baiduSecretKeyValue instanceof NullNode == false) { String baiduSecretKeyInstance; baiduSecretKeyInstance = baiduSecretKeyValue.getTextValue(); propertiesInstance7.setBaiduSecretKey(baiduSecretKeyInstance); } } } } } } result.setStatusCode(statusCode); if (httpResponse.getHeaders("x-ms-request-id").length > 0) { result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); } if (shouldTrace) { CloudTracing.exit(invocationId, result); } return result; } finally { if (httpResponse != null && httpResponse.getEntity() != null) { httpResponse.getEntity().getContent().close(); } } }
From source file:com.microsoft.windowsazure.management.storage.StorageAccountOperationsImpl.java
/** * The Get Storage Account Properties operation returns system properties * for the specified storage account. (see * http://msdn.microsoft.com/en-us/library/windowsazure/ee460802.aspx for * more information)//from w w w . j av a 2 s .co m * * @param accountName Required. Name of the storage account to get * properties for. * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations. * @throws ServiceException Thrown if an unexpected response is found. * @throws ParserConfigurationException Thrown if there was a serious * configuration error with the document parser. * @throws SAXException Thrown if there was an error parsing the XML * response. * @throws URISyntaxException Thrown if there was an error parsing a URI in * the response. * @return The Get Storage Account Properties operation response. */ @Override public StorageAccountGetResponse get(String accountName) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException { // Validate if (accountName == null) { throw new NullPointerException("accountName"); } // Tracing boolean shouldTrace = CloudTracing.getIsEnabled(); String invocationId = null; if (shouldTrace) { invocationId = Long.toString(CloudTracing.getNextInvocationId()); HashMap<String, Object> tracingParameters = new HashMap<String, Object>(); tracingParameters.put("accountName", accountName); 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/storageservices/"; url = url + URLEncoder.encode(accountName, "UTF-8"); String baseUrl = this.getClient().getBaseUri().toString(); // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl.charAt(baseUrl.length() - 1) == '/') { baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); } if (url.charAt(0) == '/') { url = url.substring(1); } url = baseUrl + "/" + url; url = url.replace(" ", "%20"); // Create HTTP transport objects HttpGet httpRequest = new HttpGet(url); // Set Headers httpRequest.setHeader("x-ms-version", "2014-10-01"); // Send Request HttpResponse httpResponse = null; try { if (shouldTrace) { CloudTracing.sendRequest(invocationId, httpRequest); } httpResponse = this.getClient().getHttpClient().execute(httpRequest); if (shouldTrace) { CloudTracing.receiveResponse(invocationId, httpResponse); } int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result StorageAccountGetResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_OK) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new StorageAccountGetResponse(); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); Element storageServiceElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "StorageService"); if (storageServiceElement != null) { StorageAccount storageServiceInstance = new StorageAccount(); result.setStorageAccount(storageServiceInstance); Element urlElement = XmlUtility.getElementByTagNameNS(storageServiceElement, "http://schemas.microsoft.com/windowsazure", "Url"); if (urlElement != null) { URI urlInstance; urlInstance = new URI(urlElement.getTextContent()); storageServiceInstance.setUri(urlInstance); } Element serviceNameElement = XmlUtility.getElementByTagNameNS(storageServiceElement, "http://schemas.microsoft.com/windowsazure", "ServiceName"); if (serviceNameElement != null) { String serviceNameInstance; serviceNameInstance = serviceNameElement.getTextContent(); storageServiceInstance.setName(serviceNameInstance); } Element storageServicePropertiesElement = XmlUtility.getElementByTagNameNS( storageServiceElement, "http://schemas.microsoft.com/windowsazure", "StorageServiceProperties"); if (storageServicePropertiesElement != null) { StorageAccountProperties storageServicePropertiesInstance = new StorageAccountProperties(); storageServiceInstance.setProperties(storageServicePropertiesInstance); Element descriptionElement = XmlUtility.getElementByTagNameNS( storageServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "Description"); if (descriptionElement != null) { boolean isNil = false; Attr nilAttribute = descriptionElement .getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); if (nilAttribute != null) { isNil = "true".equals(nilAttribute.getValue()); } if (isNil == false) { String descriptionInstance; descriptionInstance = descriptionElement.getTextContent(); storageServicePropertiesInstance.setDescription(descriptionInstance); } } Element affinityGroupElement = XmlUtility.getElementByTagNameNS( storageServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "AffinityGroup"); if (affinityGroupElement != null) { String affinityGroupInstance; affinityGroupInstance = affinityGroupElement.getTextContent(); storageServicePropertiesInstance.setAffinityGroup(affinityGroupInstance); } Element locationElement = XmlUtility.getElementByTagNameNS(storageServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "Location"); if (locationElement != null) { String locationInstance; locationInstance = locationElement.getTextContent(); storageServicePropertiesInstance.setLocation(locationInstance); } Element labelElement = XmlUtility.getElementByTagNameNS(storageServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "Label"); if (labelElement != null) { String labelInstance; labelInstance = labelElement.getTextContent() != null ? new String(Base64.decode(labelElement.getTextContent())) : null; storageServicePropertiesInstance.setLabel(labelInstance); } Element statusElement = XmlUtility.getElementByTagNameNS(storageServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "Status"); if (statusElement != null && statusElement.getTextContent() != null && !statusElement.getTextContent().isEmpty()) { StorageAccountStatus statusInstance; statusInstance = StorageAccountStatus.valueOf(statusElement.getTextContent()); storageServicePropertiesInstance.setStatus(statusInstance); } Element endpointsSequenceElement = XmlUtility.getElementByTagNameNS( storageServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "Endpoints"); if (endpointsSequenceElement != null) { for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility .getElementsByTagNameNS(endpointsSequenceElement, "http://schemas.microsoft.com/windowsazure", "Endpoint") .size(); i1 = i1 + 1) { org.w3c.dom.Element endpointsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility .getElementsByTagNameNS(endpointsSequenceElement, "http://schemas.microsoft.com/windowsazure", "Endpoint") .get(i1)); storageServicePropertiesInstance.getEndpoints() .add(new URI(endpointsElement.getTextContent())); } } Element geoPrimaryRegionElement = XmlUtility.getElementByTagNameNS( storageServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "GeoPrimaryRegion"); if (geoPrimaryRegionElement != null) { String geoPrimaryRegionInstance; geoPrimaryRegionInstance = geoPrimaryRegionElement.getTextContent(); storageServicePropertiesInstance.setGeoPrimaryRegion(geoPrimaryRegionInstance); } Element statusOfPrimaryElement = XmlUtility.getElementByTagNameNS( storageServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "StatusOfPrimary"); if (statusOfPrimaryElement != null && statusOfPrimaryElement.getTextContent() != null && !statusOfPrimaryElement.getTextContent().isEmpty()) { GeoRegionStatus statusOfPrimaryInstance; statusOfPrimaryInstance = GeoRegionStatus .valueOf(statusOfPrimaryElement.getTextContent()); storageServicePropertiesInstance.setStatusOfGeoPrimaryRegion(statusOfPrimaryInstance); } Element lastGeoFailoverTimeElement = XmlUtility.getElementByTagNameNS( storageServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "LastGeoFailoverTime"); if (lastGeoFailoverTimeElement != null && lastGeoFailoverTimeElement.getTextContent() != null && !lastGeoFailoverTimeElement.getTextContent().isEmpty()) { Calendar lastGeoFailoverTimeInstance; lastGeoFailoverTimeInstance = DatatypeConverter .parseDateTime(lastGeoFailoverTimeElement.getTextContent()); storageServicePropertiesInstance.setLastGeoFailoverTime(lastGeoFailoverTimeInstance); } Element geoSecondaryRegionElement = XmlUtility.getElementByTagNameNS( storageServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "GeoSecondaryRegion"); if (geoSecondaryRegionElement != null) { String geoSecondaryRegionInstance; geoSecondaryRegionInstance = geoSecondaryRegionElement.getTextContent(); storageServicePropertiesInstance.setGeoSecondaryRegion(geoSecondaryRegionInstance); } Element statusOfSecondaryElement = XmlUtility.getElementByTagNameNS( storageServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "StatusOfSecondary"); if (statusOfSecondaryElement != null && statusOfSecondaryElement.getTextContent() != null && !statusOfSecondaryElement.getTextContent().isEmpty()) { GeoRegionStatus statusOfSecondaryInstance; statusOfSecondaryInstance = GeoRegionStatus .valueOf(statusOfSecondaryElement.getTextContent()); storageServicePropertiesInstance .setStatusOfGeoSecondaryRegion(statusOfSecondaryInstance); } Element accountTypeElement = XmlUtility.getElementByTagNameNS( storageServicePropertiesElement, "http://schemas.microsoft.com/windowsazure", "AccountType"); if (accountTypeElement != null) { String accountTypeInstance; accountTypeInstance = accountTypeElement.getTextContent(); storageServicePropertiesInstance.setAccountType(accountTypeInstance); } } Element extendedPropertiesSequenceElement = XmlUtility.getElementByTagNameNS( storageServiceElement, "http://schemas.microsoft.com/windowsazure", "ExtendedProperties"); if (extendedPropertiesSequenceElement != null) { for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility .getElementsByTagNameNS(extendedPropertiesSequenceElement, "http://schemas.microsoft.com/windowsazure", "ExtendedProperty") .size(); i2 = i2 + 1) { org.w3c.dom.Element extendedPropertiesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility .getElementsByTagNameNS(extendedPropertiesSequenceElement, "http://schemas.microsoft.com/windowsazure", "ExtendedProperty") .get(i2)); String extendedPropertiesKey = XmlUtility .getElementByTagNameNS(extendedPropertiesElement, "http://schemas.microsoft.com/windowsazure", "Name") .getTextContent(); String extendedPropertiesValue = XmlUtility .getElementByTagNameNS(extendedPropertiesElement, "http://schemas.microsoft.com/windowsazure", "Value") .getTextContent(); storageServiceInstance.getExtendedProperties().put(extendedPropertiesKey, extendedPropertiesValue); } } } } 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.NotificationHubOperationsImpl.java
/** * Lists the notification hubs associated with a namespace. * * @param namespaceName Required. The namespace name. * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations.//from www . j av a2 s.c o 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. * @throws URISyntaxException Thrown if there was an error parsing a URI in * the response. * @return A standard service response including an HTTP status code and * request ID. */ @Override public ServiceBusNotificationHubsResponse list(String namespaceName) throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException { // Validate if (namespaceName == null) { throw new NullPointerException("namespaceName"); } // Tracing boolean shouldTrace = CloudTracing.getIsEnabled(); String invocationId = null; if (shouldTrace) { invocationId = Long.toString(CloudTracing.getNextInvocationId()); HashMap<String, Object> tracingParameters = new HashMap<String, Object>(); tracingParameters.put("namespaceName", namespaceName); 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/servicebus/namespaces/"; url = url + URLEncoder.encode(namespaceName, "UTF-8"); url = url + "/NotificationHubs"; 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-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 ServiceBusNotificationHubsResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_OK) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new ServiceBusNotificationHubsResponse(); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); Element feedElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://www.w3.org/2005/Atom", "feed"); if (feedElement != null) { if (feedElement != null) { for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility .getElementsByTagNameNS(feedElement, "http://www.w3.org/2005/Atom", "entry") .size(); i1 = i1 + 1) { org.w3c.dom.Element entriesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility .getElementsByTagNameNS(feedElement, "http://www.w3.org/2005/Atom", "entry") .get(i1)); ServiceBusNotificationHub entryInstance = new ServiceBusNotificationHub(); result.getNotificationHubs().add(entryInstance); Element titleElement = XmlUtility.getElementByTagNameNS(entriesElement, "http://www.w3.org/2005/Atom", "title"); if (titleElement != null) { String titleInstance; titleInstance = titleElement.getTextContent(); entryInstance.setName(titleInstance); } Element contentElement = XmlUtility.getElementByTagNameNS(entriesElement, "http://www.w3.org/2005/Atom", "content"); if (contentElement != null) { Element notificationHubDescriptionElement = XmlUtility.getElementByTagNameNS( contentElement, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "NotificationHubDescription"); if (notificationHubDescriptionElement != null) { Element registrationTtlElement = XmlUtility.getElementByTagNameNS( notificationHubDescriptionElement, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "RegistrationTtl"); if (registrationTtlElement != null) { String registrationTtlInstance; registrationTtlInstance = registrationTtlElement.getTextContent(); entryInstance.setRegistrationTtl(registrationTtlInstance); } Element authorizationRulesSequenceElement = XmlUtility.getElementByTagNameNS( notificationHubDescriptionElement, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "AuthorizationRules"); if (authorizationRulesSequenceElement != null) { for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility .getElementsByTagNameNS(authorizationRulesSequenceElement, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "AuthorizationRule") .size(); i2 = i2 + 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(i2)); ServiceBusSharedAccessAuthorizationRule authorizationRuleInstance = new ServiceBusSharedAccessAuthorizationRule(); entryInstance.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 i3 = 0; i3 < com.microsoft.windowsazure.core.utils.XmlUtility .getElementsByTagNameNS(rightsSequenceElement, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "AccessRights") .size(); i3 = i3 + 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(i3)); 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); } } } } } } } } } 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:ddf.catalog.impl.CatalogFrameworkImpl.java
private void applyAttributeOverridesToMetacardMap(Map<String, String> attributeOverrideMap, Map<String, Metacard> metacardMap) { if (MapUtils.isEmpty(attributeOverrideMap) || MapUtils.isEmpty(metacardMap)) { return;/*from www .j a v a2 s.co m*/ } metacardMap.values() .forEach(metacard -> attributeOverrideMap.keySet().stream() .map(attributeName -> metacard.getMetacardType().getAttributeDescriptor(attributeName)) .filter(Objects::nonNull).map(attributeDescriptor -> { String overrideValue = attributeOverrideMap.get(attributeDescriptor.getName()); try { Serializable newValue; switch (attributeDescriptor.getType().getAttributeFormat()) { case INTEGER: newValue = Integer.parseInt(overrideValue); break; case FLOAT: newValue = Float.parseFloat(overrideValue); break; case DOUBLE: newValue = Double.parseDouble(overrideValue); break; case SHORT: newValue = Short.parseShort(overrideValue); break; case LONG: newValue = Long.parseLong(overrideValue); break; case DATE: Calendar calendar = DatatypeConverter.parseDateTime(overrideValue); newValue = calendar.getTime(); break; case BOOLEAN: newValue = Boolean.parseBoolean(overrideValue); break; case BINARY: newValue = overrideValue.getBytes(); break; case OBJECT: case STRING: case GEOMETRY: case XML: newValue = overrideValue; break; default: return null; } return new AttributeImpl(attributeDescriptor.getName(), newValue); } catch (IllegalArgumentException e) { return null; } }).filter(Objects::nonNull).forEach(metacard::setAttribute)); }
From source file:com.microsoft.azure.management.sql.ServerOperationsImpl.java
/** * Returns information about Azure SQL Database Server usage. * * @param resourceGroupName Required. The name of the Resource Group to * which the server belongs.//from w ww.ja va 2 s . c o m * @param serverName Required. The name of the Azure SQL Database Server in * which the Azure SQL Databases are hosted. * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations. * @throws ServiceException Thrown if an unexpected response is found. * @return Represents the response to a List Azure Sql Database Server * metrics request. */ @Override public ServerMetricListResponse listUsages(String resourceGroupName, String serverName) throws IOException, ServiceException { // Validate if (resourceGroupName == null) { throw new NullPointerException("resourceGroupName"); } if (serverName == null) { throw new NullPointerException("serverName"); } // Tracing boolean shouldTrace = CloudTracing.getIsEnabled(); String invocationId = null; if (shouldTrace) { invocationId = Long.toString(CloudTracing.getNextInvocationId()); HashMap<String, Object> tracingParameters = new HashMap<String, Object>(); tracingParameters.put("resourceGroupName", resourceGroupName); tracingParameters.put("serverName", serverName); CloudTracing.enter(invocationId, this, "listUsagesAsync", tracingParameters); } // Construct URL String url = ""; url = url + "/subscriptions/"; if (this.getClient().getCredentials().getSubscriptionId() != null) { url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8"); } url = url + "/resourceGroups/"; url = url + URLEncoder.encode(resourceGroupName, "UTF-8"); url = url + "/providers/"; url = url + "Microsoft.Sql"; url = url + "/servers/"; url = url + URLEncoder.encode(serverName, "UTF-8"); url = url + "/usages"; ArrayList<String> queryParameters = new ArrayList<String>(); queryParameters.add("api-version=" + "2014-04-01"); if (queryParameters.size() > 0) { url = url + "?" + CollectionStringBuilder.join(queryParameters, "&"); } String baseUrl = this.getClient().getBaseUri().toString(); // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl.charAt(baseUrl.length() - 1) == '/') { baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); } if (url.charAt(0) == '/') { url = url.substring(1); } url = baseUrl + "/" + url; url = url.replace(" ", "%20"); // Create HTTP transport objects HttpGet httpRequest = new HttpGet(url); // Set Headers // Send Request HttpResponse httpResponse = null; try { if (shouldTrace) { CloudTracing.sendRequest(invocationId, httpRequest); } httpResponse = this.getClient().getHttpClient().execute(httpRequest); if (shouldTrace) { CloudTracing.receiveResponse(invocationId, httpResponse); } int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { ServiceException ex = ServiceException.createFromJson(httpRequest, null, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result ServerMetricListResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_OK) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new ServerMetricListResponse(); ObjectMapper objectMapper = new ObjectMapper(); JsonNode responseDoc = null; String responseDocContent = IOUtils.toString(responseContent); if (responseDocContent == null == false && responseDocContent.length() > 0) { responseDoc = objectMapper.readTree(responseDocContent); } if (responseDoc != null && responseDoc instanceof NullNode == false) { JsonNode valueArray = responseDoc.get("value"); if (valueArray != null && valueArray instanceof NullNode == false) { for (JsonNode valueValue : ((ArrayNode) valueArray)) { ServerMetric serverMetricInstance = new ServerMetric(); result.getMetrics().add(serverMetricInstance); JsonNode resourceNameValue = valueValue.get("resourceName"); if (resourceNameValue != null && resourceNameValue instanceof NullNode == false) { String resourceNameInstance; resourceNameInstance = resourceNameValue.getTextValue(); serverMetricInstance.setResourceName(resourceNameInstance); } JsonNode displayNameValue = valueValue.get("displayName"); if (displayNameValue != null && displayNameValue instanceof NullNode == false) { String displayNameInstance; displayNameInstance = displayNameValue.getTextValue(); serverMetricInstance.setDisplayName(displayNameInstance); } JsonNode currentValueValue = valueValue.get("currentValue"); if (currentValueValue != null && currentValueValue instanceof NullNode == false) { double currentValueInstance; currentValueInstance = currentValueValue.getDoubleValue(); serverMetricInstance.setCurrentValue(currentValueInstance); } JsonNode limitValue = valueValue.get("limit"); if (limitValue != null && limitValue instanceof NullNode == false) { double limitInstance; limitInstance = limitValue.getDoubleValue(); serverMetricInstance.setLimit(limitInstance); } JsonNode unitValue = valueValue.get("unit"); if (unitValue != null && unitValue instanceof NullNode == false) { String unitInstance; unitInstance = unitValue.getTextValue(); serverMetricInstance.setUnit(unitInstance); } JsonNode nextResetTimeValue = valueValue.get("nextResetTime"); if (nextResetTimeValue != null && nextResetTimeValue instanceof NullNode == false) { Calendar nextResetTimeInstance; nextResetTimeInstance = DatatypeConverter .parseDateTime(nextResetTimeValue.getTextValue()); serverMetricInstance.setNextResetTime(nextResetTimeInstance); } } } } } result.setStatusCode(statusCode); if (httpResponse.getHeaders("x-ms-request-id").length > 0) { result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); } if (shouldTrace) { CloudTracing.exit(invocationId, result); } return result; } finally { if (httpResponse != null && httpResponse.getEntity() != null) { httpResponse.getEntity().getContent().close(); } } }
From source file:com.microsoft.azure.management.compute.AvailabilitySetOperationsImpl.java
/** * The operation to list the availability sets. * * @param resourceGroupName Required. The name of the resource group. * @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 a va 2 s. c o m * @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 List Availability Set operation response. */ @Override public AvailabilitySetListResponse list(String resourceGroupName) throws IOException, ServiceException, URISyntaxException { // Validate if (resourceGroupName == null) { throw new NullPointerException("resourceGroupName"); } // Tracing boolean shouldTrace = CloudTracing.getIsEnabled(); String invocationId = null; if (shouldTrace) { invocationId = Long.toString(CloudTracing.getNextInvocationId()); HashMap<String, Object> tracingParameters = new HashMap<String, Object>(); tracingParameters.put("resourceGroupName", resourceGroupName); CloudTracing.enter(invocationId, this, "listAsync", tracingParameters); } // Construct URL String url = ""; url = url + "/subscriptions/"; if (this.getClient().getCredentials().getSubscriptionId() != null) { url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8"); } url = url + "/resourceGroups/"; url = url + URLEncoder.encode(resourceGroupName, "UTF-8"); url = url + "/providers/"; url = url + "Microsoft.Compute"; url = url + "/availabilitySets"; ArrayList<String> queryParameters = new ArrayList<String>(); queryParameters.add("api-version=" + "2015-06-15"); if (queryParameters.size() > 0) { url = url + "?" + CollectionStringBuilder.join(queryParameters, "&"); } String baseUrl = this.getClient().getBaseUri().toString(); // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl.charAt(baseUrl.length() - 1) == '/') { baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); } if (url.charAt(0) == '/') { url = url.substring(1); } url = baseUrl + "/" + url; url = url.replace(" ", "%20"); // Create HTTP transport objects HttpGet httpRequest = new HttpGet(url); // Set Headers httpRequest.setHeader("Content-Type", "application/json"); // Send Request HttpResponse httpResponse = null; try { if (shouldTrace) { CloudTracing.sendRequest(invocationId, httpRequest); } httpResponse = this.getClient().getHttpClient().execute(httpRequest); if (shouldTrace) { CloudTracing.receiveResponse(invocationId, httpResponse); } int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { ServiceException ex = ServiceException.createFromJson(httpRequest, null, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result AvailabilitySetListResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_OK) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new AvailabilitySetListResponse(); ObjectMapper objectMapper = new ObjectMapper(); JsonNode responseDoc = null; String responseDocContent = IOUtils.toString(responseContent); if (responseDocContent == null == false && responseDocContent.length() > 0) { responseDoc = objectMapper.readTree(responseDocContent); } if (responseDoc != null && responseDoc instanceof NullNode == false) { JsonNode valueArray = responseDoc.get("value"); if (valueArray != null && valueArray instanceof NullNode == false) { for (JsonNode valueValue : ((ArrayNode) valueArray)) { AvailabilitySet availabilitySetJsonInstance = new AvailabilitySet(); result.getAvailabilitySets().add(availabilitySetJsonInstance); JsonNode propertiesValue = valueValue.get("properties"); if (propertiesValue != null && propertiesValue instanceof NullNode == false) { JsonNode platformUpdateDomainCountValue = propertiesValue .get("platformUpdateDomainCount"); if (platformUpdateDomainCountValue != null && platformUpdateDomainCountValue instanceof NullNode == false) { int platformUpdateDomainCountInstance; platformUpdateDomainCountInstance = platformUpdateDomainCountValue .getIntValue(); availabilitySetJsonInstance .setPlatformUpdateDomainCount(platformUpdateDomainCountInstance); } JsonNode platformFaultDomainCountValue = propertiesValue .get("platformFaultDomainCount"); if (platformFaultDomainCountValue != null && platformFaultDomainCountValue instanceof NullNode == false) { int platformFaultDomainCountInstance; platformFaultDomainCountInstance = platformFaultDomainCountValue.getIntValue(); availabilitySetJsonInstance .setPlatformFaultDomainCount(platformFaultDomainCountInstance); } JsonNode virtualMachinesArray = propertiesValue.get("virtualMachines"); if (virtualMachinesArray != null && virtualMachinesArray instanceof NullNode == false) { for (JsonNode virtualMachinesValue : ((ArrayNode) virtualMachinesArray)) { VirtualMachineReference virtualMachineReferenceInstance = new VirtualMachineReference(); availabilitySetJsonInstance.getVirtualMachinesReferences() .add(virtualMachineReferenceInstance); JsonNode idValue = virtualMachinesValue.get("id"); if (idValue != null && idValue instanceof NullNode == false) { String idInstance; idInstance = idValue.getTextValue(); virtualMachineReferenceInstance.setReferenceUri(idInstance); } } } JsonNode statusesArray = propertiesValue.get("statuses"); if (statusesArray != null && statusesArray instanceof NullNode == false) { for (JsonNode statusesValue : ((ArrayNode) statusesArray)) { InstanceViewStatus instanceViewStatusInstance = new InstanceViewStatus(); availabilitySetJsonInstance.getStatuses().add(instanceViewStatusInstance); JsonNode codeValue = statusesValue.get("code"); if (codeValue != null && codeValue instanceof NullNode == false) { String codeInstance; codeInstance = codeValue.getTextValue(); instanceViewStatusInstance.setCode(codeInstance); } JsonNode levelValue = statusesValue.get("level"); if (levelValue != null && levelValue instanceof NullNode == false) { String levelInstance; levelInstance = levelValue.getTextValue(); instanceViewStatusInstance.setLevel(levelInstance); } JsonNode displayStatusValue = statusesValue.get("displayStatus"); if (displayStatusValue != null && displayStatusValue instanceof NullNode == false) { String displayStatusInstance; displayStatusInstance = displayStatusValue.getTextValue(); instanceViewStatusInstance.setDisplayStatus(displayStatusInstance); } JsonNode messageValue = statusesValue.get("message"); if (messageValue != null && messageValue instanceof NullNode == false) { String messageInstance; messageInstance = messageValue.getTextValue(); instanceViewStatusInstance.setMessage(messageInstance); } JsonNode timeValue = statusesValue.get("time"); if (timeValue != null && timeValue instanceof NullNode == false) { Calendar timeInstance; timeInstance = DatatypeConverter .parseDateTime(timeValue.getTextValue()); instanceViewStatusInstance.setTime(timeInstance); } } } } JsonNode idValue2 = valueValue.get("id"); if (idValue2 != null && idValue2 instanceof NullNode == false) { String idInstance2; idInstance2 = idValue2.getTextValue(); availabilitySetJsonInstance.setId(idInstance2); } JsonNode nameValue = valueValue.get("name"); if (nameValue != null && nameValue instanceof NullNode == false) { String nameInstance; nameInstance = nameValue.getTextValue(); availabilitySetJsonInstance.setName(nameInstance); } JsonNode typeValue = valueValue.get("type"); if (typeValue != null && typeValue instanceof NullNode == false) { String typeInstance; typeInstance = typeValue.getTextValue(); availabilitySetJsonInstance.setType(typeInstance); } JsonNode locationValue = valueValue.get("location"); if (locationValue != null && locationValue instanceof NullNode == false) { String locationInstance; locationInstance = locationValue.getTextValue(); availabilitySetJsonInstance.setLocation(locationInstance); } JsonNode tagsSequenceElement = ((JsonNode) valueValue.get("tags")); if (tagsSequenceElement != null && tagsSequenceElement instanceof NullNode == false) { Iterator<Map.Entry<String, JsonNode>> itr = tagsSequenceElement.getFields(); while (itr.hasNext()) { Map.Entry<String, JsonNode> property = itr.next(); String tagsKey = property.getKey(); String tagsValue = property.getValue().getTextValue(); availabilitySetJsonInstance.getTags().put(tagsKey, tagsValue); } } } } } } result.setStatusCode(statusCode); if (httpResponse.getHeaders("x-ms-request-id").length > 0) { result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); } if (shouldTrace) { CloudTracing.exit(invocationId, result); } return result; } finally { if (httpResponse != null && httpResponse.getEntity() != null) { httpResponse.getEntity().getContent().close(); } } }
From source file:com.microsoft.windowsazure.management.websites.WebSiteOperationsImpl.java
/** * You can swap a web site from one slot to another slot. * * @param webSpaceName Required. The name of the web space. * @param webSiteName Required. The name of the web site. * @param sourceSlotName Required. The name of the first web site slot to * swap (source).// w w w .j ava2 s .c o m * @param targetSlotName Required. The name of the second web site slot to * swap with (target). * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations. * @throws ServiceException Thrown if an unexpected response is found. * @throws ParserConfigurationException Thrown if there was a serious * configuration error with the document parser. * @throws SAXException Thrown if there was an error parsing the XML * response. * @return The response body contains the status of the specified * long-running operation, indicating whether it has succeeded, is * inprogress, has timed out, or has failed. Note that this status is * distinct from the HTTP status code returned for the Get Operation Status * operation itself. If the long-running operation failed, the response * body includes error information regarding the failure. */ @Override public WebSiteOperationStatusResponse beginSwappingSlots(String webSpaceName, String webSiteName, String sourceSlotName, String targetSlotName) throws IOException, ServiceException, ParserConfigurationException, SAXException { // Validate if (webSpaceName == null) { throw new NullPointerException("webSpaceName"); } if (webSiteName == null) { throw new NullPointerException("webSiteName"); } if (sourceSlotName == null) { throw new NullPointerException("sourceSlotName"); } if (targetSlotName == null) { throw new NullPointerException("targetSlotName"); } // 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("sourceSlotName", sourceSlotName); tracingParameters.put("targetSlotName", targetSlotName); CloudTracing.enter(invocationId, this, "beginSwappingSlotsAsync", 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 + "("; url = url + URLEncoder.encode(sourceSlotName, "UTF-8"); url = url + ")/slots"; ArrayList<String> queryParameters = new ArrayList<String>(); queryParameters.add("Command=swap"); queryParameters.add("targetSlot=" + URLEncoder.encode(targetSlotName, "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 HttpPost httpRequest = new HttpPost(url); // Set Headers httpRequest.setHeader("x-ms-version", "2014-04-01"); // Send Request HttpResponse httpResponse = null; try { if (shouldTrace) { CloudTracing.sendRequest(invocationId, httpRequest); } httpResponse = this.getClient().getHttpClient().execute(httpRequest); if (shouldTrace) { CloudTracing.receiveResponse(invocationId, httpResponse); } int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result WebSiteOperationStatusResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_OK) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new WebSiteOperationStatusResponse(); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); Element operationElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "Operation"); if (operationElement != null) { Element createdTimeElement = XmlUtility.getElementByTagNameNS(operationElement, "http://schemas.microsoft.com/windowsazure", "CreatedTime"); if (createdTimeElement != null) { Calendar createdTimeInstance; createdTimeInstance = DatatypeConverter.parseDateTime(createdTimeElement.getTextContent()); result.setCreatedTime(createdTimeInstance); } Element errorsSequenceElement = XmlUtility.getElementByTagNameNS(operationElement, "http://schemas.microsoft.com/windowsazure", "Errors"); if (errorsSequenceElement != null) { boolean isNil = false; Attr nilAttribute = errorsSequenceElement .getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); if (nilAttribute != null) { isNil = "true".equals(nilAttribute.getValue()); } if (isNil == false) { for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility .getElementsByTagNameNS(errorsSequenceElement, "http://schemas.microsoft.com/windowsazure", "Error") .size(); i1 = i1 + 1) { org.w3c.dom.Element errorsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility .getElementsByTagNameNS(errorsSequenceElement, "http://schemas.microsoft.com/windowsazure", "Error") .get(i1)); WebSiteOperationStatusResponse.Error errorInstance = new WebSiteOperationStatusResponse.Error(); result.getErrors().add(errorInstance); Element codeElement = XmlUtility.getElementByTagNameNS(errorsElement, "http://schemas.microsoft.com/windowsazure", "Code"); if (codeElement != null) { boolean isNil2 = false; Attr nilAttribute2 = codeElement .getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); if (nilAttribute2 != null) { isNil2 = "true".equals(nilAttribute2.getValue()); } if (isNil2 == false) { String codeInstance; codeInstance = codeElement.getTextContent(); errorInstance.setCode(codeInstance); } } Element messageElement = XmlUtility.getElementByTagNameNS(errorsElement, "http://schemas.microsoft.com/windowsazure", "Message"); if (messageElement != null) { boolean isNil3 = false; Attr nilAttribute3 = messageElement .getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); if (nilAttribute3 != null) { isNil3 = "true".equals(nilAttribute3.getValue()); } if (isNil3 == false) { String messageInstance; messageInstance = messageElement.getTextContent(); errorInstance.setMessage(messageInstance); } } Element extendedCodeElement = XmlUtility.getElementByTagNameNS(errorsElement, "http://schemas.microsoft.com/windowsazure", "ExtendedCode"); if (extendedCodeElement != null) { boolean isNil4 = false; Attr nilAttribute4 = extendedCodeElement .getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); if (nilAttribute4 != null) { isNil4 = "true".equals(nilAttribute4.getValue()); } if (isNil4 == false) { String extendedCodeInstance; extendedCodeInstance = extendedCodeElement.getTextContent(); errorInstance.setExtendedCode(extendedCodeInstance); } } Element messageTemplateElement = XmlUtility.getElementByTagNameNS(errorsElement, "http://schemas.microsoft.com/windowsazure", "MessageTemplate"); if (messageTemplateElement != null) { boolean isNil5 = false; Attr nilAttribute5 = messageTemplateElement .getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); if (nilAttribute5 != null) { isNil5 = "true".equals(nilAttribute5.getValue()); } if (isNil5 == false) { String messageTemplateInstance; messageTemplateInstance = messageTemplateElement.getTextContent(); errorInstance.setMessageTemplate(messageTemplateInstance); } } Element parametersSequenceElement = XmlUtility.getElementByTagNameNS(errorsElement, "http://schemas.microsoft.com/windowsazure", "Parameters"); if (parametersSequenceElement != null) { boolean isNil6 = false; Attr nilAttribute6 = parametersSequenceElement .getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); if (nilAttribute6 != null) { isNil6 = "true".equals(nilAttribute6.getValue()); } if (isNil6 == false) { for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility .getElementsByTagNameNS(parametersSequenceElement, "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string") .size(); i2 = i2 + 1) { org.w3c.dom.Element parametersElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility .getElementsByTagNameNS(parametersSequenceElement, "http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string") .get(i2)); errorInstance.getParameters().add(parametersElement.getTextContent()); } } else { errorInstance.setParameters(null); } } Element innerErrorsElement = XmlUtility.getElementByTagNameNS(errorsElement, "http://schemas.microsoft.com/windowsazure", "InnerErrors"); if (innerErrorsElement != null) { boolean isNil7 = false; Attr nilAttribute7 = innerErrorsElement .getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); if (nilAttribute7 != null) { isNil7 = "true".equals(nilAttribute7.getValue()); } if (isNil7 == false) { String innerErrorsInstance; innerErrorsInstance = innerErrorsElement.getTextContent(); errorInstance.setInnerErrors(innerErrorsInstance); } } } } else { result.setErrors(null); } } Element expirationTimeElement = XmlUtility.getElementByTagNameNS(operationElement, "http://schemas.microsoft.com/windowsazure", "ExpirationTime"); if (expirationTimeElement != null) { Calendar expirationTimeInstance; expirationTimeInstance = DatatypeConverter .parseDateTime(expirationTimeElement.getTextContent()); result.setExpirationTime(expirationTimeInstance); } Element geoMasterOperationIdElement = XmlUtility.getElementByTagNameNS(operationElement, "http://schemas.microsoft.com/windowsazure", "GeoMasterOperationId"); if (geoMasterOperationIdElement != null) { boolean isNil8 = false; Attr nilAttribute8 = geoMasterOperationIdElement .getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); if (nilAttribute8 != null) { isNil8 = "true".equals(nilAttribute8.getValue()); } if (isNil8 == false) { String geoMasterOperationIdInstance; geoMasterOperationIdInstance = geoMasterOperationIdElement.getTextContent(); result.setGeoMasterOperationId(geoMasterOperationIdInstance); } } Element idElement = XmlUtility.getElementByTagNameNS(operationElement, "http://schemas.microsoft.com/windowsazure", "Id"); if (idElement != null) { boolean isNil9 = false; Attr nilAttribute9 = idElement .getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); if (nilAttribute9 != null) { isNil9 = "true".equals(nilAttribute9.getValue()); } if (isNil9 == false) { String idInstance; idInstance = idElement.getTextContent(); result.setOperationId(idInstance); } } Element modifiedTimeElement = XmlUtility.getElementByTagNameNS(operationElement, "http://schemas.microsoft.com/windowsazure", "ModifiedTime"); if (modifiedTimeElement != null) { Calendar modifiedTimeInstance; modifiedTimeInstance = DatatypeConverter .parseDateTime(modifiedTimeElement.getTextContent()); result.setModifiedTime(modifiedTimeInstance); } Element nameElement = XmlUtility.getElementByTagNameNS(operationElement, "http://schemas.microsoft.com/windowsazure", "Name"); if (nameElement != null) { boolean isNil10 = false; Attr nilAttribute10 = nameElement .getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); if (nilAttribute10 != null) { isNil10 = "true".equals(nilAttribute10.getValue()); } if (isNil10 == false) { String nameInstance; nameInstance = nameElement.getTextContent(); result.setName(nameInstance); } } Element statusElement = XmlUtility.getElementByTagNameNS(operationElement, "http://schemas.microsoft.com/windowsazure", "Status"); if (statusElement != null && statusElement.getTextContent() != null && !statusElement.getTextContent().isEmpty()) { WebSiteOperationStatus statusInstance; statusInstance = WebSiteOperationStatus.valueOf(statusElement.getTextContent()); result.setStatus(statusInstance); } } } result.setStatusCode(statusCode); if (httpResponse.getHeaders("x-ms-request-id").length > 0) { result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); } if (shouldTrace) { CloudTracing.exit(invocationId, result); } return result; } finally { if (httpResponse != null && httpResponse.getEntity() != null) { httpResponse.getEntity().getContent().close(); } } }