List of usage examples for org.w3c.dom Element getTextContent
public String getTextContent() throws DOMException;
From source file:com.microsoft.windowsazure.management.sql.RestoreDatabaseOperationsImpl.java
/** * Issues a restore request for an Azure SQL Database. * * @param sourceServerName Required. The name of the Azure SQL Database * Server where the source database is, or was, hosted. * @param parameters Required. Additional parameters for the Create Restore * Database Operation request.//from w ww.jav a 2 s . c o m * @throws ParserConfigurationException Thrown if there was an error * configuring the parser for the response body. * @throws SAXException Thrown if there was an error parsing the response * body. * @throws TransformerException Thrown if there was an error creating the * DOM transformer. * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations. * @throws ServiceException Thrown if an unexpected response is found. * @return Contains the response to the Create Restore Database Operation * request. */ @Override public RestoreDatabaseOperationCreateResponse create(String sourceServerName, RestoreDatabaseOperationCreateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { // Validate if (sourceServerName == null) { throw new NullPointerException("sourceServerName"); } if (parameters == null) { throw new NullPointerException("parameters"); } if (parameters.getSourceDatabaseName() == null) { throw new NullPointerException("parameters.SourceDatabaseName"); } if (parameters.getTargetDatabaseName() == null) { throw new NullPointerException("parameters.TargetDatabaseName"); } // 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("sourceServerName", sourceServerName); tracingParameters.put("parameters", parameters); CloudTracing.enter(invocationId, this, "createAsync", tracingParameters); } // Construct URL String url = ""; url = url + "/"; if (this.getClient().getCredentials().getSubscriptionId() != null) { url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8"); } url = url + "/services/sqlservers/servers/"; url = url + URLEncoder.encode(sourceServerName, "UTF-8"); url = url + "/restoredatabaseoperations"; String baseUrl = this.getClient().getBaseUri().toString(); // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl.charAt(baseUrl.length() - 1) == '/') { baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); } if (url.charAt(0) == '/') { url = url.substring(1); } url = baseUrl + "/" + url; url = url.replace(" ", "%20"); // Create HTTP transport objects HttpPost httpRequest = new HttpPost(url); // Set Headers httpRequest.setHeader("Content-Type", "application/xml"); httpRequest.setHeader("x-ms-version", "2012-03-01"); // Serialize Request String requestContent = null; DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document requestDoc = documentBuilder.newDocument(); Element serviceResourceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ServiceResource"); requestDoc.appendChild(serviceResourceElement); Element sourceDatabaseNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "SourceDatabaseName"); sourceDatabaseNameElement.appendChild(requestDoc.createTextNode(parameters.getSourceDatabaseName())); serviceResourceElement.appendChild(sourceDatabaseNameElement); if (parameters.getSourceDatabaseDeletionDate() != null) { Element sourceDatabaseDeletionDateElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "SourceDatabaseDeletionDate"); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'"); simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); sourceDatabaseDeletionDateElement.appendChild(requestDoc .createTextNode(simpleDateFormat.format(parameters.getSourceDatabaseDeletionDate().getTime()))); serviceResourceElement.appendChild(sourceDatabaseDeletionDateElement); } if (parameters.getTargetServerName() != null) { Element targetServerNameElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "TargetServerName"); targetServerNameElement.appendChild(requestDoc.createTextNode(parameters.getTargetServerName())); serviceResourceElement.appendChild(targetServerNameElement); } Element targetDatabaseNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "TargetDatabaseName"); targetDatabaseNameElement.appendChild(requestDoc.createTextNode(parameters.getTargetDatabaseName())); serviceResourceElement.appendChild(targetDatabaseNameElement); if (parameters.getPointInTime() != null) { Element targetUtcPointInTimeElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "TargetUtcPointInTime"); SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'"); simpleDateFormat2.setTimeZone(TimeZone.getTimeZone("UTC")); targetUtcPointInTimeElement.appendChild( requestDoc.createTextNode(simpleDateFormat2.format(parameters.getPointInTime().getTime()))); serviceResourceElement.appendChild(targetUtcPointInTimeElement); } DOMSource domSource = new DOMSource(requestDoc); StringWriter stringWriter = new StringWriter(); StreamResult streamResult = new StreamResult(stringWriter); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.transform(domSource, streamResult); requestContent = stringWriter.toString(); StringEntity entity = new StringEntity(requestContent); httpRequest.setEntity(entity); httpRequest.setHeader("Content-Type", "application/xml"); // Send Request HttpResponse httpResponse = null; try { if (shouldTrace) { CloudTracing.sendRequest(invocationId, httpRequest); } httpResponse = this.getClient().getHttpClient().execute(httpRequest); if (shouldTrace) { CloudTracing.receiveResponse(invocationId, httpResponse); } int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_CREATED) { ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result RestoreDatabaseOperationCreateResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_CREATED) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new RestoreDatabaseOperationCreateResponse(); DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance(); documentBuilderFactory2.setNamespaceAware(true); DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder(); Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent)); Element serviceResourceElement2 = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "ServiceResource"); if (serviceResourceElement2 != null) { RestoreDatabaseOperation serviceResourceInstance = new RestoreDatabaseOperation(); result.setOperation(serviceResourceInstance); Element requestIDElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "RequestID"); if (requestIDElement != null) { String requestIDInstance; requestIDInstance = requestIDElement.getTextContent(); serviceResourceInstance.setId(requestIDInstance); } Element sourceDatabaseNameElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "SourceDatabaseName"); if (sourceDatabaseNameElement2 != null) { String sourceDatabaseNameInstance; sourceDatabaseNameInstance = sourceDatabaseNameElement2.getTextContent(); serviceResourceInstance.setSourceDatabaseName(sourceDatabaseNameInstance); } Element sourceDatabaseDeletionDateElement2 = XmlUtility.getElementByTagNameNS( serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "SourceDatabaseDeletionDate"); if (sourceDatabaseDeletionDateElement2 != null && sourceDatabaseDeletionDateElement2.getTextContent() != null && !sourceDatabaseDeletionDateElement2.getTextContent().isEmpty()) { Calendar sourceDatabaseDeletionDateInstance; sourceDatabaseDeletionDateInstance = DatatypeConverter .parseDateTime(sourceDatabaseDeletionDateElement2.getTextContent()); serviceResourceInstance.setSourceDatabaseDeletionDate(sourceDatabaseDeletionDateInstance); } Element targetServerNameElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "TargetServerName"); if (targetServerNameElement2 != null) { String targetServerNameInstance; targetServerNameInstance = targetServerNameElement2.getTextContent(); serviceResourceInstance.setTargetServerName(targetServerNameInstance); } Element targetDatabaseNameElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "TargetDatabaseName"); if (targetDatabaseNameElement2 != null) { String targetDatabaseNameInstance; targetDatabaseNameInstance = targetDatabaseNameElement2.getTextContent(); serviceResourceInstance.setTargetDatabaseName(targetDatabaseNameInstance); } Element targetUtcPointInTimeElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "TargetUtcPointInTime"); if (targetUtcPointInTimeElement2 != null) { Calendar targetUtcPointInTimeInstance; targetUtcPointInTimeInstance = DatatypeConverter .parseDateTime(targetUtcPointInTimeElement2.getTextContent()); serviceResourceInstance.setPointInTime(targetUtcPointInTimeInstance); } } } 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:it.skymedia.idolTunnel.IdolOEMConnection.java
/** * Method return List<Map> when every map contains hit fields * //from w ww . j ava2 s .c o m * @return ArrayList<Hit> list of Hit, each containing a Map (of dreFileds) * */ @WebMethod(operationName = "getQueryHitsMap") public ArrayList<Hit> getQueryHitsMap(String xml) { ArrayList<Hit> result = new ArrayList<Hit>(); Document document = getDocumentFrom(xml); NodeList temp = null; temp = document.getElementsByTagName("response"); String response = (temp.getLength() > 0) ? document.getElementsByTagName("response").item(0).getTextContent() : "FAILURE"; temp = document.getElementsByTagName("autn:numhits"); String numHits = (temp.getLength() > 0) ? document.getElementsByTagName("autn:numhits").item(0).getTextContent() : "0"; temp = document.getElementsByTagName("autn:totalhits"); String totalHits = (temp.getLength() > 0) ? document.getElementsByTagName("autn:totalhits").item(0).getTextContent() : "0"; NodeList hits = document.getElementsByTagName("autn:hit"); for (int i = 0; i < hits.getLength(); i++) { HashMap<String, String> map = new HashMap<String, String>(); Node nodo = hits.item(i); NodeList hitChilds = nodo.getChildNodes(); for (int j = 0; j < hitChilds.getLength(); j++) { Node n = hitChilds.item(j); if (n.getNodeType() == Node.ELEMENT_NODE) { Element e2 = (Element) n; if (!e2.getNodeName().equals("autn:content")) { String value = ""; if (map.containsKey(e2.getNodeName())) { value = map.get(e2.getNodeName()) + "," + e2.getTextContent(); map.put(e2.getNodeName(), value); } else { map.put(e2.getNodeName(), e2.getTextContent()); } } else { NodeList content = e2.getElementsByTagName("DOCUMENT").item(0).getChildNodes(); for (int z = 0; z < content.getLength(); z++) { Node d = content.item(z); if (d.getNodeType() == Node.ELEMENT_NODE) { Element el = (Element) d; String value = ""; if (map.containsKey(el.getNodeName())) { value = map.get(el.getNodeName()) + "," + el.getTextContent(); map.put(el.getNodeName(), value); } else { map.put(el.getNodeName(), el.getTextContent()); } } } } } } Hit hit = new Hit(map); hit.getDreFields().put("response", response); hit.getDreFields().put("numhits", numHits); hit.getDreFields().put("totalhits", totalHits); result.add(hit); } return result; }
From source file:com.alfaariss.oa.util.saml2.metadata.entitydescriptor.EntityDescriptorBuilder.java
/** * Build the optional <code><ContactPerson></code> elements. * /*w w w . j a v a 2s .c o m*/ * Optional sequence of elements identifying various kinds of contact * personnel. This method can be called multiple times to add zero or more * contact persons. * @throws OAException If configuration is invalid */ public void buildContactPersons() throws OAException { try { Element eContactPersons = _configuration.getSection(_eMetadata, "ContactPersons"); if (eContactPersons != null) { Element eContactPerson = _configuration.getSection(eContactPersons, "ContactPerson"); while (eContactPerson != null) { SAMLObjectBuilder builder = (SAMLObjectBuilder) _builderFactory .getBuilder(ContactPerson.DEFAULT_ELEMENT_NAME); ContactPerson contactPerson = (ContactPerson) builder.buildObject(); String sContactType = _configuration.getParam(eContactPerson, "contactType"); if (sContactType == null) { _logger.error("No required contactType configured for contactPerson"); throw new OAException(SystemErrors.ERROR_CONFIG_READ); } ContactPersonTypeEnumeration contactPersonType = ContactPersonTypeEnumeration.OTHER; if (sContactType.equalsIgnoreCase(ContactPersonTypeEnumeration.OTHER.toString())) contactPersonType = ContactPersonTypeEnumeration.OTHER; else if (sContactType.equalsIgnoreCase(ContactPersonTypeEnumeration.ADMINISTRATIVE.toString())) contactPersonType = ContactPersonTypeEnumeration.ADMINISTRATIVE; else if (sContactType.equalsIgnoreCase(ContactPersonTypeEnumeration.BILLING.toString())) contactPersonType = ContactPersonTypeEnumeration.BILLING; else if (sContactType.equalsIgnoreCase(ContactPersonTypeEnumeration.SUPPORT.toString())) contactPersonType = ContactPersonTypeEnumeration.SUPPORT; else if (sContactType.equalsIgnoreCase(ContactPersonTypeEnumeration.TECHNICAL.toString())) contactPersonType = ContactPersonTypeEnumeration.TECHNICAL; else { _logger.error("Unsupported contactType configured for contactPerson: " + sContactType); throw new OAException(SystemErrors.ERROR_CONFIG_READ); } contactPerson.setType(contactPersonType); String sCompany = _configuration.getParam(eContactPerson, "Company"); if (sCompany != null) { SAMLObjectBuilder companyBuilder = (SAMLObjectBuilder) _builderFactory .getBuilder(Company.DEFAULT_ELEMENT_NAME); Company company = (Company) companyBuilder.buildObject(); company.setName(sCompany); contactPerson.setCompany(company); } String sGivenName = _configuration.getParam(eContactPerson, "GivenName"); if (sGivenName != null) { SAMLObjectBuilder givenNameBuilder = (SAMLObjectBuilder) _builderFactory .getBuilder(GivenName.DEFAULT_ELEMENT_NAME); GivenName givenName = (GivenName) givenNameBuilder.buildObject(); givenName.setName(sGivenName); contactPerson.setGivenName(givenName); } String sSurName = _configuration.getParam(eContactPerson, "SurName"); if (sSurName != null) { SAMLObjectBuilder surNameBuilder = (SAMLObjectBuilder) _builderFactory .getBuilder(SurName.DEFAULT_ELEMENT_NAME); SurName surName = (SurName) surNameBuilder.buildObject(); surName.setName(sSurName); contactPerson.setSurName(surName); } Element eEmailAddresses = _configuration.getSection(eContactPerson, "EmailAddresses"); if (eEmailAddresses != null) { Element eEmailAddress = _configuration.getSection(eEmailAddresses, "EmailAddress"); while (eEmailAddress != null) { //DD using XML object directory for reading config instead of using the configmanager, because the configmanager doesn't support getNextParam() functionality String sEmailAddress = eEmailAddress.getTextContent(); if (sEmailAddress != null) { SAMLObjectBuilder emailAddressBuilder = (SAMLObjectBuilder) _builderFactory .getBuilder(EmailAddress.DEFAULT_ELEMENT_NAME); EmailAddress emailAddress = (EmailAddress) emailAddressBuilder.buildObject(); emailAddress.setAddress(sEmailAddress.trim()); contactPerson.getEmailAddresses().add(emailAddress); } eEmailAddress = _configuration.getNextSection(eEmailAddress); } } Element eTelephoneNumbers = _configuration.getSection(eContactPerson, "TelephoneNumbers"); if (eTelephoneNumbers != null) { Element eTelephoneNumber = _configuration.getSection(eTelephoneNumbers, "TelephoneNumber"); while (eTelephoneNumber != null) { //DD using XML object directory for reading config instead of using the configmanager, because the configmanager doesn't support getNextParam() functionality String sTelephoneNumber = eTelephoneNumber.getTextContent(); if (sTelephoneNumber != null) { SAMLObjectBuilder telephoneNumberBuilder = (SAMLObjectBuilder) _builderFactory .getBuilder(TelephoneNumber.DEFAULT_ELEMENT_NAME); TelephoneNumber telephoneNumber = (TelephoneNumber) telephoneNumberBuilder .buildObject(); telephoneNumber.setNumber(sTelephoneNumber.trim()); contactPerson.getTelephoneNumbers().add(telephoneNumber); } eTelephoneNumber = _configuration.getNextSection(eTelephoneNumber); } } _result.getContactPersons().add(contactPerson); eContactPerson = _configuration.getNextSection(eContactPerson); } } } catch (ConfigurationException e) { _logger.error("Error while reading ContactPersons configuration", e); throw new OAException(SystemErrors.ERROR_CONFIG_READ); } }
From source file:com.amalto.core.save.context.UpdateReportDocument.java
public void setOperationType(String operationType) { Element item = null; NodeList operationTypeNodeList = updateReportDocument.getElementsByTagName("OperationType"); //$NON-NLS-1$ for (int i = 0; i < operationTypeNodeList.getLength(); i++) { Node operationTypeNode = operationTypeNodeList.item(i); if (Node.ELEMENT_NODE == operationTypeNode.getNodeType()) { item = (Element) operationTypeNode; break; }//from www . j a v a 2 s . co m } if (item == null) { item = updateReportDocument.createElement("OperationType"); //$NON-NLS-1$ } if (operationType.equalsIgnoreCase(UpdateReportPOJO.OPERATION_TYPE_CREATE)) { if (!item.getTextContent().equalsIgnoreCase(UpdateReportPOJO.OPERATION_TYPE_CREATE)) { item.appendChild(updateReportDocument.createTextNode(UpdateReportPOJO.OPERATION_TYPE_CREATE)); updateReportDocument.getDocumentElement().appendChild(item); } } else if (operationType.equalsIgnoreCase(UpdateReportPOJO.OPERATION_TYPE_UPDATE)) { if (!isCreated) { item.appendChild(updateReportDocument.createTextNode(UpdateReportPOJO.OPERATION_TYPE_UPDATE)); updateReportDocument.getDocumentElement().appendChild(item); } } }
From source file:com.microsoft.windowsazure.management.ManagementClientImpl.java
/** * The Get Operation Status operation returns the status of the specified * operation. After calling an asynchronous operation, you can call Get * Operation Status to determine whether the operation has succeeded, * failed, or is still in progress. (see * http://msdn.microsoft.com/en-us/library/windowsazure/ee460783.aspx for * more information)/*from w ww .j a v a 2 s . c om*/ * * @param requestId Required. The request ID for the request you wish to * track. The request ID is returned in the x-ms-request-id response header * for every request. * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations. * @throws ServiceException Thrown if an unexpected response is found. * @throws ParserConfigurationException Thrown if there was a serious * configuration error with the document parser. * @throws SAXException Thrown if there was an error parsing the XML * response. * @return The response body contains the status of the specified * asynchronous operation, indicating whether it has succeeded, is * inprogress, or has failed. Note that this status is distinct from the * HTTP status code returned for the Get Operation Status operation itself. * If the asynchronous operation succeeded, the response body includes the * HTTP status code for the successful request. If the asynchronous * operation failed, the response body includes the HTTP status code for * the failed request, and also includes error information regarding the * failure. */ @Override public OperationStatusResponse getOperationStatus(String requestId) throws IOException, ServiceException, ParserConfigurationException, SAXException { // Validate if (requestId == null) { throw new NullPointerException("requestId"); } // Tracing boolean shouldTrace = CloudTracing.getIsEnabled(); String invocationId = null; if (shouldTrace) { invocationId = Long.toString(CloudTracing.getNextInvocationId()); HashMap<String, Object> tracingParameters = new HashMap<String, Object>(); tracingParameters.put("requestId", requestId); CloudTracing.enter(invocationId, this, "getOperationStatusAsync", tracingParameters); } // Construct URL String url = ""; url = url + "/"; if (this.getCredentials().getSubscriptionId() != null) { url = url + URLEncoder.encode(this.getCredentials().getSubscriptionId(), "UTF-8"); } url = url + "/operations/"; url = url + URLEncoder.encode(requestId, "UTF-8"); String baseUrl = this.getBaseUri().toString(); // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl.charAt(baseUrl.length() - 1) == '/') { baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); } if (url.charAt(0) == '/') { url = url.substring(1); } url = baseUrl + "/" + url; url = url.replace(" ", "%20"); // Create HTTP transport objects HttpGet httpRequest = new HttpGet(url); // Set Headers httpRequest.setHeader("x-ms-version", "2014-10-01"); // Send Request HttpResponse httpResponse = null; try { if (shouldTrace) { CloudTracing.sendRequest(invocationId, httpRequest); } httpResponse = this.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 OperationStatusResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_OK) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new OperationStatusResponse(); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); Element operationElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "Operation"); if (operationElement != null) { Element idElement = XmlUtility.getElementByTagNameNS(operationElement, "http://schemas.microsoft.com/windowsazure", "ID"); if (idElement != null) { String idInstance; idInstance = idElement.getTextContent(); result.setId(idInstance); } Element statusElement = XmlUtility.getElementByTagNameNS(operationElement, "http://schemas.microsoft.com/windowsazure", "Status"); if (statusElement != null && statusElement.getTextContent() != null && !statusElement.getTextContent().isEmpty()) { OperationStatus statusInstance; statusInstance = OperationStatus.valueOf(statusElement.getTextContent()); result.setStatus(statusInstance); } Element httpStatusCodeElement = XmlUtility.getElementByTagNameNS(operationElement, "http://schemas.microsoft.com/windowsazure", "HttpStatusCode"); if (httpStatusCodeElement != null && httpStatusCodeElement.getTextContent() != null && !httpStatusCodeElement.getTextContent().isEmpty()) { Integer httpStatusCodeInstance; httpStatusCodeInstance = Integer.valueOf(httpStatusCodeElement.getTextContent()); result.setHttpStatusCode(httpStatusCodeInstance); } Element errorElement = XmlUtility.getElementByTagNameNS(operationElement, "http://schemas.microsoft.com/windowsazure", "Error"); if (errorElement != null) { OperationStatusResponse.ErrorDetails errorInstance = new OperationStatusResponse.ErrorDetails(); result.setError(errorInstance); Element codeElement = XmlUtility.getElementByTagNameNS(errorElement, "http://schemas.microsoft.com/windowsazure", "Code"); if (codeElement != null) { String codeInstance; codeInstance = codeElement.getTextContent(); errorInstance.setCode(codeInstance); } Element messageElement = XmlUtility.getElementByTagNameNS(errorElement, "http://schemas.microsoft.com/windowsazure", "Message"); if (messageElement != null) { String messageInstance; messageInstance = messageElement.getTextContent(); errorInstance.setMessage(messageInstance); } } } } result.setStatusCode(statusCode); if (httpResponse.getHeaders("x-ms-request-id").length > 0) { result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); } if (shouldTrace) { CloudTracing.exit(invocationId, result); } return result; } finally { if (httpResponse != null && httpResponse.getEntity() != null) { httpResponse.getEntity().getContent().close(); } } }
From source file:com.uisteps.utils.api.zapi.Zapi.java
private void exportResultToZephyr(File file, File pom, String charset, RestApi api) throws IOException, JSONException, ParserConfigurationException, SAXException, RestApiException { Document doc = getXML(pom);//from w ww . j av a 2 s . c om Element project = (Element) doc.getElementsByTagName("project").item(0); Element properties = (Element) project.getElementsByTagName("properties").item(0); String cycleId = properties.getElementsByTagName("cycleId").item(0).getTextContent(); String projectKey = properties.getElementsByTagName("projectKey").item(0).getTextContent(); Result result = new Result(file, charset, projectKey); HashSet<String> issues = new HashSet(); Map<String, Result.Test> testMap = result.getTests(); Collection<Result.Test> tests = testMap.values(); for (Result.Test test : tests) { if (!test.getStatus().equals("IGNORED")) { issues.add(test.getIssue()); } } Element createEcecutions = (Element) properties.getElementsByTagName("createExecutions").item(0); JSONObject cycleJSON = api.getRequest("/rest/zapi/latest/cycle/" + cycleId).get().toJSONObject(); String versionId = cycleJSON.getString("versionId"); String projectId = cycleJSON.getString("projectId"); if (createEcecutions != null && createEcecutions.getTextContent().equals("true")) { JSONObject json = new JSONObject(); json.put("versionId", versionId).put("cycleId", cycleId).put("projectId", projectId).put("method", "1"); for (String issue : issues) { json.append("issues", issue); } api.getRequest("/rest/zapi/latest/execution/addTestsToCycle/").post(json); } JSONArray executions = api.getRequest("/rest/zapi/latest/execution?cycleId=" + cycleId).get().toJSONObject() .getJSONArray("executions"); Map<String, JSONObject> executionsMap = new HashMap(); for (int i = 0; i < executions.length(); i++) { JSONObject execution = executions.getJSONObject(i); executionsMap.put(execution.getString("issueKey"), execution); } for (String issueKey : issues) { Result.Test test = testMap.get(issueKey); JSONObject execution = executionsMap.get(issueKey); if (execution != null) { api.getRequest("/rest/zapi/latest/execution/" + executionsMap.get(issueKey).getString("id") + "/quickExecute").post("{'status': '" + test.getZapiStatus() + "'}"); } } cycleJSON.put("endDate", getCurrentDate()); cycleJSON.remove("createdBy"); cycleJSON.remove("modifiedBy"); api.getRequest("/rest/zapi/latest/cycle").put(cycleJSON); }
From source file:com.microsoft.windowsazure.management.servicebus.RelayOperationsImpl.java
/** * Gets the set of connection strings for a relay. * * @param namespaceName Required. The namespace name. * @param relayName Required. The relay name. * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations.//from ww w . jav a2 s .co m * @throws ServiceException Thrown if an unexpected response is found. * @throws ParserConfigurationException Thrown if there was a serious * configuration error with the document parser. * @throws SAXException Thrown if there was an error parsing the XML * response. * @return The set of connection details for a service bus entity. */ @Override public ServiceBusConnectionDetailsResponse getConnectionDetails(String namespaceName, String relayName) throws IOException, ServiceException, ParserConfigurationException, SAXException { // Validate if (namespaceName == null) { throw new NullPointerException("namespaceName"); } if (relayName == null) { throw new NullPointerException("relayName"); } // Tracing boolean shouldTrace = CloudTracing.getIsEnabled(); String invocationId = null; if (shouldTrace) { invocationId = Long.toString(CloudTracing.getNextInvocationId()); HashMap<String, Object> tracingParameters = new HashMap<String, Object>(); tracingParameters.put("namespaceName", namespaceName); tracingParameters.put("relayName", relayName); CloudTracing.enter(invocationId, this, "getConnectionDetailsAsync", tracingParameters); } // Construct URL String url = ""; url = url + "/"; if (this.getClient().getCredentials().getSubscriptionId() != null) { url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8"); } url = url + "/services/servicebus/namespaces/"; url = url + URLEncoder.encode(namespaceName, "UTF-8"); url = url + "/Relays/"; url = url + URLEncoder.encode(relayName, "UTF-8"); url = url + "/ConnectionDetails"; String baseUrl = this.getClient().getBaseUri().toString(); // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl.charAt(baseUrl.length() - 1) == '/') { baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); } if (url.charAt(0) == '/') { url = url.substring(1); } url = baseUrl + "/" + url; url = url.replace(" ", "%20"); // Create HTTP transport objects HttpGet httpRequest = new HttpGet(url); // Set Headers httpRequest.setHeader("Content-Type", "application/xml; charset=utf-8"); httpRequest.setHeader("x-ms-version", "2013-08-01"); // Send Request HttpResponse httpResponse = null; try { if (shouldTrace) { CloudTracing.sendRequest(invocationId, httpRequest); } httpResponse = this.getClient().getHttpClient().execute(httpRequest); if (shouldTrace) { CloudTracing.receiveResponse(invocationId, httpResponse); } int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result ServiceBusConnectionDetailsResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_OK) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new ServiceBusConnectionDetailsResponse(); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); Element feedElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://www.w3.org/2005/Atom", "feed"); if (feedElement != null) { if (feedElement != null) { for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility .getElementsByTagNameNS(feedElement, "http://www.w3.org/2005/Atom", "entry") .size(); i1 = i1 + 1) { org.w3c.dom.Element entriesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility .getElementsByTagNameNS(feedElement, "http://www.w3.org/2005/Atom", "entry") .get(i1)); ServiceBusConnectionDetail entryInstance = new ServiceBusConnectionDetail(); result.getConnectionDetails().add(entryInstance); Element contentElement = XmlUtility.getElementByTagNameNS(entriesElement, "http://www.w3.org/2005/Atom", "content"); if (contentElement != null) { Element connectionDetailElement = XmlUtility.getElementByTagNameNS(contentElement, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "ConnectionDetail"); if (connectionDetailElement != null) { Element keyNameElement = XmlUtility.getElementByTagNameNS( connectionDetailElement, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "KeyName"); if (keyNameElement != null) { String keyNameInstance; keyNameInstance = keyNameElement.getTextContent(); entryInstance.setKeyName(keyNameInstance); } Element connectionStringElement = XmlUtility.getElementByTagNameNS( connectionDetailElement, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "ConnectionString"); if (connectionStringElement != null) { String connectionStringInstance; connectionStringInstance = connectionStringElement.getTextContent(); entryInstance.setConnectionString(connectionStringInstance); } Element authorizationTypeElement = XmlUtility.getElementByTagNameNS( connectionDetailElement, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "AuthorizationType"); if (authorizationTypeElement != null) { String authorizationTypeInstance; authorizationTypeInstance = authorizationTypeElement.getTextContent(); entryInstance.setAuthorizationType(authorizationTypeInstance); } Element rightsSequenceElement = XmlUtility.getElementByTagNameNS( connectionDetailElement, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "Rights"); if (rightsSequenceElement != null) { for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility .getElementsByTagNameNS(rightsSequenceElement, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "AccessRights") .size(); i2 = i2 + 1) { org.w3c.dom.Element rightsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility .getElementsByTagNameNS(rightsSequenceElement, "http://schemas.microsoft.com/netservices/2010/10/servicebus/connect", "AccessRights") .get(i2)); entryInstance.getRights() .add(AccessRight.valueOf(rightsElement.getTextContent())); } } } } } } } } result.setStatusCode(statusCode); if (httpResponse.getHeaders("x-ms-request-id").length > 0) { result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); } if (shouldTrace) { CloudTracing.exit(invocationId, result); } return result; } finally { if (httpResponse != null && httpResponse.getEntity() != null) { httpResponse.getEntity().getContent().close(); } } }
From source file:com.evolveum.midpoint.model.common.expression.functions.BasicExpressionFunctions.java
/** * Converts whatever it gets to a string. But it does it in a sensitive way. * E.g. it tries to detect collections and returns the first element (if there is only one). * Never returns null. Returns empty string instead. */// ww w. j av a 2 s. c o m public String stringify(Object whatever) { if (whatever == null) { return ""; } if (whatever instanceof String) { return (String) whatever; } if (whatever instanceof PolyString) { return ((PolyString) whatever).getOrig(); } if (whatever instanceof PolyStringType) { return ((PolyStringType) whatever).getOrig(); } if (whatever instanceof Collection) { Collection collection = (Collection) whatever; if (collection.isEmpty()) { return ""; } if (collection.size() > 1) { throw new IllegalArgumentException( "Cannot stringify collection because it has " + collection.size() + " values"); } whatever = collection.iterator().next(); } Class<? extends Object> whateverClass = whatever.getClass(); if (whateverClass.isArray()) { Object[] array = (Object[]) whatever; if (array.length == 0) { return ""; } if (array.length > 1) { throw new IllegalArgumentException( "Cannot stringify array because it has " + array.length + " values"); } whatever = array[0]; } if (whatever == null) { return ""; } if (whatever instanceof String) { return (String) whatever; } if (whatever instanceof PolyString) { return ((PolyString) whatever).getOrig(); } if (whatever instanceof PolyStringType) { return ((PolyStringType) whatever).getOrig(); } if (whatever instanceof Element) { Element element = (Element) whatever; Element origElement = DOMUtil.getChildElement(element, PolyString.F_ORIG); if (origElement != null) { // This is most likely a PolyStringType return origElement.getTextContent(); } else { return element.getTextContent(); } } if (whatever instanceof Node) { return ((Node) whatever).getTextContent(); } return whatever.toString(); }
From source file:es.itecban.deployment.executionmanager.gui.swf.service.CommonCreationManager.java
/** * //w w w . j a v a 2 s. c om * @param context * @throws Exception */ public List<InstalledUnit> getInstalledUnits(RequestContext context, DeploymentGroup[] deploymentGroupArray, DeploymentTargetType environment) throws Exception { logger.fine("Getting the already installed units"); // Get the selected unit String unitName = (String) context.getFlowScope().get(Constants.FLOW_SELECTED_UNIT_NAME); List<InstalledUnit> installedUnitList = new ArrayList<InstalledUnit>(); // Getting the xml object String envXML = this.getEnvironmentXML(environment); InputStream is = null; try { is = new ByteArrayInputStream(envXML.getBytes()); } catch (Exception e) { e.printStackTrace(); } // Get Xpath instance XPath xpath = XPathFactory.newInstance().newXPath(); String expression = ""; NodeList nodeSet = null; for (DeploymentGroup deploymentGroup : deploymentGroupArray) { List<DeploymentUnit> unitList = deploymentGroup.getUnits(); for (DeploymentUnit unit : unitList) { // Asking with XPath to get the version of an specific unit expression = "//unit[name[text()='" + unit.getName() + "']]/version"; try { is = new ByteArrayInputStream(envXML.getBytes()); nodeSet = (NodeList) xpath.evaluate(expression, new InputSource(is), XPathConstants.NODESET); } catch (Exception e) { e.printStackTrace(); } String[] versionArray = new String[nodeSet.getLength()]; for (int i = 0; i < nodeSet.getLength(); i++) { Element element = (Element) nodeSet.item(i); versionArray[i] = (String) element.getTextContent(); } // if is an updating or deletion, the unit must exist in any // container if (versionArray.length == 0 && unit.getName().equals(unitName) && ((context.getFlowScope().get(Constants.FLOW_OPERATION_FLOW)) .equals(Constants.FLOW_OPERATION_UPDATE) || (context.getFlowScope().get(Constants.FLOW_OPERATION_FLOW)) .equals(Constants.FLOW_OPERATION_DELETE))) { if ((context.getFlowScope().get(Constants.FLOW_OPERATION_FLOW)) .equals(Constants.FLOW_OPERATION_UPDATE)) { String[] args = { unit.getName() + "_" + unit.getVersion(), "'UPDATE OPERATION'" }; ErrorUtils.createMessageError(context, "running.error.noSuitableContaierForUpdate", args); } else { String[] args = { unit.getName() + "_" + unit.getVersion(), "'DELETE OPERATION'" }; ErrorUtils.createMessageError(context, "running.error.noSuitableContaierForUpdate", args); } throw new Exception(); } // We have an array with the name of the containers where the // unit is in any version. Search with exact version has each // container for (String version : versionArray) { expression = "//nodeContainer[runtimeUnits/unit/name[text()='" + unit.getName() + "'] and runtimeUnits/unit/version[text()='" + version + "']]/name"; try { is = new ByteArrayInputStream(envXML.getBytes()); nodeSet = (NodeList) xpath.evaluate(expression, new InputSource(is), XPathConstants.NODESET); } catch (Exception e) { e.printStackTrace(); } String[] containerArray = new String[nodeSet.getLength()]; for (int i = 0; i < nodeSet.getLength(); i++) { Element element = (Element) nodeSet.item(i); containerArray[i] = (String) element.getTextContent(); } if (containerArray.length > 0) { InstalledUnit installedUnit = new InstalledUnit(unit.getName(), version, containerArray); installedUnitList.add(installedUnit); } } } } return installedUnitList; }
From source file:com.microsoft.windowsazure.management.sql.RecoverableDatabaseOperationsImpl.java
/** * Returns information about a recoverable Azure SQL Database. * * @param serverName Required. The name of the Azure SQL Database Server on * which the database was hosted./*from w w w .j a v a 2 s . co m*/ * @param databaseName Required. The name of the recoverable 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 Recoverable Database request. */ @Override public RecoverableDatabaseGetResponse get(String serverName, String databaseName) throws IOException, ServiceException, ParserConfigurationException, SAXException { // Validate if (serverName == null) { throw new NullPointerException("serverName"); } if (databaseName == null) { throw new NullPointerException("databaseName"); } // Tracing boolean shouldTrace = CloudTracing.getIsEnabled(); String invocationId = null; if (shouldTrace) { invocationId = Long.toString(CloudTracing.getNextInvocationId()); HashMap<String, Object> tracingParameters = new HashMap<String, Object>(); tracingParameters.put("serverName", serverName); tracingParameters.put("databaseName", databaseName); CloudTracing.enter(invocationId, this, "getAsync", tracingParameters); } // Construct URL String url = ""; url = url + "/"; if (this.getClient().getCredentials().getSubscriptionId() != null) { url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8"); } url = url + "/services/sqlservers/servers/"; url = url + URLEncoder.encode(serverName, "UTF-8"); url = url + "/recoverabledatabases/"; url = url + URLEncoder.encode(databaseName, "UTF-8"); String baseUrl = this.getClient().getBaseUri().toString(); // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl.charAt(baseUrl.length() - 1) == '/') { baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); } if (url.charAt(0) == '/') { url = url.substring(1); } url = baseUrl + "/" + url; url = url.replace(" ", "%20"); // Create HTTP transport objects HttpGet httpRequest = new HttpGet(url); // Set Headers httpRequest.setHeader("x-ms-version", "2012-03-01"); // Send Request HttpResponse httpResponse = null; try { if (shouldTrace) { CloudTracing.sendRequest(invocationId, httpRequest); } httpResponse = this.getClient().getHttpClient().execute(httpRequest); if (shouldTrace) { CloudTracing.receiveResponse(invocationId, httpResponse); } int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result RecoverableDatabaseGetResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_OK) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new RecoverableDatabaseGetResponse(); 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) { RecoverableDatabase serviceResourceInstance = new RecoverableDatabase(); 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 lastAvailableBackupDateElement = XmlUtility.getElementByTagNameNS( serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "LastAvailableBackupDate"); if (lastAvailableBackupDateElement != null) { Calendar lastAvailableBackupDateInstance; lastAvailableBackupDateInstance = DatatypeConverter .parseDateTime(lastAvailableBackupDateElement.getTextContent()); serviceResourceInstance.setLastAvailableBackupDate(lastAvailableBackupDateInstance); } 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(); } } }