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.sql.ServiceTierAdvisorOperationsImpl.java
/** * Returns information about a service tier advisor. * * @param resourceGroupName Required. The name of the Resource Group. * @param serverName Required. The name of server. * @param databaseName Required. The name of database. * @param serviceTierAdvisorName Required. The name of service tier advisor. * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations.//w w w. ja va 2s . c o m * @throws ServiceException Thrown if an unexpected response is found. * @return Represents the response to a get service tier advisor request. */ @Override public ServiceTierAdvisorGetResponse get(String resourceGroupName, String serverName, String databaseName, String serviceTierAdvisorName) throws IOException, ServiceException { // Validate if (resourceGroupName == null) { throw new NullPointerException("resourceGroupName"); } if (serverName == null) { throw new NullPointerException("serverName"); } if (databaseName == null) { throw new NullPointerException("databaseName"); } if (serviceTierAdvisorName == null) { throw new NullPointerException("serviceTierAdvisorName"); } // Tracing boolean shouldTrace = CloudTracing.getIsEnabled(); String invocationId = null; if (shouldTrace) { invocationId = Long.toString(CloudTracing.getNextInvocationId()); HashMap<String, Object> tracingParameters = new HashMap<String, Object>(); tracingParameters.put("resourceGroupName", resourceGroupName); tracingParameters.put("serverName", serverName); tracingParameters.put("databaseName", databaseName); tracingParameters.put("serviceTierAdvisorName", serviceTierAdvisorName); CloudTracing.enter(invocationId, this, "getAsync", tracingParameters); } // Construct URL String url = ""; url = url + "/subscriptions/"; if (this.getClient().getCredentials().getSubscriptionId() != null) { url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8"); } url = url + "/resourceGroups/"; url = url + URLEncoder.encode(resourceGroupName, "UTF-8"); url = url + "/providers/"; url = url + "Microsoft.Sql"; url = url + "/servers/"; url = url + URLEncoder.encode(serverName, "UTF-8"); url = url + "/databases/"; url = url + URLEncoder.encode(databaseName, "UTF-8"); url = url + "/serviceTierAdvisors/"; url = url + URLEncoder.encode(serviceTierAdvisorName, "UTF-8"); ArrayList<String> queryParameters = new ArrayList<String>(); queryParameters.add("api-version=" + "2014-04-01"); if (queryParameters.size() > 0) { url = url + "?" + CollectionStringBuilder.join(queryParameters, "&"); } String baseUrl = this.getClient().getBaseUri().toString(); // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl.charAt(baseUrl.length() - 1) == '/') { baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); } if (url.charAt(0) == '/') { url = url.substring(1); } url = baseUrl + "/" + url; url = url.replace(" ", "%20"); // Create HTTP transport objects HttpGet httpRequest = new HttpGet(url); // Set Headers // Send Request HttpResponse httpResponse = null; try { if (shouldTrace) { CloudTracing.sendRequest(invocationId, httpRequest); } httpResponse = this.getClient().getHttpClient().execute(httpRequest); if (shouldTrace) { CloudTracing.receiveResponse(invocationId, httpResponse); } int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { ServiceException ex = ServiceException.createFromJson(httpRequest, null, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result ServiceTierAdvisorGetResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_OK) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new ServiceTierAdvisorGetResponse(); 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) { ServiceTierAdvisor serviceTierAdvisorInstance = new ServiceTierAdvisor(); result.setServiceTierAdvisor(serviceTierAdvisorInstance); JsonNode propertiesValue = responseDoc.get("properties"); if (propertiesValue != null && propertiesValue instanceof NullNode == false) { ServiceTierAdvisorProperties propertiesInstance = new ServiceTierAdvisorProperties(); serviceTierAdvisorInstance.setProperties(propertiesInstance); JsonNode observationPeriodStartValue = propertiesValue.get("observationPeriodStart"); if (observationPeriodStartValue != null && observationPeriodStartValue instanceof NullNode == false) { Calendar observationPeriodStartInstance; observationPeriodStartInstance = DatatypeConverter .parseDateTime(observationPeriodStartValue.getTextValue()); propertiesInstance.setObservationPeriodStart(observationPeriodStartInstance); } JsonNode observationPeriodEndValue = propertiesValue.get("observationPeriodEnd"); if (observationPeriodEndValue != null && observationPeriodEndValue instanceof NullNode == false) { Calendar observationPeriodEndInstance; observationPeriodEndInstance = DatatypeConverter .parseDateTime(observationPeriodEndValue.getTextValue()); propertiesInstance.setObservationPeriodEnd(observationPeriodEndInstance); } JsonNode activeTimeRatioValue = propertiesValue.get("activeTimeRatio"); if (activeTimeRatioValue != null && activeTimeRatioValue instanceof NullNode == false) { double activeTimeRatioInstance; activeTimeRatioInstance = activeTimeRatioValue.getDoubleValue(); propertiesInstance.setActiveTimeRatio(activeTimeRatioInstance); } JsonNode minDtuValue = propertiesValue.get("minDtu"); if (minDtuValue != null && minDtuValue instanceof NullNode == false) { double minDtuInstance; minDtuInstance = minDtuValue.getDoubleValue(); propertiesInstance.setMinDtu(minDtuInstance); } JsonNode avgDtuValue = propertiesValue.get("avgDtu"); if (avgDtuValue != null && avgDtuValue instanceof NullNode == false) { double avgDtuInstance; avgDtuInstance = avgDtuValue.getDoubleValue(); propertiesInstance.setAvgDtu(avgDtuInstance); } JsonNode maxDtuValue = propertiesValue.get("maxDtu"); if (maxDtuValue != null && maxDtuValue instanceof NullNode == false) { double maxDtuInstance; maxDtuInstance = maxDtuValue.getDoubleValue(); propertiesInstance.setMaxDtu(maxDtuInstance); } JsonNode maxSizeInGBValue = propertiesValue.get("maxSizeInGB"); if (maxSizeInGBValue != null && maxSizeInGBValue instanceof NullNode == false) { double maxSizeInGBInstance; maxSizeInGBInstance = maxSizeInGBValue.getDoubleValue(); propertiesInstance.setMaxSizeInGB(maxSizeInGBInstance); } JsonNode serviceLevelObjectiveUsageMetricsArray = propertiesValue .get("serviceLevelObjectiveUsageMetrics"); if (serviceLevelObjectiveUsageMetricsArray != null && serviceLevelObjectiveUsageMetricsArray instanceof NullNode == false) { for (JsonNode serviceLevelObjectiveUsageMetricsValue : ((ArrayNode) serviceLevelObjectiveUsageMetricsArray)) { SloUsageMetric sloUsageMetricInstance = new SloUsageMetric(); propertiesInstance.getServiceLevelObjectiveUsageMetrics() .add(sloUsageMetricInstance); JsonNode serviceLevelObjectiveValue = serviceLevelObjectiveUsageMetricsValue .get("serviceLevelObjective"); if (serviceLevelObjectiveValue != null && serviceLevelObjectiveValue instanceof NullNode == false) { String serviceLevelObjectiveInstance; serviceLevelObjectiveInstance = serviceLevelObjectiveValue.getTextValue(); sloUsageMetricInstance.setServiceLevelObjective(serviceLevelObjectiveInstance); } JsonNode serviceLevelObjectiveIdValue = serviceLevelObjectiveUsageMetricsValue .get("serviceLevelObjectiveId"); if (serviceLevelObjectiveIdValue != null && serviceLevelObjectiveIdValue instanceof NullNode == false) { String serviceLevelObjectiveIdInstance; serviceLevelObjectiveIdInstance = serviceLevelObjectiveIdValue.getTextValue(); sloUsageMetricInstance .setServiceLevelObjectiveId(serviceLevelObjectiveIdInstance); } JsonNode inRangeTimeRatioValue = serviceLevelObjectiveUsageMetricsValue .get("inRangeTimeRatio"); if (inRangeTimeRatioValue != null && inRangeTimeRatioValue instanceof NullNode == false) { double inRangeTimeRatioInstance; inRangeTimeRatioInstance = inRangeTimeRatioValue.getDoubleValue(); sloUsageMetricInstance.setInRangeTimeRatio(inRangeTimeRatioInstance); } JsonNode idValue = serviceLevelObjectiveUsageMetricsValue.get("id"); if (idValue != null && idValue instanceof NullNode == false) { String idInstance; idInstance = idValue.getTextValue(); sloUsageMetricInstance.setId(idInstance); } JsonNode nameValue = serviceLevelObjectiveUsageMetricsValue.get("name"); if (nameValue != null && nameValue instanceof NullNode == false) { String nameInstance; nameInstance = nameValue.getTextValue(); sloUsageMetricInstance.setName(nameInstance); } JsonNode typeValue = serviceLevelObjectiveUsageMetricsValue.get("type"); if (typeValue != null && typeValue instanceof NullNode == false) { String typeInstance; typeInstance = typeValue.getTextValue(); sloUsageMetricInstance.setType(typeInstance); } JsonNode locationValue = serviceLevelObjectiveUsageMetricsValue.get("location"); if (locationValue != null && locationValue instanceof NullNode == false) { String locationInstance; locationInstance = locationValue.getTextValue(); sloUsageMetricInstance.setLocation(locationInstance); } JsonNode tagsSequenceElement = ((JsonNode) serviceLevelObjectiveUsageMetricsValue .get("tags")); if (tagsSequenceElement != null && tagsSequenceElement instanceof NullNode == false) { Iterator<Map.Entry<String, JsonNode>> itr = tagsSequenceElement.getFields(); while (itr.hasNext()) { Map.Entry<String, JsonNode> property = itr.next(); String tagsKey = property.getKey(); String tagsValue = property.getValue().getTextValue(); sloUsageMetricInstance.getTags().put(tagsKey, tagsValue); } } } } JsonNode currentServiceLevelObjectiveValue = propertiesValue .get("currentServiceLevelObjective"); if (currentServiceLevelObjectiveValue != null && currentServiceLevelObjectiveValue instanceof NullNode == false) { String currentServiceLevelObjectiveInstance; currentServiceLevelObjectiveInstance = currentServiceLevelObjectiveValue.getTextValue(); propertiesInstance .setCurrentServiceLevelObjective(currentServiceLevelObjectiveInstance); } JsonNode currentServiceLevelObjectiveIdValue = propertiesValue .get("currentServiceLevelObjectiveId"); if (currentServiceLevelObjectiveIdValue != null && currentServiceLevelObjectiveIdValue instanceof NullNode == false) { String currentServiceLevelObjectiveIdInstance; currentServiceLevelObjectiveIdInstance = currentServiceLevelObjectiveIdValue .getTextValue(); propertiesInstance .setCurrentServiceLevelObjectiveId(currentServiceLevelObjectiveIdInstance); } JsonNode usageBasedRecommendationServiceLevelObjectiveValue = propertiesValue .get("usageBasedRecommendationServiceLevelObjective"); if (usageBasedRecommendationServiceLevelObjectiveValue != null && usageBasedRecommendationServiceLevelObjectiveValue instanceof NullNode == false) { String usageBasedRecommendationServiceLevelObjectiveInstance; usageBasedRecommendationServiceLevelObjectiveInstance = usageBasedRecommendationServiceLevelObjectiveValue .getTextValue(); propertiesInstance.setUsageBasedRecommendationServiceLevelObjective( usageBasedRecommendationServiceLevelObjectiveInstance); } JsonNode usageBasedRecommendationServiceLevelObjectiveIdValue = propertiesValue .get("usageBasedRecommendationServiceLevelObjectiveId"); if (usageBasedRecommendationServiceLevelObjectiveIdValue != null && usageBasedRecommendationServiceLevelObjectiveIdValue instanceof NullNode == false) { String usageBasedRecommendationServiceLevelObjectiveIdInstance; usageBasedRecommendationServiceLevelObjectiveIdInstance = usageBasedRecommendationServiceLevelObjectiveIdValue .getTextValue(); propertiesInstance.setUsageBasedRecommendationServiceLevelObjectiveId( usageBasedRecommendationServiceLevelObjectiveIdInstance); } JsonNode databaseSizeBasedRecommendationServiceLevelObjectiveValue = propertiesValue .get("databaseSizeBasedRecommendationServiceLevelObjective"); if (databaseSizeBasedRecommendationServiceLevelObjectiveValue != null && databaseSizeBasedRecommendationServiceLevelObjectiveValue instanceof NullNode == false) { String databaseSizeBasedRecommendationServiceLevelObjectiveInstance; databaseSizeBasedRecommendationServiceLevelObjectiveInstance = databaseSizeBasedRecommendationServiceLevelObjectiveValue .getTextValue(); propertiesInstance.setDatabaseSizeBasedRecommendationServiceLevelObjective( databaseSizeBasedRecommendationServiceLevelObjectiveInstance); } JsonNode databaseSizeBasedRecommendationServiceLevelObjectiveIdValue = propertiesValue .get("databaseSizeBasedRecommendationServiceLevelObjectiveId"); if (databaseSizeBasedRecommendationServiceLevelObjectiveIdValue != null && databaseSizeBasedRecommendationServiceLevelObjectiveIdValue instanceof NullNode == false) { String databaseSizeBasedRecommendationServiceLevelObjectiveIdInstance; databaseSizeBasedRecommendationServiceLevelObjectiveIdInstance = databaseSizeBasedRecommendationServiceLevelObjectiveIdValue .getTextValue(); propertiesInstance.setDatabaseSizeBasedRecommendationServiceLevelObjectiveId( databaseSizeBasedRecommendationServiceLevelObjectiveIdInstance); } JsonNode disasterPlanBasedRecommendationServiceLevelObjectiveValue = propertiesValue .get("disasterPlanBasedRecommendationServiceLevelObjective"); if (disasterPlanBasedRecommendationServiceLevelObjectiveValue != null && disasterPlanBasedRecommendationServiceLevelObjectiveValue instanceof NullNode == false) { String disasterPlanBasedRecommendationServiceLevelObjectiveInstance; disasterPlanBasedRecommendationServiceLevelObjectiveInstance = disasterPlanBasedRecommendationServiceLevelObjectiveValue .getTextValue(); propertiesInstance.setDisasterPlanBasedRecommendationServiceLevelObjective( disasterPlanBasedRecommendationServiceLevelObjectiveInstance); } JsonNode disasterPlanBasedRecommendationServiceLevelObjectiveIdValue = propertiesValue .get("disasterPlanBasedRecommendationServiceLevelObjectiveId"); if (disasterPlanBasedRecommendationServiceLevelObjectiveIdValue != null && disasterPlanBasedRecommendationServiceLevelObjectiveIdValue instanceof NullNode == false) { String disasterPlanBasedRecommendationServiceLevelObjectiveIdInstance; disasterPlanBasedRecommendationServiceLevelObjectiveIdInstance = disasterPlanBasedRecommendationServiceLevelObjectiveIdValue .getTextValue(); propertiesInstance.setDisasterPlanBasedRecommendationServiceLevelObjectiveId( disasterPlanBasedRecommendationServiceLevelObjectiveIdInstance); } JsonNode overallRecommendationServiceLevelObjectiveValue = propertiesValue .get("overallRecommendationServiceLevelObjective"); if (overallRecommendationServiceLevelObjectiveValue != null && overallRecommendationServiceLevelObjectiveValue instanceof NullNode == false) { String overallRecommendationServiceLevelObjectiveInstance; overallRecommendationServiceLevelObjectiveInstance = overallRecommendationServiceLevelObjectiveValue .getTextValue(); propertiesInstance.setOverallRecommendationServiceLevelObjective( overallRecommendationServiceLevelObjectiveInstance); } JsonNode overallRecommendationServiceLevelObjectiveIdValue = propertiesValue .get("overallRecommendationServiceLevelObjectiveId"); if (overallRecommendationServiceLevelObjectiveIdValue != null && overallRecommendationServiceLevelObjectiveIdValue instanceof NullNode == false) { String overallRecommendationServiceLevelObjectiveIdInstance; overallRecommendationServiceLevelObjectiveIdInstance = overallRecommendationServiceLevelObjectiveIdValue .getTextValue(); propertiesInstance.setOverallRecommendationServiceLevelObjectiveId( overallRecommendationServiceLevelObjectiveIdInstance); } JsonNode confidenceValue = propertiesValue.get("confidence"); if (confidenceValue != null && confidenceValue instanceof NullNode == false) { double confidenceInstance; confidenceInstance = confidenceValue.getDoubleValue(); propertiesInstance.setConfidence(confidenceInstance); } } JsonNode idValue2 = responseDoc.get("id"); if (idValue2 != null && idValue2 instanceof NullNode == false) { String idInstance2; idInstance2 = idValue2.getTextValue(); serviceTierAdvisorInstance.setId(idInstance2); } JsonNode nameValue2 = responseDoc.get("name"); if (nameValue2 != null && nameValue2 instanceof NullNode == false) { String nameInstance2; nameInstance2 = nameValue2.getTextValue(); serviceTierAdvisorInstance.setName(nameInstance2); } JsonNode typeValue2 = responseDoc.get("type"); if (typeValue2 != null && typeValue2 instanceof NullNode == false) { String typeInstance2; typeInstance2 = typeValue2.getTextValue(); serviceTierAdvisorInstance.setType(typeInstance2); } JsonNode locationValue2 = responseDoc.get("location"); if (locationValue2 != null && locationValue2 instanceof NullNode == false) { String locationInstance2; locationInstance2 = locationValue2.getTextValue(); serviceTierAdvisorInstance.setLocation(locationInstance2); } JsonNode tagsSequenceElement2 = ((JsonNode) responseDoc.get("tags")); if (tagsSequenceElement2 != null && tagsSequenceElement2 instanceof NullNode == false) { Iterator<Map.Entry<String, JsonNode>> itr2 = tagsSequenceElement2.getFields(); while (itr2.hasNext()) { Map.Entry<String, JsonNode> property2 = itr2.next(); String tagsKey2 = property2.getKey(); String tagsValue2 = property2.getValue().getTextValue(); serviceTierAdvisorInstance.getTags().put(tagsKey2, tagsValue2); } } } } result.setStatusCode(statusCode); if (httpResponse.getHeaders("x-ms-request-id").length > 0) { result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); } if (shouldTrace) { CloudTracing.exit(invocationId, result); } return result; } finally { if (httpResponse != null && httpResponse.getEntity() != null) { httpResponse.getEntity().getContent().close(); } } }
From source file:com.microsoft.windowsazure.management.sql.RestorableDroppedDatabaseOperationsImpl.java
/** * Returns information about a dropped Azure SQL Database that can be * restored./*from w ww. j a v a 2s. c o m*/ * * @param serverName Required. The name of the Azure SQL Database Server on * which the database was hosted. * @param entityId Required. The entity ID of the restorable dropped Azure * SQL Database to be obtained. * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations. * @throws ServiceException Thrown if an unexpected response is found. * @throws ParserConfigurationException Thrown if there was a serious * configuration error with the document parser. * @throws SAXException Thrown if there was an error parsing the XML * response. * @return Contains the response to the Get Restorable Dropped Database * request. */ @Override public RestorableDroppedDatabaseGetResponse get(String serverName, String entityId) throws IOException, ServiceException, ParserConfigurationException, SAXException { // Validate if (serverName == null) { throw new NullPointerException("serverName"); } if (entityId == null) { throw new NullPointerException("entityId"); } // Tracing boolean shouldTrace = CloudTracing.getIsEnabled(); String invocationId = null; if (shouldTrace) { invocationId = Long.toString(CloudTracing.getNextInvocationId()); HashMap<String, Object> tracingParameters = new HashMap<String, Object>(); tracingParameters.put("serverName", serverName); tracingParameters.put("entityId", entityId); CloudTracing.enter(invocationId, this, "getAsync", tracingParameters); } // Construct URL String url = ""; url = url + "/"; if (this.getClient().getCredentials().getSubscriptionId() != null) { url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8"); } url = url + "/services/sqlservers/servers/"; url = url + URLEncoder.encode(serverName, "UTF-8"); url = url + "/restorabledroppeddatabases/"; url = url + URLEncoder.encode(entityId, "UTF-8"); String baseUrl = this.getClient().getBaseUri().toString(); // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl.charAt(baseUrl.length() - 1) == '/') { baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); } if (url.charAt(0) == '/') { url = url.substring(1); } url = baseUrl + "/" + url; url = url.replace(" ", "%20"); // Create HTTP transport objects HttpGet httpRequest = new HttpGet(url); // Set Headers httpRequest.setHeader("x-ms-version", "2012-03-01"); // Send Request HttpResponse httpResponse = null; try { if (shouldTrace) { CloudTracing.sendRequest(invocationId, httpRequest); } httpResponse = this.getClient().getHttpClient().execute(httpRequest); if (shouldTrace) { CloudTracing.receiveResponse(invocationId, httpResponse); } int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result RestorableDroppedDatabaseGetResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_OK) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new RestorableDroppedDatabaseGetResponse(); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); Element serviceResourceElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "ServiceResource"); if (serviceResourceElement != null) { RestorableDroppedDatabase serviceResourceInstance = new RestorableDroppedDatabase(); result.setDatabase(serviceResourceInstance); Element entityIdElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "EntityId"); if (entityIdElement != null) { String entityIdInstance; entityIdInstance = entityIdElement.getTextContent(); serviceResourceInstance.setEntityId(entityIdInstance); } Element serverNameElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "ServerName"); if (serverNameElement != null) { String serverNameInstance; serverNameInstance = serverNameElement.getTextContent(); serviceResourceInstance.setServerName(serverNameInstance); } Element editionElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "Edition"); if (editionElement != null) { String editionInstance; editionInstance = editionElement.getTextContent(); serviceResourceInstance.setEdition(editionInstance); } Element maxSizeBytesElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "MaxSizeBytes"); if (maxSizeBytesElement != null) { long maxSizeBytesInstance; maxSizeBytesInstance = DatatypeConverter.parseLong(maxSizeBytesElement.getTextContent()); serviceResourceInstance.setMaximumDatabaseSizeInBytes(maxSizeBytesInstance); } Element creationDateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "CreationDate"); if (creationDateElement != null) { Calendar creationDateInstance; creationDateInstance = DatatypeConverter .parseDateTime(creationDateElement.getTextContent()); serviceResourceInstance.setCreationDate(creationDateInstance); } Element deletionDateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "DeletionDate"); if (deletionDateElement != null) { Calendar deletionDateInstance; deletionDateInstance = DatatypeConverter .parseDateTime(deletionDateElement.getTextContent()); serviceResourceInstance.setDeletionDate(deletionDateInstance); } Element recoveryPeriodStartDateElement = XmlUtility.getElementByTagNameNS( serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "RecoveryPeriodStartDate"); if (recoveryPeriodStartDateElement != null && recoveryPeriodStartDateElement.getTextContent() != null && !recoveryPeriodStartDateElement.getTextContent().isEmpty()) { Calendar recoveryPeriodStartDateInstance; recoveryPeriodStartDateInstance = DatatypeConverter .parseDateTime(recoveryPeriodStartDateElement.getTextContent()); serviceResourceInstance.setRecoveryPeriodStartDate(recoveryPeriodStartDateInstance); } Element nameElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "Name"); if (nameElement != null) { String nameInstance; nameInstance = nameElement.getTextContent(); serviceResourceInstance.setName(nameInstance); } Element typeElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "Type"); if (typeElement != null) { String typeInstance; typeInstance = typeElement.getTextContent(); serviceResourceInstance.setType(typeInstance); } Element stateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "State"); if (stateElement != null) { String stateInstance; stateInstance = stateElement.getTextContent(); serviceResourceInstance.setState(stateInstance); } } } result.setStatusCode(statusCode); if (httpResponse.getHeaders("x-ms-request-id").length > 0) { result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); } if (shouldTrace) { CloudTracing.exit(invocationId, result); } return result; } finally { if (httpResponse != null && httpResponse.getEntity() != null) { httpResponse.getEntity().getContent().close(); } } }
From source file:com.microsoft.azure.management.resources.DeploymentOperationOperationsImpl.java
/** * Get a list of deployments operations.//from www .j a v a 2 s. c o m * * @param resourceGroupName Required. The name of the resource group. The * name is case insensitive. * @param deploymentName Required. The name of the deployment. * @param operationId Required. Operation Id. * @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 Deployment operation. */ @Override public DeploymentOperationsGetResult get(String resourceGroupName, String deploymentName, String operationId) throws IOException, ServiceException, URISyntaxException { // Validate if (resourceGroupName == null) { throw new NullPointerException("resourceGroupName"); } if (resourceGroupName != null && resourceGroupName.length() > 1000) { throw new IllegalArgumentException("resourceGroupName"); } if (Pattern.matches("^[-\\w\\._]+$", resourceGroupName) == false) { throw new IllegalArgumentException("resourceGroupName"); } if (deploymentName == null) { throw new NullPointerException("deploymentName"); } if (operationId == null) { throw new NullPointerException("operationId"); } // Tracing boolean shouldTrace = CloudTracing.getIsEnabled(); String invocationId = null; if (shouldTrace) { invocationId = Long.toString(CloudTracing.getNextInvocationId()); HashMap<String, Object> tracingParameters = new HashMap<String, Object>(); tracingParameters.put("resourceGroupName", resourceGroupName); tracingParameters.put("deploymentName", deploymentName); tracingParameters.put("operationId", operationId); CloudTracing.enter(invocationId, this, "getAsync", tracingParameters); } // Construct URL String url = ""; url = url + "/subscriptions/"; if (this.getClient().getCredentials().getSubscriptionId() != null) { url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8"); } url = url + "/resourcegroups/"; url = url + URLEncoder.encode(resourceGroupName, "UTF-8"); url = url + "/deployments/"; url = url + URLEncoder.encode(deploymentName, "UTF-8"); url = url + "/operations/"; url = url + URLEncoder.encode(operationId, "UTF-8"); ArrayList<String> queryParameters = new ArrayList<String>(); queryParameters.add("api-version=" + "2014-04-01-preview"); if (queryParameters.size() > 0) { url = url + "?" + CollectionStringBuilder.join(queryParameters, "&"); } String baseUrl = this.getClient().getBaseUri().toString(); // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl.charAt(baseUrl.length() - 1) == '/') { baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); } if (url.charAt(0) == '/') { url = url.substring(1); } url = baseUrl + "/" + url; url = url.replace(" ", "%20"); // Create HTTP transport objects HttpGet httpRequest = new HttpGet(url); // Set Headers httpRequest.setHeader("Content-Type", "application/json; charset=utf-8"); // Send Request HttpResponse httpResponse = null; try { if (shouldTrace) { CloudTracing.sendRequest(invocationId, httpRequest); } httpResponse = this.getClient().getHttpClient().execute(httpRequest); if (shouldTrace) { CloudTracing.receiveResponse(invocationId, httpResponse); } int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { ServiceException ex = ServiceException.createFromJson(httpRequest, null, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result DeploymentOperationsGetResult result = null; // Deserialize Response if (statusCode == HttpStatus.SC_OK) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new DeploymentOperationsGetResult(); 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) { DeploymentOperation operationInstance = new DeploymentOperation(); result.setOperation(operationInstance); JsonNode idValue = responseDoc.get("id"); if (idValue != null && idValue instanceof NullNode == false) { String idInstance; idInstance = idValue.getTextValue(); operationInstance.setId(idInstance); } JsonNode operationIdValue = responseDoc.get("operationId"); if (operationIdValue != null && operationIdValue instanceof NullNode == false) { String operationIdInstance; operationIdInstance = operationIdValue.getTextValue(); operationInstance.setOperationId(operationIdInstance); } JsonNode propertiesValue = responseDoc.get("properties"); if (propertiesValue != null && propertiesValue instanceof NullNode == false) { DeploymentOperationProperties propertiesInstance = new DeploymentOperationProperties(); operationInstance.setProperties(propertiesInstance); JsonNode provisioningStateValue = propertiesValue.get("provisioningState"); if (provisioningStateValue != null && provisioningStateValue instanceof NullNode == false) { String provisioningStateInstance; provisioningStateInstance = provisioningStateValue.getTextValue(); propertiesInstance.setProvisioningState(provisioningStateInstance); } JsonNode timestampValue = propertiesValue.get("timestamp"); if (timestampValue != null && timestampValue instanceof NullNode == false) { Calendar timestampInstance; timestampInstance = DatatypeConverter.parseDateTime(timestampValue.getTextValue()); propertiesInstance.setTimestamp(timestampInstance); } JsonNode statusCodeValue = propertiesValue.get("statusCode"); if (statusCodeValue != null && statusCodeValue instanceof NullNode == false) { String statusCodeInstance; statusCodeInstance = statusCodeValue.getTextValue(); propertiesInstance.setStatusCode(statusCodeInstance); } JsonNode statusMessageValue = propertiesValue.get("statusMessage"); if (statusMessageValue != null && statusMessageValue instanceof NullNode == false) { String statusMessageInstance; statusMessageInstance = statusMessageValue.getTextValue(); propertiesInstance.setStatusMessage(statusMessageInstance); } JsonNode targetResourceValue = propertiesValue.get("targetResource"); if (targetResourceValue != null && targetResourceValue instanceof NullNode == false) { TargetResource targetResourceInstance = new TargetResource(); propertiesInstance.setTargetResource(targetResourceInstance); JsonNode idValue2 = targetResourceValue.get("id"); if (idValue2 != null && idValue2 instanceof NullNode == false) { String idInstance2; idInstance2 = idValue2.getTextValue(); targetResourceInstance.setId(idInstance2); } JsonNode resourceNameValue = targetResourceValue.get("resourceName"); if (resourceNameValue != null && resourceNameValue instanceof NullNode == false) { String resourceNameInstance; resourceNameInstance = resourceNameValue.getTextValue(); targetResourceInstance.setResourceName(resourceNameInstance); } JsonNode resourceTypeValue = targetResourceValue.get("resourceType"); if (resourceTypeValue != null && resourceTypeValue instanceof NullNode == false) { String resourceTypeInstance; resourceTypeInstance = resourceTypeValue.getTextValue(); targetResourceInstance.setResourceType(resourceTypeInstance); } } } } } 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.security.assertion.impl.SecurityAssertionImpl.java
/** * Parses the SecurityToken by wrapping within an AssertionWrapper. * * @param securityToken SecurityToken//from w w w. j a v a 2 s . c om */ private void parseToken(SecurityToken securityToken) { XMLStreamReader xmlStreamReader = StaxUtils.createXMLStreamReader(securityToken.getToken()); try { AttrStatement attributeStatement = null; AuthenticationStatement authenticationStatement = null; Attr attribute = null; int attrs = 0; while (xmlStreamReader.hasNext()) { int event = xmlStreamReader.next(); switch (event) { case XMLStreamConstants.START_ELEMENT: { String localName = xmlStreamReader.getLocalName(); switch (localName) { case NameID.DEFAULT_ELEMENT_LOCAL_NAME: name = xmlStreamReader.getElementText(); for (int i = 0; i < xmlStreamReader.getAttributeCount(); i++) { if (xmlStreamReader.getAttributeLocalName(i).equals(NameID.FORMAT_ATTRIB_NAME)) { nameIDFormat = xmlStreamReader.getAttributeValue(i); break; } } break; case AttributeStatement.DEFAULT_ELEMENT_LOCAL_NAME: attributeStatement = new AttrStatement(); attributeStatements.add(attributeStatement); break; case AuthnStatement.DEFAULT_ELEMENT_LOCAL_NAME: authenticationStatement = new AuthenticationStatement(); authenticationStatements.add(authenticationStatement); attrs = xmlStreamReader.getAttributeCount(); for (int i = 0; i < attrs; i++) { String name = xmlStreamReader.getAttributeLocalName(i); String value = xmlStreamReader.getAttributeValue(i); if (AuthnStatement.AUTHN_INSTANT_ATTRIB_NAME.equals(name)) { authenticationStatement.setAuthnInstant(DateTime.parse(value)); } } break; case AuthnContextClassRef.DEFAULT_ELEMENT_LOCAL_NAME: if (authenticationStatement != null) { String classValue = xmlStreamReader.getText(); classValue = classValue.trim(); AuthenticationContextClassRef authenticationContextClassRef = new AuthenticationContextClassRef(); authenticationContextClassRef.setAuthnContextClassRef(classValue); AuthenticationContext authenticationContext = new AuthenticationContext(); authenticationContext.setAuthnContextClassRef(authenticationContextClassRef); authenticationStatement.setAuthnContext(authenticationContext); } break; case Attribute.DEFAULT_ELEMENT_LOCAL_NAME: attribute = new Attr(); if (attributeStatement != null) { attributeStatement.addAttribute(attribute); } attrs = xmlStreamReader.getAttributeCount(); for (int i = 0; i < attrs; i++) { String name = xmlStreamReader.getAttributeLocalName(i); String value = xmlStreamReader.getAttributeValue(i); if (Attribute.NAME_ATTTRIB_NAME.equals(name)) { attribute.setName(value); } else if (Attribute.NAME_FORMAT_ATTRIB_NAME.equals(name)) { attribute.setNameFormat(value); } } break; case AttributeValue.DEFAULT_ELEMENT_LOCAL_NAME: XSString xsString = new XMLString(); xsString.setValue(xmlStreamReader.getElementText()); if (attribute != null) { attribute.addAttributeValue(xsString); } break; case Issuer.DEFAULT_ELEMENT_LOCAL_NAME: issuer = xmlStreamReader.getElementText(); break; case Conditions.DEFAULT_ELEMENT_LOCAL_NAME: attrs = xmlStreamReader.getAttributeCount(); for (int i = 0; i < attrs; i++) { String name = xmlStreamReader.getAttributeLocalName(i); String value = xmlStreamReader.getAttributeValue(i); if (Conditions.NOT_BEFORE_ATTRIB_NAME.equals(name)) { notBefore = DatatypeConverter.parseDateTime(value).getTime(); } else if (Conditions.NOT_ON_OR_AFTER_ATTRIB_NAME.equals(name)) { notOnOrAfter = DatatypeConverter.parseDateTime(value).getTime(); } } break; case SubjectConfirmation.DEFAULT_ELEMENT_LOCAL_NAME: attrs = xmlStreamReader.getAttributeCount(); for (int i = 0; i < attrs; i++) { String name = xmlStreamReader.getAttributeLocalName(i); String value = xmlStreamReader.getAttributeValue(i); if (SubjectConfirmation.METHOD_ATTRIB_NAME.equals(name)) { subjectConfirmations.add(value); } } case Assertion.DEFAULT_ELEMENT_LOCAL_NAME: attrs = xmlStreamReader.getAttributeCount(); for (int i = 0; i < attrs; i++) { String name = xmlStreamReader.getAttributeLocalName(i); String value = xmlStreamReader.getAttributeValue(i); if (Assertion.VERSION_ATTRIB_NAME.equals(name)) { if ("2.0".equals(value)) { tokenType = "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0"; } else if ("1.1".equals(value)) { tokenType = "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV1.1"; } } } } break; } case XMLStreamConstants.END_ELEMENT: { String localName = xmlStreamReader.getLocalName(); switch (localName) { case AttributeStatement.DEFAULT_ELEMENT_LOCAL_NAME: attributeStatement = null; break; case Attribute.DEFAULT_ELEMENT_LOCAL_NAME: attribute = null; break; default: break; } break; } } } } catch (XMLStreamException e) { LOGGER.error("Unable to parse security token.", e); } finally { try { xmlStreamReader.close(); } catch (XMLStreamException ignore) { //ignore } } }
From source file:com.marklogic.client.functionaltest.TestBiTemporal.java
private void validateLSQTQueryData(DatabaseClient client) throws Exception { // Fetch documents associated with a search term (such as XML) in Address // element/*from ww w . j av a 2s .co m*/ QueryManager queryMgr = client.newQueryManager(); StructuredQueryBuilder sqb = queryMgr.newStructuredQueryBuilder(); Calendar queryTime = DatatypeConverter.parseDateTime("2007-01-01T00:00:01"); StructuredQueryDefinition periodQuery = sqb.temporalLsqtQuery(temporalLsqtCollectionName, queryTime, 0, new String[] {}); long start = 1; JSONDocumentManager docMgr = client.newJSONDocumentManager(); docMgr.setMetadataCategories(Metadata.ALL); // Get all metadata DocumentPage termQueryResults = docMgr.search(periodQuery, start); long count = 0; while (termQueryResults.hasNext()) { ++count; DocumentRecord record = termQueryResults.next(); System.out.println("URI = " + record.getUri()); DocumentMetadataHandle metadataHandle = new DocumentMetadataHandle(); record.getMetadata(metadataHandle); Iterator<String> resCollections = metadataHandle.getCollections().iterator(); while (resCollections.hasNext()) { System.out.println("Collection = " + resCollections.next()); } if (record.getFormat() == Format.XML) { DOMHandle recordHandle = new DOMHandle(); record.getContent(recordHandle); System.out.println("Content = " + recordHandle.toString()); } else { JacksonDatabindHandle<ObjectNode> recordHandle = new JacksonDatabindHandle<ObjectNode>( ObjectNode.class); record.getContent(recordHandle); System.out.println("Content = " + recordHandle.toString()); JsonFactory factory = new JsonFactory(); ObjectMapper mapper = new ObjectMapper(factory); TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>() { }; HashMap<String, Object> docObject = mapper.readValue(recordHandle.toString(), typeRef); @SuppressWarnings("unchecked") HashMap<String, Object> systemNode = (HashMap<String, Object>) (docObject.get(systemNodeName)); String systemStartDate = (String) systemNode.get(systemStartERIName); String systemEndDate = (String) systemNode.get(systemEndERIName); System.out.println("systemStartDate = " + systemStartDate); System.out.println("systemEndDate = " + systemEndDate); @SuppressWarnings("unchecked") HashMap<String, Object> validNode = (HashMap<String, Object>) (docObject.get(validNodeName)); String validStartDate = (String) validNode.get(validStartERIName); String validEndDate = (String) validNode.get(validEndERIName); System.out.println("validStartDate = " + validStartDate); System.out.println("validEndDate = " + validEndDate); assertTrue("Valid start date check failed", (validStartDate.equals("2001-01-01T00:00:00") && validEndDate.equals("2011-12-31T23:59:59") && systemStartDate.equals("2005-01-01T00:00:01-08:00") && systemEndDate.equals("2010-01-01T00:00:01-08:00"))); } } System.out.println("Number of results using SQB = " + count); assertEquals("Wrong number of results", 1, count); }
From source file:com.microsoft.azure.management.sql.RecommendedIndexOperationsImpl.java
/** * Returns details on recommended index./*from w w w . j a v a 2s . c om*/ * * @param resourceGroupName Required. The name of the Resource Group. * @param serverName Required. The name of the Azure SQL server. * @param databaseName Required. The name of the Azure SQL database. * @param schemaName Required. The name of the Azure SQL database schema. * @param tableName Required. The name of the Azure SQL database table. * @param indexName Required. The name of the Azure SQL database recommended * index. * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations. * @throws ServiceException Thrown if an unexpected response is found. * @return Represents the response to a get recommended index request. */ @Override public RecommendedIndexGetResponse get(String resourceGroupName, String serverName, String databaseName, String schemaName, String tableName, String indexName) throws IOException, ServiceException { // Validate if (resourceGroupName == null) { throw new NullPointerException("resourceGroupName"); } if (serverName == null) { throw new NullPointerException("serverName"); } if (databaseName == null) { throw new NullPointerException("databaseName"); } if (schemaName == null) { throw new NullPointerException("schemaName"); } if (tableName == null) { throw new NullPointerException("tableName"); } if (indexName == null) { throw new NullPointerException("indexName"); } // Tracing boolean shouldTrace = CloudTracing.getIsEnabled(); String invocationId = null; if (shouldTrace) { invocationId = Long.toString(CloudTracing.getNextInvocationId()); HashMap<String, Object> tracingParameters = new HashMap<String, Object>(); tracingParameters.put("resourceGroupName", resourceGroupName); tracingParameters.put("serverName", serverName); tracingParameters.put("databaseName", databaseName); tracingParameters.put("schemaName", schemaName); tracingParameters.put("tableName", tableName); tracingParameters.put("indexName", indexName); CloudTracing.enter(invocationId, this, "getAsync", tracingParameters); } // Construct URL String url = ""; url = url + "/subscriptions/"; if (this.getClient().getCredentials().getSubscriptionId() != null) { url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8"); } url = url + "/resourceGroups/"; url = url + URLEncoder.encode(resourceGroupName, "UTF-8"); url = url + "/providers/"; url = url + "Microsoft.Sql"; url = url + "/servers/"; url = url + URLEncoder.encode(serverName, "UTF-8"); url = url + "/databases/"; url = url + URLEncoder.encode(databaseName, "UTF-8"); url = url + "/schemas/"; url = url + URLEncoder.encode(schemaName, "UTF-8"); url = url + "/tables/"; url = url + URLEncoder.encode(tableName, "UTF-8"); url = url + "/recommendedIndexes/"; url = url + URLEncoder.encode(indexName, "UTF-8"); ArrayList<String> queryParameters = new ArrayList<String>(); queryParameters.add("api-version=" + "2014-04-01"); if (queryParameters.size() > 0) { url = url + "?" + CollectionStringBuilder.join(queryParameters, "&"); } String baseUrl = this.getClient().getBaseUri().toString(); // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl.charAt(baseUrl.length() - 1) == '/') { baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); } if (url.charAt(0) == '/') { url = url.substring(1); } url = baseUrl + "/" + url; url = url.replace(" ", "%20"); // Create HTTP transport objects HttpGet httpRequest = new HttpGet(url); // Set Headers // Send Request HttpResponse httpResponse = null; try { if (shouldTrace) { CloudTracing.sendRequest(invocationId, httpRequest); } httpResponse = this.getClient().getHttpClient().execute(httpRequest); if (shouldTrace) { CloudTracing.receiveResponse(invocationId, httpResponse); } int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { ServiceException ex = ServiceException.createFromJson(httpRequest, null, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result RecommendedIndexGetResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_OK) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new RecommendedIndexGetResponse(); 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) { RecommendedIndex recommendedIndexInstance = new RecommendedIndex(); result.setRecommendedIndex(recommendedIndexInstance); JsonNode propertiesValue = responseDoc.get("properties"); if (propertiesValue != null && propertiesValue instanceof NullNode == false) { RecommendedIndexProperties propertiesInstance = new RecommendedIndexProperties(); recommendedIndexInstance.setProperties(propertiesInstance); JsonNode actionValue = propertiesValue.get("action"); if (actionValue != null && actionValue instanceof NullNode == false) { String actionInstance; actionInstance = actionValue.getTextValue(); propertiesInstance.setAction(actionInstance); } JsonNode stateValue = propertiesValue.get("state"); if (stateValue != null && stateValue instanceof NullNode == false) { String stateInstance; stateInstance = stateValue.getTextValue(); propertiesInstance.setState(stateInstance); } JsonNode createdValue = propertiesValue.get("created"); if (createdValue != null && createdValue instanceof NullNode == false) { Calendar createdInstance; createdInstance = DatatypeConverter.parseDateTime(createdValue.getTextValue()); propertiesInstance.setCreated(createdInstance); } JsonNode lastModifiedValue = propertiesValue.get("lastModified"); if (lastModifiedValue != null && lastModifiedValue instanceof NullNode == false) { Calendar lastModifiedInstance; lastModifiedInstance = DatatypeConverter .parseDateTime(lastModifiedValue.getTextValue()); propertiesInstance.setLastModified(lastModifiedInstance); } JsonNode indexTypeValue = propertiesValue.get("indexType"); if (indexTypeValue != null && indexTypeValue instanceof NullNode == false) { String indexTypeInstance; indexTypeInstance = indexTypeValue.getTextValue(); propertiesInstance.setIndexType(indexTypeInstance); } JsonNode schemaValue = propertiesValue.get("schema"); if (schemaValue != null && schemaValue instanceof NullNode == false) { String schemaInstance; schemaInstance = schemaValue.getTextValue(); propertiesInstance.setSchema(schemaInstance); } JsonNode tableValue = propertiesValue.get("table"); if (tableValue != null && tableValue instanceof NullNode == false) { String tableInstance; tableInstance = tableValue.getTextValue(); propertiesInstance.setTable(tableInstance); } JsonNode columnsArray = propertiesValue.get("columns"); if (columnsArray != null && columnsArray instanceof NullNode == false) { for (JsonNode columnsValue : ((ArrayNode) columnsArray)) { propertiesInstance.getColumns().add(columnsValue.getTextValue()); } } JsonNode includedColumnsArray = propertiesValue.get("includedColumns"); if (includedColumnsArray != null && includedColumnsArray instanceof NullNode == false) { for (JsonNode includedColumnsValue : ((ArrayNode) includedColumnsArray)) { propertiesInstance.getIncludedColumns().add(includedColumnsValue.getTextValue()); } } JsonNode indexScriptValue = propertiesValue.get("indexScript"); if (indexScriptValue != null && indexScriptValue instanceof NullNode == false) { String indexScriptInstance; indexScriptInstance = indexScriptValue.getTextValue(); propertiesInstance.setIndexScript(indexScriptInstance); } JsonNode estimatedImpactArray = propertiesValue.get("estimatedImpact"); if (estimatedImpactArray != null && estimatedImpactArray instanceof NullNode == false) { for (JsonNode estimatedImpactValue : ((ArrayNode) estimatedImpactArray)) { OperationImpact operationImpactInstance = new OperationImpact(); propertiesInstance.getEstimatedImpact().add(operationImpactInstance); JsonNode nameValue = estimatedImpactValue.get("name"); if (nameValue != null && nameValue instanceof NullNode == false) { String nameInstance; nameInstance = nameValue.getTextValue(); operationImpactInstance.setName(nameInstance); } JsonNode unitValue = estimatedImpactValue.get("unit"); if (unitValue != null && unitValue instanceof NullNode == false) { String unitInstance; unitInstance = unitValue.getTextValue(); operationImpactInstance.setUnit(unitInstance); } JsonNode changeValueAbsoluteValue = estimatedImpactValue.get("changeValueAbsolute"); if (changeValueAbsoluteValue != null && changeValueAbsoluteValue instanceof NullNode == false) { double changeValueAbsoluteInstance; changeValueAbsoluteInstance = changeValueAbsoluteValue.getDoubleValue(); operationImpactInstance.setChangeValueAbsolute(changeValueAbsoluteInstance); } JsonNode changeValueRelativeValue = estimatedImpactValue.get("changeValueRelative"); if (changeValueRelativeValue != null && changeValueRelativeValue instanceof NullNode == false) { double changeValueRelativeInstance; changeValueRelativeInstance = changeValueRelativeValue.getDoubleValue(); operationImpactInstance.setChangeValueRelative(changeValueRelativeInstance); } } } JsonNode reportedImpactArray = propertiesValue.get("reportedImpact"); if (reportedImpactArray != null && reportedImpactArray instanceof NullNode == false) { for (JsonNode reportedImpactValue : ((ArrayNode) reportedImpactArray)) { OperationImpact operationImpactInstance2 = new OperationImpact(); propertiesInstance.getReportedImpact().add(operationImpactInstance2); JsonNode nameValue2 = reportedImpactValue.get("name"); if (nameValue2 != null && nameValue2 instanceof NullNode == false) { String nameInstance2; nameInstance2 = nameValue2.getTextValue(); operationImpactInstance2.setName(nameInstance2); } JsonNode unitValue2 = reportedImpactValue.get("unit"); if (unitValue2 != null && unitValue2 instanceof NullNode == false) { String unitInstance2; unitInstance2 = unitValue2.getTextValue(); operationImpactInstance2.setUnit(unitInstance2); } JsonNode changeValueAbsoluteValue2 = reportedImpactValue.get("changeValueAbsolute"); if (changeValueAbsoluteValue2 != null && changeValueAbsoluteValue2 instanceof NullNode == false) { double changeValueAbsoluteInstance2; changeValueAbsoluteInstance2 = changeValueAbsoluteValue2.getDoubleValue(); operationImpactInstance2.setChangeValueAbsolute(changeValueAbsoluteInstance2); } JsonNode changeValueRelativeValue2 = reportedImpactValue.get("changeValueRelative"); if (changeValueRelativeValue2 != null && changeValueRelativeValue2 instanceof NullNode == false) { double changeValueRelativeInstance2; changeValueRelativeInstance2 = changeValueRelativeValue2.getDoubleValue(); operationImpactInstance2.setChangeValueRelative(changeValueRelativeInstance2); } } } } JsonNode idValue = responseDoc.get("id"); if (idValue != null && idValue instanceof NullNode == false) { String idInstance; idInstance = idValue.getTextValue(); recommendedIndexInstance.setId(idInstance); } JsonNode nameValue3 = responseDoc.get("name"); if (nameValue3 != null && nameValue3 instanceof NullNode == false) { String nameInstance3; nameInstance3 = nameValue3.getTextValue(); recommendedIndexInstance.setName(nameInstance3); } JsonNode typeValue = responseDoc.get("type"); if (typeValue != null && typeValue instanceof NullNode == false) { String typeInstance; typeInstance = typeValue.getTextValue(); recommendedIndexInstance.setType(typeInstance); } JsonNode locationValue = responseDoc.get("location"); if (locationValue != null && locationValue instanceof NullNode == false) { String locationInstance; locationInstance = locationValue.getTextValue(); recommendedIndexInstance.setLocation(locationInstance); } JsonNode tagsSequenceElement = ((JsonNode) responseDoc.get("tags")); if (tagsSequenceElement != null && tagsSequenceElement instanceof NullNode == false) { Iterator<Map.Entry<String, JsonNode>> itr = tagsSequenceElement.getFields(); while (itr.hasNext()) { Map.Entry<String, JsonNode> property = itr.next(); String tagsKey = property.getKey(); String tagsValue = property.getValue().getTextValue(); recommendedIndexInstance.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:br.com.upic.camel.openedge.OpenEdgeEndpoint.java
@Override protected void onExchange(final Exchange exchange) throws Exception { try {//from w ww. j a v a 2s .com LOG.info("Unmarshalling the request"); final Request req = (Request) unmarshaller.unmarshal(exchange.getIn().getBody(Document.class)); LOG.info("Setting the input params"); final List<JAXBElement<? extends Serializable>> reqParamElementList = req.getParamElementList(); final ParamArray proParams = new ParamArray(reqParamElementList.size()); for (final JAXBElement<? extends Serializable> reqParamElement : reqParamElementList) { final Serializable reqParam = reqParamElement.getValue(); if (reqParam instanceof CharArrayParam) { final CharArrayParam charArrayParam = (CharArrayParam) reqParam; final ParamMode mode = charArrayParam.getMode(); final int id = charArrayParam.getId(); if (((ParamMode.INPUT == mode) || (ParamMode.INPUT_OUTPUT == mode)) && (!reqParamElement.isNil())) { final List<String> value = new ArrayList<String>(); for (final JAXBElement<String> valueElement : charArrayParam.getValueElementList()) { if (!valueElement.isNil()) value.add(DatatypeConverter.parseString(valueElement.getValue())); else value.add(null); } proParams.addCharacterArray(id, value.toArray(new String[] {}), mode.value(), value.size()); } else { proParams.addCharacterArray(id, null, mode.value(), 0); } } else if (reqParam instanceof CharParam) { final CharParam charParam = (CharParam) reqParam; final ParamMode mode = charParam.getMode(); final int id = charParam.getId(); if (((ParamMode.INPUT == mode) || (ParamMode.INPUT_OUTPUT == mode)) && (!reqParamElement.isNil())) proParams.addCharacter(id, DatatypeConverter.parseString(charParam.getContent()), mode.value()); else proParams.addCharacter(id, null, mode.value()); } else if (reqParam instanceof DateArrayParam) { final DateArrayParam dateArrayParam = (DateArrayParam) reqParam; final ParamMode mode = dateArrayParam.getMode(); final int id = dateArrayParam.getId(); if (((ParamMode.INPUT == mode) || (ParamMode.INPUT_OUTPUT == mode)) && (!reqParamElement.isNil())) { final List<GregorianCalendar> value = new ArrayList<GregorianCalendar>(); for (final JAXBElement<String> valueElement : dateArrayParam.getValueElementList()) { if (!valueElement.isNil()) { final GregorianCalendar cal = new GregorianCalendar(); cal.setTime(DatatypeConverter.parseDate(valueElement.getValue()).getTime()); value.add(cal); } else { value.add(null); } } proParams.addDateArray(id, value.toArray(new GregorianCalendar[] {}), mode.value(), value.size()); } else { proParams.addDateArray(id, null, mode.value(), 0); } } else if (reqParam instanceof DateParam) { final DateParam dateParam = (DateParam) reqParam; final ParamMode mode = dateParam.getMode(); final int id = dateParam.getId(); if (((ParamMode.INPUT == mode) || (ParamMode.INPUT_OUTPUT == mode)) && (!reqParamElement.isNil())) { final GregorianCalendar cal = new GregorianCalendar(); cal.setTime(DatatypeConverter.parseDate(dateParam.getContent()).getTime()); proParams.addDate(id, cal, mode.value()); } else { proParams.addDate(id, null, mode.value()); } } else if (reqParam instanceof DateTimeArrayParam) { final DateTimeArrayParam dateTimeArrayParam = (DateTimeArrayParam) reqParam; final ParamMode mode = dateTimeArrayParam.getMode(); final int id = dateTimeArrayParam.getId(); if (((ParamMode.INPUT == mode) || (ParamMode.INPUT_OUTPUT == mode)) && (!reqParamElement.isNil())) { final List<GregorianCalendar> value = new ArrayList<GregorianCalendar>(); for (final JAXBElement<String> valueElement : dateTimeArrayParam.getValueElementList()) { if (!valueElement.isNil()) { final GregorianCalendar cal = new GregorianCalendar(); cal.setTime(DatatypeConverter.parseDateTime(valueElement.getValue()).getTime()); value.add(cal); } else { value.add(null); } } proParams.addDatetimeArray(id, value.toArray(new GregorianCalendar[] {}), mode.value(), value.size()); } else { proParams.addDatetimeArray(id, null, mode.value(), 0); } } else if (reqParam instanceof DateTimeParam) { final DateTimeParam dateTimeParam = (DateTimeParam) reqParam; final ParamMode mode = dateTimeParam.getMode(); final int id = dateTimeParam.getId(); if (((ParamMode.INPUT == mode) || (ParamMode.INPUT_OUTPUT == mode)) && (!reqParamElement.isNil())) { final GregorianCalendar cal = new GregorianCalendar(); cal.setTime(DatatypeConverter.parseDateTime(dateTimeParam.getContent()).getTime()); proParams.addDatetime(id, cal, mode.value()); } else { proParams.addDatetime(id, null, mode.value()); } } else if (reqParam instanceof DateTimeTZArrayParam) { final DateTimeTZArrayParam dateTimeTZArrayParam = (DateTimeTZArrayParam) reqParam; final ParamMode mode = dateTimeTZArrayParam.getMode(); final int id = dateTimeTZArrayParam.getId(); if (((ParamMode.INPUT == mode) || (ParamMode.INPUT_OUTPUT == mode)) && (!reqParamElement.isNil())) { final List<GregorianCalendar> value = new ArrayList<GregorianCalendar>(); for (final JAXBElement<String> valueElement : dateTimeTZArrayParam.getValueElementList()) { if (!valueElement.isNil()) { final GregorianCalendar cal = new GregorianCalendar(); cal.setTime(DatatypeConverter.parseDateTime(valueElement.getValue()).getTime()); value.add(cal); } else { value.add(null); } } proParams.addDatetimeTZArray(id, value.toArray(new GregorianCalendar[] {}), mode.value(), value.size()); } else { proParams.addDatetimeTZArray(id, null, mode.value(), 0); } } else if (reqParam instanceof DateTimeTZParam) { final DateTimeTZParam dateTimeTZParam = (DateTimeTZParam) reqParam; final ParamMode mode = dateTimeTZParam.getMode(); final int id = dateTimeTZParam.getId(); if (((ParamMode.INPUT == mode) || (ParamMode.INPUT_OUTPUT == mode)) && (!reqParamElement.isNil())) { final GregorianCalendar cal = new GregorianCalendar(); cal.setTime(DatatypeConverter.parseDateTime(dateTimeTZParam.getContent()).getTime()); proParams.addDatetimeTZ(id, cal, mode.value()); } else { proParams.addDatetimeTZ(id, null, mode.value()); } } else if (reqParam instanceof DecArrayParam) { final DecArrayParam decArrayParam = (DecArrayParam) reqParam; final ParamMode mode = decArrayParam.getMode(); final int id = decArrayParam.getId(); if (((ParamMode.INPUT == mode) || (ParamMode.INPUT_OUTPUT == mode)) && (!reqParamElement.isNil())) { final List<BigDecimal> value = new ArrayList<BigDecimal>(); for (final JAXBElement<String> valueElement : decArrayParam.getValueElementList()) { if (!valueElement.isNil()) value.add(DatatypeConverter.parseDecimal(valueElement.getValue())); else value.add(null); } proParams.addDecimalArray(id, value.toArray(new BigDecimal[] {}), mode.value(), value.size()); } else { proParams.addDecimalArray(id, null, mode.value(), 0); } } else if (reqParam instanceof DecParam) { final DecParam decParam = (DecParam) reqParam; final ParamMode mode = decParam.getMode(); final int id = decParam.getId(); if (((ParamMode.INPUT == mode) || (ParamMode.INPUT_OUTPUT == mode)) && (!reqParamElement.isNil())) proParams.addDecimal(id, DatatypeConverter.parseDecimal(decParam.getContent()), mode.value()); else proParams.addDecimal(id, null, mode.value()); } else if (reqParam instanceof IntArrayParam) { final IntArrayParam intArrayParam = (IntArrayParam) reqParam; final ParamMode mode = intArrayParam.getMode(); final int id = intArrayParam.getId(); if (((ParamMode.INPUT == mode) || (ParamMode.INPUT_OUTPUT == mode)) && (!reqParamElement.isNil())) { final List<Integer> value = new ArrayList<Integer>(); for (final JAXBElement<String> valueElement : intArrayParam.getValueElementList()) { if (!valueElement.isNil()) value.add(DatatypeConverter.parseInt(valueElement.getValue())); else value.add(null); } proParams.addIntegerArray(id, value.toArray(new Integer[] {}), mode.value(), value.size()); } else { proParams.addIntegerArray(id, (Integer[]) null, mode.value(), 0); } } else if (reqParam instanceof IntParam) { final IntParam intParam = (IntParam) reqParam; final ParamMode mode = intParam.getMode(); final int id = intParam.getId(); if (((ParamMode.INPUT == mode) || (ParamMode.INPUT_OUTPUT == mode)) && (!reqParamElement.isNil())) proParams.addInteger(id, new Integer(DatatypeConverter.parseInt(intParam.getContent())), mode.value()); else proParams.addInteger(id, null, mode.value()); } else if (reqParam instanceof LogArrayParam) { final LogArrayParam logArrayParam = (LogArrayParam) reqParam; final ParamMode mode = logArrayParam.getMode(); final int id = logArrayParam.getId(); if (((ParamMode.INPUT == mode) || (ParamMode.INPUT_OUTPUT == mode)) && (!reqParamElement.isNil())) { final List<Boolean> value = new ArrayList<Boolean>(); for (final JAXBElement<String> valueElement : logArrayParam.getValueElementList()) { if (!valueElement.isNil()) value.add(DatatypeConverter.parseBoolean(valueElement.getValue())); else value.add(null); } proParams.addLogicalArray(id, value.toArray(new Boolean[] {}), mode.value(), value.size()); } else { proParams.addLogicalArray(id, (Boolean[]) null, mode.value(), 0); } } else if (reqParam instanceof LogParam) { final LogParam logParam = (LogParam) reqParam; final ParamMode mode = logParam.getMode(); final int id = logParam.getId(); if (((ParamMode.INPUT == mode) || (ParamMode.INPUT_OUTPUT == mode)) && (!reqParamElement.isNil())) proParams.addLogical(id, new Boolean(DatatypeConverter.parseBoolean(logParam.getContent())), mode.value()); else proParams.addLogical(id, null, mode.value()); } else if (reqParam instanceof ResultSetParam) { final ResultSetParam rsParam = (ResultSetParam) reqParam; final ParamMode mode = rsParam.getMode(); final int id = rsParam.getId(); final ResultSetMetaData rsMetaData = rsParam.getResultSetMetaData(); final List<Serializable> fieldMetaDataList = rsMetaData.getFieldMetaDataList(); final ProResultSetMetaDataImpl proRsMetaData = new ProResultSetMetaDataImpl( fieldMetaDataList.size()); for (final Serializable fieldMetaData : fieldMetaDataList) { if (fieldMetaData instanceof CharFieldMetaData) { final CharFieldMetaData charFieldMetaData = (CharFieldMetaData) fieldMetaData; proRsMetaData.setFieldMetaData(charFieldMetaData.getId(), charFieldMetaData.getName(), charFieldMetaData.getExtent(), Parameter.PRO_CHARACTER); } else if (fieldMetaData instanceof DateFieldMetaData) { final DateFieldMetaData dateFieldMetaData = (DateFieldMetaData) fieldMetaData; proRsMetaData.setFieldMetaData(dateFieldMetaData.getId(), dateFieldMetaData.getName(), dateFieldMetaData.getExtent(), Parameter.PRO_DATE); } else if (fieldMetaData instanceof DateTimeFieldMetaData) { final DateTimeFieldMetaData dateTimeFieldMetaData = (DateTimeFieldMetaData) fieldMetaData; proRsMetaData.setFieldMetaData(dateTimeFieldMetaData.getId(), dateTimeFieldMetaData.getName(), dateTimeFieldMetaData.getExtent(), Parameter.PRO_DATETIME); } else if (fieldMetaData instanceof DateTimeTZFieldMetaData) { final DateTimeTZFieldMetaData dateTimeTZFieldMetaData = (DateTimeTZFieldMetaData) fieldMetaData; proRsMetaData.setFieldMetaData(dateTimeTZFieldMetaData.getId(), dateTimeTZFieldMetaData.getName(), dateTimeTZFieldMetaData.getExtent(), Parameter.PRO_DATETIMETZ); } else if (fieldMetaData instanceof DecFieldMetaData) { final DecFieldMetaData decFieldMetaData = (DecFieldMetaData) fieldMetaData; proRsMetaData.setFieldMetaData(decFieldMetaData.getId(), decFieldMetaData.getName(), decFieldMetaData.getExtent(), Parameter.PRO_DECIMAL); } else if (fieldMetaData instanceof IntFieldMetaData) { final IntFieldMetaData intFieldMetaData = (IntFieldMetaData) fieldMetaData; proRsMetaData.setFieldMetaData(intFieldMetaData.getId(), intFieldMetaData.getName(), intFieldMetaData.getExtent(), Parameter.PRO_INTEGER); } else if (fieldMetaData instanceof LogFieldMetaData) { final LogFieldMetaData logFieldMetaData = (LogFieldMetaData) fieldMetaData; proRsMetaData.setFieldMetaData(logFieldMetaData.getId(), logFieldMetaData.getName(), logFieldMetaData.getExtent(), Parameter.PRO_LOGICAL); } } if (((ParamMode.INPUT == mode) || (ParamMode.INPUT_OUTPUT == mode)) && (!reqParamElement.isNil())) proParams.addTable(id, new OpenEdgeResultSet(rsParam.getRowList().iterator()), mode.value(), proRsMetaData); else proParams.addTable(id, null, mode.value(), proRsMetaData); } } LOG.info("Connecting to the AppServer"); if (SESSION_MODEL_MANAGED == sessionModel) RunTimeProperties.setSessionModel(0); else if (SESSION_MODEL_FREE == sessionModel) RunTimeProperties.setSessionModel(1); final OpenAppObject proAppObject = new OpenAppObject(url, user, password, null, null); proAppObject.runProc(req.getProgram(), proParams); LOG.info("Marshalling the response"); final Response res = OBJECT_FACTORY.createResponse(); res.setResult(proParams.getProcReturnString()); LOG.info("Setting the output params"); for (final JAXBElement<? extends Serializable> reqParamElement : reqParamElementList) { final Serializable reqParam = reqParamElement.getValue(); if (reqParam instanceof CharArrayParam) { final CharArrayParam reqCharArrayParam = (CharArrayParam) reqParam; if (ParamMode.INPUT != reqCharArrayParam.getMode()) { final JAXBElement<CharArrayParam> resParamElement = new JAXBElement<CharArrayParam>( new QName(NS, "CharArray"), CharArrayParam.class, null); final CharArrayParam resParam = OBJECT_FACTORY.createCharArrayParam(); resParam.setId(reqCharArrayParam.getId()); resParam.setName(reqCharArrayParam.getName()); final String[] proParam = (String[]) proParams.getOutputParameter(resParam.getId()); if (proParam != null) { for (int i = 0; i < proParam.length; i++) { final JAXBElement<String> valueElement = new JAXBElement<String>( new QName(NS, "Value"), String.class, null); if (proParam[i] != null) valueElement.setValue(DatatypeConverter.printString(proParam[i])); else valueElement.setNil(true); resParam.getValueElementList().add(valueElement); } resParamElement.setValue(resParam); } else { resParamElement.setNil(true); } res.getParamElementList().add(resParamElement); } } else if (reqParam instanceof CharParam) { final CharParam reqCharParam = (CharParam) reqParam; if (ParamMode.INPUT != reqCharParam.getMode()) { final JAXBElement<CharParam> resParamElement = new JAXBElement<CharParam>( new QName(NS, "Char"), CharParam.class, null); final CharParam resParam = OBJECT_FACTORY.createCharParam(); resParam.setId(reqCharParam.getId()); resParam.setName(reqCharParam.getName()); final String proParam = (String) proParams.getOutputParameter(resParam.getId()); if (proParam != null) { resParam.setContent(DatatypeConverter.printString(proParam)); resParamElement.setValue(resParam); } else { resParamElement.setNil(true); } res.getParamElementList().add(resParamElement); } } else if (reqParam instanceof DateArrayParam) { final DateArrayParam reqDateArrayParam = (DateArrayParam) reqParam; if (ParamMode.INPUT != reqDateArrayParam.getMode()) { final JAXBElement<DateArrayParam> resParamElement = new JAXBElement<DateArrayParam>( new QName(NS, "DateArray"), DateArrayParam.class, null); final DateArrayParam resParam = OBJECT_FACTORY.createDateArrayParam(); resParam.setId(reqDateArrayParam.getId()); resParam.setName(reqDateArrayParam.getName()); final Date[] proParam = (Date[]) proParams.getOutputParameter(resParam.getId()); if (proParam != null) { for (int i = 0; i < proParam.length; i++) { final JAXBElement<String> valueElement = new JAXBElement<String>( new QName(NS, "Value"), String.class, null); if (proParam[i] != null) { final Calendar cal = Calendar.getInstance(); cal.setTime(proParam[i]); valueElement.setValue(DatatypeConverter.printDate(cal)); } else { valueElement.setNil(true); } resParam.getValueElementList().add(valueElement); } resParamElement.setValue(resParam); } else { resParamElement.setNil(true); } res.getParamElementList().add(resParamElement); } } else if (reqParam instanceof DateParam) { final DateParam reqDateParam = (DateParam) reqParam; if (ParamMode.INPUT != reqDateParam.getMode()) { final JAXBElement<DateParam> resParamElement = new JAXBElement<DateParam>( new QName(NS, "Date"), DateParam.class, null); final DateParam resParam = OBJECT_FACTORY.createDateParam(); resParam.setId(reqDateParam.getId()); resParam.setName(reqDateParam.getName()); final Date proParam = (Date) proParams.getOutputParameter(resParam.getId()); if (proParam != null) { final Calendar cal = Calendar.getInstance(); cal.setTime(proParam); resParam.setContent(DatatypeConverter.printDate(cal)); resParamElement.setValue(resParam); } else { resParamElement.setNil(true); } res.getParamElementList().add(resParamElement); } } else if (reqParam instanceof DateTimeArrayParam) { final DateTimeArrayParam reqDateTimeArrayParam = (DateTimeArrayParam) reqParam; if (ParamMode.INPUT != reqDateTimeArrayParam.getMode()) { final JAXBElement<DateTimeArrayParam> resParamElement = new JAXBElement<DateTimeArrayParam>( new QName(NS, "DateTimeArray"), DateTimeArrayParam.class, null); final DateTimeArrayParam resParam = OBJECT_FACTORY.createDateTimeArrayParam(); resParam.setId(reqDateTimeArrayParam.getId()); resParam.setName(reqDateTimeArrayParam.getName()); final GregorianCalendar[] proParam = (GregorianCalendar[]) proParams .getOutputParameter(resParam.getId()); if (proParam != null) { for (int i = 0; i < proParam.length; i++) { final JAXBElement<String> valueElement = new JAXBElement<String>( new QName(NS, "Value"), String.class, null); if (proParam[i] != null) valueElement.setValue(DatatypeConverter.printDateTime(proParam[i])); else valueElement.setNil(true); resParam.getValueElementList().add(valueElement); } resParamElement.setValue(resParam); } else { resParamElement.setNil(true); } res.getParamElementList().add(resParamElement); } } else if (reqParam instanceof DateTimeParam) { final DateTimeParam reqDateTimeParam = (DateTimeParam) reqParam; if (ParamMode.INPUT != reqDateTimeParam.getMode()) { final JAXBElement<DateTimeParam> resParamElement = new JAXBElement<DateTimeParam>( new QName(NS, "DateTime"), DateTimeParam.class, null); final DateTimeParam resParam = OBJECT_FACTORY.createDateTimeParam(); resParam.setId(reqDateTimeParam.getId()); resParam.setName(reqDateTimeParam.getName()); final GregorianCalendar proParam = (GregorianCalendar) proParams .getOutputParameter(resParam.getId()); if (proParam != null) { resParam.setContent(DatatypeConverter.printDateTime(proParam)); resParamElement.setValue(resParam); } else { resParamElement.setNil(true); } res.getParamElementList().add(resParamElement); } } else if (reqParam instanceof DateTimeTZArrayParam) { final DateTimeTZArrayParam reqDateTimeTZArrayParam = (DateTimeTZArrayParam) reqParam; if (ParamMode.INPUT != reqDateTimeTZArrayParam.getMode()) { final JAXBElement<DateTimeTZArrayParam> resParamElement = new JAXBElement<DateTimeTZArrayParam>( new QName(NS, "DateTimeTZArray"), DateTimeTZArrayParam.class, null); final DateTimeTZArrayParam resParam = OBJECT_FACTORY.createDateTimeTZArrayParam(); resParam.setId(reqDateTimeTZArrayParam.getId()); resParam.setName(reqDateTimeTZArrayParam.getName()); final GregorianCalendar[] proParam = (GregorianCalendar[]) proParams .getOutputParameter(resParam.getId()); if (proParam != null) { for (int i = 0; i < proParam.length; i++) { final JAXBElement<String> valueElement = new JAXBElement<String>( new QName(NS, "Value"), String.class, null); if (proParam[i] != null) valueElement.setValue(DatatypeConverter.printDateTime(proParam[i])); else valueElement.setNil(true); resParam.getValueElementList().add(valueElement); } resParamElement.setValue(resParam); } else { resParamElement.setNil(true); } res.getParamElementList().add(resParamElement); } } else if (reqParam instanceof DateTimeTZParam) { final DateTimeTZParam reqDateTimeTZParam = (DateTimeTZParam) reqParam; if (ParamMode.INPUT != reqDateTimeTZParam.getMode()) { final JAXBElement<DateTimeTZParam> resParamElement = new JAXBElement<DateTimeTZParam>( new QName(NS, "DateTimeTZ"), DateTimeTZParam.class, null); final DateTimeTZParam resParam = OBJECT_FACTORY.createDateTimeTZParam(); resParam.setId(reqDateTimeTZParam.getId()); resParam.setName(reqDateTimeTZParam.getName()); final GregorianCalendar proParam = (GregorianCalendar) proParams .getOutputParameter(resParam.getId()); if (proParam != null) { resParam.setContent(DatatypeConverter.printDateTime(proParam)); resParamElement.setValue(resParam); } else { resParamElement.setNil(true); } res.getParamElementList().add(resParamElement); } } else if (reqParam instanceof DecArrayParam) { final DecArrayParam reqDecArrayParam = (DecArrayParam) reqParam; if (ParamMode.INPUT != reqDecArrayParam.getMode()) { final JAXBElement<DecArrayParam> resParamElement = new JAXBElement<DecArrayParam>( new QName(NS, "DecArray"), DecArrayParam.class, null); final DecArrayParam resParam = OBJECT_FACTORY.createDecArrayParam(); resParam.setId(reqDecArrayParam.getId()); resParam.setName(reqDecArrayParam.getName()); final BigDecimal[] proParam = (BigDecimal[]) proParams.getOutputParameter(resParam.getId()); if (proParam != null) { for (int i = 0; i < proParam.length; i++) { final JAXBElement<String> valueElement = new JAXBElement<String>( new QName(NS, "Value"), String.class, null); if (proParam[i] != null) valueElement.setValue(DatatypeConverter.printDecimal(proParam[i])); else valueElement.setNil(true); resParam.getValueElementList().add(valueElement); } resParamElement.setValue(resParam); } else { resParamElement.setNil(true); } res.getParamElementList().add(resParamElement); } } else if (reqParam instanceof DecParam) { final DecParam reqDecParam = (DecParam) reqParam; if (ParamMode.INPUT != reqDecParam.getMode()) { final JAXBElement<DecParam> resParamElement = new JAXBElement<DecParam>( new QName(NS, "Dec"), DecParam.class, null); final DecParam resParam = OBJECT_FACTORY.createDecParam(); resParam.setId(reqDecParam.getId()); resParam.setName(reqDecParam.getName()); final BigDecimal proParam = (BigDecimal) proParams.getOutputParameter(resParam.getId()); if (proParam != null) { resParam.setContent(DatatypeConverter.printDecimal(proParam)); resParamElement.setValue(resParam); } else { resParamElement.setNil(true); } res.getParamElementList().add(resParamElement); } } else if (reqParam instanceof IntArrayParam) { final IntArrayParam reqIntArrayParam = (IntArrayParam) reqParam; if (ParamMode.INPUT != reqIntArrayParam.getMode()) { final JAXBElement<IntArrayParam> resParamElement = new JAXBElement<IntArrayParam>( new QName(NS, "IntArray"), IntArrayParam.class, null); final IntArrayParam resParam = OBJECT_FACTORY.createIntArrayParam(); resParam.setId(reqIntArrayParam.getId()); resParam.setName(reqIntArrayParam.getName()); final Integer[] proParam = (Integer[]) proParams.getOutputParameter(resParam.getId()); if (proParam != null) { for (int i = 0; i < proParam.length; i++) { final JAXBElement<String> valueElement = new JAXBElement<String>( new QName(NS, "Value"), String.class, null); if (proParam[i] != null) valueElement.setValue(DatatypeConverter.printInt(proParam[i])); else valueElement.setNil(true); resParam.getValueElementList().add(valueElement); } resParamElement.setValue(resParam); } else { resParamElement.setNil(true); } res.getParamElementList().add(resParamElement); } } else if (reqParam instanceof IntParam) { final IntParam reqIntParam = (IntParam) reqParam; if (ParamMode.INPUT != reqIntParam.getMode()) { final JAXBElement<IntParam> resParamElement = new JAXBElement<IntParam>( new QName(NS, "Int"), IntParam.class, null); final IntParam resParam = OBJECT_FACTORY.createIntParam(); resParam.setId(reqIntParam.getId()); resParam.setName(reqIntParam.getName()); final Integer proParam = (Integer) proParams.getOutputParameter(resParam.getId()); if (proParam != null) { resParam.setContent(DatatypeConverter.printInt(proParam)); resParamElement.setValue(resParam); } else { resParamElement.setNil(true); } res.getParamElementList().add(resParamElement); } } else if (reqParam instanceof LogArrayParam) { final LogArrayParam reqLogArrayParam = (LogArrayParam) reqParam; if (ParamMode.INPUT != reqLogArrayParam.getMode()) { final JAXBElement<LogArrayParam> resParamElement = new JAXBElement<LogArrayParam>( new QName(NS, "LogArray"), LogArrayParam.class, null); final LogArrayParam resParam = OBJECT_FACTORY.createLogArrayParam(); resParam.setId(reqLogArrayParam.getId()); resParam.setName(reqLogArrayParam.getName()); final Boolean[] proParam = (Boolean[]) proParams.getOutputParameter(resParam.getId()); if (proParam != null) { for (int i = 0; i < proParam.length; i++) { final JAXBElement<String> valueElement = new JAXBElement<String>( new QName(NS, "Value"), String.class, null); if (proParam[i] != null) valueElement.setValue(DatatypeConverter.printBoolean(proParam[i])); else valueElement.setNil(true); resParam.getValueElementList().add(valueElement); } resParamElement.setValue(resParam); } else { resParamElement.setNil(true); } res.getParamElementList().add(resParamElement); } } else if (reqParam instanceof LogParam) { final LogParam reqLogParam = (LogParam) reqParam; if (ParamMode.INPUT != reqLogParam.getMode()) { final JAXBElement<LogParam> resParamElement = new JAXBElement<LogParam>( new QName(NS, "Log"), LogParam.class, null); final LogParam resParam = OBJECT_FACTORY.createLogParam(); resParam.setId(reqLogParam.getId()); resParam.setName(reqLogParam.getName()); final Boolean proParam = (Boolean) proParams.getOutputParameter(resParam.getId()); if (proParam != null) { resParam.setContent(DatatypeConverter.printBoolean(proParam)); resParamElement.setValue(resParam); } else { resParamElement.setNil(true); } res.getParamElementList().add(resParamElement); } } else if (reqParam instanceof ResultSetParam) { final ResultSetParam reqResultSetParam = (ResultSetParam) reqParam; if (ParamMode.INPUT != reqResultSetParam.getMode()) { final JAXBElement<ResultSetParam> resParamElement = new JAXBElement<ResultSetParam>( new QName(NS, "ResultSet"), ResultSetParam.class, null); final ResultSetParam resParam = OBJECT_FACTORY.createResultSetParam(); resParam.setId(reqResultSetParam.getId()); resParam.setName(reqResultSetParam.getName()); final ProResultSet proParam = (ProResultSet) proParams.getOutputParameter(resParam.getId()); if (proParam != null) { while (proParam.next()) { final Row row = OBJECT_FACTORY.createRow(); final ResultSetMetaData rsMetaData = reqResultSetParam.getResultSetMetaData(); for (final Serializable fieldMetaData : rsMetaData.getFieldMetaDataList()) { if (fieldMetaData instanceof CharFieldMetaData) { final CharFieldMetaData charFieldMetaData = (CharFieldMetaData) fieldMetaData; final int extent = charFieldMetaData.getExtent(); if (extent < 1) { final JAXBElement<CharField> fieldElement = new JAXBElement<CharField>( new QName(NS, "Char"), CharField.class, null); final CharField field = OBJECT_FACTORY.createCharField(); field.setId(charFieldMetaData.getId()); field.setName(charFieldMetaData.getName()); final String value = proParam.getString(field.getId()); if (value != null) { field.setContent(DatatypeConverter.printString(value)); fieldElement.setValue(field); } else { fieldElement.setNil(true); } row.getFieldElementList().add(fieldElement); } else { for (int i = 1; i <= extent; i++) { final JAXBElement<CharField> fieldElement = new JAXBElement<CharField>( new QName(NS, "Char"), CharField.class, null); final CharField field = OBJECT_FACTORY.createCharField(); field.setId(charFieldMetaData.getId()); field.setName(charFieldMetaData.getName()); final String value = proParam.getString(field.getId(), i); if (value != null) { field.setContent(DatatypeConverter.printString(value)); fieldElement.setValue(field); } else { fieldElement.setNil(true); } row.getFieldElementList().add(fieldElement); } } } else if (fieldMetaData instanceof DateFieldMetaData) { final DateFieldMetaData dateFieldMetaData = (DateFieldMetaData) fieldMetaData; final int extent = dateFieldMetaData.getExtent(); if (extent < 1) { final JAXBElement<DateField> fieldElement = new JAXBElement<DateField>( new QName(NS, "Date"), DateField.class, null); final DateField field = OBJECT_FACTORY.createDateField(); field.setId(dateFieldMetaData.getId()); field.setName(dateFieldMetaData.getName()); final Date value = proParam.getDate(field.getId()); if (value != null) { final Calendar cal = Calendar.getInstance(); cal.setTime(value); field.setContent(DatatypeConverter.printDate(cal)); fieldElement.setValue(field); } else { fieldElement.setNil(true); } row.getFieldElementList().add(fieldElement); } else { for (int i = 1; i <= extent; i++) { final JAXBElement<DateField> fieldElement = new JAXBElement<DateField>( new QName(NS, "Date"), DateField.class, null); final DateField field = OBJECT_FACTORY.createDateField(); field.setId(dateFieldMetaData.getId()); field.setName(dateFieldMetaData.getName()); final Date value = proParam.getDate(field.getId(), i); if (value != null) { final Calendar cal = Calendar.getInstance(); cal.setTime(value); field.setContent(DatatypeConverter.printDate(cal)); fieldElement.setValue(field); } else { fieldElement.setNil(true); } row.getFieldElementList().add(fieldElement); } } } else if (fieldMetaData instanceof DateTimeFieldMetaData) { final DateTimeFieldMetaData dateTimeFieldMetaData = (DateTimeFieldMetaData) fieldMetaData; final int extent = dateTimeFieldMetaData.getExtent(); if (extent < 1) { final JAXBElement<DateTimeField> fieldElement = new JAXBElement<DateTimeField>( new QName(NS, "DateTime"), DateTimeField.class, null); final DateTimeField field = OBJECT_FACTORY.createDateTimeField(); field.setId(dateTimeFieldMetaData.getId()); field.setName(dateTimeFieldMetaData.getName()); final GregorianCalendar value = (GregorianCalendar) proParam .getObject(field.getId()); if (value != null) { field.setContent(DatatypeConverter.printDateTime(value)); fieldElement.setValue(field); } else { fieldElement.setNil(true); } row.getFieldElementList().add(fieldElement); } else { for (int i = 1; i <= extent; i++) { final JAXBElement<DateTimeField> fieldElement = new JAXBElement<DateTimeField>( new QName(NS, "DateTime"), DateTimeField.class, null); final DateTimeField field = OBJECT_FACTORY.createDateTimeField(); field.setId(dateTimeFieldMetaData.getId()); field.setName(dateTimeFieldMetaData.getName()); final GregorianCalendar value = (GregorianCalendar) proParam .getObject(field.getId(), i); if (value != null) { field.setContent(DatatypeConverter.printDateTime(value)); fieldElement.setValue(field); } else { fieldElement.setNil(true); } row.getFieldElementList().add(fieldElement); } } } else if (fieldMetaData instanceof DateTimeTZFieldMetaData) { final DateTimeTZFieldMetaData dateTimeTZFieldMetaData = (DateTimeTZFieldMetaData) fieldMetaData; final int extent = dateTimeTZFieldMetaData.getExtent(); if (extent < 1) { final JAXBElement<DateTimeTZField> fieldElement = new JAXBElement<DateTimeTZField>( new QName(NS, "DateTimeTZ"), DateTimeTZField.class, null); final DateTimeTZField field = OBJECT_FACTORY.createDateTimeTZField(); field.setId(dateTimeTZFieldMetaData.getId()); field.setName(dateTimeTZFieldMetaData.getName()); final GregorianCalendar value = (GregorianCalendar) proParam .getObject(field.getId()); if (value != null) { field.setContent(DatatypeConverter.printDateTime(value)); fieldElement.setValue(field); } else { fieldElement.setNil(true); } row.getFieldElementList().add(fieldElement); } else { for (int i = 1; i <= extent; i++) { final JAXBElement<DateTimeTZField> fieldElement = new JAXBElement<DateTimeTZField>( new QName(NS, "DateTimeTZ"), DateTimeTZField.class, null); final DateTimeTZField field = OBJECT_FACTORY .createDateTimeTZField(); field.setId(dateTimeTZFieldMetaData.getId()); field.setName(dateTimeTZFieldMetaData.getName()); final GregorianCalendar value = (GregorianCalendar) proParam .getObject(field.getId(), i); if (value != null) { field.setContent(DatatypeConverter.printDateTime(value)); fieldElement.setValue(field); } else { fieldElement.setNil(true); } row.getFieldElementList().add(fieldElement); } } } else if (fieldMetaData instanceof DecFieldMetaData) { final DecFieldMetaData decFieldMetaData = (DecFieldMetaData) fieldMetaData; final int extent = decFieldMetaData.getExtent(); if (extent < 1) { final JAXBElement<DecField> fieldElement = new JAXBElement<DecField>( new QName(NS, "Dec"), DecField.class, null); final DecField field = OBJECT_FACTORY.createDecField(); field.setId(decFieldMetaData.getId()); field.setName(decFieldMetaData.getName()); final BigDecimal value = proParam.getBigDecimal(field.getId()); if (value != null) { field.setContent(DatatypeConverter.printDecimal(value)); fieldElement.setValue(field); } else { fieldElement.setNil(true); } row.getFieldElementList().add(fieldElement); } else { for (int i = 1; i <= extent; i++) { final JAXBElement<DecField> fieldElement = new JAXBElement<DecField>( new QName(NS, "Dec"), DecField.class, null); final DecField field = OBJECT_FACTORY.createDecField(); field.setId(decFieldMetaData.getId()); field.setName(decFieldMetaData.getName()); final BigDecimal value = proParam.getBigDecimal(field.getId(), i, 0); if (value != null) { field.setContent(DatatypeConverter.printDecimal(value)); fieldElement.setValue(field); } else { fieldElement.setNil(true); } row.getFieldElementList().add(fieldElement); } } } else if (fieldMetaData instanceof IntFieldMetaData) { final IntFieldMetaData intFieldMetaData = (IntFieldMetaData) fieldMetaData; final int extent = intFieldMetaData.getExtent(); if (extent < 1) { final JAXBElement<IntField> fieldElement = new JAXBElement<IntField>( new QName(NS, "Int"), IntField.class, null); final IntField field = OBJECT_FACTORY.createIntField(); field.setId(intFieldMetaData.getId()); field.setName(intFieldMetaData.getName()); final String value = proParam.getString(field.getId()); if (value != null) { field.setContent( DatatypeConverter.printInt(Integer.parseInt(value))); fieldElement.setValue(field); } else { fieldElement.setNil(true); } row.getFieldElementList().add(fieldElement); } else { for (int i = 1; i <= extent; i++) { final JAXBElement<IntField> fieldElement = new JAXBElement<IntField>( new QName(NS, "Int"), IntField.class, null); final IntField field = OBJECT_FACTORY.createIntField(); field.setId(intFieldMetaData.getId()); field.setName(intFieldMetaData.getName()); final String value = proParam.getString(field.getId(), i); if (value != null) { field.setContent( DatatypeConverter.printInt(Integer.parseInt(value))); fieldElement.setValue(field); } else { fieldElement.setNil(true); } row.getFieldElementList().add(fieldElement); } } } else if (fieldMetaData instanceof LogFieldMetaData) { final LogFieldMetaData logFieldMetaData = (LogFieldMetaData) fieldMetaData; final int extent = logFieldMetaData.getExtent(); if (extent < 1) { final JAXBElement<LogField> fieldElement = new JAXBElement<LogField>( new QName(NS, "Log"), LogField.class, null); final LogField field = OBJECT_FACTORY.createLogField(); field.setId(logFieldMetaData.getId()); field.setName(logFieldMetaData.getName()); final String value = proParam.getString(field.getId()); if (value != null) { field.setContent( DatatypeConverter.printBoolean(Boolean.valueOf(value))); fieldElement.setValue(field); } else { fieldElement.setNil(true); } row.getFieldElementList().add(fieldElement); } else { for (int i = 1; i <= extent; i++) { final JAXBElement<LogField> fieldElement = new JAXBElement<LogField>( new QName(NS, "Log"), LogField.class, null); final LogField field = OBJECT_FACTORY.createLogField(); field.setId(logFieldMetaData.getId()); field.setName(logFieldMetaData.getName()); final String value = proParam.getString(field.getId(), i); if (value != null) { field.setContent( DatatypeConverter.printBoolean(Boolean.valueOf(value))); fieldElement.setValue(field); } else { fieldElement.setNil(true); } row.getFieldElementList().add(fieldElement); } } } } resParam.getRowList().add(row); } resParamElement.setValue(resParam); } else { resParamElement.setNil(true); } res.getParamElementList().add(resParamElement); } } } final Document doc = builder.newDocument(); marshaller.marshal(res, doc); exchange.getOut().setBody(doc); } catch (final RunTime4GLErrorException e) { LOG.error(e.getProcReturnString(), e); throw new OpenEdgeException(e.getProcReturnString(), e); } }
From source file:com.netflix.governator.lifecycle.LifecycleManager.java
private Date parseDate(String configurationName, String value, Configuration configuration) { DateFormat formatter = DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault()); formatter.setLenient(false);/*from www . j a va2 s . co m*/ try { return formatter.parse(value); } catch (ParseException e) { // ignore as the fallback is the DatattypeConverter. } try { return DatatypeConverter.parseDateTime(value).getTime(); } catch (IllegalArgumentException e) { ignoreTypeMismtachIfConfigured(configuration, configurationName, e); } return null; }
From source file:com.microsoft.windowsazure.management.sql.DatabaseOperationOperationsImpl.java
/** * Returns information about a specific operation by using the operation * Guid.//from w w w . ja va2 s. c o m * * @param serverName Required. The name of the Azure SQL Database Server * where the database is hosted. * @param operationGuid Required. The Guid of the Azure SQL Database * operation to be obtained. * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations. * @throws ServiceException Thrown if an unexpected response is found. * @throws ParserConfigurationException Thrown if there was a serious * configuration error with the document parser. * @throws SAXException Thrown if there was an error parsing the XML * response. * @return Represents the database operation for a given operation Guid. */ @Override public DatabaseOperationGetResponse get(String serverName, String operationGuid) throws IOException, ServiceException, ParserConfigurationException, SAXException { // Validate if (serverName == null) { throw new NullPointerException("serverName"); } if (operationGuid == null) { throw new NullPointerException("operationGuid"); } // Tracing boolean shouldTrace = CloudTracing.getIsEnabled(); String invocationId = null; if (shouldTrace) { invocationId = Long.toString(CloudTracing.getNextInvocationId()); HashMap<String, Object> tracingParameters = new HashMap<String, Object>(); tracingParameters.put("serverName", serverName); tracingParameters.put("operationGuid", operationGuid); CloudTracing.enter(invocationId, this, "getAsync", tracingParameters); } // Construct URL String url = ""; if (this.getClient().getCredentials().getSubscriptionId() != null) { url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8"); } url = url + "/services/sqlservers/servers/"; url = url + URLEncoder.encode(serverName, "UTF-8"); url = url + "/databaseoperations/"; url = url + URLEncoder.encode(operationGuid, "UTF-8"); String baseUrl = this.getClient().getBaseUri().toString(); // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl.charAt(baseUrl.length() - 1) == '/') { baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); } if (url.charAt(0) == '/') { url = url.substring(1); } url = baseUrl + "/" + url; url = url.replace(" ", "%20"); // Create HTTP transport objects HttpGet httpRequest = new HttpGet(url); // Set Headers httpRequest.setHeader("x-ms-version", "2012-03-01"); // Send Request HttpResponse httpResponse = null; try { if (shouldTrace) { CloudTracing.sendRequest(invocationId, httpRequest); } httpResponse = this.getClient().getHttpClient().execute(httpRequest); if (shouldTrace) { CloudTracing.receiveResponse(invocationId, httpResponse); } int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result DatabaseOperationGetResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_OK) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new DatabaseOperationGetResponse(); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); Element serviceResourceElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "ServiceResource"); if (serviceResourceElement != null) { DatabaseOperation serviceResourceInstance = new DatabaseOperation(); result.setDatabaseOperation(serviceResourceInstance); Element idElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "Id"); if (idElement != null) { String idInstance; idInstance = idElement.getTextContent(); serviceResourceInstance.setId(idInstance); } Element stateIdElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "StateId"); if (stateIdElement != null) { int stateIdInstance; stateIdInstance = DatatypeConverter.parseInt(stateIdElement.getTextContent()); serviceResourceInstance.setStateId(stateIdInstance); } Element sessionActivityIdElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "SessionActivityId"); if (sessionActivityIdElement != null) { String sessionActivityIdInstance; sessionActivityIdInstance = sessionActivityIdElement.getTextContent(); serviceResourceInstance.setSessionActivityId(sessionActivityIdInstance); } Element databaseNameElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "DatabaseName"); if (databaseNameElement != null) { String databaseNameInstance; databaseNameInstance = databaseNameElement.getTextContent(); serviceResourceInstance.setDatabaseName(databaseNameInstance); } Element percentCompleteElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "PercentComplete"); if (percentCompleteElement != null) { int percentCompleteInstance; percentCompleteInstance = DatatypeConverter .parseInt(percentCompleteElement.getTextContent()); serviceResourceInstance.setPercentComplete(percentCompleteInstance); } Element errorCodeElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "ErrorCode"); if (errorCodeElement != null) { int errorCodeInstance; errorCodeInstance = DatatypeConverter.parseInt(errorCodeElement.getTextContent()); serviceResourceInstance.setErrorCode(errorCodeInstance); } Element errorElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "Error"); if (errorElement != null) { String errorInstance; errorInstance = errorElement.getTextContent(); serviceResourceInstance.setError(errorInstance); } Element errorSeverityElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "ErrorSeverity"); if (errorSeverityElement != null) { int errorSeverityInstance; errorSeverityInstance = DatatypeConverter.parseInt(errorSeverityElement.getTextContent()); serviceResourceInstance.setErrorSeverity(errorSeverityInstance); } Element errorStateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "ErrorState"); if (errorStateElement != null) { int errorStateInstance; errorStateInstance = DatatypeConverter.parseInt(errorStateElement.getTextContent()); serviceResourceInstance.setErrorState(errorStateInstance); } Element startTimeElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "StartTime"); if (startTimeElement != null) { Calendar startTimeInstance; startTimeInstance = DatatypeConverter.parseDateTime(startTimeElement.getTextContent()); serviceResourceInstance.setStartTime(startTimeInstance); } Element lastModifyTimeElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "LastModifyTime"); if (lastModifyTimeElement != null) { Calendar lastModifyTimeInstance; lastModifyTimeInstance = DatatypeConverter .parseDateTime(lastModifyTimeElement.getTextContent()); serviceResourceInstance.setLastModifyTime(lastModifyTimeInstance); } Element nameElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "Name"); if (nameElement != null) { String nameInstance; nameInstance = nameElement.getTextContent(); serviceResourceInstance.setName(nameInstance); } Element typeElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "Type"); if (typeElement != null) { String typeInstance; typeInstance = typeElement.getTextContent(); serviceResourceInstance.setType(typeInstance); } Element stateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "State"); if (stateElement != null) { String stateInstance; stateInstance = stateElement.getTextContent(); serviceResourceInstance.setState(stateInstance); } } } result.setStatusCode(statusCode); if (httpResponse.getHeaders("x-ms-request-id").length > 0) { result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); } if (shouldTrace) { CloudTracing.exit(invocationId, result); } return result; } finally { if (httpResponse != null && httpResponse.getEntity() != null) { httpResponse.getEntity().getContent().close(); } } }
From source file:eu.riscoss.rdc.RDCGithub.java
private void parseJsonIssues(JSONAware jv, String entity, Map<String, RiskData> values, int created_at_years) { if (jv instanceof JSONArray) { JSONArray ja = (JSONArray) jv;/*from ww w . j a v a 2s. c o m*/ int closedissues = 0; int openissues = 0; int pullrequests = 0; ArrayList<Double> diffList = new ArrayList<Double>();//should be Long, but only Double is supported in the REST data ArrayList<Double> numCommentsList = new ArrayList<Double>();//should be integer for (Object o : ja) { if (o instanceof JSONObject) { JSONObject jo = (JSONObject) o; //System.out.println(" issue state: "+(((JSONObject)jo).get("state"))); if (jo.get("pull_request") != null) { pullrequests++; continue; } String s = ((JSONObject) jo).get("state").toString(); if (s.equals("open")) openissues++; else if (s.equals("closed")) closedissues++; Calendar closedDate = null; Calendar openedDate = null; String openedAt = (String) ((JSONObject) jo).get("created_at"); if (openedAt != null) { openedDate = DatatypeConverter.parseDateTime(openedAt); //System.out.println("open: "+openedDate.getTime()); String closedAt = (String) ((JSONObject) jo).get("closed_at"); if (closedAt != null && !closedAt.equals("")) { closedDate = DatatypeConverter.parseDateTime(closedAt); //System.out.println("parse: opening date: "+openedDate.get(Calendar.YEAR)+" "+openedDate.get(Calendar.MONTH)); Calendar calendar = Calendar.getInstance();//actual calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR) - created_at_years); if (openedDate.compareTo(calendar) < 0) { break; } long diff = closedDate.getTimeInMillis() - openedDate.getTimeInMillis(); double diffd = diff / 1000 / 60 / 60 / 24; //difference in days. diffList.add(diffd); } } numCommentsList.add(new Double((Long) ((JSONObject) jo).get("comments"))); } } double sum = ja.size(); //assert(sum == openissues + closedissues); //??sure?? System.out.println(openissues + " openissues + " + closedissues + " closedissues = " + sum); RiskData rd = null; if (sum > 0) { rd = new RiskData(GITHUB_PREFIX + "issue-closedratio", entity, new Date(), RiskDataType.NUMBER, closedissues / sum); values.put(rd.getId(), rd); rd = new RiskData(GITHUB_PREFIX + "issue-openratio", entity, new Date(), RiskDataType.NUMBER, openissues / sum); values.put(rd.getId(), rd); } Distribution d = new Distribution(diffList); //days for closing issues rd = new RiskData(GITHUB_PREFIX + "issue-open-close-diff", entity, new Date(), RiskDataType.DISTRIBUTION, new Distribution(diffList)); values.put(rd.getId(), rd); //average days for closing an issue rd = new RiskData(GITHUB_PREFIX + "issue-open-close-diff-avg", entity, new Date(), RiskDataType.NUMBER, d.getAverage()); values.put(rd.getId(), rd); rd = new RiskData(GITHUB_PREFIX + "pull-requests", entity, new Date(), RiskDataType.NUMBER, pullrequests); values.put(rd.getId(), rd); d = new Distribution(numCommentsList); rd = new RiskData(GITHUB_PREFIX + "issue-comments", entity, new Date(), RiskDataType.DISTRIBUTION, d); values.put(rd.getId(), rd); rd = new RiskData(GITHUB_PREFIX + "issue-comments-avg", entity, new Date(), RiskDataType.NUMBER, d.getAverage()); values.put(rd.getId(), rd); } }