List of usage examples for org.w3c.dom Document createTextNode
public Text createTextNode(String data);
Text
node given the specified string. From source file:com.msopentech.odatajclient.engine.performance.BasicPerfTest.java
@Test public void writeAtomViaLowerlevelLibs() throws ParserConfigurationException, ClassNotFoundException, InstantiationException, IllegalAccessException { final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); final DocumentBuilder builder = factory.newDocumentBuilder(); final Document doc = builder.newDocument(); final Element entry = doc.createElement("entry"); entry.setAttribute("xmlns", "http://www.w3.org/2005/Atom"); entry.setAttribute("xmlns:m", "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"); entry.setAttribute("xmlns:d", "http://schemas.microsoft.com/ado/2007/08/dataservices"); entry.setAttribute("xmlns:gml", "http://www.opengis.net/gml"); entry.setAttribute("xmlns:georss", "http://www.georss.org/georss"); doc.appendChild(entry);/* w w w. j av a 2 s . c o m*/ final Element category = doc.createElement("category"); category.setAttribute("term", "Microsoft.Test.OData.Services.AstoriaDefaultService.Customer"); category.setAttribute("scheme", "http://schemas.microsoft.com/ado/2007/08/dataservices/scheme"); entry.appendChild(category); final Element properties = doc.createElement("m:properties"); entry.appendChild(properties); final Element name = doc.createElement("d:Name"); name.setAttribute("m:type", "Edm.String"); name.appendChild(doc.createTextNode("A name")); properties.appendChild(name); final Element customerId = doc.createElement("d:CustomerId"); customerId.setAttribute("m:type", "Edm.Int32"); customerId.appendChild(doc.createTextNode("0")); properties.appendChild(customerId); final Element bci = doc.createElement("d:BackupContactInfo"); bci.setAttribute("m:type", "Collection(Microsoft.Test.OData.Services.AstoriaDefaultService.ContactDetails)"); properties.appendChild(bci); final Element topelement = doc.createElement("d:element"); topelement.setAttribute("m:type", "Microsoft.Test.OData.Services.AstoriaDefaultService.ContactDetails"); bci.appendChild(topelement); final Element altNames = doc.createElement("d:AlternativeNames"); altNames.setAttribute("m:type", "Collection(Edm.String)"); topelement.appendChild(altNames); final Element element1 = doc.createElement("d:element"); element1.setAttribute("m:type", "Edm.String"); element1.appendChild(doc.createTextNode("myname")); altNames.appendChild(element1); final Element emailBag = doc.createElement("d:EmailBag"); emailBag.setAttribute("m:type", "Collection(Edm.String)"); topelement.appendChild(emailBag); final Element element2 = doc.createElement("d:element"); element2.setAttribute("m:type", "Edm.String"); element2.appendChild(doc.createTextNode("myname@mydomain.com")); emailBag.appendChild(element2); final Element contactAlias = doc.createElement("d:ContactAlias"); contactAlias.setAttribute("m:type", "Microsoft.Test.OData.Services.AstoriaDefaultService.Aliases"); topelement.appendChild(contactAlias); final Element altNames2 = doc.createElement("d:AlternativeNames"); altNames2.setAttribute("m:type", "Collection(Edm.String)"); contactAlias.appendChild(altNames2); final Element element3 = doc.createElement("d:element"); element3.setAttribute("m:type", "Edm.String"); element3.appendChild(doc.createTextNode("myAlternativeName")); altNames2.appendChild(element3); final StringWriter writer = new StringWriter(); final DOMImplementationRegistry reg = DOMImplementationRegistry.newInstance(); final DOMImplementationLS impl = (DOMImplementationLS) reg.getDOMImplementation("LS"); final LSSerializer serializer = impl.createLSSerializer(); final LSOutput lso = impl.createLSOutput(); lso.setCharacterStream(writer); serializer.write(doc, lso); assertFalse(writer.toString().isEmpty()); }
From source file:io.fabric8.tooling.archetype.builder.ArchetypeBuilder.java
/** * This method:<ul>//from www.j a v a 2 s .c o m * <li>Copies POM from original project to archetype-resources</li> * <li>Generates <code></code>archetype-descriptor.xml</code></li> * <li>Generates Archetype's <code>pom.xml</code> if not present in target directory.</li> * </ul> * * @param projectPom POM file of original project * @param archetypeDir target directory of created Maven Archetype project * @param archetypePom created POM file for Maven Archetype project * @param metadataXmlOutFile generated archetype-metadata.xml file * @param replaceFn replace function * @throws IOException */ private void createArchetypeDescriptors(File projectPom, File archetypeDir, File archetypePom, File metadataXmlOutFile, Replacement replaceFn) throws IOException { LOG.debug("Parsing " + projectPom); String text = replaceFn.replace(FileUtils.readFileToString(projectPom)); // lets update the XML Document doc = archetypeUtils.parseXml(new InputSource(new StringReader(text))); Element root = doc.getDocumentElement(); // let's get some values from the original project String originalArtifactId, originalName, originalDescription; Element artifactIdEl = (Element) findChild(root, "artifactId"); Element nameEl = (Element) findChild(root, "name"); Element descriptionEl = (Element) findChild(root, "description"); if (artifactIdEl != null && artifactIdEl.getTextContent() != null && artifactIdEl.getTextContent().trim().length() > 0) { originalArtifactId = artifactIdEl.getTextContent().trim(); } else { originalArtifactId = archetypeDir.getName(); } if (nameEl != null && nameEl.getTextContent() != null && nameEl.getTextContent().trim().length() > 0) { originalName = nameEl.getTextContent().trim(); } else { originalName = originalArtifactId; } if (descriptionEl != null && descriptionEl.getTextContent() != null && descriptionEl.getTextContent().trim().length() > 0) { originalDescription = descriptionEl.getTextContent().trim(); } else { originalDescription = originalName; } Set<String> propertyNameSet = new TreeSet<String>(); if (root != null) { // remove the parent element and the following text Node NodeList parents = root.getElementsByTagName("parent"); if (parents.getLength() > 0) { if (parents.item(0).getNextSibling().getNodeType() == Node.TEXT_NODE) { root.removeChild(parents.item(0).getNextSibling()); } root.removeChild(parents.item(0)); } // lets load all the properties defined in the <properties> element in the pom. Set<String> pomPropertyNames = new LinkedHashSet<String>(); NodeList propertyElements = root.getElementsByTagName("properties"); if (propertyElements.getLength() > 0) { Element propertyElement = (Element) propertyElements.item(0); NodeList children = propertyElement.getChildNodes(); for (int cn = 0; cn < children.getLength(); cn++) { Node e = children.item(cn); if (e instanceof Element) { pomPropertyNames.add(e.getNodeName()); } } } LOG.debug("Found <properties> in the pom: {}", pomPropertyNames); // lets find all the property names NodeList children = root.getElementsByTagName("*"); for (int cn = 0; cn < children.getLength(); cn++) { Node e = children.item(cn); if (e instanceof Element) { //val text = e.childrenText String cText = e.getTextContent(); String prefix = "${"; if (cText.startsWith(prefix)) { int offset = prefix.length(); int idx = cText.indexOf("}", offset + 1); if (idx > 0) { String name = cText.substring(offset, idx); if (!pomPropertyNames.contains(name) && isValidRequiredPropertyName(name)) { propertyNameSet.add(name); } } } } } // now lets replace the contents of some elements (adding new elements if they are not present) List<String> beforeNames = Arrays.asList("artifactId", "version", "packaging", "name", "properties"); replaceOrAddElementText(doc, root, "version", "${version}", beforeNames); replaceOrAddElementText(doc, root, "artifactId", "${artifactId}", beforeNames); replaceOrAddElementText(doc, root, "groupId", "${groupId}", beforeNames); } archetypePom.getParentFile().mkdirs(); archetypeUtils.writeXmlDocument(doc, archetypePom); // lets update the archetype-metadata.xml file String archetypeXmlText = defaultArchetypeXmlText(); Document archDoc = archetypeUtils.parseXml(new InputSource(new StringReader(archetypeXmlText))); Element archRoot = archDoc.getDocumentElement(); // replace @name attribute on root element archRoot.setAttribute("name", archetypeDir.getName()); LOG.debug(("Found property names: {}"), propertyNameSet); // lets add all the properties Element requiredProperties = replaceOrAddElement(archDoc, archRoot, "requiredProperties", Arrays.asList("fileSets")); // lets add the various properties in for (String propertyName : propertyNameSet) { requiredProperties.appendChild(archDoc.createTextNode("\n" + indent + indent)); Element requiredProperty = archDoc.createElement("requiredProperty"); requiredProperties.appendChild(requiredProperty); requiredProperty.setAttribute("key", propertyName); requiredProperty.appendChild(archDoc.createTextNode("\n" + indent + indent + indent)); Element defaultValue = archDoc.createElement("defaultValue"); requiredProperty.appendChild(defaultValue); defaultValue.appendChild(archDoc.createTextNode("${" + propertyName + "}")); requiredProperty.appendChild(archDoc.createTextNode("\n" + indent + indent)); } requiredProperties.appendChild(archDoc.createTextNode("\n" + indent)); metadataXmlOutFile.getParentFile().mkdirs(); archetypeUtils.writeXmlDocument(archDoc, metadataXmlOutFile); File archetypeProjectPom = new File(archetypeDir, "pom.xml"); // now generate Archetype's pom if (!archetypeProjectPom.exists()) { StringWriter sw = new StringWriter(); IOUtils.copy(getClass().getResourceAsStream("default-archetype-pom.xml"), sw, "UTF-8"); Document pomDocument = archetypeUtils.parseXml(new InputSource(new StringReader(sw.toString()))); List<String> emptyList = Collections.emptyList(); // artifactId = original artifactId with "-archetype" Element artifactId = replaceOrAddElement(pomDocument, pomDocument.getDocumentElement(), "artifactId", emptyList); artifactId.setTextContent(archetypeDir.getName()); // name = "Fabric8 :: Qickstarts :: xxx" -> "Fabric8 :: Archetypes :: xxx" Element name = replaceOrAddElement(pomDocument, pomDocument.getDocumentElement(), "name", emptyList); if (originalName.contains(" :: ")) { String[] originalNameTab = originalName.split(" :: "); if (originalNameTab.length > 2) { StringBuilder sb = new StringBuilder(); sb.append("Fabric8 :: Archetypes"); for (int idx = 2; idx < originalNameTab.length; idx++) { sb.append(" :: ").append(originalNameTab[idx]); } name.setTextContent(sb.toString()); } else { name.setTextContent("Fabric8 :: Archetypes :: " + originalNameTab[1]); } } else { name.setTextContent("Fabric8 :: Archetypes :: " + originalName); } // description = "Creates a new " + originalDescription Element description = replaceOrAddElement(pomDocument, pomDocument.getDocumentElement(), "description", emptyList); description.setTextContent("Creates a new " + originalDescription); archetypeUtils.writeXmlDocument(pomDocument, archetypeProjectPom); } }
From source file:com.aliyun.odps.conf.Configuration.java
/** * ?? {@link OutputStream}/*from w w w .j a v a2 s . c o m*/ * * @param out * {@link OutputStream} */ @SuppressWarnings("rawtypes") public void writeXml(OutputStream out) throws IOException { Properties properties = getProps(); try { Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Element conf = doc.createElement("configuration"); doc.appendChild(conf); conf.appendChild(doc.createTextNode("\n")); for (Enumeration e = properties.keys(); e.hasMoreElements();) { String name = (String) e.nextElement(); Object object = properties.get(name); String value = null; if (object instanceof String) { value = (String) object; } else { continue; } Element propNode = doc.createElement("property"); conf.appendChild(propNode); Element nameNode = doc.createElement("name"); nameNode.appendChild(doc.createTextNode(name)); propNode.appendChild(nameNode); Element valueNode = doc.createElement("value"); valueNode.appendChild(doc.createTextNode(value)); propNode.appendChild(valueNode); conf.appendChild(doc.createTextNode("\n")); } DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(out); TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer = transFactory.newTransformer(); transformer.transform(source, result); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.gvnix.support.WebProjectUtilsImpl.java
/** * Add variable to contain request Locale in string format. * <p/>//from ww w. jav a2 s . co m * * <pre> * {@code * <c:set var="VAR_NAME"> * <!-- Get the user local from the page context (it was set by * Spring MVC's locale resolver) --> * <c:set var="jqlocale">${pageContext.response.locale}</c:set> * <c:if test="${fn:length(jqlocale) eq 2}"> * <c:out value="${jqlocale}" /> * </c:if> * <c:if test="${fn:length(jqlocale) gt 2}"> * <c:out value="${fn:substringBefore(jqlocale, '_')}" default="en" /> * </c:if> * <c:if test="${fn:length(jqlocale) lt 2}"> * <c:out value="en" /> * </c:if> * </c:set> * } * </pre> * * @param docTagx {@code .tagx} file document * @param root XML root node * @param varName name of variable to create, see {@code VAR_NAME} in * example above */ public boolean addLocaleVarToTag(Document docTagx, Element root, String varName) { // Add locale var Element varElement = XmlUtils.findFirstElement(String.format("c:set[@var='${%s}']", varName), root); if (varElement == null) { varElement = docTagx.createElement("c:set"); varElement.setAttribute("var", varName); varElement.appendChild(docTagx.createComment( " Get the user local from the page context (it was set by Spring MVC's locale resolver) ")); Element pElement = docTagx.createElement("c:set"); pElement.setAttribute("var", "jqlocale"); pElement.appendChild(docTagx.createTextNode("${pageContext.response.locale}")); varElement.appendChild(pElement); Element ifElement = docTagx.createElement("c:if"); ifElement.setAttribute("test", "${fn:length(jqlocale) eq 2}"); Element outElement = docTagx.createElement("c:out"); outElement.setAttribute(VALUE, "${jqlocale}"); ifElement.appendChild(outElement); varElement.appendChild(ifElement); ifElement = docTagx.createElement("c:if"); ifElement.setAttribute("test", "${fn:length(jqlocale) gt 2}"); outElement = docTagx.createElement("c:out"); outElement.setAttribute(VALUE, "${fn:substringBefore(jqlocale, '_')}"); outElement.setAttribute("default", "en"); ifElement.appendChild(outElement); varElement.appendChild(ifElement); ifElement = docTagx.createElement("c:if"); ifElement.setAttribute("test", "${fn:length(jqlocale) lt 2}"); outElement = docTagx.createElement("c:out"); outElement.setAttribute(VALUE, "en"); ifElement.appendChild(outElement); varElement.appendChild(ifElement); root.appendChild(varElement); return true; } return false; }
From source file:com.microsoft.windowsazure.management.compute.DNSServerOperationsImpl.java
/** * Add a definition for a DNS server to an existing deployment. VM's in this * deployment will be programmed to use this DNS server for all DNS * resolutions/*from www. j a v a2 s . c o m*/ * * @param serviceName Required. The name of the service. * @param deploymentName Required. The name of the deployment. * @param parameters Required. Parameters supplied to the Add DNS Server * 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. * @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 error information regarding the failure. */ @Override public OperationStatusResponse beginAddingDNSServer(String serviceName, String deploymentName, DNSAddParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { // Validate if (serviceName == null) { throw new NullPointerException("serviceName"); } if (deploymentName == null) { throw new NullPointerException("deploymentName"); } 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("serviceName", serviceName); tracingParameters.put("deploymentName", deploymentName); tracingParameters.put("parameters", parameters); CloudTracing.enter(invocationId, this, "beginAddingDNSServerAsync", tracingParameters); } // Construct URL String url = ""; url = url + "/"; if (this.getClient().getCredentials().getSubscriptionId() != null) { url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8"); } url = url + "/services/hostedservices/"; url = url + URLEncoder.encode(serviceName, "UTF-8"); url = url + "/deployments/"; url = url + URLEncoder.encode(deploymentName, "UTF-8"); url = url + "/dnsservers"; String baseUrl = this.getClient().getBaseUri().toString(); // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl.charAt(baseUrl.length() - 1) == '/') { baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); } if (url.charAt(0) == '/') { url = url.substring(1); } url = baseUrl + "/" + url; url = url.replace(" ", "%20"); // Create HTTP transport objects HttpPost httpRequest = new HttpPost(url); // Set Headers httpRequest.setHeader("Content-Type", "application/xml"); httpRequest.setHeader("x-ms-version", "2015-04-01"); // Serialize Request String requestContent = null; DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document requestDoc = documentBuilder.newDocument(); Element dnsServerElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "DnsServer"); requestDoc.appendChild(dnsServerElement); if (parameters.getName() != null) { Element nameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); nameElement.appendChild(requestDoc.createTextNode(parameters.getName())); dnsServerElement.appendChild(nameElement); } if (parameters.getAddress() != null) { Element addressElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Address"); addressElement.appendChild(requestDoc.createTextNode(parameters.getAddress().getHostAddress())); dnsServerElement.appendChild(addressElement); } 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_ACCEPTED) { ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result OperationStatusResponse result = null; // Deserialize Response result = new OperationStatusResponse(); result.setStatusCode(statusCode); if (httpResponse.getHeaders("x-ms-request-id").length > 0) { result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); } if (shouldTrace) { CloudTracing.exit(invocationId, result); } return result; } finally { if (httpResponse != null && httpResponse.getEntity() != null) { httpResponse.getEntity().getContent().close(); } } }
From source file:com.microsoft.windowsazure.management.compute.ServiceCertificateOperationsImpl.java
/** * The Begin Creating Service Certificate operation adds a certificate to a * hosted service. This operation is an asynchronous operation. To * determine whether the management service has finished processing the * request, call Get Operation Status. (see * http://msdn.microsoft.com/en-us/library/windowsazure/ee460817.aspx for * more information)/*from ww w . ja va 2 s . c o m*/ * * @param serviceName Required. The DNS prefix name of your service. * @param parameters Required. Parameters supplied to the Begin Creating * Service Certificate 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. * @return A standard service response including an HTTP status code and * request ID. */ @Override public OperationResponse beginCreating(String serviceName, ServiceCertificateCreateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { // Validate if (serviceName == null) { throw new NullPointerException("serviceName"); } // TODO: Validate serviceName is a valid DNS name. if (parameters == null) { throw new NullPointerException("parameters"); } if (parameters.getCertificateFormat() == null) { throw new NullPointerException("parameters.CertificateFormat"); } if (parameters.getData() == null) { throw new NullPointerException("parameters.Data"); } // Tracing boolean shouldTrace = CloudTracing.getIsEnabled(); String invocationId = null; if (shouldTrace) { invocationId = Long.toString(CloudTracing.getNextInvocationId()); HashMap<String, Object> tracingParameters = new HashMap<String, Object>(); tracingParameters.put("serviceName", serviceName); tracingParameters.put("parameters", parameters); CloudTracing.enter(invocationId, this, "beginCreatingAsync", tracingParameters); } // Construct URL String url = ""; url = url + "/"; if (this.getClient().getCredentials().getSubscriptionId() != null) { url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8"); } url = url + "/services/hostedservices/"; url = url + URLEncoder.encode(serviceName, "UTF-8"); url = url + "/certificates"; String baseUrl = this.getClient().getBaseUri().toString(); // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl.charAt(baseUrl.length() - 1) == '/') { baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); } if (url.charAt(0) == '/') { url = url.substring(1); } url = baseUrl + "/" + url; url = url.replace(" ", "%20"); // Create HTTP transport objects HttpPost httpRequest = new HttpPost(url); // Set Headers httpRequest.setHeader("Content-Type", "application/xml"); httpRequest.setHeader("x-ms-version", "2015-04-01"); // Serialize Request String requestContent = null; DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document requestDoc = documentBuilder.newDocument(); Element certificateFileElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "CertificateFile"); requestDoc.appendChild(certificateFileElement); Element dataElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Data"); dataElement.appendChild(requestDoc.createTextNode(Base64.encode(parameters.getData()))); certificateFileElement.appendChild(dataElement); Element certificateFormatElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "CertificateFormat"); certificateFormatElement.appendChild(requestDoc.createTextNode( ComputeManagementClientImpl.certificateFormatToString(parameters.getCertificateFormat()))); certificateFileElement.appendChild(certificateFormatElement); if (parameters.getPassword() != null) { Element passwordElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Password"); passwordElement.appendChild(requestDoc.createTextNode(parameters.getPassword())); certificateFileElement.appendChild(passwordElement); } 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_ACCEPTED) { ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result OperationResponse result = null; // Deserialize Response result = new OperationResponse(); result.setStatusCode(statusCode); if (httpResponse.getHeaders("x-ms-request-id").length > 0) { result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); } if (shouldTrace) { CloudTracing.exit(invocationId, result); } return result; } finally { if (httpResponse != null && httpResponse.getEntity() != null) { httpResponse.getEntity().getContent().close(); } } }
From source file:com.microsoft.windowsazure.management.compute.DNSServerOperationsImpl.java
/** * Updates a definition for an existing DNS server. Updates to address is * the only change allowed. DNS server name cannot be changed * * @param serviceName Required. The name of the service. * @param deploymentName Required. The name of the deployment. * @param dnsServerName Required. The name of the dns server. * @param parameters Required. Parameters supplied to the Update DNS Server * operation./*from w ww .j a v a 2s . c om*/ * @throws ParserConfigurationException Thrown if there was an error * configuring the parser for the response body. * @throws SAXException Thrown if there was an error parsing the response * body. * @throws TransformerException Thrown if there was an error creating the * DOM transformer. * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations. * @throws ServiceException Thrown if an unexpected response is found. * @return The 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 error information regarding the failure. */ @Override public OperationStatusResponse beginUpdatingDNSServer(String serviceName, String deploymentName, String dnsServerName, DNSUpdateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { // Validate if (serviceName == null) { throw new NullPointerException("serviceName"); } if (deploymentName == null) { throw new NullPointerException("deploymentName"); } if (dnsServerName == null) { throw new NullPointerException("dnsServerName"); } 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("serviceName", serviceName); tracingParameters.put("deploymentName", deploymentName); tracingParameters.put("dnsServerName", dnsServerName); tracingParameters.put("parameters", parameters); CloudTracing.enter(invocationId, this, "beginUpdatingDNSServerAsync", tracingParameters); } // Construct URL String url = ""; url = url + "/"; if (this.getClient().getCredentials().getSubscriptionId() != null) { url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8"); } url = url + "/services/hostedservices/"; url = url + URLEncoder.encode(serviceName, "UTF-8"); url = url + "/deployments/"; url = url + URLEncoder.encode(deploymentName, "UTF-8"); url = url + "/dnsservers/"; url = url + URLEncoder.encode(dnsServerName, "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", "2015-04-01"); // Serialize Request String requestContent = null; DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document requestDoc = documentBuilder.newDocument(); Element dnsServerElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "DnsServer"); requestDoc.appendChild(dnsServerElement); if (parameters.getName() != null) { Element nameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); nameElement.appendChild(requestDoc.createTextNode(parameters.getName())); dnsServerElement.appendChild(nameElement); } if (parameters.getAddress() != null) { Element addressElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Address"); addressElement.appendChild(requestDoc.createTextNode(parameters.getAddress().getHostAddress())); dnsServerElement.appendChild(addressElement); } 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_ACCEPTED) { ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result OperationStatusResponse result = null; // Deserialize Response result = new OperationStatusResponse(); 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.network.IPForwardingOperationsImpl.java
/** * Sets IP Forwarding on a role./*from w ww .j av a 2 s. c om*/ * * @param serviceName Required. * @param deploymentName Required. * @param roleName Required. * @param parameters Required. Parameters supplied to the Set IP Forwarding * on role 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. * @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 beginSettingIPForwardingOnRole(String serviceName, String deploymentName, String roleName, IPForwardingSetParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { // Validate if (serviceName == null) { throw new NullPointerException("serviceName"); } if (deploymentName == null) { throw new NullPointerException("deploymentName"); } if (roleName == null) { throw new NullPointerException("roleName"); } if (parameters == null) { throw new NullPointerException("parameters"); } if (parameters.getState() == null) { throw new NullPointerException("parameters.State"); } // Tracing boolean shouldTrace = CloudTracing.getIsEnabled(); String invocationId = null; if (shouldTrace) { invocationId = Long.toString(CloudTracing.getNextInvocationId()); HashMap<String, Object> tracingParameters = new HashMap<String, Object>(); tracingParameters.put("serviceName", serviceName); tracingParameters.put("deploymentName", deploymentName); tracingParameters.put("roleName", roleName); tracingParameters.put("parameters", parameters); CloudTracing.enter(invocationId, this, "beginSettingIPForwardingOnRoleAsync", tracingParameters); } // Construct URL String url = ""; url = url + "/"; if (this.getClient().getCredentials().getSubscriptionId() != null) { url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8"); } url = url + "/services/hostedservices/"; url = url + URLEncoder.encode(serviceName, "UTF-8"); url = url + "/deployments/"; url = url + URLEncoder.encode(deploymentName, "UTF-8"); url = url + "/roles/"; url = url + URLEncoder.encode(roleName, "UTF-8"); url = url + "/ipforwarding"; String baseUrl = this.getClient().getBaseUri().toString(); // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl.charAt(baseUrl.length() - 1) == '/') { baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); } if (url.charAt(0) == '/') { url = url.substring(1); } url = baseUrl + "/" + url; url = url.replace(" ", "%20"); // Create HTTP transport objects HttpPost httpRequest = new HttpPost(url); // Set Headers httpRequest.setHeader("Content-Type", "application/xml"); httpRequest.setHeader("x-ms-version", "2015-04-01"); // Serialize Request String requestContent = null; DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document requestDoc = documentBuilder.newDocument(); Element iPForwardingElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "IPForwarding"); requestDoc.appendChild(iPForwardingElement); Element stateElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "State"); stateElement.appendChild(requestDoc.createTextNode(parameters.getState())); iPForwardingElement.appendChild(stateElement); 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_ACCEPTED) { ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result OperationStatusResponse result = null; // Deserialize Response result = new OperationStatusResponse(); 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.network.IPForwardingOperationsImpl.java
/** * Sets IP Forwarding on a network interface. * * @param serviceName Required.//from w w w .j a v a2 s. c om * @param deploymentName Required. * @param roleName Required. * @param networkInterfaceName Required. * @param parameters Required. Parameters supplied to the Set IP Forwarding * on network interface 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. * @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 beginSettingIPForwardingOnNetworkInterface(String serviceName, String deploymentName, String roleName, String networkInterfaceName, IPForwardingSetParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { // Validate if (serviceName == null) { throw new NullPointerException("serviceName"); } if (deploymentName == null) { throw new NullPointerException("deploymentName"); } if (roleName == null) { throw new NullPointerException("roleName"); } if (networkInterfaceName == null) { throw new NullPointerException("networkInterfaceName"); } if (parameters == null) { throw new NullPointerException("parameters"); } if (parameters.getState() == null) { throw new NullPointerException("parameters.State"); } // Tracing boolean shouldTrace = CloudTracing.getIsEnabled(); String invocationId = null; if (shouldTrace) { invocationId = Long.toString(CloudTracing.getNextInvocationId()); HashMap<String, Object> tracingParameters = new HashMap<String, Object>(); tracingParameters.put("serviceName", serviceName); tracingParameters.put("deploymentName", deploymentName); tracingParameters.put("roleName", roleName); tracingParameters.put("networkInterfaceName", networkInterfaceName); tracingParameters.put("parameters", parameters); CloudTracing.enter(invocationId, this, "beginSettingIPForwardingOnNetworkInterfaceAsync", tracingParameters); } // Construct URL String url = ""; url = url + "/"; if (this.getClient().getCredentials().getSubscriptionId() != null) { url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8"); } url = url + "/services/hostedservices/"; url = url + URLEncoder.encode(serviceName, "UTF-8"); url = url + "/deployments/"; url = url + URLEncoder.encode(deploymentName, "UTF-8"); url = url + "/roles/"; url = url + URLEncoder.encode(roleName, "UTF-8"); url = url + "/networkinterfaces/"; url = url + URLEncoder.encode(networkInterfaceName, "UTF-8"); url = url + "/ipforwarding"; String baseUrl = this.getClient().getBaseUri().toString(); // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl.charAt(baseUrl.length() - 1) == '/') { baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); } if (url.charAt(0) == '/') { url = url.substring(1); } url = baseUrl + "/" + url; url = url.replace(" ", "%20"); // Create HTTP transport objects HttpPost httpRequest = new HttpPost(url); // Set Headers httpRequest.setHeader("Content-Type", "application/xml"); httpRequest.setHeader("x-ms-version", "2015-04-01"); // Serialize Request String requestContent = null; DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document requestDoc = documentBuilder.newDocument(); Element iPForwardingElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "IPForwarding"); requestDoc.appendChild(iPForwardingElement); Element stateElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "State"); stateElement.appendChild(requestDoc.createTextNode(parameters.getState())); iPForwardingElement.appendChild(stateElement); 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_ACCEPTED) { ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result OperationStatusResponse result = null; // Deserialize Response result = new OperationStatusResponse(); 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.twinsoft.convertigo.engine.util.CarUtils.java
private static Document exportProject(Project project, final List<TestCase> selectedTestCases) throws EngineException { try {//from w w w. ja va 2s.co m final Document document = XMLUtils.getDefaultDocumentBuilder().newDocument(); // ProcessingInstruction pi = document.createProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF-8\""); // document.appendChild(pi); final Element rootElement = document.createElement("convertigo"); rootElement.setAttribute("version", com.twinsoft.convertigo.engine.Version.fullProductVersion); rootElement.setAttribute("engine", com.twinsoft.convertigo.engine.Version.version); rootElement.setAttribute("beans", com.twinsoft.convertigo.beans.Version.version); String studioVersion = ""; try { Class<?> c = Class.forName("com.twinsoft.convertigo.eclipse.Version"); studioVersion = (String) c.getDeclaredField("version").get(null); } catch (Exception e) { } catch (Throwable th) { } rootElement.setAttribute("studio", studioVersion); document.appendChild(rootElement); new WalkHelper() { protected Element parentElement = rootElement; @Override protected void walk(DatabaseObject databaseObject) throws Exception { Element parentElement = this.parentElement; Element element = parentElement; element = databaseObject.toXml(document); String name = " : " + databaseObject.getName(); try { name = CachedIntrospector.getBeanInfo(databaseObject.getClass()).getBeanDescriptor() .getDisplayName() + name; } catch (IntrospectionException e) { name = databaseObject.getClass().getSimpleName() + name; } Integer depth = (Integer) document.getUserData("depth"); if (depth == null) { depth = 0; } String openpad = StringUtils.repeat(" ", depth); String closepad = StringUtils.repeat(" ", depth); parentElement.appendChild(document.createTextNode("\n")); parentElement.appendChild( document.createComment(StringUtils.rightPad(openpad + "<" + name + ">", 150))); if (databaseObject instanceof TestCase && selectedTestCases.size() > 0) { if (selectedTestCases.contains((TestCase) databaseObject)) { parentElement.appendChild(element); } } else { parentElement.appendChild(element); } document.setUserData("depth", depth + 1, null); this.parentElement = element; super.walk(databaseObject); element.appendChild(document.createTextNode("\n")); element.appendChild( document.createComment(StringUtils.rightPad(closepad + "</" + name + ">", 150))); document.setUserData("depth", depth, null); databaseObject.hasChanged = false; databaseObject.bNew = false; this.parentElement = parentElement; } }.init(project); return document; } catch (Exception e) { throw new EngineException("Unable to export the project \"" + project.getName() + "\".", e); } }