List of usage examples for org.w3c.dom Document appendChild
public Node appendChild(Node newChild) throws DOMException;
newChild
to the end of the list of children of this node. From source file:com.microsoft.windowsazure.management.sql.DacOperationsImpl.java
/** * Gets the status of the import or export operation in the specified server * with the corresponding request ID. The request ID is provided in the * responses of the import or export operation. * * @param serverName Required. The name of the server in which the import or * export operation is taking place./*from w w w .j ava 2 s .c o m*/ * @param parameters Required. The parameters needed to get the status of an * import or export operation. * @throws ParserConfigurationException Thrown if there was an error * configuring the parser for the response body. * @throws SAXException Thrown if there was an error parsing the response * body. * @throws TransformerException Thrown if there was an error creating the * DOM transformer. * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations. * @throws ServiceException Thrown if an unexpected response is found. * @throws URISyntaxException Thrown if there was an error parsing a URI in * the response. * @return Represents a list of import or export status values returned from * GetStatus. */ @Override public DacGetStatusResponse getStatusPost(String serverName, DacGetStatusParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException, URISyntaxException { // Validate if (serverName == null) { throw new NullPointerException("serverName"); } if (parameters == null) { throw new NullPointerException("parameters"); } if (parameters.getPassword() == null) { throw new NullPointerException("parameters.Password"); } if (parameters.getRequestId() == null) { throw new NullPointerException("parameters.RequestId"); } if (parameters.getServerName() == null) { throw new NullPointerException("parameters.ServerName"); } if (parameters.getUserName() == null) { throw new NullPointerException("parameters.UserName"); } // 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("parameters", parameters); CloudTracing.enter(invocationId, this, "getStatusPostAsync", tracingParameters); } // Construct URL String url = ""; url = url + "/"; if (this.getClient().getCredentials().getSubscriptionId() != null) { url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8"); } url = url + "/services/sqlservers/servers/"; url = url + URLEncoder.encode(serverName, "UTF-8"); url = url + "/DacOperations/Status"; 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 statusInputElement = requestDoc.createElementNS( "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "StatusInput"); requestDoc.appendChild(statusInputElement); Element passwordElement = requestDoc.createElementNS( "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "Password"); passwordElement.appendChild(requestDoc.createTextNode(parameters.getPassword())); statusInputElement.appendChild(passwordElement); Element requestIdElement = requestDoc.createElementNS( "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "RequestId"); requestIdElement.appendChild(requestDoc.createTextNode(parameters.getRequestId())); statusInputElement.appendChild(requestIdElement); Element serverNameElement = requestDoc.createElementNS( "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "ServerName"); serverNameElement.appendChild(requestDoc.createTextNode(parameters.getServerName())); statusInputElement.appendChild(serverNameElement); Element userNameElement = requestDoc.createElementNS( "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "UserName"); userNameElement.appendChild(requestDoc.createTextNode(parameters.getUserName())); statusInputElement.appendChild(userNameElement); DOMSource domSource = new DOMSource(requestDoc); StringWriter stringWriter = new StringWriter(); StreamResult streamResult = new StreamResult(stringWriter); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.transform(domSource, streamResult); requestContent = stringWriter.toString(); StringEntity entity = new StringEntity(requestContent); httpRequest.setEntity(entity); httpRequest.setHeader("Content-Type", "application/xml"); // Send Request HttpResponse httpResponse = null; try { if (shouldTrace) { CloudTracing.sendRequest(invocationId, httpRequest); } httpResponse = this.getClient().getHttpClient().execute(httpRequest); if (shouldTrace) { CloudTracing.receiveResponse(invocationId, httpResponse); } int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result DacGetStatusResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_OK) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new DacGetStatusResponse(); DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance(); documentBuilderFactory2.setNamespaceAware(true); DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder(); Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent)); Element arrayOfStatusInfoElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "ArrayOfStatusInfo"); if (arrayOfStatusInfoElement != null) { if (arrayOfStatusInfoElement != null) { for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility .getElementsByTagNameNS(arrayOfStatusInfoElement, "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "StatusInfo") .size(); i1 = i1 + 1) { org.w3c.dom.Element statusInfoElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility .getElementsByTagNameNS(arrayOfStatusInfoElement, "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "StatusInfo") .get(i1)); StatusInfo statusInfoInstance = new StatusInfo(); result.getStatusInfoList().add(statusInfoInstance); Element blobUriElement = XmlUtility.getElementByTagNameNS(statusInfoElement, "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "BlobUri"); if (blobUriElement != null) { URI blobUriInstance; blobUriInstance = new URI(blobUriElement.getTextContent()); statusInfoInstance.setBlobUri(blobUriInstance); } Element databaseNameElement = XmlUtility.getElementByTagNameNS(statusInfoElement, "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "DatabaseName"); if (databaseNameElement != null) { String databaseNameInstance; databaseNameInstance = databaseNameElement.getTextContent(); statusInfoInstance.setDatabaseName(databaseNameInstance); } Element errorMessageElement = XmlUtility.getElementByTagNameNS(statusInfoElement, "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "ErrorMessage"); if (errorMessageElement != null) { boolean isNil = false; Attr nilAttribute = errorMessageElement .getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "nil"); if (nilAttribute != null) { isNil = "true".equals(nilAttribute.getValue()); } if (isNil == false) { String errorMessageInstance; errorMessageInstance = errorMessageElement.getTextContent(); statusInfoInstance.setErrorMessage(errorMessageInstance); } } Element lastModifiedTimeElement = XmlUtility.getElementByTagNameNS(statusInfoElement, "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "LastModifiedTime"); if (lastModifiedTimeElement != null) { Calendar lastModifiedTimeInstance; lastModifiedTimeInstance = DatatypeConverter .parseDateTime(lastModifiedTimeElement.getTextContent()); statusInfoInstance.setLastModifiedTime(lastModifiedTimeInstance); } Element queuedTimeElement = XmlUtility.getElementByTagNameNS(statusInfoElement, "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "QueuedTime"); if (queuedTimeElement != null) { Calendar queuedTimeInstance; queuedTimeInstance = DatatypeConverter .parseDateTime(queuedTimeElement.getTextContent()); statusInfoInstance.setQueuedTime(queuedTimeInstance); } Element requestIdElement2 = XmlUtility.getElementByTagNameNS(statusInfoElement, "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "RequestId"); if (requestIdElement2 != null) { String requestIdInstance; requestIdInstance = requestIdElement2.getTextContent(); statusInfoInstance.setRequestId(requestIdInstance); } Element requestTypeElement = XmlUtility.getElementByTagNameNS(statusInfoElement, "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "RequestType"); if (requestTypeElement != null) { String requestTypeInstance; requestTypeInstance = requestTypeElement.getTextContent(); statusInfoInstance.setRequestType(requestTypeInstance); } Element serverNameElement2 = XmlUtility.getElementByTagNameNS(statusInfoElement, "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "ServerName"); if (serverNameElement2 != null) { String serverNameInstance; serverNameInstance = serverNameElement2.getTextContent(); statusInfoInstance.setServerName(serverNameInstance); } Element statusElement = XmlUtility.getElementByTagNameNS(statusInfoElement, "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "Status"); if (statusElement != null) { String statusInstance; statusInstance = statusElement.getTextContent(); statusInfoInstance.setStatus(statusInstance); } } } } } result.setStatusCode(statusCode); if (httpResponse.getHeaders("x-ms-request-id").length > 0) { result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); } if (shouldTrace) { CloudTracing.exit(invocationId, result); } return result; } finally { if (httpResponse != null && httpResponse.getEntity() != null) { httpResponse.getEntity().getContent().close(); } } }
From source file:com.microsoft.windowsazure.management.sql.DacOperationsImpl.java
/** * Initiates an Import of a DACPAC file from Azure Blob Storage into a Azure * SQL Database.// w ww . j a va 2 s . com * * @param serverName Required. The name of the Azure SQL Database Server * into which the database is being imported. * @param parameters Optional. The parameters needed to initiated the Import * request. * @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 Represents the response that the service returns once an import * or export operation has been initiated. */ @Override public DacImportExportResponse importMethod(String serverName, DacImportParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { // Validate if (serverName == null) { throw new NullPointerException("serverName"); } if (parameters != null) { if (parameters.getBlobCredentials() != null) { if (parameters.getBlobCredentials().getStorageAccessKey() == null) { throw new NullPointerException("parameters.BlobCredentials.StorageAccessKey"); } if (parameters.getBlobCredentials().getUri() == null) { throw new NullPointerException("parameters.BlobCredentials.Uri"); } } if (parameters.getConnectionInfo() != null) { if (parameters.getConnectionInfo().getDatabaseName() == null) { throw new NullPointerException("parameters.ConnectionInfo.DatabaseName"); } if (parameters.getConnectionInfo().getPassword() == null) { throw new NullPointerException("parameters.ConnectionInfo.Password"); } if (parameters.getConnectionInfo().getServerName() == null) { throw new NullPointerException("parameters.ConnectionInfo.ServerName"); } if (parameters.getConnectionInfo().getUserName() == null) { throw new NullPointerException("parameters.ConnectionInfo.UserName"); } } } // 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("parameters", parameters); CloudTracing.enter(invocationId, this, "importMethodAsync", tracingParameters); } // Construct URL String url = ""; url = url + "/"; if (this.getClient().getCredentials().getSubscriptionId() != null) { url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8"); } url = url + "/services/sqlservers/servers/"; url = url + URLEncoder.encode(serverName, "UTF-8"); url = url + "/DacOperations/Import"; 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(); if (parameters != null) { Element importInputElement = requestDoc.createElementNS( "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "ImportInput"); requestDoc.appendChild(importInputElement); if (parameters.getAzureEdition() != null) { Element azureEditionElement = requestDoc.createElementNS( "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "AzureEdition"); azureEditionElement.appendChild(requestDoc.createTextNode(parameters.getAzureEdition())); importInputElement.appendChild(azureEditionElement); } if (parameters.getBlobCredentials() != null) { Element blobCredentialsElement = requestDoc.createElementNS( "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "BlobCredentials"); importInputElement.appendChild(blobCredentialsElement); Attr typeAttribute = requestDoc.createAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "type"); typeAttribute.setValue("BlobStorageAccessKeyCredentials"); blobCredentialsElement.setAttributeNode(typeAttribute); Element uriElement = requestDoc.createElementNS( "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "Uri"); uriElement.appendChild( requestDoc.createTextNode(parameters.getBlobCredentials().getUri().toString())); blobCredentialsElement.appendChild(uriElement); Element storageAccessKeyElement = requestDoc.createElementNS( "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "StorageAccessKey"); storageAccessKeyElement.appendChild( requestDoc.createTextNode(parameters.getBlobCredentials().getStorageAccessKey())); blobCredentialsElement.appendChild(storageAccessKeyElement); } if (parameters.getConnectionInfo() != null) { Element connectionInfoElement = requestDoc.createElementNS( "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "ConnectionInfo"); importInputElement.appendChild(connectionInfoElement); Element databaseNameElement = requestDoc.createElementNS( "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "DatabaseName"); databaseNameElement .appendChild(requestDoc.createTextNode(parameters.getConnectionInfo().getDatabaseName())); connectionInfoElement.appendChild(databaseNameElement); Element passwordElement = requestDoc.createElementNS( "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "Password"); passwordElement .appendChild(requestDoc.createTextNode(parameters.getConnectionInfo().getPassword())); connectionInfoElement.appendChild(passwordElement); Element serverNameElement = requestDoc.createElementNS( "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "ServerName"); serverNameElement .appendChild(requestDoc.createTextNode(parameters.getConnectionInfo().getServerName())); connectionInfoElement.appendChild(serverNameElement); Element userNameElement = requestDoc.createElementNS( "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "UserName"); userNameElement .appendChild(requestDoc.createTextNode(parameters.getConnectionInfo().getUserName())); connectionInfoElement.appendChild(userNameElement); } Element databaseSizeInGBElement = requestDoc.createElementNS( "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes", "DatabaseSizeInGB"); databaseSizeInGBElement .appendChild(requestDoc.createTextNode(Integer.toString(parameters.getDatabaseSizeInGB()))); importInputElement.appendChild(databaseSizeInGBElement); } DOMSource domSource = new DOMSource(requestDoc); StringWriter stringWriter = new StringWriter(); StreamResult streamResult = new StreamResult(stringWriter); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.transform(domSource, streamResult); requestContent = stringWriter.toString(); StringEntity entity = new StringEntity(requestContent); httpRequest.setEntity(entity); httpRequest.setHeader("Content-Type", "application/xml"); // Send Request HttpResponse httpResponse = null; try { if (shouldTrace) { CloudTracing.sendRequest(invocationId, httpRequest); } httpResponse = this.getClient().getHttpClient().execute(httpRequest); if (shouldTrace) { CloudTracing.receiveResponse(invocationId, httpResponse); } int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result DacImportExportResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_OK) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new DacImportExportResponse(); DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance(); documentBuilderFactory2.setNamespaceAware(true); DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder(); Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent)); Element guidElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/2003/10/Serialization/", "guid"); if (guidElement != null) { result.setGuid(guidElement.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.bluexml.xforms.generator.mapping.MappingGenerator.java
/** * Writes a skeleton of the redirection file filled with default values. The * file is not created// w ww .j a v a 2s .c om * if no workflow forms were generated. * <p/> * The format is: * * <pre> * <entry> * <name>FORM_NAME</name> * <url>URL</url> * <auto>false</auto> * <addParams>true</addParams> * </entry> *</pre> * * @throws IOException */ private void writeSkeletonRedirector() throws IOException { // redirector configuration Document doc = DOMUtil.getNewDocument(); if (doc != null) { List<JAXBElement<? extends CanisterType>> elements = mapping.getCanister(); Element entriesElt = doc.createElement("entries"); doc.appendChild(entriesElt); int numberOfEntries = 0; for (JAXBElement<? extends CanisterType> element : elements) { if (element.getValue() instanceof WorkflowTaskType) { WorkflowTaskType taskType = (WorkflowTaskType) element.getValue(); Element nameElt = doc.createElement(MsgId.INT_REDIRECTION_NAME.getText()); nameElt.setTextContent(taskType.getName()); Element urlElt = doc.createElement(MsgId.INT_REDIRECTION_URL.getText()); Element autoElt = doc.createElement(MsgId.INT_REDIRECTION_AUTO_ADVANCE.getText()); autoElt.setTextContent("false"); Element addElt = doc.createElement(MsgId.INT_REDIRECTION_ADD_PARAMS.getText()); addElt.setTextContent("true"); Element entryElt = doc.createElement(MsgId.INT_REDIRECTION_ENTRY.getText()); entryElt.appendChild(nameElt); entryElt.appendChild(urlElt); entryElt.appendChild(autoElt); entryElt.appendChild(addElt); entriesElt.appendChild(entryElt); numberOfEntries++; } } if (numberOfEntries > 0) { String docStr = DOMUtil.convertDocument2String(doc); FileWriter fw; fw = new FileWriter(RedirectFile); PrintWriter pw = new PrintWriter(fw); pw.print(docStr); pw.close(); } } }
From source file:edu.kit.dama.mdm.content.mets.MetsMetadataExtractor.java
/** * Create an 'empty' document with the linked namespace. Only needed if no * content metadata exists./*from ww w. j a v a 2 s.co m*/ * * @return Empty document. */ protected Document createEmptyDocument() { Document xmlDocument = null; // <editor-fold defaultstate="collapsed" desc="create empty xml "> try { LOGGER.debug("Create empty document."); xmlDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); MetaDataSchema linkedSchema = getLinkedSchema(); StringBuilder elementName = new StringBuilder(); StringBuilder attribute = new StringBuilder("xmlns"); if (linkedSchema != null) { elementName.append(linkedSchema.getSchemaIdentifier()).append(":"); attribute.append(":").append(linkedSchema.getSchemaIdentifier()); } elementName.append("nometadata"); Element rootElement = xmlDocument.createElement(elementName.toString()); if (linkedSchema != null) { rootElement.setAttribute(attribute.toString(), linkedSchema.getMetaDataSchemaUrl()); } xmlDocument.appendChild(rootElement); } catch (ParserConfigurationException ex) { LOGGER.error("Error creating empty document.", ex); } // </editor-fold> return xmlDocument; }
From source file:com.aurel.track.exchange.track.exporter.TrackExportBL.java
/** * Exports the reportBeans to an xml file * @param reportBeans//from w w w . j a v a 2s. c o m * @param personID * @return */ private static Document exportWorkItems(List<ReportBean> reportBeansList, Integer personID) { Document dom = null; try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); dom = builder.newDocument(); } catch (FactoryConfigurationError e) { LOGGER.error("Creating the DOM document failed with FactoryConfigurationError:" + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); return null; } catch (ParserConfigurationException e) { LOGGER.error("Creating the DOM document failed with ParserConfigurationException: " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); return null; } //create the DOM object Element root = dom.createElement(ExchangeFieldNames.TRACKPLUS_EXCHANGE); dom.appendChild(root); if (reportBeansList == null || reportBeansList.isEmpty()) { return dom; } LOGGER.info("Number of workItems exported: " + reportBeansList.size()); //load also the full history List<ReportBeanWithHistory> reportBeansWithHistoryList = ReportBeanHistoryLoader .getReportBeanWithHistoryList(reportBeansList, Locale.ENGLISH, true, false, true, null, true, true, true, true, true, personID, null, null, null, true, LONG_TEXT_TYPE.ISFULLHTML); //get the workItemIDs List<Integer> workItemIDsList = new ArrayList<Integer>(); Set<Integer> issueTypeSet = new HashSet<Integer>(); Set<Integer> projectTypeSet = new HashSet<Integer>(); Set<Integer> projectSet = new HashSet<Integer>(); for (ReportBean reportBean : reportBeansWithHistoryList) { TWorkItemBean workItemBean = reportBean.getWorkItemBean(); workItemIDsList.add(workItemBean.getObjectID()); issueTypeSet.add(workItemBean.getListTypeID()); projectSet.add(workItemBean.getProjectID()); } List<TProjectBean> projectBeans = ProjectBL.loadByProjectIDs(GeneralUtils.createListFromSet(projectSet)); if (projectBeans != null) { for (TProjectBean projectBean : projectBeans) { projectTypeSet.add(projectBean.getProjectType()); } } //load the dropdown container based on the workItemIDsList DropDownContainer dropDownContainer = HistoryDropdownContainerLoader .loadExporterDropDownContainer(GeneralUtils.createIntArrFromIntegerList(workItemIDsList)); /** * fieldType based lookup values will be gathered in the lookup map: * fieldID_parametercode keyed -> lookup objectID keyed -> attribute name to attribute string value map */ Map<Integer, ILabelBean> personBeansMap = dropDownContainer .getDataSourceMap(MergeUtil.mergeKey(SystemFields.INTEGER_PERSON, null)); Map<String, Map<Integer, Map<String, String>>> serializedLookupsMap = new HashMap<String, Map<Integer, Map<String, String>>>(); //initialize the serialized person map explicitly because it will be loaded also //from other parts (consultants/informants, budget, cost etc.) Map<Integer, Map<String, String>> serializedPersonsMap = new HashMap<Integer, Map<String, String>>(); serializedLookupsMap.put(MergeUtil.mergeKey(SystemFields.INTEGER_PERSON, null), serializedPersonsMap); /** * gather all non-fieldType based lookup values in the additionalSerializedEntitiesMap map: * accounts, costcenteres, departments, system states, projectTypes and lists */ Map<String, Map<Integer, Map<String, String>>> additionalSerializedLookupsMap = new HashMap<String, Map<Integer, Map<String, String>>>(); Map<Integer, TCostCenterBean> costCentersMap = GeneralUtils .createMapFromList(AccountBL.getAllCostcenters()); Map<Integer, TAccountBean> accountsMap = GeneralUtils.createMapFromList(AccountBL.getAllAccounts()); //get the custom fields map Map<Integer, ISerializableLabelBean> customFieldBeansMap = GeneralUtils .createMapFromList(FieldBL.loadCustom()); Set<Integer> pseudoHistoryFields = HistoryLoaderBL.getPseudoHistoryFields(); /** * add the actual attribute values */ Set<Integer> nonNullFields = new HashSet<Integer>(); //linked through parent, issueNos in descriptions/comments and later issueLinks Set<Integer> linkedWorkItemIDs = new HashSet<Integer>(); for (int n = 0; n < reportBeansWithHistoryList.size(); n++) { ReportBean reportBean = (ReportBean) reportBeansWithHistoryList.get(n); TWorkItemBean workItemBean = reportBean.getWorkItemBean(); Map<String, String> attributes = new HashMap<String, String>(); attributes.put(ExchangeFieldNames.UUID, workItemBean.getUuid()); attributes.put(ExchangeFieldNames.WORKITEMID, workItemBean.getObjectID().toString()); Element itemElement = createElementWithAttributes(ExchangeFieldNames.ITEM, null, false, attributes, dom); //system field nodes for (int i = 0; i < SystemFields.getSystemFieldsArray().length; i++) { Integer fieldID = Integer.valueOf(SystemFields.getSystemFieldsArray()[i]); if (!fieldID.equals(SystemFields.INTEGER_ISSUENO)) { //the issueNo is added directly to item element { Object workItemAttribute = workItemBean.getAttribute(fieldID, null); if (workItemAttribute != null) { IFieldTypeRT fieldTypeRT = FieldTypeManager.getFieldTypeRT(fieldID); if (fieldTypeRT != null) { nonNullFields.add(fieldID); gatherLinkedWorkItems(workItemAttribute, fieldTypeRT, linkedWorkItemIDs); Map<String, String> fieldAndParameterCodeAttributes = new HashMap<String, String>(); fieldAndParameterCodeAttributes.put(ExchangeFieldNames.FIELDID, fieldID.toString()); appendAttributeElement(ExchangeFieldNames.ITEM_ATTRIBUTE, itemElement, workItemAttribute, fieldTypeRT, fieldID, null, dropDownContainer, serializedLookupsMap, additionalSerializedLookupsMap, fieldAndParameterCodeAttributes, dom); } } } } //custom field nodes Map<String, Object> customAttributes = workItemBean.getCustomAttributeValues(); Integer parameterCode; if (customAttributes != null && !customAttributes.isEmpty()) { Iterator<String> iterator = customAttributes.keySet().iterator(); while (iterator.hasNext()) { String key = iterator.next(); String[] splittedKey = MergeUtil.splitKey(key); String strFieldID = splittedKey[0].substring(1); //get rid of "f" Integer fieldID = Integer.valueOf(strFieldID); String strParameterCode = null; parameterCode = null; if (splittedKey.length > 1) { //whether the workItemAttribute is a part of a composite custom field strParameterCode = splittedKey[1]; if (strParameterCode != null && !"null".equals(strParameterCode)) { try { parameterCode = Integer.valueOf(strParameterCode); } catch (Exception e) { LOGGER.error("Converting the parameterCode " + strParameterCode + " to an integer failed with " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); } } } //add to custom field beans addToAdditionalSerializedLookupsMap(customFieldBeansMap.get(fieldID), ExchangeFieldNames.FIELD, additionalSerializedLookupsMap); Object workItemAttribute = workItemBean.getAttribute(fieldID, parameterCode); if (workItemAttribute != null) { IFieldTypeRT fieldTypeRT = FieldTypeManager.getFieldTypeRT(fieldID, parameterCode); nonNullFields.add(fieldID); gatherLinkedWorkItems(workItemAttribute, fieldTypeRT, linkedWorkItemIDs); Map<String, String> fieldAndParameterCodeAttributes = new HashMap<String, String>(); if (strFieldID != null) { fieldAndParameterCodeAttributes.put(ExchangeFieldNames.FIELDID, strFieldID); } if (strParameterCode != null) { fieldAndParameterCodeAttributes.put(ExchangeFieldNames.PARAMETERCODE, strParameterCode); } appendAttributeElement(ExchangeFieldNames.ITEM_ATTRIBUTE, itemElement, workItemAttribute, fieldTypeRT, fieldID, parameterCode, dropDownContainer, serializedLookupsMap, additionalSerializedLookupsMap, fieldAndParameterCodeAttributes, dom); } } } /** * add the consulted and informed nodes */ Set<Integer> consultedList = reportBean.getConsultedList(); if (consultedList != null && !consultedList.isEmpty()) { itemElement.appendChild(createConsInfElement(ExchangeFieldNames.CONSULTANT_LIST, ExchangeFieldNames.CONSULTANT, consultedList, personBeansMap, serializedPersonsMap, dom)); } Set<Integer> informedList = reportBean.getInformedList(); if (informedList != null && !informedList.isEmpty()) { itemElement.appendChild(createConsInfElement(ExchangeFieldNames.INFORMANT_LIST, ExchangeFieldNames.INFORMANT, informedList, personBeansMap, serializedPersonsMap, dom)); } /** * add the history nodes */ ReportBeanWithHistory reportBeanWithHistory = (ReportBeanWithHistory) reportBean; Element historyElement = createHistoryElement(reportBeanWithHistory.getHistoryValuesMap(), dropDownContainer, dom, serializedLookupsMap, additionalSerializedLookupsMap, pseudoHistoryFields, linkedWorkItemIDs); if (historyElement != null) { itemElement.appendChild(historyElement); } /** * add the budget nodes */ Element budgetElement = createBudgetPlanElement(reportBeanWithHistory.getBudgetHistory(), personBeansMap, serializedPersonsMap, dom, false); if (budgetElement != null) { itemElement.appendChild(budgetElement); } Element plannedValueElement = createBudgetPlanElement(reportBeanWithHistory.getPlannedValueHistory(), personBeansMap, serializedPersonsMap, dom, true); if (plannedValueElement != null) { itemElement.appendChild(plannedValueElement); } if (budgetElement != null) { //do not add estimated remaining budget element if no budget exists Element remainingBudgetElement = createRemainingBudgetElement( reportBeanWithHistory.getActualEstimatedBudgetBean(), personBeansMap, serializedPersonsMap, dom); if (remainingBudgetElement != null) { itemElement.appendChild(remainingBudgetElement); } } /** * add the expense nodes */ Element costElement = createExpenseElement(reportBeanWithHistory.getCosts(), personBeansMap, accountsMap, costCentersMap, serializedPersonsMap, dom, additionalSerializedLookupsMap); if (costElement != null) { itemElement.appendChild(costElement); } List<TAttachmentBean> existingAttachments = AttachBL .getExistingAttachments(reportBeanWithHistory.getAttachments()); Element attachmentElement = createAttachmentElement(existingAttachments, personBeansMap, serializedPersonsMap, dom); if (attachmentElement != null) { itemElement.appendChild(attachmentElement); } root.appendChild(itemElement); } /** * load the not explicitly exported linked workItems */ linkedWorkItemIDs.removeAll(workItemIDsList); if (!linkedWorkItemIDs.isEmpty()) { List<TWorkItemBean> workItemBeanList = ItemBL .loadByWorkItemKeys(GeneralUtils.createIntArrFromSet(linkedWorkItemIDs)); if (workItemIDsList != null) { Iterator<TWorkItemBean> itrWorkItemBean = workItemBeanList.iterator(); while (itrWorkItemBean.hasNext()) { TWorkItemBean workItemBean = itrWorkItemBean.next(); Map<String, String> attributeValues = workItemBean.serializeBean(); root.appendChild(createElementWithAttributes(ExchangeFieldNames.LINKED_ITEMS, "", false, attributeValues, dom)); } } } /** * add the systemState entries to the additionalSerializedEntitiesMap */ Map<Integer, Map<String, String>> serializedProjectMap = serializedLookupsMap .get(MergeUtil.mergeKey(SystemFields.INTEGER_PROJECT, null)); Map<Integer, Map<String, String>> serializedReleaseMap = serializedLookupsMap .get(MergeUtil.mergeKey(SystemFields.RELEASE, null)); Map<Integer, Map<String, String>> serializedAccountsMap = additionalSerializedLookupsMap .get(ExchangeFieldNames.ACCOUNT); Map<Integer, TSystemStateBean> systemStateMap = GeneralUtils.createMapFromList(SystemStatusBL.loadAll()); addSystemState(serializedProjectMap, systemStateMap, additionalSerializedLookupsMap); addSystemState(serializedReleaseMap, systemStateMap, additionalSerializedLookupsMap); addSystemState(serializedAccountsMap, systemStateMap, additionalSerializedLookupsMap); /** * add each option for the list (which have at least one option set on an issue) */ Map<Integer, Map<String, String>> serializedListMap = additionalSerializedLookupsMap .get(ExchangeFieldNames.LIST); addListAdditional(serializedListMap, dropDownContainer, serializedLookupsMap, additionalSerializedLookupsMap); /** * add the project related additional entities to serializedEntitiesMap and additionalSerializedEntitiesMap */ Map<Integer, TProjectTypeBean> projetcTypesMap = GeneralUtils.createMapFromList(ProjectTypesBL.loadAll()); addProjectAdditional(serializedProjectMap, projetcTypesMap, serializedLookupsMap, additionalSerializedLookupsMap, accountsMap, costCentersMap); /** * add field related entities: the owners */ Map<Integer, Map<String, String>> serializedCustomFields = additionalSerializedLookupsMap .get(ExchangeFieldNames.FIELD); addFieldAdditional(serializedCustomFields, serializedLookupsMap); /** * add the used fieldConfigs */ List<TFieldConfigBean> fieldConfigBeans = FieldConfigBL.loadAllForFields(nonNullFields); for (Iterator<TFieldConfigBean> iterator = fieldConfigBeans.iterator(); iterator.hasNext();) { //remove the field configurations for not used issueTypes, projectTypes and projects TFieldConfigBean fieldConfigBean = iterator.next(); Integer issueTypeID = fieldConfigBean.getIssueType(); Integer projectTypeID = fieldConfigBean.getProjectType(); Integer projectID = fieldConfigBean.getProject(); if (issueTypeID != null && !issueTypeSet.contains(issueTypeID)) { iterator.remove(); continue; } if (projectTypeID != null && !projectTypeSet.contains(projectTypeID)) { iterator.remove(); continue; } if (projectID != null && !projectSet.contains(projectID)) { iterator.remove(); continue; } } //comment this and uncomment the coming block to add fewer field configs addToAdditionalSerializedLookupsMap((List) fieldConfigBeans, ExchangeFieldNames.FIELDCONFIG, additionalSerializedLookupsMap); Map<Integer, Map<String, String>> serializedFieldConfigs = additionalSerializedLookupsMap .get(ExchangeFieldNames.FIELDCONFIG); addFieldConfigsAdditional(serializedFieldConfigs, projetcTypesMap, serializedLookupsMap, additionalSerializedLookupsMap); /** * add the field settings */ List<Integer> userFieldConfigIDs = GeneralUtils.createListFromSet(serializedFieldConfigs.keySet()); //option settings List<ISerializableLabelBean> optionSettingsList = (List) OptionSettingsBL .loadByConfigList(userFieldConfigIDs); if (optionSettingsList != null) { Iterator<ISerializableLabelBean> itrOptionSettings = optionSettingsList.iterator(); while (itrOptionSettings.hasNext()) { TOptionSettingsBean optionSettingsBean = (TOptionSettingsBean) itrOptionSettings.next(); Integer listID = optionSettingsBean.getList(); if (serializedListMap == null || !serializedListMap.containsKey(listID)) { //do not export the option settings if the corresponding list is not exported //(none of the selected workItems has a value from this list) //because creating the optionSetings will fail without the listID itrOptionSettings.remove(); } } } addToAdditionalSerializedLookupsMap(optionSettingsList, ExchangeFieldNames.OPTIONSETTINGS, additionalSerializedLookupsMap); //textbox settings List<ISerializableLabelBean> textBoxSettingsList = (List) TextBoxSettingsBL .loadByConfigList(userFieldConfigIDs); addToAdditionalSerializedLookupsMap(textBoxSettingsList, ExchangeFieldNames.TEXTBOXSETTINGS, additionalSerializedLookupsMap); //general settings List<ISerializableLabelBean> generalSettingsList = (List) GeneralSettingsBL .loadByConfigList(userFieldConfigIDs); addToAdditionalSerializedLookupsMap(generalSettingsList, ExchangeFieldNames.GENERALSETTINGS, additionalSerializedLookupsMap); /** * add the person related additional entities to serializedEntitiesMap and additionalSerializedEntitiesMap */ addPersonAdditional(serializedPersonsMap, GeneralUtils.createMapFromList(DepartmentBL.getAllDepartments()), costCentersMap, serializedLookupsMap, additionalSerializedLookupsMap); /** * add the role assignments and the roles * the role assignments cannot be added to the additionalSerializedLookupsMap because they have no objectID * consequently they will be serialized directly */ List<ISerializableLabelBean> accessControlListBeanList = (List) AccessControlBL.loadByPersonsAndProjects( GeneralUtils.createIntegerListFromCollection(serializedPersonsMap.keySet()), GeneralUtils.createIntegerListFromCollection(serializedProjectMap.keySet())); if (accessControlListBeanList != null) { Map<Integer, TRoleBean> roleMap = GeneralUtils.createMapFromList(RoleBL.loadAll()); Iterator<ISerializableLabelBean> iterator = accessControlListBeanList.iterator(); while (iterator.hasNext()) { TAccessControlListBean accessControlListBean = (TAccessControlListBean) iterator.next(); //serialize the role assignment directly root.appendChild(createElementWithAttributes(ExchangeFieldNames.ACL, null, false, accessControlListBean.serializeBean(), dom)); Integer role = accessControlListBean.getRoleID(); TRoleBean roleBean = roleMap.get(role); if (roleBean != null) { //add the roles which are present in the role assignments addToAdditionalSerializedLookupsMap(roleBean, ExchangeFieldNames.ROLE, additionalSerializedLookupsMap); } } } /** * first add the additional serialized entities first because the fieldID mapping is needed by parsing the serialized entities */ Iterator<String> iterator = additionalSerializedLookupsMap.keySet().iterator(); while (iterator.hasNext()) { String entityName = iterator.next(); Map<Integer, Map<String, String>> lookupEntityMap = additionalSerializedLookupsMap.get(entityName); if (lookupEntityMap != null && !lookupEntityMap.isEmpty()) { Iterator<Integer> itrObjectID = lookupEntityMap.keySet().iterator(); while (itrObjectID.hasNext()) { Integer objectID = itrObjectID.next(); Map<String, String> attributes = lookupEntityMap.get(objectID); if (attributes != null && !attributes.isEmpty()) { root.appendChild(createElementWithAttributes(entityName, null, false, attributes, dom)); } } } } /** * add the serialized entities */ iterator = serializedLookupsMap.keySet().iterator(); while (iterator.hasNext()) { String mergedKey = iterator.next(); Integer[] parts = MergeUtil.getParts(mergedKey); Integer fieldID = parts[0]; Integer parameterCode = parts[1]; Map<Integer, Map<String, String>> lookupEntityMap = serializedLookupsMap.get(mergedKey); if (lookupEntityMap != null && !lookupEntityMap.isEmpty()) { Iterator<Integer> itrObjectID = lookupEntityMap.keySet().iterator(); while (itrObjectID.hasNext()) { Integer objectID = itrObjectID.next(); Map<String, String> attributes = lookupEntityMap.get(objectID); if (attributes != null && !attributes.isEmpty()) { if (fieldID != null) { attributes.put(ExchangeFieldNames.FIELDID, fieldID.toString()); } if (parameterCode != null) { attributes.put(ExchangeFieldNames.PARAMETERCODE, parameterCode.toString()); } root.appendChild(createElementWithAttributes(ExchangeFieldNames.DROPDOWN_ELEMENT, null, false, attributes, dom)); } } } } return dom; }
From source file:com.microsoft.windowsazure.management.websites.WebHostingPlanOperationsImpl.java
/** * Updates an existing Web Hosting Plan. (see * http://azure.microsoft.com/en-us/documentation/articles/azure-web-sites-web-hosting-plans-in-depth-overview/ * for more information)// w w w . ja va 2s . c om * * @param webSpaceName Required. The name of the web space. * @param webHostingPlanName Required. The name of the web hosting plan. * @param parameters Required. Parameters supplied to the Update Web Hosting * Plan operation. * @throws ParserConfigurationException Thrown if there was an error * configuring the parser for the response body. * @throws SAXException Thrown if there was an error parsing the response * body. * @throws TransformerException Thrown if there was an error creating the * DOM transformer. * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations. * @throws ServiceException Thrown if an unexpected response is found. * @throws URISyntaxException Thrown if there was an error parsing a URI in * the response. * @return The Create Web Hosting Plan operation response. */ @Override public WebHostingPlanUpdateResponse update(String webSpaceName, String webHostingPlanName, WebHostingPlanUpdateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException, URISyntaxException { // Validate if (webSpaceName == null) { throw new NullPointerException("webSpaceName"); } if (webHostingPlanName == null) { throw new NullPointerException("webHostingPlanName"); } if (parameters == null) { throw new NullPointerException("parameters"); } // Tracing boolean shouldTrace = CloudTracing.getIsEnabled(); String invocationId = null; if (shouldTrace) { invocationId = Long.toString(CloudTracing.getNextInvocationId()); HashMap<String, Object> tracingParameters = new HashMap<String, Object>(); tracingParameters.put("webSpaceName", webSpaceName); tracingParameters.put("webHostingPlanName", webHostingPlanName); tracingParameters.put("parameters", parameters); CloudTracing.enter(invocationId, this, "updateAsync", tracingParameters); } // Construct URL String url = ""; url = url + "/"; if (this.getClient().getCredentials().getSubscriptionId() != null) { url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8"); } url = url + "/services/WebSpaces/"; url = url + URLEncoder.encode(webSpaceName, "UTF-8"); url = url + "/ServerFarms/"; url = url + URLEncoder.encode(webHostingPlanName, "UTF-8"); String baseUrl = this.getClient().getBaseUri().toString(); // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl.charAt(baseUrl.length() - 1) == '/') { baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); } if (url.charAt(0) == '/') { url = url.substring(1); } url = baseUrl + "/" + url; url = url.replace(" ", "%20"); // Create HTTP transport objects HttpPut httpRequest = new HttpPut(url); // Set Headers httpRequest.setHeader("Content-Type", "application/xml"); httpRequest.setHeader("x-ms-version", "2014-04-01"); // Serialize Request String requestContent = null; DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document requestDoc = documentBuilder.newDocument(); Element serverFarmElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ServerFarm"); requestDoc.appendChild(serverFarmElement); if (parameters.getNumberOfWorkers() != null) { Element numberOfWorkersElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "NumberOfWorkers"); numberOfWorkersElement .appendChild(requestDoc.createTextNode(Integer.toString(parameters.getNumberOfWorkers()))); serverFarmElement.appendChild(numberOfWorkersElement); } if (parameters.getSKU() != null) { Element sKUElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "SKU"); sKUElement.appendChild(requestDoc.createTextNode(parameters.getSKU().toString())); serverFarmElement.appendChild(sKUElement); } if (parameters.getWorkerSize() != null) { Element workerSizeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "WorkerSize"); workerSizeElement.appendChild(requestDoc.createTextNode(parameters.getWorkerSize().toString())); serverFarmElement.appendChild(workerSizeElement); } if (parameters.getAdminSiteName() != null) { Element adminSiteNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "AdminSiteName"); adminSiteNameElement.appendChild(requestDoc.createTextNode(parameters.getAdminSiteName())); serverFarmElement.appendChild(adminSiteNameElement); } DOMSource domSource = new DOMSource(requestDoc); StringWriter stringWriter = new StringWriter(); StreamResult streamResult = new StreamResult(stringWriter); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.transform(domSource, streamResult); requestContent = stringWriter.toString(); StringEntity entity = new StringEntity(requestContent); httpRequest.setEntity(entity); httpRequest.setHeader("Content-Type", "application/xml"); // Send Request HttpResponse httpResponse = null; try { if (shouldTrace) { CloudTracing.sendRequest(invocationId, httpRequest); } httpResponse = this.getClient().getHttpClient().execute(httpRequest); if (shouldTrace) { CloudTracing.receiveResponse(invocationId, httpResponse); } int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result WebHostingPlanUpdateResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_OK) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new WebHostingPlanUpdateResponse(); DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance(); documentBuilderFactory2.setNamespaceAware(true); DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder(); Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent)); Element serverFarmElement2 = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "ServerFarm"); if (serverFarmElement2 != null) { WebHostingPlan webHostingPlanInstance = new WebHostingPlan(); result.setWebHostingPlan(webHostingPlanInstance); Element nameElement = XmlUtility.getElementByTagNameNS(serverFarmElement2, "http://schemas.microsoft.com/windowsazure", "Name"); if (nameElement != null) { String nameInstance; nameInstance = nameElement.getTextContent(); webHostingPlanInstance.setName(nameInstance); } Element numberOfWorkersElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2, "http://schemas.microsoft.com/windowsazure", "NumberOfWorkers"); if (numberOfWorkersElement2 != null && numberOfWorkersElement2.getTextContent() != null && !numberOfWorkersElement2.getTextContent().isEmpty()) { int numberOfWorkersInstance; numberOfWorkersInstance = DatatypeConverter .parseInt(numberOfWorkersElement2.getTextContent()); webHostingPlanInstance.setNumberOfWorkers(numberOfWorkersInstance); } Element sKUElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2, "http://schemas.microsoft.com/windowsazure", "SKU"); if (sKUElement2 != null && sKUElement2.getTextContent() != null && !sKUElement2.getTextContent().isEmpty()) { SkuOptions sKUInstance; sKUInstance = SkuOptions.valueOf(sKUElement2.getTextContent()); webHostingPlanInstance.setSKU(sKUInstance); } Element workerSizeElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2, "http://schemas.microsoft.com/windowsazure", "WorkerSize"); if (workerSizeElement2 != null && workerSizeElement2.getTextContent() != null && !workerSizeElement2.getTextContent().isEmpty()) { WorkerSizeOptions workerSizeInstance; workerSizeInstance = WorkerSizeOptions.valueOf(workerSizeElement2.getTextContent()); webHostingPlanInstance.setWorkerSize(workerSizeInstance); } Element adminSiteNameElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2, "http://schemas.microsoft.com/windowsazure", "AdminSiteName"); if (adminSiteNameElement2 != null) { String adminSiteNameInstance; adminSiteNameInstance = adminSiteNameElement2.getTextContent(); webHostingPlanInstance.setAdminSiteName(adminSiteNameInstance); } } } result.setStatusCode(statusCode); if (httpResponse.getHeaders("x-ms-request-id").length > 0) { result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); } if (shouldTrace) { CloudTracing.exit(invocationId, result); } return result; } finally { if (httpResponse != null && httpResponse.getEntity() != null) { httpResponse.getEntity().getContent().close(); } } }
From source file:com.microsoft.windowsazure.management.websites.WebHostingPlanOperationsImpl.java
/** * Creates a new Web Hosting Plan. (see// w w w. ja va2s. c om * http://azure.microsoft.com/en-us/documentation/articles/azure-web-sites-web-hosting-plans-in-depth-overview/ * for more information) * * @param webSpaceName Required. The name of the web space. * @param parameters Required. Web Hosting Plan Parameters. * @throws ParserConfigurationException Thrown if there was an error * configuring the parser for the response body. * @throws SAXException Thrown if there was an error parsing the response * body. * @throws TransformerException Thrown if there was an error creating the * DOM transformer. * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations. * @throws ServiceException Thrown if an unexpected response is found. * @throws URISyntaxException Thrown if there was an error parsing a URI in * the response. * @return The Create Web Web Hosting Plan operation response. */ @Override public WebHostingPlanCreateResponse create(String webSpaceName, WebHostingPlanCreateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException, URISyntaxException { // Validate if (webSpaceName == null) { throw new NullPointerException("webSpaceName"); } if (parameters == null) { throw new NullPointerException("parameters"); } if (parameters.getName() == null) { throw new NullPointerException("parameters.Name"); } // Tracing boolean shouldTrace = CloudTracing.getIsEnabled(); String invocationId = null; if (shouldTrace) { invocationId = Long.toString(CloudTracing.getNextInvocationId()); HashMap<String, Object> tracingParameters = new HashMap<String, Object>(); tracingParameters.put("webSpaceName", webSpaceName); 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/WebSpaces/"; url = url + URLEncoder.encode(webSpaceName, "UTF-8"); url = url + "/ServerFarms"; 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", "2014-04-01"); // Serialize Request String requestContent = null; DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document requestDoc = documentBuilder.newDocument(); Element serverFarmElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ServerFarm"); requestDoc.appendChild(serverFarmElement); Element nameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); nameElement.appendChild(requestDoc.createTextNode(parameters.getName())); serverFarmElement.appendChild(nameElement); if (parameters.getNumberOfWorkers() != null) { Element numberOfWorkersElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "NumberOfWorkers"); numberOfWorkersElement .appendChild(requestDoc.createTextNode(Integer.toString(parameters.getNumberOfWorkers()))); serverFarmElement.appendChild(numberOfWorkersElement); } if (parameters.getSKU() != null) { Element sKUElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "SKU"); sKUElement.appendChild(requestDoc.createTextNode(parameters.getSKU().toString())); serverFarmElement.appendChild(sKUElement); } if (parameters.getWorkerSize() != null) { Element workerSizeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "WorkerSize"); workerSizeElement.appendChild(requestDoc.createTextNode(parameters.getWorkerSize().toString())); serverFarmElement.appendChild(workerSizeElement); } if (parameters.getAdminSiteName() != null) { Element adminSiteNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "AdminSiteName"); adminSiteNameElement.appendChild(requestDoc.createTextNode(parameters.getAdminSiteName())); serverFarmElement.appendChild(adminSiteNameElement); } DOMSource domSource = new DOMSource(requestDoc); StringWriter stringWriter = new StringWriter(); StreamResult streamResult = new StreamResult(stringWriter); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.transform(domSource, streamResult); requestContent = stringWriter.toString(); StringEntity entity = new StringEntity(requestContent); httpRequest.setEntity(entity); httpRequest.setHeader("Content-Type", "application/xml"); // Send Request HttpResponse httpResponse = null; try { if (shouldTrace) { CloudTracing.sendRequest(invocationId, httpRequest); } httpResponse = this.getClient().getHttpClient().execute(httpRequest); if (shouldTrace) { CloudTracing.receiveResponse(invocationId, httpResponse); } int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result WebHostingPlanCreateResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_OK) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new WebHostingPlanCreateResponse(); DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance(); documentBuilderFactory2.setNamespaceAware(true); DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder(); Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent)); Element serverFarmElement2 = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "ServerFarm"); if (serverFarmElement2 != null) { WebHostingPlan webHostingPlanInstance = new WebHostingPlan(); result.setWebHostingPlan(webHostingPlanInstance); Element nameElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2, "http://schemas.microsoft.com/windowsazure", "Name"); if (nameElement2 != null) { String nameInstance; nameInstance = nameElement2.getTextContent(); webHostingPlanInstance.setName(nameInstance); } Element numberOfWorkersElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2, "http://schemas.microsoft.com/windowsazure", "NumberOfWorkers"); if (numberOfWorkersElement2 != null && numberOfWorkersElement2.getTextContent() != null && !numberOfWorkersElement2.getTextContent().isEmpty()) { int numberOfWorkersInstance; numberOfWorkersInstance = DatatypeConverter .parseInt(numberOfWorkersElement2.getTextContent()); webHostingPlanInstance.setNumberOfWorkers(numberOfWorkersInstance); } Element sKUElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2, "http://schemas.microsoft.com/windowsazure", "SKU"); if (sKUElement2 != null && sKUElement2.getTextContent() != null && !sKUElement2.getTextContent().isEmpty()) { SkuOptions sKUInstance; sKUInstance = SkuOptions.valueOf(sKUElement2.getTextContent()); webHostingPlanInstance.setSKU(sKUInstance); } Element workerSizeElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2, "http://schemas.microsoft.com/windowsazure", "WorkerSize"); if (workerSizeElement2 != null && workerSizeElement2.getTextContent() != null && !workerSizeElement2.getTextContent().isEmpty()) { WorkerSizeOptions workerSizeInstance; workerSizeInstance = WorkerSizeOptions.valueOf(workerSizeElement2.getTextContent()); webHostingPlanInstance.setWorkerSize(workerSizeInstance); } Element adminSiteNameElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2, "http://schemas.microsoft.com/windowsazure", "AdminSiteName"); if (adminSiteNameElement2 != null) { String adminSiteNameInstance; adminSiteNameInstance = adminSiteNameElement2.getTextContent(); webHostingPlanInstance.setAdminSiteName(adminSiteNameInstance); } } } 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.mirth.connect.server.servlets.WebStartServlet.java
private Document getExtensionJnlp(String extensionPath) throws Exception { List<MetaData> allExtensions = new ArrayList<MetaData>(); allExtensions// w w w . j a v a 2 s . c om .addAll(ControllerFactory.getFactory().createExtensionController().getConnectorMetaData().values()); allExtensions .addAll(ControllerFactory.getFactory().createExtensionController().getPluginMetaData().values()); Set<String> librariesToAddToJnlp = new HashSet<String>(); List<String> extensionsWithThePath = new ArrayList<String>(); for (MetaData metaData : allExtensions) { if (metaData.getPath().equals(extensionPath)) { extensionsWithThePath.add(metaData.getName()); for (ExtensionLibrary library : metaData.getLibraries()) { if (library.getType().equals(ExtensionLibrary.Type.CLIENT) || library.getType().equals(ExtensionLibrary.Type.SHARED)) { librariesToAddToJnlp.add(library.getPath()); } } } } if (extensionsWithThePath.isEmpty()) { throw new Exception("Extension metadata could not be located for the path: " + extensionPath); } Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Element jnlpElement = document.createElement("jnlp"); Element informationElement = document.createElement("information"); Element titleElement = document.createElement("title"); titleElement .setTextContent("Mirth Connect Extension - [" + StringUtils.join(extensionsWithThePath, ",") + "]"); informationElement.appendChild(titleElement); Element vendorElement = document.createElement("vendor"); vendorElement.setTextContent("Mirth Corporation"); informationElement.appendChild(vendorElement); jnlpElement.appendChild(informationElement); Element securityElement = document.createElement("security"); securityElement.appendChild(document.createElement("all-permissions")); jnlpElement.appendChild(securityElement); Element resourcesElement = document.createElement("resources"); for (String library : librariesToAddToJnlp) { Element jarElement = document.createElement("jar"); jarElement.setAttribute("download", "eager"); // this path is relative to the servlet path jarElement.setAttribute("href", "libs/" + extensionPath + "/" + library); resourcesElement.appendChild(jarElement); } jnlpElement.appendChild(resourcesElement); jnlpElement.appendChild(document.createElement("component-desc")); document.appendChild(jnlpElement); return document; }
From source file:com.bluexml.xforms.controller.mapping.MappingToolAlfrescoToForms.java
/** * Gets the form instance for a specific object whose id is given. * /* w w w . j a v a 2 s.c o m*/ * @param transaction * the login * @param formName * the form name * @param alfrescoId * the alfresco id * @param initParams * * @return the form instance * * @throws ServletException */ public Document getFormInstance(AlfrescoTransaction transaction, String formName, String alfrescoId, Map<String, String> initParams, boolean formIsReadOnly) throws ServletException { Document formInstance = documentBuilder.newDocument(); Map<String, GenericClass> alfrescoNodes = new HashMap<String, GenericClass>(); Element rootElement = formInstance.createElement("root"); String realName = formName; // WorkflowTaskType entry = getWorkflowTaskType(formName, false); // if (entry != null) { // // on a workflow form; we'll need to add the data form // realName = entry.getDataForm(); // getWorkflowInstance(formInstance, rootElement, alfrescoNodes); // } getDataFormInstance(formInstance, rootElement, transaction, realName, alfrescoId, alfrescoNodes, formIsReadOnly, initParams); formInstance.appendChild(rootElement); return formInstance; }