List of usage examples for org.w3c.dom Document createTextNode
public Text createTextNode(String data);
Text
node given the specified string. From source file:fitnesse.wiki.WikiPageProperties.java
private void toXml(WikiPageProperty context, String key, Document document, Element parent) { Element element = document.createElement(key); String value = context.getValue(); if (context.hasChildren()) { if (value != null) element.setAttribute("value", value); Set<String> childKeys = context.keySet(); for (String childKey : childKeys) { WikiPageProperty child = context.getProperty(childKey); if (child == null) { System.err.println("Property key \"" + childKey + "\" has null value for {" + context + "}"); } else { toXml(child, childKey, document, element); }/*from www . j a va2 s . c o m*/ } } else if (value != null) element.appendChild(document.createTextNode(Utils.escapeHTML(value))); parent.appendChild(element); }
From source file:com.twinsoft.convertigo.engine.Context.java
public Node addTextNode(Node parentNode, String tagName, String text) { Document doc = parentNode.getOwnerDocument(); Element newElement = doc.createElement(tagName); if (text != null) { Text textElement = doc.createTextNode(text); newElement.appendChild(textElement); }// www .ja va2 s .c o m parentNode.appendChild(newElement); return newElement; }
From source file:net.sourceforge.eclipsetrader.ats.Repository.java
void saveStrategy(Strategy obj, Document document, Element root) { Element element = document.createElement("strategy"); element.setAttribute("id", String.valueOf(obj.getId())); if (obj.getPluginId() != null) element.setAttribute("pluginId", obj.getPluginId()); element.setAttribute("autostart", obj.isAutoStart() ? "true" : "false"); root.appendChild(element);//w w w .java 2 s . c o m if (obj.getName() != null) { Element node = document.createElement("name"); node.appendChild(document.createTextNode(obj.getName())); element.appendChild(node); } if (obj.getMarketManager() != null) { Element node = document.createElement("marketManager"); saveComponent(obj.getMarketManager(), document, node); element.appendChild(node); } if (obj.getEntry() != null) { Element node = document.createElement("entry"); saveComponent(obj.getEntry(), document, node); element.appendChild(node); } if (obj.getExit() != null) { Element node = document.createElement("exit"); saveComponent(obj.getExit(), document, node); element.appendChild(node); } if (obj.getMoneyManager() != null) { Element node = document.createElement("moneyManager"); saveComponent(obj.getMoneyManager(), document, node); element.appendChild(node); } for (Iterator iter = obj.getSecurities().iterator(); iter.hasNext();) { Element node = document.createElement("security"); node.setAttribute("id", String.valueOf(((Security) iter.next()).getId())); element.appendChild(node); } for (Iterator paramIter = obj.getParams().keySet().iterator(); paramIter.hasNext();) { String key = (String) paramIter.next(); Element node = document.createElement("param"); node.setAttribute("key", key); node.setAttribute("value", (String) obj.getParams().get(key)); element.appendChild(node); } }
From source file:com.limegroup.gnutella.archive.ArchiveContribution.java
/** * @throws IllegalStateException/*from ww w . j a va 2s .c o m*/ * If java's xml parser configuration is bad */ private Document getMetaDocument() { /* * Sample _meta.xml file: * * <metadata> * <collection>opensource_movies</collection> * <mediatype>movies</mediatype> * <title>My Home Movie</title> * <runtime>2:30</runtime> * <director>Joe Producer</director> * </metadata> * */ final String METADATA_ELEMENT = "metadata"; final String COLLECTION_ELEMENT = "collection"; final String MEDIATYPE_ELEMENT = "mediatype"; final String TITLE_ELEMENT = "title"; final String DESCRIPTION_ELEMENT = "description"; final String LICENSE_URL_ELEMENT = "licenseurl"; final String UPLOAD_APPLICATION_ELEMENT = "upload_application"; final String APPID_ATTR = "appid"; final String APPID_ATTR_VALUE = "LimeWire"; final String VERSION_ATTR = "version"; final String UPLOADER_ELEMENT = "uploader"; final String IDENTIFIER_ELEMENT = "identifier"; final String TYPE_ELEMENT = "type"; try { final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); final DocumentBuilder db = dbf.newDocumentBuilder(); final Document document = db.newDocument(); final Element metadataElement = document.createElement(METADATA_ELEMENT); document.appendChild(metadataElement); final Element collectionElement = document.createElement(COLLECTION_ELEMENT); metadataElement.appendChild(collectionElement); collectionElement.appendChild(document.createTextNode(Archives.getCollectionString(getCollection()))); final Element mediatypeElement = document.createElement(MEDIATYPE_ELEMENT); metadataElement.appendChild(mediatypeElement); mediatypeElement.appendChild(document.createTextNode(Archives.getMediaString(getMedia()))); final Element typeElement = document.createElement(TYPE_ELEMENT); metadataElement.appendChild(typeElement); typeElement.appendChild(document.createTextNode(Archives.getTypeString(getType()))); final Element titleElement = document.createElement(TITLE_ELEMENT); metadataElement.appendChild(titleElement); titleElement.appendChild(document.createTextNode(getTitle())); final Element descriptionElement = document.createElement(DESCRIPTION_ELEMENT); metadataElement.appendChild(descriptionElement); descriptionElement.appendChild(document.createTextNode(getDescription())); final Element identifierElement = document.createElement(IDENTIFIER_ELEMENT); metadataElement.appendChild(identifierElement); identifierElement.appendChild(document.createTextNode(getIdentifier())); final Element uploadApplicationElement = document.createElement(UPLOAD_APPLICATION_ELEMENT); metadataElement.appendChild(uploadApplicationElement); uploadApplicationElement.setAttribute(APPID_ATTR, APPID_ATTR_VALUE); uploadApplicationElement.setAttribute(VERSION_ATTR, CommonUtils.getLimeWireVersion()); final Element uploaderElement = document.createElement(UPLOADER_ELEMENT); metadataElement.appendChild(uploaderElement); uploaderElement.appendChild(document.createTextNode(getUsername())); //take licenseurl from the first File final Iterator filesIterator = getFiles().iterator(); if (filesIterator.hasNext()) { final File firstFile = (File) filesIterator.next(); final String licenseUrl = firstFile.getLicenseUrl(); if (licenseUrl != null) { final Element licenseUrlElement = document.createElement(LICENSE_URL_ELEMENT); metadataElement.appendChild(licenseUrlElement); licenseUrlElement.appendChild(document.createTextNode(licenseUrl)); } } // now build user-defined elements final Map userFields = getFields(); for (final Iterator i = userFields.keySet().iterator(); i.hasNext();) { final Object field = i.next(); final Object value = userFields.get(field); if (field instanceof String) { final Element e = document.createElement((String) field); metadataElement.appendChild(e); if (value != null && value instanceof String) { e.appendChild(document.createTextNode((String) value)); } } } return document; } catch (final ParserConfigurationException e) { final IllegalStateException ise = new IllegalStateException(); ise.initCause(e); throw ise; } }
From source file:com.microsoft.windowsazure.management.sql.RecoverDatabaseOperationsImpl.java
/** * Issues a recovery request for an Azure SQL Database. * * @param sourceServerName Required. The name of the Azure SQL Database * Server on which the database was hosted. * @param parameters Required. Additional parameters for the Create Recover * Database Operation request./*from w w w. j a v a 2 s . 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 Contains the response to the Create Recover Database Operation * request. */ @Override public RecoverDatabaseOperationCreateResponse create(String sourceServerName, RecoverDatabaseOperationCreateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { // Validate if (sourceServerName == null) { throw new NullPointerException("sourceServerName"); } if (parameters == null) { throw new NullPointerException("parameters"); } if (parameters.getSourceDatabaseName() == null) { throw new NullPointerException("parameters.SourceDatabaseName"); } // Tracing boolean shouldTrace = CloudTracing.getIsEnabled(); String invocationId = null; if (shouldTrace) { invocationId = Long.toString(CloudTracing.getNextInvocationId()); HashMap<String, Object> tracingParameters = new HashMap<String, Object>(); tracingParameters.put("sourceServerName", sourceServerName); tracingParameters.put("parameters", parameters); CloudTracing.enter(invocationId, this, "createAsync", tracingParameters); } // Construct URL String url = ""; url = url + "/"; if (this.getClient().getCredentials().getSubscriptionId() != null) { url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8"); } url = url + "/services/sqlservers/servers/"; url = url + URLEncoder.encode(sourceServerName, "UTF-8"); url = url + "/recoverdatabaseoperations"; String baseUrl = this.getClient().getBaseUri().toString(); // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl.charAt(baseUrl.length() - 1) == '/') { baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); } if (url.charAt(0) == '/') { url = url.substring(1); } url = baseUrl + "/" + url; url = url.replace(" ", "%20"); // Create HTTP transport objects HttpPost httpRequest = new HttpPost(url); // Set Headers httpRequest.setHeader("Content-Type", "application/xml"); httpRequest.setHeader("x-ms-version", "2012-03-01"); // Serialize Request String requestContent = null; DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document requestDoc = documentBuilder.newDocument(); Element serviceResourceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ServiceResource"); requestDoc.appendChild(serviceResourceElement); Element sourceDatabaseNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "SourceDatabaseName"); sourceDatabaseNameElement.appendChild(requestDoc.createTextNode(parameters.getSourceDatabaseName())); serviceResourceElement.appendChild(sourceDatabaseNameElement); if (parameters.getTargetServerName() != null) { Element targetServerNameElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "TargetServerName"); targetServerNameElement.appendChild(requestDoc.createTextNode(parameters.getTargetServerName())); serviceResourceElement.appendChild(targetServerNameElement); } if (parameters.getTargetDatabaseName() != null) { Element targetDatabaseNameElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "TargetDatabaseName"); targetDatabaseNameElement.appendChild(requestDoc.createTextNode(parameters.getTargetDatabaseName())); serviceResourceElement.appendChild(targetDatabaseNameElement); } DOMSource domSource = new DOMSource(requestDoc); StringWriter stringWriter = new StringWriter(); StreamResult streamResult = new StreamResult(stringWriter); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.transform(domSource, streamResult); requestContent = stringWriter.toString(); StringEntity entity = new StringEntity(requestContent); httpRequest.setEntity(entity); httpRequest.setHeader("Content-Type", "application/xml"); // Send Request HttpResponse httpResponse = null; try { if (shouldTrace) { CloudTracing.sendRequest(invocationId, httpRequest); } httpResponse = this.getClient().getHttpClient().execute(httpRequest); if (shouldTrace) { CloudTracing.receiveResponse(invocationId, httpResponse); } int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_CREATED) { ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result RecoverDatabaseOperationCreateResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_CREATED) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new RecoverDatabaseOperationCreateResponse(); DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance(); documentBuilderFactory2.setNamespaceAware(true); DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder(); Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent)); Element serviceResourceElement2 = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "ServiceResource"); if (serviceResourceElement2 != null) { RecoverDatabaseOperation serviceResourceInstance = new RecoverDatabaseOperation(); result.setOperation(serviceResourceInstance); Element requestIDElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "RequestID"); if (requestIDElement != null) { String requestIDInstance; requestIDInstance = requestIDElement.getTextContent(); serviceResourceInstance.setId(requestIDInstance); } Element sourceDatabaseNameElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "SourceDatabaseName"); if (sourceDatabaseNameElement2 != null) { String sourceDatabaseNameInstance; sourceDatabaseNameInstance = sourceDatabaseNameElement2.getTextContent(); serviceResourceInstance.setSourceDatabaseName(sourceDatabaseNameInstance); } Element targetServerNameElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "TargetServerName"); if (targetServerNameElement2 != null) { String targetServerNameInstance; targetServerNameInstance = targetServerNameElement2.getTextContent(); serviceResourceInstance.setTargetServerName(targetServerNameInstance); } Element targetDatabaseNameElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "TargetDatabaseName"); if (targetDatabaseNameElement2 != null) { String targetDatabaseNameInstance; targetDatabaseNameInstance = targetDatabaseNameElement2.getTextContent(); serviceResourceInstance.setTargetDatabaseName(targetDatabaseNameInstance); } Element nameElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "Name"); if (nameElement != null) { String nameInstance; nameInstance = nameElement.getTextContent(); serviceResourceInstance.setName(nameInstance); } Element typeElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "Type"); if (typeElement != null) { String typeInstance; typeInstance = typeElement.getTextContent(); serviceResourceInstance.setType(typeInstance); } Element stateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "State"); if (stateElement != null) { String stateInstance; stateInstance = stateElement.getTextContent(); serviceResourceInstance.setState(stateInstance); } } } result.setStatusCode(statusCode); if (httpResponse.getHeaders("x-ms-request-id").length > 0) { result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); } if (shouldTrace) { CloudTracing.exit(invocationId, result); } return result; } finally { if (httpResponse != null && httpResponse.getEntity() != null) { httpResponse.getEntity().getContent().close(); } } }
From source file:com.msopentech.odatajclient.engine.data.json.JSONPropertyDeserializer.java
@Override protected JSONProperty doDeserializeV4(JsonParser parser, DeserializationContext ctxt) throws IOException, JsonProcessingException { final ObjectNode tree = (ObjectNode) parser.getCodec().readTree(parser); final JSONProperty property = new JSONProperty(); try {//from w w w . j a v a 2 s . c om final DocumentBuilder builder = ODataConstants.DOC_BUILDER_FACTORY.newDocumentBuilder(); final Document document = builder.newDocument(); Element content = document.createElement(ODataConstants.ELEM_PROPERTY); JsonNode subtree = null; if (tree.has(ODataConstants.JSON_VALUE)) { if (tree.has(v4AnnotationPrefix + ODataConstants.JSON_TYPE) && StringUtils.isBlank(content.getAttribute(ODataConstants.ATTR_M_TYPE))) { content.setAttribute(ODataConstants.ATTR_M_TYPE, tree.get(v4AnnotationPrefix + ODataConstants.JSON_TYPE).asText()); } final JsonNode value = tree.get(ODataConstants.JSON_VALUE); if (value.isValueNode()) { content.appendChild(document.createTextNode(value.asText())); } else if (EdmSimpleType.isGeospatial(content.getAttribute(ODataConstants.ATTR_M_TYPE))) { subtree = tree.objectNode(); ((ObjectNode) subtree).put(ODataConstants.JSON_VALUE, tree.get(ODataConstants.JSON_VALUE)); if (StringUtils.isNotBlank(content.getAttribute(ODataConstants.ATTR_M_TYPE))) { ((ObjectNode) subtree).put(ODataConstants.JSON_VALUE + "@" + ODataConstants.JSON_TYPE, content.getAttribute(ODataConstants.ATTR_M_TYPE)); } } else { subtree = tree.get(ODataConstants.JSON_VALUE); } } else { subtree = tree; } if (subtree != null) { DOMTreeUtilsV4.buildSubtree(content, subtree); } final List<Node> children = XMLUtils.getChildNodes(content, Node.ELEMENT_NODE); if (children.size() == 1) { final Element value = (Element) children.iterator().next(); if (ODataConstants.JSON_VALUE.equals(XMLUtils.getSimpleName(value))) { if (StringUtils.isNotBlank(content.getAttribute(ODataConstants.ATTR_M_TYPE))) { value.setAttribute(ODataConstants.ATTR_M_TYPE, content.getAttribute(ODataConstants.ATTR_M_TYPE)); } content = value; } } property.setContent(content); } catch (ParserConfigurationException e) { throw new JsonParseException("Cannot build property", parser.getCurrentLocation(), e); } return property; }
From source file:com.verisign.epp.codec.verificationcode.EPPEncodedSignedCodeValue.java
/** * Sets all this instance's data in the given XML document * //from w w w .j a v a 2s . c om * @param aDocument * a DOM Document to attach data to. * @return The root element of this component. * @throws EPPEncodeException * Thrown if any errors prevent encoding. */ public Element encode(Document aDocument) throws EPPEncodeException { cat.debug("EPPEncodedSignedCodeValue.encode(Document): enter"); if (aDocument == null) { throw new EPPEncodeException("aDocument is null" + " on in EPPSignedCode.encode(Document)"); } Element root = aDocument.createElementNS(EPPVerificationCodeExtFactory.NS, EPPVerificationCodeExtFactory.NS_PREFIX + ":" + ELM_LOCALNAME); byte[] signedCodeXml = super.encode(); String base64EncodedText = new String(Base64.encodeBase64(signedCodeXml, true)); Text currVal = aDocument.createTextNode(base64EncodedText); root.appendChild(currVal); cat.debug("EPPEncodedSignedCodeValue.encode(Document): exit - encoded"); return root; }
From source file:com.verisign.epp.codec.gen.EPPUtil.java
/** * Encode a <code>String</code> in XML with a given XML namespace and tag * name./*from w w w . j a va 2 s.c om*/ * * @param aDocument * DOM Document of <code>aRoot</code>. This parameter also acts * as a factory for XML elements. * @param aRoot * XML Element to add children nodes to. For example, the root * node could be <domain:update> * @param aString * <code>String</code> to add. * @param aNS * XML namespace of the element. For example, for domain element * this is "urn:iana:xmlns:domain". * @param aTagName * Tag name of the element including an optional namespace * prefix. For example, the tag name for the domain name is * "domain:name". * @exception EPPEncodeException * Error encoding the <code>String</code>. */ public static void encodeString(Document aDocument, Element aRoot, String aString, String aNS, String aTagName) throws EPPEncodeException { if (aString != null) { Element currElm = aDocument.createElementNS(aNS, aTagName); Text currVal = aDocument.createTextNode(aString); currElm.appendChild(currVal); aRoot.appendChild(currElm); } }
From source file:Main.java
@SuppressWarnings("null") public static void copyInto(Node src, Node dest) throws DOMException { Document factory = dest.getOwnerDocument(); //Node start = src; Node parent = null;//from ww w . j av a2s . co m Node place = src; // traverse source tree while (place != null) { // copy this node Node node = null; int type = place.getNodeType(); switch (type) { case Node.CDATA_SECTION_NODE: { node = factory.createCDATASection(place.getNodeValue()); break; } case Node.COMMENT_NODE: { node = factory.createComment(place.getNodeValue()); break; } case Node.ELEMENT_NODE: { Element element = factory.createElement(place.getNodeName()); node = element; NamedNodeMap attrs = place.getAttributes(); int attrCount = attrs.getLength(); for (int i = 0; i < attrCount; i++) { Attr attr = (Attr) attrs.item(i); String attrName = attr.getNodeName(); String attrValue = attr.getNodeValue(); element.setAttribute(attrName, attrValue); /* if (domimpl && !attr.getSpecified()) { ((Attr) element.getAttributeNode(attrName)).setSpecified(false); } */ } break; } case Node.ENTITY_REFERENCE_NODE: { node = factory.createEntityReference(place.getNodeName()); break; } case Node.PROCESSING_INSTRUCTION_NODE: { node = factory.createProcessingInstruction(place.getNodeName(), place.getNodeValue()); break; } case Node.TEXT_NODE: { node = factory.createTextNode(place.getNodeValue()); break; } default: { throw new IllegalArgumentException( "can't copy node type, " + type + " (" + node.getNodeName() + ')'); } } dest.appendChild(node); // iterate over children if (place.hasChildNodes()) { parent = place; place = place.getFirstChild(); dest = node; } else if (parent == null) { place = null; } else { // advance place = place.getNextSibling(); while (place == null && parent != null && dest != null) { place = parent.getNextSibling(); parent = parent.getParentNode(); dest = dest.getParentNode(); } } } }
From source file:com.microsoft.windowsazure.management.sql.RestoreDatabaseOperationsImpl.java
/** * Issues a restore request for an Azure SQL Database. * * @param sourceServerName Required. The name of the Azure SQL Database * Server where the source database is, or was, hosted. * @param parameters Required. Additional parameters for the Create Restore * Database Operation request./*from ww w .j a v a2 s. 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 Contains the response to the Create Restore Database Operation * request. */ @Override public RestoreDatabaseOperationCreateResponse create(String sourceServerName, RestoreDatabaseOperationCreateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { // Validate if (sourceServerName == null) { throw new NullPointerException("sourceServerName"); } if (parameters == null) { throw new NullPointerException("parameters"); } if (parameters.getSourceDatabaseName() == null) { throw new NullPointerException("parameters.SourceDatabaseName"); } if (parameters.getTargetDatabaseName() == null) { throw new NullPointerException("parameters.TargetDatabaseName"); } // Tracing boolean shouldTrace = CloudTracing.getIsEnabled(); String invocationId = null; if (shouldTrace) { invocationId = Long.toString(CloudTracing.getNextInvocationId()); HashMap<String, Object> tracingParameters = new HashMap<String, Object>(); tracingParameters.put("sourceServerName", sourceServerName); tracingParameters.put("parameters", parameters); CloudTracing.enter(invocationId, this, "createAsync", tracingParameters); } // Construct URL String url = ""; url = url + "/"; if (this.getClient().getCredentials().getSubscriptionId() != null) { url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8"); } url = url + "/services/sqlservers/servers/"; url = url + URLEncoder.encode(sourceServerName, "UTF-8"); url = url + "/restoredatabaseoperations"; String baseUrl = this.getClient().getBaseUri().toString(); // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl.charAt(baseUrl.length() - 1) == '/') { baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); } if (url.charAt(0) == '/') { url = url.substring(1); } url = baseUrl + "/" + url; url = url.replace(" ", "%20"); // Create HTTP transport objects HttpPost httpRequest = new HttpPost(url); // Set Headers httpRequest.setHeader("Content-Type", "application/xml"); httpRequest.setHeader("x-ms-version", "2012-03-01"); // Serialize Request String requestContent = null; DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document requestDoc = documentBuilder.newDocument(); Element serviceResourceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ServiceResource"); requestDoc.appendChild(serviceResourceElement); Element sourceDatabaseNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "SourceDatabaseName"); sourceDatabaseNameElement.appendChild(requestDoc.createTextNode(parameters.getSourceDatabaseName())); serviceResourceElement.appendChild(sourceDatabaseNameElement); if (parameters.getSourceDatabaseDeletionDate() != null) { Element sourceDatabaseDeletionDateElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "SourceDatabaseDeletionDate"); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'"); simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); sourceDatabaseDeletionDateElement.appendChild(requestDoc .createTextNode(simpleDateFormat.format(parameters.getSourceDatabaseDeletionDate().getTime()))); serviceResourceElement.appendChild(sourceDatabaseDeletionDateElement); } if (parameters.getTargetServerName() != null) { Element targetServerNameElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "TargetServerName"); targetServerNameElement.appendChild(requestDoc.createTextNode(parameters.getTargetServerName())); serviceResourceElement.appendChild(targetServerNameElement); } Element targetDatabaseNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "TargetDatabaseName"); targetDatabaseNameElement.appendChild(requestDoc.createTextNode(parameters.getTargetDatabaseName())); serviceResourceElement.appendChild(targetDatabaseNameElement); if (parameters.getPointInTime() != null) { Element targetUtcPointInTimeElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "TargetUtcPointInTime"); SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'"); simpleDateFormat2.setTimeZone(TimeZone.getTimeZone("UTC")); targetUtcPointInTimeElement.appendChild( requestDoc.createTextNode(simpleDateFormat2.format(parameters.getPointInTime().getTime()))); serviceResourceElement.appendChild(targetUtcPointInTimeElement); } DOMSource domSource = new DOMSource(requestDoc); StringWriter stringWriter = new StringWriter(); StreamResult streamResult = new StreamResult(stringWriter); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.transform(domSource, streamResult); requestContent = stringWriter.toString(); StringEntity entity = new StringEntity(requestContent); httpRequest.setEntity(entity); httpRequest.setHeader("Content-Type", "application/xml"); // Send Request HttpResponse httpResponse = null; try { if (shouldTrace) { CloudTracing.sendRequest(invocationId, httpRequest); } httpResponse = this.getClient().getHttpClient().execute(httpRequest); if (shouldTrace) { CloudTracing.receiveResponse(invocationId, httpResponse); } int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_CREATED) { ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result RestoreDatabaseOperationCreateResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_CREATED) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new RestoreDatabaseOperationCreateResponse(); DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance(); documentBuilderFactory2.setNamespaceAware(true); DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder(); Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent)); Element serviceResourceElement2 = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "ServiceResource"); if (serviceResourceElement2 != null) { RestoreDatabaseOperation serviceResourceInstance = new RestoreDatabaseOperation(); result.setOperation(serviceResourceInstance); Element requestIDElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "RequestID"); if (requestIDElement != null) { String requestIDInstance; requestIDInstance = requestIDElement.getTextContent(); serviceResourceInstance.setId(requestIDInstance); } Element sourceDatabaseNameElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "SourceDatabaseName"); if (sourceDatabaseNameElement2 != null) { String sourceDatabaseNameInstance; sourceDatabaseNameInstance = sourceDatabaseNameElement2.getTextContent(); serviceResourceInstance.setSourceDatabaseName(sourceDatabaseNameInstance); } Element sourceDatabaseDeletionDateElement2 = XmlUtility.getElementByTagNameNS( serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "SourceDatabaseDeletionDate"); if (sourceDatabaseDeletionDateElement2 != null && sourceDatabaseDeletionDateElement2.getTextContent() != null && !sourceDatabaseDeletionDateElement2.getTextContent().isEmpty()) { Calendar sourceDatabaseDeletionDateInstance; sourceDatabaseDeletionDateInstance = DatatypeConverter .parseDateTime(sourceDatabaseDeletionDateElement2.getTextContent()); serviceResourceInstance.setSourceDatabaseDeletionDate(sourceDatabaseDeletionDateInstance); } Element targetServerNameElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "TargetServerName"); if (targetServerNameElement2 != null) { String targetServerNameInstance; targetServerNameInstance = targetServerNameElement2.getTextContent(); serviceResourceInstance.setTargetServerName(targetServerNameInstance); } Element targetDatabaseNameElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "TargetDatabaseName"); if (targetDatabaseNameElement2 != null) { String targetDatabaseNameInstance; targetDatabaseNameInstance = targetDatabaseNameElement2.getTextContent(); serviceResourceInstance.setTargetDatabaseName(targetDatabaseNameInstance); } Element targetUtcPointInTimeElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2, "http://schemas.microsoft.com/windowsazure", "TargetUtcPointInTime"); if (targetUtcPointInTimeElement2 != null) { Calendar targetUtcPointInTimeInstance; targetUtcPointInTimeInstance = DatatypeConverter .parseDateTime(targetUtcPointInTimeElement2.getTextContent()); serviceResourceInstance.setPointInTime(targetUtcPointInTimeInstance); } } } result.setStatusCode(statusCode); if (httpResponse.getHeaders("x-ms-request-id").length > 0) { result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); } if (shouldTrace) { CloudTracing.exit(invocationId, result); } return result; } finally { if (httpResponse != null && httpResponse.getEntity() != null) { httpResponse.getEntity().getContent().close(); } } }