List of usage examples for javax.xml.parsers DocumentBuilder newDocument
public abstract Document newDocument();
From source file:com.rest4j.generator.Generator.java
public void generate() throws Exception { ApiFactory fac = new ApiFactory(apiXml, null, null); for (String className : preprocessors) { Preprocessor p = (Preprocessor) Class.forName(className).newInstance(); fac.addPreprocessor(p);//from w ww . j a va 2 s .c om } Document xml = fac.getDocument(); preprocess(xml); URL url = getStylesheet(); String filename = "index.html"; for (TemplateParam param : params) { if (param.getName().equals("filename")) { filename = param.getValue(); } } Document doc = transform(xml, url); cleanupBeforePostprocess(doc.getDocumentElement()); if (postprocessingXSLT != null) { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document composed = documentBuilder.newDocument(); org.w3c.dom.Element top = composed.createElementNS("http://rest4j.com/api-description", "top"); composed.appendChild(top); top.appendChild(composed.adoptNode(xml.getDocumentElement())); top.appendChild(composed.adoptNode(doc.getDocumentElement())); xml = null; doc = null; // free some mem doc = transform(composed, postprocessingXSLT); } if ("files".equals(doc.getDocumentElement().getLocalName())) { // break the result into files for (Node child : Util.it(doc.getDocumentElement().getChildNodes())) { if ("file".equals(child.getLocalName())) { if (child.getAttributes().getNamedItem("name") == null) { throw new IllegalArgumentException("Attribute name not found in <file>"); } String name = child.getAttributes().getNamedItem("name").getTextContent(); File file = new File(outputDir, name); file.getParentFile().mkdirs(); System.out.println("Write " + file.getAbsolutePath()); Attr copyFromAttr = (Attr) child.getAttributes().getNamedItem("copy-from"); if (copyFromAttr == null) { cleanupFinal((Element) child); if (child.getAttributes().getNamedItem("text") != null) { // plain-text output FileOutputStream fos = new FileOutputStream(file); try { IOUtils.write(child.getTextContent(), fos, "UTF-8"); } finally { IOUtils.closeQuietly(fos); } } else { output(child, file); } } else { String copyFrom = copyFromAttr.getValue(); URL asset = getClass().getClassLoader().getResource(copyFrom); if (asset == null) { asset = getClass().getResource(copyFrom); } if (asset == null) { File assetFile = new File(copyFrom); if (!assetFile.canRead()) { if (postprocessingXSLT != null) { asset = new URL(postprocessingXSLT, copyFrom); try { asset.openStream().close(); } catch (FileNotFoundException fnfe) { asset = null; } } if (asset == null) { asset = new URL(getStylesheet(), copyFrom); try { asset.openStream().close(); } catch (FileNotFoundException fnfe) { asset = null; } } if (asset == null) throw new IllegalArgumentException("File '" + copyFrom + "' specified by @copy-from not found in the classpath or filesystem"); } else { asset = assetFile.toURI().toURL(); } } InputStream is = asset.openStream(); OutputStream fos = new FileOutputStream(file); try { IOUtils.copy(is, fos); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(fos); } } } else if (child.getNodeType() == Node.ELEMENT_NODE) { throw new IllegalArgumentException("Something but <file> found inside <files>"); } } } else { File file = new File(outputDir, filename); System.out.println("Write " + file.getAbsolutePath()); cleanupFinal(doc.getDocumentElement()); DOMSource source = new DOMSource(doc); FileOutputStream fos = new FileOutputStream(file); try { StreamResult result = new StreamResult(fos); Transformer trans = tFactory.newTransformer(); trans.transform(source, result); } finally { IOUtils.closeQuietly(fos); } } }
From source file:edu.clemson.lph.civet.xml.StdeCviXmlBuilder.java
public StdeCviXmlBuilder(StdeCviXml cviIn) { try {//from w w w .java 2 s . c o m if (cviIn != null) { doc = cviIn.getDocument(); doc.setXmlStandalone(true); helper = cviIn.getHelper(); root = cviIn.getRoot(); } if (doc == null) { DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); doc = db.newDocument(); doc.setXmlStandalone(true); root = doc.createElementNS("http://www.usaha.org/xmlns/ecvi", "eCVI"); doc.appendChild(root); helper = new XMLDocHelper(doc); } } catch (ParserConfigurationException e) { logger.error("Could not set up parser for stdXML", e); } }
From source file:com.appdynamics.connectors.vcd.VappClient.java
public IMachine createVm(IImage image, IMachineDescriptor machineDescriptor, IComputeCenter computeCenter) throws ConnectorException { String vmName = createName(Utils.VM_PREFIX); try {/*www.j a va2 s . co m*/ // // Getting appropriate information for creating recompose body // String response = doGet(vAppLink); Document doc = RestClient.stringToXmlDocument(response); Element childrenElement = (Element) doc.getElementsByTagName(Constants.CHILDREN).item(0); Element vmElement = (Element) childrenElement.getElementsByTagName(Constants.VM).item(0); String vmType = vmElement.getAttribute(Constants.TYPE); String vmRef = vmElement.getAttribute(Constants.HREF); // // Create RecomposeVAppParams body // DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); doc = docBuilder.newDocument(); Element rootElement = doc.createElement(Constants.RECOMPOSE_VAPP); doc.appendChild(rootElement); rootElement.setAttribute("name", getvAppName()); rootElement.setAttribute("xmlns", Constants.XMLNS); rootElement.setAttribute("xmlns:xsi", Constants.XMLNS_XSI); rootElement.setAttribute("xmlns:ovf", Constants.XMLNS_OVF); Element sourcedItem = doc.createElement(Constants.SOURCED_ITEM); sourcedItem.setAttribute(Constants.SOURCE_DELETE, "false"); Element source = doc.createElement(Constants.SOURCE); source.setAttribute(Constants.TYPE, vmType); source.setAttribute(Constants.NAME, vmName); source.setAttribute(Constants.HREF, vmRef); sourcedItem.appendChild(source); rootElement.appendChild(sourcedItem); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); DOMSource dSource = new DOMSource(doc); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); transformer.transform(dSource, result); String xmlBody = writer.toString(); // // sending a POST request // StringEntity entity = new StringEntity(xmlBody); entity.setContentType(Constants.RECOMPOSE_VAPP_LINK); String createResponse = doPost(vAppLink + Constants.RECOMPOSE_ACTION, entity); IMachine machine = controllerServices.createMachineInstance(vmName, vmName, computeCenter, machineDescriptor, image, controllerServices.getDefaultAgentPort()); return machine; } catch (Exception e) { throw new ConnectorException(e.getMessage()); } }
From source file:com.evolveum.midpoint.prism.marshaller.ItemPathHolder.java
public Element toElement(String elementNamespace, String localElementName) { // TODO: is this efficient? try {/* ww w .j ava2 s . c o m*/ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder loader = factory.newDocumentBuilder(); return toElement(elementNamespace, localElementName, loader.newDocument()); } catch (ParserConfigurationException ex) { throw new AssertionError("Error on creating XML document " + ex.getMessage()); } }
From source file:test.integ.be.agiv.security.IPSTSTest.java
@Test public void testRSTS_JAXWS_Client() throws Exception { ServletTester servletTester = new ServletTester(); servletTester.addServlet(MyTestServlet.class, "/"); Security.addProvider(new BouncyCastleProvider()); KeyPair keyPair = generateKeyPair(); DateTime notBefore = new DateTime(); DateTime notAfter = notBefore.plusMonths(1); X509Certificate certificate = generateSelfSignedCertificate(keyPair, "CN=localhost", notBefore, notAfter); File tmpP12File = File.createTempFile("ssl-", ".p12"); LOG.debug("p12 file: " + tmpP12File.getAbsolutePath()); persistKey(tmpP12File, keyPair.getPrivate(), certificate, "secret".toCharArray(), "secret".toCharArray()); SslSocketConnector sslSocketConnector = new SslSocketConnector(); sslSocketConnector.setKeystore(tmpP12File.getAbsolutePath()); sslSocketConnector.setTruststore(tmpP12File.getAbsolutePath()); sslSocketConnector.setTruststoreType("pkcs12"); sslSocketConnector.setKeystoreType("pkcs12"); sslSocketConnector.setPassword("secret"); sslSocketConnector.setKeyPassword("secret"); sslSocketConnector.setTrustPassword("secret"); sslSocketConnector.setMaxIdleTime(30000); int sslPort = getFreePort(); sslSocketConnector.setPort(sslPort); servletTester.getContext().getServer().addConnector(sslSocketConnector); String sslLocation = "https://localhost:" + sslPort + "/"; servletTester.start();//from w ww .j ava2s . com String location = servletTester.createSocketConnector(true); SSLContext sslContext = SSLContext.getInstance("TLS"); TrustManager trustManager = new TestTrustManager(certificate); sslContext.init(null, new TrustManager[] { trustManager }, null); SSLContext.setDefault(sslContext); try { LOG.debug("running R-STS test..."); RSTSClient client = new RSTSClient(sslLocation); SecurityToken inputSecurityToken = new SecurityToken(); byte[] key = new byte[256 / 8]; SecureRandom random = new SecureRandom(); random.nextBytes(key); inputSecurityToken.setKey(key); inputSecurityToken.setAttachedReference("_" + UUID.randomUUID().toString()); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.newDocument(); Element tokenElement = document.createElement("Token"); tokenElement.setTextContent("hello world"); inputSecurityToken.setToken(tokenElement); client.getSecurityToken(inputSecurityToken, "https://auth.beta.agiv.be/ClaimsAwareService/Service.svc"); } finally { servletTester.stop(); } }
From source file:com.evolveum.midpoint.prism.schema.SchemaToDomProcessor.java
/** * Create schema XSD DOM document.// ww w . j av a 2 s . c om */ private void init() throws ParserConfigurationException { if (namespacePrefixMapper == null) { // TODO: clone? namespacePrefixMapper = prismContext.getSchemaRegistry().getNamespacePrefixMapper(); } // We don't want the "tns" prefix to be kept in the mapper namespacePrefixMapper = namespacePrefixMapper.clone(); namespacePrefixMapper.registerPrefixLocal(getNamespace(), "tns"); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Using namespace prefix mapper to serialize schema:\n{}", DebugUtil.dump(namespacePrefixMapper)); } DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setValidating(false); DocumentBuilder db = dbf.newDocumentBuilder(); document = db.newDocument(); Element root = createElement(new QName(W3C_XML_SCHEMA_NS_URI, "schema")); document.appendChild(root); rootXsdElement = document.getDocumentElement(); setAttribute(rootXsdElement, "targetNamespace", getNamespace()); setAttribute(rootXsdElement, "elementFormDefault", "qualified"); DOMUtil.setNamespaceDeclaration(rootXsdElement, "tns", getNamespace()); if (attributeQualified) { setAttribute(rootXsdElement, "attributeFormDefault", "qualified"); } }
From source file:eu.betaas.service.securitymanager.service.impl.AuthorizationService.java
/** * Check the condition specified in the token with the condition saved in the * GW (concerning the specific thingService) * @param ct: extracted Condition from the token * @param req: RequestCtx (required by XACML API) * @return boolean true or false (true if the condition matches) *//* w ww.j a v a2 s .c om*/ private boolean checkCondition(ConditionType ct, RequestCtx req) { boolean access = false; JAXBElement<ConditionType> jaxbCT = of.createCondition(ct); JAXBContext jc = null; try { jc = JAXBContext.newInstance(ConditionType.class); Marshaller mar = jc.createMarshaller(); // create DOM Document DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.newDocument(); mar.marshal(jaxbCT, doc); // convert ConditionType to XML Node (org.w3c.dom.Node) DOMResult res = new DOMResult(); res.setNode(doc.getDocumentElement()); Node conditionNode = res.getNode(); // prepare for the Condition PolicyMetaData metadata = new PolicyMetaData(2, 0); VariableManager vm = new VariableManager(new HashMap(), metadata); Condition condition = Condition.getInstance(conditionNode, metadata, vm); // evaluate condition -- first convert RequestCtx into EvaluationCtx EvaluationCtx context = new BasicEvaluationCtx(req); EvaluationResult result = condition.evaluate(context); BooleanAttribute bool = (BooleanAttribute) (result.getAttributeValue()); // get the condition evaluation result in boolean access = bool.getValue(); } catch (JAXBException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParsingException e) { // TODO Auto-generated catch block e.printStackTrace(); } log.info("Checking Condition in the Access Right return: " + access); return access; }
From source file:be.fedict.eid.applet.service.signer.AbstractXmlSignatureService.java
@SuppressWarnings("unchecked") private byte[] getXmlSignatureDigestValue(DigestAlgo digestAlgo, List<DigestInfo> digestInfos, List<X509Certificate> signingCertificateChain) throws ParserConfigurationException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, MarshalException, javax.xml.crypto.dsig.XMLSignatureException, TransformerFactoryConfigurationError, TransformerException, IOException, SAXException { /*//from w ww .j a va2 s. co m * DOM Document construction. */ Document document = getEnvelopingDocument(); if (null == document) { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); document = documentBuilder.newDocument(); } /* * Signature context construction. */ Key key = new Key() { private static final long serialVersionUID = 1L; public String getAlgorithm() { return null; } public byte[] getEncoded() { return null; } public String getFormat() { return null; } }; XMLSignContext xmlSignContext = new DOMSignContext(key, document); URIDereferencer uriDereferencer = getURIDereferencer(); if (null != uriDereferencer) { xmlSignContext.setURIDereferencer(uriDereferencer); } if (null != this.signatureNamespacePrefix) { /* * OOo doesn't like ds namespaces so per default prefixing is off. */ xmlSignContext.putNamespacePrefix(javax.xml.crypto.dsig.XMLSignature.XMLNS, this.signatureNamespacePrefix); } XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM", new org.apache.jcp.xml.dsig.internal.dom.XMLDSigRI()); /* * Add ds:References that come from signing client local files. */ List<Reference> references = new LinkedList<Reference>(); addDigestInfosAsReferences(digestInfos, signatureFactory, references); /* * Invoke the signature facets. */ String localSignatureId; if (null == this.signatureId) { localSignatureId = "xmldsig-" + UUID.randomUUID().toString(); } else { localSignatureId = this.signatureId; } List<XMLObject> objects = new LinkedList<XMLObject>(); for (SignatureFacet signatureFacet : this.signatureFacets) { LOG.debug("invoking signature facet: " + signatureFacet.getClass().getSimpleName()); signatureFacet.preSign(signatureFactory, document, localSignatureId, signingCertificateChain, references, objects); } /* * ds:SignedInfo */ SignatureMethod signatureMethod = signatureFactory.newSignatureMethod(getSignatureMethod(digestAlgo), null); CanonicalizationMethod canonicalizationMethod = signatureFactory .newCanonicalizationMethod(getCanonicalizationMethod(), (C14NMethodParameterSpec) null); SignedInfo signedInfo = signatureFactory.newSignedInfo(canonicalizationMethod, signatureMethod, references); /* * JSR105 ds:Signature creation */ String signatureValueId = localSignatureId + "-signature-value"; javax.xml.crypto.dsig.XMLSignature xmlSignature = signatureFactory.newXMLSignature(signedInfo, null, objects, localSignatureId, signatureValueId); /* * ds:Signature Marshalling. */ DOMXMLSignature domXmlSignature = (DOMXMLSignature) xmlSignature; Node documentNode = document.getDocumentElement(); if (null == documentNode) { /* * In case of an empty DOM document. */ documentNode = document; } domXmlSignature.marshal(documentNode, this.signatureNamespacePrefix, (DOMCryptoContext) xmlSignContext); /* * Completion of undigested ds:References in the ds:Manifests. */ for (XMLObject object : objects) { LOG.debug("object java type: " + object.getClass().getName()); List<XMLStructure> objectContentList = object.getContent(); for (XMLStructure objectContent : objectContentList) { LOG.debug("object content java type: " + objectContent.getClass().getName()); if (false == objectContent instanceof Manifest) { continue; } Manifest manifest = (Manifest) objectContent; List<Reference> manifestReferences = manifest.getReferences(); for (Reference manifestReference : manifestReferences) { if (null != manifestReference.getDigestValue()) { continue; } DOMReference manifestDOMReference = (DOMReference) manifestReference; manifestDOMReference.digest(xmlSignContext); } } } /* * Completion of undigested ds:References. */ List<Reference> signedInfoReferences = signedInfo.getReferences(); for (Reference signedInfoReference : signedInfoReferences) { DOMReference domReference = (DOMReference) signedInfoReference; if (null != domReference.getDigestValue()) { // ds:Reference with external digest value continue; } domReference.digest(xmlSignContext); } /* * Store the intermediate XML signature document. */ TemporaryDataStorage temporaryDataStorage = getTemporaryDataStorage(); OutputStream tempDocumentOutputStream = temporaryDataStorage.getTempOutputStream(); writeDocument(document, tempDocumentOutputStream); temporaryDataStorage.setAttribute(SIGNATURE_ID_ATTRIBUTE, localSignatureId); /* * Calculation of XML signature digest value. */ DOMSignedInfo domSignedInfo = (DOMSignedInfo) signedInfo; ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); domSignedInfo.canonicalize(xmlSignContext, dataStream); byte[] octets = dataStream.toByteArray(); /* * TODO: we could be using DigestOutputStream here to optimize memory * usage. */ MessageDigest jcaMessageDigest = MessageDigest.getInstance(digestAlgo.getAlgoId()); byte[] digestValue = jcaMessageDigest.digest(octets); return digestValue; }
From source file:org.dasein.cloud.terremark.TerremarkMethod.java
public Document invoke(boolean debug) throws TerremarkException, CloudException, InternalException { if (logger.isTraceEnabled()) { logger.trace("ENTER - " + TerremarkMethod.class.getName() + ".invoke(" + debug + ")"); }/* www . j a va2 s . co m*/ try { if (logger.isDebugEnabled()) { logger.debug("Talking to server at " + url); } if (parameters != null) { URIBuilder uri = null; try { uri = new URIBuilder(url); } catch (URISyntaxException e) { e.printStackTrace(); } for (NameValuePair parameter : parameters) { uri.addParameter(parameter.getName(), parameter.getValue()); } url = uri.toString(); } HttpUriRequest method = null; if (methodType.equals(HttpMethodName.GET)) { method = new HttpGet(url); } else if (methodType.equals(HttpMethodName.POST)) { method = new HttpPost(url); } else if (methodType.equals(HttpMethodName.DELETE)) { method = new HttpDelete(url); } else if (methodType.equals(HttpMethodName.PUT)) { method = new HttpPut(url); } else if (methodType.equals(HttpMethodName.HEAD)) { method = new HttpHead(url); } else { method = new HttpGet(url); } HttpResponse status = null; try { HttpClient client = new DefaultHttpClient(); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); HttpProtocolParams.setUserAgent(params, "Dasein Cloud"); attempts++; String proxyHost = provider.getProxyHost(); if (proxyHost != null) { int proxyPort = provider.getProxyPort(); boolean ssl = url.startsWith("https"); params.setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxyHost, proxyPort, ssl ? "https" : "http")); } for (Map.Entry<String, String> entry : headers.entrySet()) { method.addHeader(entry.getKey(), entry.getValue()); } if (body != null && body != "" && (methodType.equals(HttpMethodName.PUT) || methodType.equals(HttpMethodName.POST))) { try { HttpEntity entity = new StringEntity(body, "UTF-8"); ((HttpEntityEnclosingRequestBase) method).setEntity(entity); } catch (UnsupportedEncodingException e) { logger.warn(e); } } if (wire.isDebugEnabled()) { wire.debug(methodType.name() + " " + method.getURI()); for (Header header : method.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } if (body != null) { wire.debug(body); } } try { status = client.execute(method); if (wire.isDebugEnabled()) { wire.debug("HTTP STATUS: " + status); } } catch (IOException e) { logger.error("I/O error from server communications: " + e.getMessage()); e.printStackTrace(); throw new InternalException(e); } int statusCode = status.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED || statusCode == HttpStatus.SC_ACCEPTED) { try { InputStream input = status.getEntity().getContent(); try { return parseResponse(input); } finally { input.close(); } } catch (IOException e) { logger.error("Error parsing response from Teremark: " + e.getMessage()); e.printStackTrace(); throw new CloudException(CloudErrorType.COMMUNICATION, statusCode, null, e.getMessage()); } } else if (statusCode == HttpStatus.SC_NO_CONTENT) { logger.debug("Recieved no content in response. Creating an empty doc."); DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = null; try { docBuilder = dbfac.newDocumentBuilder(); } catch (ParserConfigurationException e) { e.printStackTrace(); } return docBuilder.newDocument(); } else if (statusCode == HttpStatus.SC_FORBIDDEN) { String msg = "OperationNotAllowed "; try { msg += parseResponseToString(status.getEntity().getContent()); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } wire.error(msg); throw new TerremarkException(statusCode, "OperationNotAllowed", msg); } else { String response = "Failed to parse response."; ParsedError parsedError = null; try { response = parseResponseToString(status.getEntity().getContent()); parsedError = parseErrorResponse(response); } catch (IllegalStateException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } if (logger.isDebugEnabled()) { logger.debug("Received " + status + " from " + url); } if (statusCode == HttpStatus.SC_SERVICE_UNAVAILABLE || statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR) { if (attempts >= 5) { String msg; wire.warn(response); if (statusCode == HttpStatus.SC_SERVICE_UNAVAILABLE) { msg = "Cloud service is currently unavailable."; } else { msg = "The cloud service encountered a server error while processing your request."; try { msg = msg + "Response from server was:\n" + response; } catch (RuntimeException runException) { logger.warn(runException); } catch (Error error) { logger.warn(error); } } wire.error(response); logger.error(msg); if (parsedError != null) { throw new TerremarkException(parsedError); } else { throw new CloudException("HTTP Status " + statusCode + msg); } } else { try { Thread.sleep(5000L); } catch (InterruptedException e) { /* ignore */ } return invoke(); } } wire.error(response); if (parsedError != null) { throw new TerremarkException(parsedError); } else { String msg = "\nResponse from server was:\n" + response; logger.error(msg); throw new CloudException("HTTP Status " + statusCode + msg); } } } finally { try { if (status != null) { EntityUtils.consume(status.getEntity()); } } catch (IOException e) { e.printStackTrace(); } } } finally { if (logger.isTraceEnabled()) { logger.trace("EXIT - " + TerremarkMethod.class.getName() + ".invoke()"); } } }
From source file:com.appdynamics.connectors.vcd.VappClient.java
public String newvAppFromTemplate(String vAppName, String templateLink, String catalogLink, String vdcLink, String network) throws Exception { // Step 1// w ww . j av a2s. c om String response = doGet(templateLink); // Step 2 - look for NetowrkConnection element in the Vms contained Document doc = RestClient.stringToXmlDocument(response); Element childrenElement = (Element) doc.getElementsByTagName(Constants.CHILDREN).item(0); Element vmElement = (Element) childrenElement.getElementsByTagName(Constants.VM).item(0); Element netElement = (Element) vmElement.getElementsByTagName("NetworkConnectionSection").item(0); String ovfInfo = doc.getElementsByTagName("ovf:Info").item(0).getTextContent(); String networkName = netElement.getElementsByTagName("NetworkConnection").item(0).getAttributes() .getNamedItem("network").getTextContent().trim(); String vdcResponse = doGet(vdcLink); String parentNetwork; if (network.isEmpty()) { parentNetwork = findElement(vdcResponse, Constants.NETWORK, Constants.NETWORK_LINK, null); } else { parentNetwork = findElement(vdcResponse, Constants.NETWORK, Constants.NETWORK_LINK, network); } // Step 3 - create an InstantiateVAppTemplate Params element DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); // root elements doc = docBuilder.newDocument(); Element rootElement = doc.createElement("InstantiateVAppTemplateParams"); doc.appendChild(rootElement); rootElement.setAttribute("name", vAppName); rootElement.setAttribute("xmlns", Constants.XMLNS); rootElement.setAttribute("deploy", "true"); rootElement.setAttribute("powerOn", "false"); rootElement.setAttribute("xmlns:xsi", Constants.XMLNS_XSI); rootElement.setAttribute("xmlns:ovf", Constants.XMLNS_OVF); Element descElement = doc.createElement("Description"); descElement.appendChild(doc.createTextNode("Created through Appdynamics controller")); rootElement.appendChild(descElement); Element paramsElement = doc.createElement("InstantiationParams"); Element configElement = doc.createElement("Configuration"); Element parentNetElement = doc.createElement("ParentNetwork"); parentNetElement.setAttribute("href", parentNetwork); configElement.appendChild(parentNetElement); Element fenceElement = doc.createElement("FenceMode"); fenceElement.appendChild(doc.createTextNode("bridged")); configElement.appendChild(fenceElement); Element netconfigSectionElement = doc.createElement("NetworkConfigSection"); Element ovfInfoElement = doc.createElement("ovf:Info"); ovfInfoElement.appendChild(doc.createTextNode(ovfInfo)); netconfigSectionElement.appendChild(ovfInfoElement); Element netConfElement = doc.createElement("NetworkConfig"); netConfElement.setAttribute("networkName", networkName); netConfElement.appendChild(configElement); netconfigSectionElement.appendChild(netConfElement); paramsElement.appendChild(netconfigSectionElement); rootElement.appendChild(paramsElement); Element sourceElement = doc.createElement("Source"); sourceElement.setAttribute("href", templateLink); rootElement.appendChild(sourceElement); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); DOMSource source = new DOMSource(doc); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); transformer.transform(source, result); String xmlBody = writer.toString(); // Step 4 - make a POST String instantiateVAppLink = findElement(vdcResponse, Constants.LINK, Constants.INSTANTIATE_VAPP, null); StringEntity entity = new StringEntity(xmlBody); entity.setContentType(Constants.INSTANTIATE_VAPP); return doPost(instantiateVAppLink, entity); }