List of usage examples for org.w3c.dom Document createElementNS
public Element createElementNS(String namespaceURI, String qualifiedName) throws DOMException;
From source file:com.microsoft.windowsazure.management.network.ApplicationGatewayOperationsImpl.java
/** * The Begin Update Application Gateway operation updates Application * Gateway with the specified parameters. (see * http://msdn.microsoft.com/en-us/library/windowsazure/jj154114.aspx for * more information)/*from w w w.j a v a2 s .co m*/ * * @param gatewayName Required. Gateway name * @param updateParameters Required. Parameters supplied to the Begin * UpdateApplication Gateway request. * @throws ParserConfigurationException Thrown if there was an error * configuring the parser for the response body. * @throws SAXException Thrown if there was an error parsing the response * body. * @throws TransformerException Thrown if there was an error creating the * DOM transformer. * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations. * @throws ServiceException Thrown if an unexpected response is found. * @return A standard service response including an HTTP status code and * request ID. */ @Override public GatewayOperationResponse beginUpdateApplicationGateway(String gatewayName, UpdateApplicationGatewayParameters updateParameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { // Validate if (gatewayName == null) { throw new NullPointerException("gatewayName"); } if (updateParameters == null) { throw new NullPointerException("updateParameters"); } // 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("gatewayName", gatewayName); tracingParameters.put("updateParameters", updateParameters); CloudTracing.enter(invocationId, this, "beginUpdateApplicationGatewayAsync", 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/networking/ApplicationGateways/"; url = url + URLEncoder.encode(gatewayName, "UTF-8"); ArrayList<String> queryParameters = new ArrayList<String>(); queryParameters.add("api-version=" + "2015-04-01"); if (queryParameters.size() > 0) { url = url + "?" + CollectionStringBuilder.join(queryParameters, "&"); } 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 updateApplicationGatewayParametersElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "UpdateApplicationGatewayParameters"); requestDoc.appendChild(updateApplicationGatewayParametersElement); if (updateParameters.getDescription() != null) { Element descriptionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Description"); descriptionElement.appendChild(requestDoc.createTextNode(updateParameters.getDescription())); updateApplicationGatewayParametersElement.appendChild(descriptionElement); } if (updateParameters.getGatewaySize() != null) { Element gatewaySizeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "GatewaySize"); gatewaySizeElement.appendChild(requestDoc.createTextNode(updateParameters.getGatewaySize())); updateApplicationGatewayParametersElement.appendChild(gatewaySizeElement); } Element instanceCountElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "InstanceCount"); instanceCountElement .appendChild(requestDoc.createTextNode(Long.toString(updateParameters.getInstanceCount()))); updateApplicationGatewayParametersElement.appendChild(instanceCountElement); if (updateParameters.getSubnets() != null) { if (updateParameters.getSubnets() instanceof LazyCollection == false || ((LazyCollection) updateParameters.getSubnets()).isInitialized()) { Element subnetsSequenceElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "Subnets"); for (String subnetsItem : updateParameters.getSubnets()) { Element subnetsItemElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "Subnet"); subnetsItemElement.appendChild(requestDoc.createTextNode(subnetsItem)); subnetsSequenceElement.appendChild(subnetsItemElement); } updateApplicationGatewayParametersElement.appendChild(subnetsSequenceElement); } } if (updateParameters.getVnetName() != null) { Element vnetNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "VnetName"); vnetNameElement.appendChild(requestDoc.createTextNode(updateParameters.getVnetName())); updateApplicationGatewayParametersElement.appendChild(vnetNameElement); } 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 GatewayOperationResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_ACCEPTED) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new GatewayOperationResponse(); DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance(); documentBuilderFactory2.setNamespaceAware(true); DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder(); Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent)); Element gatewayOperationAsyncResponseElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "GatewayOperationAsyncResponse"); if (gatewayOperationAsyncResponseElement != null) { Element idElement = XmlUtility.getElementByTagNameNS(gatewayOperationAsyncResponseElement, "http://schemas.microsoft.com/windowsazure", "ID"); if (idElement != null) { String idInstance; idInstance = idElement.getTextContent(); result.setOperationId(idInstance); } } } 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.ApplicationGatewayOperationsImpl.java
/** * The Begin Set Application Gateway config operation sets the specified * config on the application gateway (see * http://msdn.microsoft.com/en-us/library/windowsazure/jj154114.aspx for * more information)/* w w w. j ava2s . c o m*/ * * @param gatewayName Required. Gateway name * @param config Required. The Begin Set Application Gateway Config * operation sets the specified config on the application gateway * @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 GatewayOperationResponse beginSetConfig(String gatewayName, ApplicationGatewaySetConfiguration config) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { // Validate if (gatewayName == null) { throw new NullPointerException("gatewayName"); } if (config == null) { throw new NullPointerException("config"); } // 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("gatewayName", gatewayName); tracingParameters.put("config", config); CloudTracing.enter(invocationId, this, "beginSetConfigAsync", 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/networking/ApplicationGateways/"; url = url + URLEncoder.encode(gatewayName, "UTF-8"); url = url + "/configuration"; ArrayList<String> queryParameters = new ArrayList<String>(); queryParameters.add("api-version=" + "2015-04-01"); if (queryParameters.size() > 0) { url = url + "?" + CollectionStringBuilder.join(queryParameters, "&"); } 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 applicationGatewayConfigurationElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "ApplicationGatewayConfiguration"); requestDoc.appendChild(applicationGatewayConfigurationElement); if (config.getFrontendIPConfigurations() != null) { if (config.getFrontendIPConfigurations() instanceof LazyCollection == false || ((LazyCollection) config.getFrontendIPConfigurations()).isInitialized()) { Element frontendIPConfigurationsSequenceElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "FrontendIPConfigurations"); for (FrontendIPConfiguration frontendIPConfigurationsItem : config.getFrontendIPConfigurations()) { Element frontendIPConfigurationElement = requestDoc.createElementNS( "http://schemas.microsoft.com/windowsazure", "FrontendIPConfiguration"); frontendIPConfigurationsSequenceElement.appendChild(frontendIPConfigurationElement); if (frontendIPConfigurationsItem.getName() != null) { Element nameElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); nameElement.appendChild(requestDoc.createTextNode(frontendIPConfigurationsItem.getName())); frontendIPConfigurationElement.appendChild(nameElement); } if (frontendIPConfigurationsItem.getType() != null) { Element typeElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "Type"); typeElement.appendChild(requestDoc.createTextNode(frontendIPConfigurationsItem.getType())); frontendIPConfigurationElement.appendChild(typeElement); } if (frontendIPConfigurationsItem.getStaticIPAddress() != null) { Element staticIPAddressElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "StaticIPAddress"); staticIPAddressElement.appendChild( requestDoc.createTextNode(frontendIPConfigurationsItem.getStaticIPAddress())); frontendIPConfigurationElement.appendChild(staticIPAddressElement); } } applicationGatewayConfigurationElement.appendChild(frontendIPConfigurationsSequenceElement); } } if (config.getFrontendPorts() != null) { if (config.getFrontendPorts() instanceof LazyCollection == false || ((LazyCollection) config.getFrontendPorts()).isInitialized()) { Element frontendPortsSequenceElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "FrontendPorts"); for (FrontendPort frontendPortsItem : config.getFrontendPorts()) { Element frontendPortElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "FrontendPort"); frontendPortsSequenceElement.appendChild(frontendPortElement); if (frontendPortsItem.getName() != null) { Element nameElement2 = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); nameElement2.appendChild(requestDoc.createTextNode(frontendPortsItem.getName())); frontendPortElement.appendChild(nameElement2); } Element portElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Port"); portElement .appendChild(requestDoc.createTextNode(Integer.toString(frontendPortsItem.getPort()))); frontendPortElement.appendChild(portElement); } applicationGatewayConfigurationElement.appendChild(frontendPortsSequenceElement); } } if (config.getBackendAddressPools() != null) { if (config.getBackendAddressPools() instanceof LazyCollection == false || ((LazyCollection) config.getBackendAddressPools()).isInitialized()) { Element backendAddressPoolsSequenceElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "BackendAddressPools"); for (BackendAddressPool backendAddressPoolsItem : config.getBackendAddressPools()) { Element backendAddressPoolElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "BackendAddressPool"); backendAddressPoolsSequenceElement.appendChild(backendAddressPoolElement); if (backendAddressPoolsItem.getName() != null) { Element nameElement3 = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); nameElement3.appendChild(requestDoc.createTextNode(backendAddressPoolsItem.getName())); backendAddressPoolElement.appendChild(nameElement3); } if (backendAddressPoolsItem.getBackendServers() != null) { if (backendAddressPoolsItem.getBackendServers() instanceof LazyCollection == false || ((LazyCollection) backendAddressPoolsItem.getBackendServers()).isInitialized()) { Element iPAddressesSequenceElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "IPAddresses"); for (BackendServer iPAddressesItem : backendAddressPoolsItem.getBackendServers()) { Element iPAddressElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "IPAddress"); iPAddressesSequenceElement.appendChild(iPAddressElement); if (iPAddressesItem.getIPAddress() != null) { iPAddressElement .appendChild(requestDoc.createTextNode(iPAddressesItem.getIPAddress())); } } backendAddressPoolElement.appendChild(iPAddressesSequenceElement); } } } applicationGatewayConfigurationElement.appendChild(backendAddressPoolsSequenceElement); } } if (config.getBackendHttpSettingsList() != null) { if (config.getBackendHttpSettingsList() instanceof LazyCollection == false || ((LazyCollection) config.getBackendHttpSettingsList()).isInitialized()) { Element backendHttpSettingsListSequenceElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "BackendHttpSettingsList"); for (BackendHttpSettings backendHttpSettingsListItem : config.getBackendHttpSettingsList()) { Element backendHttpSettingsElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "BackendHttpSettings"); backendHttpSettingsListSequenceElement.appendChild(backendHttpSettingsElement); if (backendHttpSettingsListItem.getName() != null) { Element nameElement4 = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); nameElement4.appendChild(requestDoc.createTextNode(backendHttpSettingsListItem.getName())); backendHttpSettingsElement.appendChild(nameElement4); } Element portElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Port"); portElement2.appendChild( requestDoc.createTextNode(Integer.toString(backendHttpSettingsListItem.getPort()))); backendHttpSettingsElement.appendChild(portElement2); if (backendHttpSettingsListItem.getProtocol() != null) { Element protocolElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "Protocol"); protocolElement.appendChild( requestDoc.createTextNode(backendHttpSettingsListItem.getProtocol().toString())); backendHttpSettingsElement.appendChild(protocolElement); } if (backendHttpSettingsListItem.getCookieBasedAffinity() != null) { Element cookieBasedAffinityElement = requestDoc.createElementNS( "http://schemas.microsoft.com/windowsazure", "CookieBasedAffinity"); cookieBasedAffinityElement.appendChild( requestDoc.createTextNode(backendHttpSettingsListItem.getCookieBasedAffinity())); backendHttpSettingsElement.appendChild(cookieBasedAffinityElement); } } applicationGatewayConfigurationElement.appendChild(backendHttpSettingsListSequenceElement); } } if (config.getHttpListeners() != null) { if (config.getHttpListeners() instanceof LazyCollection == false || ((LazyCollection) config.getHttpListeners()).isInitialized()) { Element httpListenersSequenceElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "HttpListeners"); for (AGHttpListener httpListenersItem : config.getHttpListeners()) { Element httpListenerElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "HttpListener"); httpListenersSequenceElement.appendChild(httpListenerElement); if (httpListenersItem.getName() != null) { Element nameElement5 = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); nameElement5.appendChild(requestDoc.createTextNode(httpListenersItem.getName())); httpListenerElement.appendChild(nameElement5); } if (httpListenersItem.getFrontendIP() != null) { Element frontendIPElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "FrontendIP"); frontendIPElement.appendChild(requestDoc.createTextNode(httpListenersItem.getFrontendIP())); httpListenerElement.appendChild(frontendIPElement); } if (httpListenersItem.getFrontendPort() != null) { Element frontendPortElement2 = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "FrontendPort"); frontendPortElement2 .appendChild(requestDoc.createTextNode(httpListenersItem.getFrontendPort())); httpListenerElement.appendChild(frontendPortElement2); } if (httpListenersItem.getProtocol() != null) { Element protocolElement2 = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "Protocol"); protocolElement2 .appendChild(requestDoc.createTextNode(httpListenersItem.getProtocol().toString())); httpListenerElement.appendChild(protocolElement2); } if (httpListenersItem.getSslCert() != null) { Element sslCertElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "SslCert"); sslCertElement.appendChild(requestDoc.createTextNode(httpListenersItem.getSslCert())); httpListenerElement.appendChild(sslCertElement); } } applicationGatewayConfigurationElement.appendChild(httpListenersSequenceElement); } } if (config.getHttpLoadBalancingRules() != null) { if (config.getHttpLoadBalancingRules() instanceof LazyCollection == false || ((LazyCollection) config.getHttpLoadBalancingRules()).isInitialized()) { Element httpLoadBalancingRulesSequenceElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "HttpLoadBalancingRules"); for (HttpLoadBalancingRule httpLoadBalancingRulesItem : config.getHttpLoadBalancingRules()) { Element httpLoadBalancingRuleElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "HttpLoadBalancingRule"); httpLoadBalancingRulesSequenceElement.appendChild(httpLoadBalancingRuleElement); if (httpLoadBalancingRulesItem.getName() != null) { Element nameElement6 = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); nameElement6.appendChild(requestDoc.createTextNode(httpLoadBalancingRulesItem.getName())); httpLoadBalancingRuleElement.appendChild(nameElement6); } if (httpLoadBalancingRulesItem.getType() != null) { Element typeElement2 = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "Type"); typeElement2.appendChild(requestDoc.createTextNode(httpLoadBalancingRulesItem.getType())); httpLoadBalancingRuleElement.appendChild(typeElement2); } if (httpLoadBalancingRulesItem.getBackendHttpSettings() != null) { Element backendHttpSettingsElement2 = requestDoc.createElementNS( "http://schemas.microsoft.com/windowsazure", "BackendHttpSettings"); backendHttpSettingsElement2.appendChild( requestDoc.createTextNode(httpLoadBalancingRulesItem.getBackendHttpSettings())); httpLoadBalancingRuleElement.appendChild(backendHttpSettingsElement2); } if (httpLoadBalancingRulesItem.getListener() != null) { Element listenerElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "Listener"); listenerElement .appendChild(requestDoc.createTextNode(httpLoadBalancingRulesItem.getListener())); httpLoadBalancingRuleElement.appendChild(listenerElement); } if (httpLoadBalancingRulesItem.getBackendAddressPool() != null) { Element backendAddressPoolElement2 = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "BackendAddressPool"); backendAddressPoolElement2.appendChild( requestDoc.createTextNode(httpLoadBalancingRulesItem.getBackendAddressPool())); httpLoadBalancingRuleElement.appendChild(backendAddressPoolElement2); } } applicationGatewayConfigurationElement.appendChild(httpLoadBalancingRulesSequenceElement); } } 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 GatewayOperationResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_ACCEPTED) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new GatewayOperationResponse(); DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance(); documentBuilderFactory2.setNamespaceAware(true); DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder(); Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent)); Element gatewayOperationAsyncResponseElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "GatewayOperationAsyncResponse"); if (gatewayOperationAsyncResponseElement != null) { Element idElement = XmlUtility.getElementByTagNameNS(gatewayOperationAsyncResponseElement, "http://schemas.microsoft.com/windowsazure", "ID"); if (idElement != null) { String idInstance; idInstance = idElement.getTextContent(); result.setOperationId(idInstance); } } } 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.occamlab.te.parsers.ImageParser.java
private static void processBufferedImage(BufferedImage buffimage, String formatName, NodeList nodes) throws Exception { HashMap<Object, Object> bandMap = new HashMap<Object, Object>(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { if (node.getLocalName().equals("subimage")) { Element e = (Element) node; int x = Integer.parseInt(e.getAttribute("x")); int y = Integer.parseInt(e.getAttribute("y")); int w = Integer.parseInt(e.getAttribute("width")); int h = Integer.parseInt(e.getAttribute("height")); processBufferedImage(buffimage.getSubimage(x, y, w, h), formatName, e.getChildNodes()); } else if (node.getLocalName().equals("checksum")) { CRC32 checksum = new CRC32(); Raster raster = buffimage.getRaster(); DataBufferByte buffer; if (node.getParentNode().getLocalName().equals("subimage")) { WritableRaster outRaster = raster.createCompatibleWritableRaster(); buffimage.copyData(outRaster); buffer = (DataBufferByte) outRaster.getDataBuffer(); } else { buffer = (DataBufferByte) raster.getDataBuffer(); }/*www . j a v a 2s . com*/ int numbanks = buffer.getNumBanks(); for (int j = 0; j < numbanks; j++) { checksum.update(buffer.getData(j)); } Document doc = node.getOwnerDocument(); node.appendChild(doc.createTextNode(Long.toString(checksum.getValue()))); } else if (node.getLocalName().equals("count")) { String band = ((Element) node).getAttribute("bands"); String sample = ((Element) node).getAttribute("sample"); if (sample.equals("all")) { bandMap.put(band, null); } else { HashMap<Object, Object> sampleMap = (HashMap<Object, Object>) bandMap.get(band); if (sampleMap == null) { if (!bandMap.containsKey(band)) { sampleMap = new HashMap<Object, Object>(); bandMap.put(band, sampleMap); } } sampleMap.put(Integer.decode(sample), new Integer(0)); } } else if (node.getLocalName().equals("transparentNodata")) { // 2011-08-24 // PwD String transparentNodata = checkTransparentNodata(buffimage, node); node.setTextContent(transparentNodata); } } } Iterator bandIt = bandMap.keySet().iterator(); while (bandIt.hasNext()) { String band_str = (String) bandIt.next(); int band_indexes[]; if (buffimage.getType() == BufferedImage.TYPE_BYTE_BINARY || buffimage.getType() == BufferedImage.TYPE_BYTE_GRAY) { band_indexes = new int[1]; band_indexes[0] = 0; } else { band_indexes = new int[band_str.length()]; for (int i = 0; i < band_str.length(); i++) { if (band_str.charAt(i) == 'A') band_indexes[i] = 3; if (band_str.charAt(i) == 'B') band_indexes[i] = 2; if (band_str.charAt(i) == 'G') band_indexes[i] = 1; if (band_str.charAt(i) == 'R') band_indexes[i] = 0; } } Raster raster = buffimage.getRaster(); java.util.HashMap sampleMap = (java.util.HashMap) bandMap.get(band_str); boolean addall = (sampleMap == null); if (sampleMap == null) { sampleMap = new java.util.HashMap(); bandMap.put(band_str, sampleMap); } int minx = raster.getMinX(); int maxx = minx + raster.getWidth(); int miny = raster.getMinY(); int maxy = miny + raster.getHeight(); int bands[][] = new int[band_indexes.length][raster.getWidth()]; for (int y = miny; y < maxy; y++) { for (int i = 0; i < band_indexes.length; i++) { raster.getSamples(minx, y, maxx, 1, band_indexes[i], bands[i]); } for (int x = minx; x < maxx; x++) { int sample = 0; for (int i = 0; i < band_indexes.length; i++) { sample |= bands[i][x] << ((band_indexes.length - i - 1) * 8); } Integer sampleObj = new Integer(sample); boolean add = addall; if (!addall) { add = sampleMap.containsKey(sampleObj); } if (add) { Integer count = (Integer) sampleMap.get(sampleObj); if (count == null) { count = new Integer(0); } count = new Integer(count.intValue() + 1); sampleMap.put(sampleObj, count); } } } } Node node = nodes.item(0); while (node != null) { if (node.getNodeType() == Node.ELEMENT_NODE) { if (node.getLocalName().equals("count")) { String band = ((Element) node).getAttribute("bands"); String sample = ((Element) node).getAttribute("sample"); HashMap sampleMap = (HashMap) bandMap.get(band); Document doc = node.getOwnerDocument(); if (sample.equals("all")) { Node parent = node.getParentNode(); Node prevSibling = node.getPreviousSibling(); Iterator sampleIt = sampleMap.keySet().iterator(); Element countnode = null; int digits; String prefix; switch (buffimage.getType()) { case BufferedImage.TYPE_BYTE_BINARY: digits = 1; prefix = ""; break; case BufferedImage.TYPE_BYTE_GRAY: digits = 2; prefix = "0x"; break; default: prefix = "0x"; digits = band.length() * 2; } while (sampleIt.hasNext()) { countnode = doc.createElementNS(node.getNamespaceURI(), "count"); Integer sampleInt = (Integer) sampleIt.next(); Integer count = (Integer) sampleMap.get(sampleInt); if (band.length() > 0) { countnode.setAttribute("bands", band); } countnode.setAttribute("sample", prefix + HexString(sampleInt.intValue(), digits)); Node textnode = doc.createTextNode(count.toString()); countnode.appendChild(textnode); parent.insertBefore(countnode, node); if (sampleIt.hasNext()) { if (prevSibling != null && prevSibling.getNodeType() == Node.TEXT_NODE) { parent.insertBefore(prevSibling.cloneNode(false), node); } } } parent.removeChild(node); node = countnode; } else { Integer count = (Integer) sampleMap.get(Integer.decode(sample)); if (count == null) count = new Integer(0); Node textnode = doc.createTextNode(count.toString()); node.appendChild(textnode); } } } node = node.getNextSibling(); } }
From source file:ddf.catalog.services.xsltlistener.XsltResponseQueueTransformer.java
@Override public ddf.catalog.data.BinaryContent transform(SourceResponse upstreamResponse, Map<String, Serializable> arguments) throws CatalogTransformerException { LOGGER.debug("Transforming ResponseQueue with XSLT tranformer"); long grandTotal = -1; try {/*from w w w . ja va2 s .c om*/ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.newDocument(); Node resultsElement = doc.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "results", null)); // TODO use streaming XSLT, not DOM List<Result> results = upstreamResponse.getResults(); grandTotal = upstreamResponse.getHits(); for (Result result : results) { Metacard metacard = result.getMetacard(); String thisMetacard = metacard.getMetadata(); if (metacard != null && thisMetacard != null) { Element metacardElement = createElement(doc, XML_RESULTS_NAMESPACE, "metacard", null); if (metacard.getId() != null) { metacardElement .appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "id", metacard.getId())); } if (metacard.getMetacardType().toString() != null) { metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "type", metacard.getMetacardType().getName())); } if (metacard.getTitle() != null) { metacardElement.appendChild( createElement(doc, XML_RESULTS_NAMESPACE, "title", metacard.getTitle())); } if (result.getRelevanceScore() != null) { metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "score", result.getRelevanceScore().toString())); } if (result.getDistanceInMeters() != null) { metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "distance", result.getDistanceInMeters().toString())); } if (metacard.getSourceId() != null) { metacardElement.appendChild( createElement(doc, XML_RESULTS_NAMESPACE, "site", metacard.getSourceId())); } if (metacard.getContentTypeName() != null) { String contentType = metacard.getContentTypeName(); Element typeElement = createElement(doc, XML_RESULTS_NAMESPACE, "content-type", contentType); // TODO revisit what to put in the qualifier typeElement.setAttribute("qualifier", "content-type"); metacardElement.appendChild(typeElement); } if (metacard.getResourceURI() != null) { try { metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "product", metacard.getResourceURI().toString())); } catch (DOMException e) { LOGGER.warn(" Unable to create resource uri element", e); } } if (metacard.getThumbnail() != null) { metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "thumbnail", Base64.encodeBase64String(metacard.getThumbnail()))); try { String mimeType = URLConnection .guessContentTypeFromStream(new ByteArrayInputStream(metacard.getThumbnail())); metacardElement .appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "t_mimetype", mimeType)); } catch (IOException e) { // TODO Auto-generated catch block metacardElement.appendChild( createElement(doc, XML_RESULTS_NAMESPACE, "t_mimetype", "image/png")); } } DateTimeFormatter fmt = ISODateTimeFormat.dateTime(); if (metacard.getCreatedDate() != null) { metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "created", fmt.print(metacard.getCreatedDate().getTime()))); } // looking at the date last modified if (metacard.getModifiedDate() != null) { metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "updated", fmt.print(metacard.getModifiedDate().getTime()))); } if (metacard.getEffectiveDate() != null) { metacardElement.appendChild(createElement(doc, XML_RESULTS_NAMESPACE, "effective", fmt.print(metacard.getEffectiveDate().getTime()))); } if (metacard.getLocation() != null) { metacardElement.appendChild( createElement(doc, XML_RESULTS_NAMESPACE, "location", metacard.getLocation())); } Element documentElement = doc.createElementNS(XML_RESULTS_NAMESPACE, "document"); metacardElement.appendChild(documentElement); resultsElement.appendChild(metacardElement); Node importedNode = doc.importNode(new XPathHelper(thisMetacard).getDocument().getFirstChild(), true); documentElement.appendChild(importedNode); } else { LOGGER.debug("Null content/document returned to XSLT ResponseQueueTransformer"); continue; } } if (LOGGER.isDebugEnabled()) { DOMImplementationLS domImplementation = (DOMImplementationLS) doc.getImplementation(); LSSerializer lsSerializer = domImplementation.createLSSerializer(); LOGGER.debug("Generated XML input for transform: " + lsSerializer.writeToString(doc)); } LOGGER.debug("Starting responsequeue xslt transform."); Transformer transformer; Map<String, Object> mergedMap = new HashMap<String, Object>(); mergedMap.put(GRAND_TOTAL, grandTotal); if (arguments != null) { mergedMap.putAll(arguments); } BinaryContent resultContent; StreamResult resultOutput = null; Source source = new DOMSource(doc); ByteArrayOutputStream baos = new ByteArrayOutputStream(); resultOutput = new StreamResult(baos); try { transformer = templates.newTransformer(); } catch (TransformerConfigurationException tce) { throw new CatalogTransformerException("Could not perform Xslt transform: " + tce.getException(), tce.getCause()); } if (mergedMap != null && !mergedMap.isEmpty()) { for (Map.Entry<String, Object> entry : mergedMap.entrySet()) { if (LOGGER.isDebugEnabled()) { LOGGER.debug( "Adding parameter to transform {" + entry.getKey() + ":" + entry.getValue() + "}"); } transformer.setParameter(entry.getKey(), entry.getValue()); } } try { transformer.transform(source, resultOutput); byte[] bytes = baos.toByteArray(); LOGGER.debug("Transform complete."); resultContent = new XsltTransformedContent(bytes, mimeType); } catch (TransformerException te) { LOGGER.error("Could not perform Xslt transform: " + te.getException(), te.getCause()); throw new CatalogTransformerException("Could not perform Xslt transform: " + te.getException(), te.getCause()); } finally { // transformer.reset(); // don't need to do that unless we are putting it back into a // pool -- which we should do, but that can wait until later. } return resultContent; } catch (ParserConfigurationException e) { LOGGER.warn("Error creating new document: " + e.getMessage(), e.getCause()); throw new CatalogTransformerException("Error merging entries to xml feed.", e); } }
From source file:it.cnr.icar.eric.common.security.wss4j.WSS4JSignatureSAML.java
/** * Initialize a WSSec SAML Signature.// w ww.ja va2s. c om * * The method sets up and initializes a WSSec SAML Signature structure after * the relevant information was set. After setup of the references to * elements to sign may be added. After all references are added they can be * signed. * * This method does not add the Signature element to the security header. * See <code>prependSignatureElementToHeader()</code> method. * * @param doc * The SOAP envelope as <code>Document</code> * @param uCrypto * The user's Crypto instance * @param assertion * the complete SAML assertion * @param iCrypto * An instance of the Crypto API to handle keystore SAML token * issuer and to generate certificates * @param iKeyName * Private key to use in case of "sender-Vouches" * @param iKeyPW * Password for issuer private key * @param secHeader * The Security header * @throws WSSecurityException */ public void prepare(Document doc, Crypto uCrypto, AssertionWrapper assertion, Crypto iCrypto, String iKeyName, String iKeyPW, WSSecHeader secHeader) throws WSSecurityException { if (doDebug) { log.debug("Beginning ST signing..."); } userCrypto = uCrypto; issuerCrypto = iCrypto; document = doc; issuerKeyName = iKeyName; issuerKeyPW = iKeyPW; samlToken = assertion.toDOM(doc); // // Get some information about the SAML token content. This controls how // to deal with the whole stuff. First get the Authentication statement // (includes Subject), then get the _first_ confirmation method only // thats if "senderVouches" is true. // String confirmMethod = null; List<String> methods = assertion.getConfirmationMethods(); if (methods != null && methods.size() > 0) { confirmMethod = methods.get(0); } if (OpenSAMLUtil.isMethodSenderVouches(confirmMethod)) { senderVouches = true; } // // Gather some info about the document to process and store it for // retrieval // wsDocInfo = new WSDocInfo(doc); X509Certificate[] certs = null; PublicKey publicKey = null; if (senderVouches) { CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS); cryptoType.setAlias(issuerKeyName); certs = issuerCrypto.getX509Certificates(cryptoType); wsDocInfo.setCrypto(issuerCrypto); } // // in case of key holder: - get the user's certificate that _must_ be // included in the SAML token. To ensure the cert integrity the SAML // token must be signed (by the issuer). // else { if (userCrypto == null || !assertion.isSigned()) { throw new WSSecurityException(WSSecurityException.FAILURE, "invalidSAMLsecurity", new Object[] { "for SAML Signature (Key Holder)" }); } if (secretKey == null) { RequestData data = new RequestData(); data.setSigCrypto(userCrypto); data.setWssConfig(getWsConfig()); SAMLKeyInfo samlKeyInfo = SAMLUtil.getCredentialFromSubject(assertion, data, wsDocInfo, getWsConfig().isWsiBSPCompliant()); publicKey = samlKeyInfo.getPublicKey(); certs = samlKeyInfo.getCerts(); wsDocInfo.setCrypto(userCrypto); } } if ((certs == null || certs.length == 0 || certs[0] == null) && publicKey == null && secretKey == null) { throw new WSSecurityException(WSSecurityException.FAILURE, "noCertsFound", new Object[] { "SAML signature" }); } if (sigAlgo == null) { PublicKey key = null; if (certs != null && certs[0] != null) { key = certs[0].getPublicKey(); } else if (publicKey != null) { key = publicKey; } String pubKeyAlgo = key.getAlgorithm(); log.debug("automatic sig algo detection: " + pubKeyAlgo); if (pubKeyAlgo.equalsIgnoreCase("DSA")) { sigAlgo = WSConstants.DSA; } else if (pubKeyAlgo.equalsIgnoreCase("RSA")) { sigAlgo = WSConstants.RSA; } else { throw new WSSecurityException(WSSecurityException.FAILURE, "unknownSignatureAlgorithm", new Object[] { pubKeyAlgo }); } } sig = null; try { C14NMethodParameterSpec c14nSpec = null; if (getWsConfig().isWsiBSPCompliant() && canonAlgo.equals(WSConstants.C14N_EXCL_OMIT_COMMENTS)) { List<String> prefixes = getInclusivePrefixes(secHeader.getSecurityHeader(), false); c14nSpec = new ExcC14NParameterSpec(prefixes); } c14nMethod = signatureFactory.newCanonicalizationMethod(canonAlgo, c14nSpec); } catch (Exception ex) { log.error("", ex); throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, "noXMLSig", null, ex); } keyInfoUri = getWsConfig().getIdAllocator().createSecureId("KeyId-", keyInfo); secRef = new SecurityTokenReference(doc); strUri = getWsConfig().getIdAllocator().createSecureId("STRId-", secRef); secRef.setID(strUri); if (certs != null && certs.length != 0) { // __MOD__ 2012-01-15 if (certUri == null) certUri = getWsConfig().getIdAllocator().createSecureId("CertId-", certs[0]); } // // If the sender vouches, then we must sign the SAML token _and_ at // least one part of the message (usually the SOAP body). To do so we // need to - put in a reference to the SAML token. Thus we create a STR // and insert it into the wsse:Security header - set a reference of the // created STR to the signature and use STR Transform during the // signature // try { if (senderVouches) { secRefSaml = new SecurityTokenReference(doc); secRefID = getWsConfig().getIdAllocator().createSecureId("STRSAMLId-", secRefSaml); secRefSaml.setID(secRefID); if (useDirectReferenceToAssertion) { Reference ref = new Reference(doc); ref.setURI("#" + assertion.getId()); if (assertion.getSaml1() != null) { ref.setValueType(WSConstants.WSS_SAML_KI_VALUE_TYPE); secRefSaml.addTokenType(WSConstants.WSS_SAML_TOKEN_TYPE); } else if (assertion.getSaml2() != null) { secRefSaml.addTokenType(WSConstants.WSS_SAML2_TOKEN_TYPE); } secRefSaml.setReference(ref); } else { Element keyId = doc.createElementNS(WSConstants.WSSE_NS, "wsse:KeyIdentifier"); String valueType = null; if (assertion.getSaml1() != null) { valueType = WSConstants.WSS_SAML_KI_VALUE_TYPE; secRefSaml.addTokenType(WSConstants.WSS_SAML_TOKEN_TYPE); } else if (assertion.getSaml2() != null) { valueType = WSConstants.WSS_SAML2_KI_VALUE_TYPE; secRefSaml.addTokenType(WSConstants.WSS_SAML2_TOKEN_TYPE); } keyId.setAttributeNS(null, "ValueType", valueType); keyId.appendChild(doc.createTextNode(assertion.getId())); Element elem = secRefSaml.getElement(); elem.appendChild(keyId); } wsDocInfo.addTokenElement(secRefSaml.getElement(), false); } } catch (Exception ex) { throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, "noXMLSig", null, ex); } if (senderVouches) { switch (keyIdentifierType) { case WSConstants.BST_DIRECT_REFERENCE: Reference ref = new Reference(doc); ref.setURI("#" + certUri); bstToken = new X509Security(doc); ((X509Security) bstToken).setX509Certificate(certs[0]); bstToken.setID(certUri); wsDocInfo.addTokenElement(bstToken.getElement(), false); ref.setValueType(bstToken.getValueType()); secRef.setReference(ref); break; case WSConstants.X509_KEY_IDENTIFIER: secRef.setKeyIdentifier(certs[0]); break; case WSConstants.SKI_KEY_IDENTIFIER: secRef.setKeyIdentifierSKI(certs[0], iCrypto != null ? iCrypto : uCrypto); break; case WSConstants.THUMBPRINT_IDENTIFIER: secRef.setKeyIdentifierThumb(certs[0]); break; case WSConstants.ISSUER_SERIAL: final String issuer = certs[0].getIssuerDN().getName(); final java.math.BigInteger serialNumber = certs[0].getSerialNumber(); final DOMX509IssuerSerial domIssuerSerial = new DOMX509IssuerSerial(document, issuer, serialNumber); final DOMX509Data domX509Data = new DOMX509Data(document, domIssuerSerial); secRef.setX509Data(domX509Data); break; default: throw new WSSecurityException(WSSecurityException.FAILURE, "unsupportedKeyId", new Object[] {}); } } else if (useDirectReferenceToAssertion) { Reference ref = new Reference(doc); ref.setURI("#" + assertion.getId()); if (assertion.getSaml1() != null) { ref.setValueType(WSConstants.WSS_SAML_KI_VALUE_TYPE); secRef.addTokenType(WSConstants.WSS_SAML_TOKEN_TYPE); } else if (assertion.getSaml2() != null) { secRef.addTokenType(WSConstants.WSS_SAML2_TOKEN_TYPE); } secRef.setReference(ref); } else { Element keyId = doc.createElementNS(WSConstants.WSSE_NS, "wsse:KeyIdentifier"); String valueType = null; if (assertion.getSaml1() != null) { valueType = WSConstants.WSS_SAML_KI_VALUE_TYPE; secRef.addTokenType(WSConstants.WSS_SAML_TOKEN_TYPE); } else if (assertion.getSaml2() != null) { valueType = WSConstants.WSS_SAML2_KI_VALUE_TYPE; secRef.addTokenType(WSConstants.WSS_SAML2_TOKEN_TYPE); } keyId.setAttributeNS(null, "ValueType", valueType); keyId.appendChild(doc.createTextNode(assertion.getId())); Element elem = secRef.getElement(); elem.appendChild(keyId); } XMLStructure structure = new DOMStructure(secRef.getElement()); wsDocInfo.addTokenElement(secRef.getElement(), false); keyInfo = keyInfoFactory.newKeyInfo(java.util.Collections.singletonList(structure), keyInfoUri); wsDocInfo.addTokenElement(samlToken, false); }
From source file:com.microsoft.windowsazure.management.compute.HostedServiceOperationsImpl.java
/** * The Begin Adding Extension operation adds an available extension to your * cloud service. In Azure, a process can run as an extension of a cloud * service. For example, Remote Desktop Access or the Azure Diagnostics * Agent can run as extensions to the cloud service. You can find the * available extension by using the List Available Extensions operation. * (see http://msdn.microsoft.com/en-us/library/windowsazure/dn169558.aspx * for more information)/*from ww w . java2s . co m*/ * * @param serviceName Required. The name of the cloud service. * @param parameters Required. Parameters supplied to the Begin Adding * Extension 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 beginAddingExtension(String serviceName, HostedServiceAddExtensionParameters 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.getId() == null) { throw new NullPointerException("parameters.Id"); } if (parameters.getType() == null) { throw new NullPointerException("parameters.Type"); } // 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, "beginAddingExtensionAsync", 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 + "/extensions"; 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 extensionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Extension"); requestDoc.appendChild(extensionElement); if (parameters.getProviderNamespace() != null) { Element providerNameSpaceElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "ProviderNameSpace"); providerNameSpaceElement.appendChild(requestDoc.createTextNode(parameters.getProviderNamespace())); extensionElement.appendChild(providerNameSpaceElement); } Element typeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Type"); typeElement.appendChild(requestDoc.createTextNode(parameters.getType())); extensionElement.appendChild(typeElement); Element idElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Id"); idElement.appendChild(requestDoc.createTextNode(parameters.getId())); extensionElement.appendChild(idElement); if (parameters.getThumbprint() != null) { Element thumbprintElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Thumbprint"); thumbprintElement.appendChild(requestDoc.createTextNode(parameters.getThumbprint())); extensionElement.appendChild(thumbprintElement); } if (parameters.getThumbprintAlgorithm() != null) { Element thumbprintAlgorithmElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "ThumbprintAlgorithm"); thumbprintAlgorithmElement.appendChild(requestDoc.createTextNode(parameters.getThumbprintAlgorithm())); extensionElement.appendChild(thumbprintAlgorithmElement); } if (parameters.getPublicConfiguration() != null) { Element publicConfigurationElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "PublicConfiguration"); publicConfigurationElement.appendChild( requestDoc.createTextNode(Base64.encode(parameters.getPublicConfiguration().getBytes()))); extensionElement.appendChild(publicConfigurationElement); } if (parameters.getPrivateConfiguration() != null) { Element privateConfigurationElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "PrivateConfiguration"); privateConfigurationElement.appendChild( requestDoc.createTextNode(Base64.encode(parameters.getPrivateConfiguration().getBytes()))); extensionElement.appendChild(privateConfigurationElement); } if (parameters.getVersion() != null) { Element versionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Version"); versionElement.appendChild(requestDoc.createTextNode(parameters.getVersion())); extensionElement.appendChild(versionElement); } 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.HostedServiceOperationsImpl.java
/** * The Update Hosted Service operation can update the label or description * of a cloud service in Azure. (see/* w w w. ja va 2 s.c om*/ * http://msdn.microsoft.com/en-us/library/windowsazure/gg441303.aspx for * more information) * * @param serviceName Required. The name of the cloud service. * @param parameters Required. Parameters supplied to the Update Hosted * Service operation. * @throws InterruptedException Thrown when a thread is waiting, sleeping, * or otherwise occupied, and the thread is interrupted, either before or * during the activity. Occasionally a method may wish to test whether the * current thread has been interrupted, and if so, to immediately throw * this exception. The following code can be used to achieve this effect: * @throws ExecutionException Thrown when attempting to retrieve the result * of a task that aborted by throwing an exception. This exception can be * inspected using the Throwable.getCause() method. * @throws ServiceException Thrown if the server returned an error for the * request. * @throws IOException Thrown if there was an error setting up tracing for * the request. * @throws ParserConfigurationException Thrown if there was an error * configuring the parser for the response body. * @throws SAXException Thrown if there was an error parsing the response * body. * @throws TransformerException Thrown if there was an error creating the * DOM transformer. * @throws ServiceException Thrown if an unexpected response is found. * @throws URISyntaxException Thrown if there was an error parsing a URI in * the response. * @return A standard service response including an HTTP status code and * request ID. */ @Override public OperationResponse update(String serviceName, HostedServiceUpdateParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException, ParserConfigurationException, SAXException, TransformerException, URISyntaxException { // 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.getDescription() != null && parameters.getDescription().length() > 1024) { throw new IllegalArgumentException("parameters.Description"); } // 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, "updateAsync", tracingParameters); } // Construct URL String url = ""; url = url + "/"; if (this.getClient().getCredentials().getSubscriptionId() != null) { url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8"); } url = url + "/services/hostedservices/"; url = url + URLEncoder.encode(serviceName, "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 updateHostedServiceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "UpdateHostedService"); requestDoc.appendChild(updateHostedServiceElement); if (parameters.getLabel() != null) { Element labelElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Label"); labelElement.appendChild(requestDoc.createTextNode(Base64.encode(parameters.getLabel().getBytes()))); updateHostedServiceElement.appendChild(labelElement); } if (parameters.getDescription() != null) { Element descriptionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Description"); descriptionElement.appendChild(requestDoc.createTextNode(parameters.getDescription())); updateHostedServiceElement.appendChild(descriptionElement); } if (parameters.getReverseDnsFqdn() != null) { Element reverseDnsFqdnElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ReverseDnsFqdn"); reverseDnsFqdnElement.appendChild(requestDoc.createTextNode(parameters.getReverseDnsFqdn())); updateHostedServiceElement.appendChild(reverseDnsFqdnElement); } if (parameters.getExtendedProperties() != null) { if (parameters.getExtendedProperties() instanceof LazyCollection == false || ((LazyCollection) parameters.getExtendedProperties()).isInitialized()) { Element extendedPropertiesDictionaryElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "ExtendedProperties"); for (Map.Entry<String, String> entry : parameters.getExtendedProperties().entrySet()) { String extendedPropertiesKey = entry.getKey(); String extendedPropertiesValue = entry.getValue(); Element extendedPropertiesElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "ExtendedProperty"); extendedPropertiesDictionaryElement.appendChild(extendedPropertiesElement); Element extendedPropertiesKeyElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); extendedPropertiesKeyElement.appendChild(requestDoc.createTextNode(extendedPropertiesKey)); extendedPropertiesElement.appendChild(extendedPropertiesKeyElement); Element extendedPropertiesValueElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "Value"); extendedPropertiesValueElement.appendChild(requestDoc.createTextNode(extendedPropertiesValue)); extendedPropertiesElement.appendChild(extendedPropertiesValueElement); } updateHostedServiceElement.appendChild(extendedPropertiesDictionaryElement); } } DOMSource domSource = new DOMSource(requestDoc); StringWriter stringWriter = new StringWriter(); StreamResult streamResult = new StreamResult(stringWriter); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.transform(domSource, streamResult); requestContent = stringWriter.toString(); StringEntity entity = new StringEntity(requestContent); httpRequest.setEntity(entity); httpRequest.setHeader("Content-Type", "application/xml"); // Send Request HttpResponse httpResponse = null; try { if (shouldTrace) { CloudTracing.sendRequest(invocationId, httpRequest); } httpResponse = this.getClient().getHttpClient().execute(httpRequest); if (shouldTrace) { CloudTracing.receiveResponse(invocationId, httpResponse); } int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result 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.HostedServiceOperationsImpl.java
/** * The Create Hosted Service operation creates a new cloud service in Azure. * (see http://msdn.microsoft.com/en-us/library/windowsazure/gg441304.aspx * for more information)//from w w w . j av a2s . c om * * @param parameters Required. Parameters supplied to the Create Hosted * Service operation. * @throws InterruptedException Thrown when a thread is waiting, sleeping, * or otherwise occupied, and the thread is interrupted, either before or * during the activity. Occasionally a method may wish to test whether the * current thread has been interrupted, and if so, to immediately throw * this exception. The following code can be used to achieve this effect: * @throws ExecutionException Thrown when attempting to retrieve the result * of a task that aborted by throwing an exception. This exception can be * inspected using the Throwable.getCause() method. * @throws ServiceException Thrown if the server returned an error for the * request. * @throws IOException Thrown if there was an error setting up tracing for * the request. * @throws ParserConfigurationException Thrown if there was an error * configuring the parser for the response body. * @throws SAXException Thrown if there was an error parsing the response * body. * @throws TransformerException Thrown if there was an error creating the * DOM transformer. * @throws ServiceException Thrown if an unexpected response is found. * @throws URISyntaxException Thrown if there was an error parsing a URI in * the response. * @return A standard service response including an HTTP status code and * request ID. */ @Override public OperationResponse create(HostedServiceCreateParameters parameters) throws InterruptedException, ExecutionException, ServiceException, IOException, ParserConfigurationException, SAXException, TransformerException, URISyntaxException { // Validate if (parameters == null) { throw new NullPointerException("parameters"); } if (parameters.getDescription() != null && parameters.getDescription().length() > 1024) { throw new IllegalArgumentException("parameters.Description"); } if (parameters.getLabel() == null) { throw new NullPointerException("parameters.Label"); } if (parameters.getServiceName() == null) { throw new NullPointerException("parameters.ServiceName"); } // TODO: Validate parameters.ServiceName is a valid DNS name. // Tracing boolean shouldTrace = CloudTracing.getIsEnabled(); String invocationId = null; if (shouldTrace) { invocationId = Long.toString(CloudTracing.getNextInvocationId()); HashMap<String, Object> tracingParameters = new HashMap<String, Object>(); tracingParameters.put("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/hostedservices"; 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 createHostedServiceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "CreateHostedService"); requestDoc.appendChild(createHostedServiceElement); Element serviceNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ServiceName"); serviceNameElement.appendChild(requestDoc.createTextNode(parameters.getServiceName())); createHostedServiceElement.appendChild(serviceNameElement); Element labelElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Label"); labelElement.appendChild(requestDoc.createTextNode(Base64.encode(parameters.getLabel().getBytes()))); createHostedServiceElement.appendChild(labelElement); if (parameters.getDescription() != null) { Element descriptionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Description"); descriptionElement.appendChild(requestDoc.createTextNode(parameters.getDescription())); createHostedServiceElement.appendChild(descriptionElement); } if (parameters.getLocation() != null) { Element locationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Location"); locationElement.appendChild(requestDoc.createTextNode(parameters.getLocation())); createHostedServiceElement.appendChild(locationElement); } if (parameters.getAffinityGroup() != null) { Element affinityGroupElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "AffinityGroup"); affinityGroupElement.appendChild(requestDoc.createTextNode(parameters.getAffinityGroup())); createHostedServiceElement.appendChild(affinityGroupElement); } if (parameters.getExtendedProperties() != null) { if (parameters.getExtendedProperties() instanceof LazyCollection == false || ((LazyCollection) parameters.getExtendedProperties()).isInitialized()) { Element extendedPropertiesDictionaryElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "ExtendedProperties"); for (Map.Entry<String, String> entry : parameters.getExtendedProperties().entrySet()) { String extendedPropertiesKey = entry.getKey(); String extendedPropertiesValue = entry.getValue(); Element extendedPropertiesElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "ExtendedProperty"); extendedPropertiesDictionaryElement.appendChild(extendedPropertiesElement); Element extendedPropertiesKeyElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); extendedPropertiesKeyElement.appendChild(requestDoc.createTextNode(extendedPropertiesKey)); extendedPropertiesElement.appendChild(extendedPropertiesKeyElement); Element extendedPropertiesValueElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "Value"); extendedPropertiesValueElement.appendChild(requestDoc.createTextNode(extendedPropertiesValue)); extendedPropertiesElement.appendChild(extendedPropertiesValueElement); } createHostedServiceElement.appendChild(extendedPropertiesDictionaryElement); } } if (parameters.getReverseDnsFqdn() != null) { Element reverseDnsFqdnElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ReverseDnsFqdn"); reverseDnsFqdnElement.appendChild(requestDoc.createTextNode(parameters.getReverseDnsFqdn())); createHostedServiceElement.appendChild(reverseDnsFqdnElement); } 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 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.websites.WebSiteOperationsImpl.java
/** * Updates an association to a hybrid connection for a web site. * * @param webSpaceName Required. The name of the web space. * @param siteName Required. The name of the web site. * @param parameters Required. Parameters supplied to the Create Hybrid * Connection operation.//from w w w .j av a 2 s.co m * @throws ParserConfigurationException Thrown if there was an error * configuring the parser for the response body. * @throws SAXException Thrown if there was an error parsing the response * body. * @throws TransformerException Thrown if there was an error creating the * DOM transformer. * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations. * @throws ServiceException Thrown if an unexpected response is found. * @return A standard service response including an HTTP status code and * request ID. */ @Override public OperationResponse updateHybridConnection(String webSpaceName, String siteName, HybridConnectionUpdateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { // Validate if (webSpaceName == null) { throw new NullPointerException("webSpaceName"); } if (siteName == null) { throw new NullPointerException("siteName"); } if (parameters == null) { throw new NullPointerException("parameters"); } if (parameters.getEntityName() == null) { throw new NullPointerException("parameters.EntityName"); } // Tracing boolean shouldTrace = CloudTracing.getIsEnabled(); String invocationId = null; if (shouldTrace) { invocationId = Long.toString(CloudTracing.getNextInvocationId()); HashMap<String, Object> tracingParameters = new HashMap<String, Object>(); tracingParameters.put("webSpaceName", webSpaceName); tracingParameters.put("siteName", siteName); tracingParameters.put("parameters", parameters); CloudTracing.enter(invocationId, this, "updateHybridConnectionAsync", tracingParameters); } // Construct URL String url = ""; url = url + "/"; if (this.getClient().getCredentials().getSubscriptionId() != null) { url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8"); } url = url + "/services/WebSpaces/"; url = url + URLEncoder.encode(webSpaceName, "UTF-8"); url = url + "/sites/"; url = url + URLEncoder.encode(siteName, "UTF-8"); url = url + "/hybridconnection"; String baseUrl = this.getClient().getBaseUri().toString(); // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl.charAt(baseUrl.length() - 1) == '/') { baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); } if (url.charAt(0) == '/') { url = url.substring(1); } url = baseUrl + "/" + url; url = url.replace(" ", "%20"); // Create HTTP transport objects HttpPut httpRequest = new HttpPut(url); // Set Headers httpRequest.setHeader("Content-Type", "application/xml"); httpRequest.setHeader("x-ms-version", "2014-04-01"); // Serialize Request String requestContent = null; DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document requestDoc = documentBuilder.newDocument(); Element relayServiceConnectionEntityElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "RelayServiceConnectionEntity"); requestDoc.appendChild(relayServiceConnectionEntityElement); if (parameters.getBiztalkUri() != null) { Element biztalkUriElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "BiztalkUri"); biztalkUriElement.appendChild(requestDoc.createTextNode(parameters.getBiztalkUri())); relayServiceConnectionEntityElement.appendChild(biztalkUriElement); } if (parameters.getEntityConnectionString() != null) { Element entityConnectionStringElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "EntityConnectionString"); entityConnectionStringElement .appendChild(requestDoc.createTextNode(parameters.getEntityConnectionString())); relayServiceConnectionEntityElement.appendChild(entityConnectionStringElement); } Element entityNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "EntityName"); entityNameElement.appendChild(requestDoc.createTextNode(parameters.getEntityName())); relayServiceConnectionEntityElement.appendChild(entityNameElement); if (parameters.getHostname() != null) { Element hostnameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Hostname"); hostnameElement.appendChild(requestDoc.createTextNode(parameters.getHostname())); relayServiceConnectionEntityElement.appendChild(hostnameElement); } Element portElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Port"); portElement.appendChild(requestDoc.createTextNode(Integer.toString(parameters.getPort()))); relayServiceConnectionEntityElement.appendChild(portElement); if (parameters.getResourceConnectionString() != null) { Element resourceConnectionStringElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "ResourceConnectionString"); resourceConnectionStringElement .appendChild(requestDoc.createTextNode(parameters.getResourceConnectionString())); relayServiceConnectionEntityElement.appendChild(resourceConnectionStringElement); } if (parameters.getResourceType() != null) { Element resourceTypeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "ResourceType"); resourceTypeElement.appendChild(requestDoc.createTextNode(parameters.getResourceType())); relayServiceConnectionEntityElement.appendChild(resourceTypeElement); } DOMSource domSource = new DOMSource(requestDoc); StringWriter stringWriter = new StringWriter(); StreamResult streamResult = new StreamResult(stringWriter); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.transform(domSource, streamResult); requestContent = stringWriter.toString(); StringEntity entity = new StringEntity(requestContent); httpRequest.setEntity(entity); httpRequest.setHeader("Content-Type", "application/xml"); // Send Request HttpResponse httpResponse = null; try { if (shouldTrace) { CloudTracing.sendRequest(invocationId, httpRequest); } httpResponse = this.getClient().getHttpClient().execute(httpRequest); if (shouldTrace) { CloudTracing.receiveResponse(invocationId, httpResponse); } int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result 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.websites.WebSiteOperationsImpl.java
/** * Restores a site to either a new site or existing site (Overwrite flag has * to be set to true for that)./*from w ww. ja v a 2 s.c o m*/ * * @param webSpaceName Required. The name of the web space. * @param webSiteName Required. The name of the web site. * @param restoreRequest Required. A restore request. * @throws ParserConfigurationException Thrown if there was an error * configuring the parser for the response body. * @throws SAXException Thrown if there was an error parsing the response * body. * @throws TransformerException Thrown if there was an error creating the * DOM transformer. * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations. * @throws ServiceException Thrown if an unexpected response is found. * @return Restore operation information. */ @Override public WebSiteRestoreResponse restore(String webSpaceName, String webSiteName, RestoreRequest restoreRequest) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { // Validate if (webSpaceName == null) { throw new NullPointerException("webSpaceName"); } if (webSiteName == null) { throw new NullPointerException("webSiteName"); } if (restoreRequest == null) { throw new NullPointerException("restoreRequest"); } // Tracing boolean shouldTrace = CloudTracing.getIsEnabled(); String invocationId = null; if (shouldTrace) { invocationId = Long.toString(CloudTracing.getNextInvocationId()); HashMap<String, Object> tracingParameters = new HashMap<String, Object>(); tracingParameters.put("webSpaceName", webSpaceName); tracingParameters.put("webSiteName", webSiteName); tracingParameters.put("restoreRequest", restoreRequest); CloudTracing.enter(invocationId, this, "restoreAsync", tracingParameters); } // Construct URL String url = ""; url = url + "/"; if (this.getClient().getCredentials().getSubscriptionId() != null) { url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8"); } url = url + "/services/WebSpaces/"; url = url + URLEncoder.encode(webSpaceName, "UTF-8"); url = url + "/sites/"; url = url + URLEncoder.encode(webSiteName, "UTF-8"); url = url + "/restore"; String baseUrl = this.getClient().getBaseUri().toString(); // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl.charAt(baseUrl.length() - 1) == '/') { baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); } if (url.charAt(0) == '/') { url = url.substring(1); } url = baseUrl + "/" + url; url = url.replace(" ", "%20"); // Create HTTP transport objects HttpPut httpRequest = new HttpPut(url); // Set Headers httpRequest.setHeader("Content-Type", "application/xml"); httpRequest.setHeader("x-ms-version", "2014-04-01"); // Serialize Request String requestContent = null; DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document requestDoc = documentBuilder.newDocument(); Element restoreRequestElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "RestoreRequest"); requestDoc.appendChild(restoreRequestElement); Element adjustConnectionStringsElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "AdjustConnectionStrings"); adjustConnectionStringsElement.appendChild(requestDoc .createTextNode(Boolean.toString(restoreRequest.isAdjustConnectionStrings()).toLowerCase())); restoreRequestElement.appendChild(adjustConnectionStringsElement); if (restoreRequest.getBlobName() != null) { Element blobNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "BlobName"); blobNameElement.appendChild(requestDoc.createTextNode(restoreRequest.getBlobName())); restoreRequestElement.appendChild(blobNameElement); } if (restoreRequest.getDatabases() != null) { if (restoreRequest.getDatabases() instanceof LazyCollection == false || ((LazyCollection) restoreRequest.getDatabases()).isInitialized()) { Element databasesSequenceElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "Databases"); for (DatabaseBackupSetting databasesItem : restoreRequest.getDatabases()) { Element databaseBackupSettingElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "DatabaseBackupSetting"); databasesSequenceElement.appendChild(databaseBackupSettingElement); if (databasesItem.getConnectionString() != null) { Element connectionStringElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "ConnectionString"); connectionStringElement .appendChild(requestDoc.createTextNode(databasesItem.getConnectionString())); databaseBackupSettingElement.appendChild(connectionStringElement); } if (databasesItem.getConnectionStringName() != null) { Element connectionStringNameElement = requestDoc.createElementNS( "http://schemas.microsoft.com/windowsazure", "ConnectionStringName"); connectionStringNameElement .appendChild(requestDoc.createTextNode(databasesItem.getConnectionStringName())); databaseBackupSettingElement.appendChild(connectionStringNameElement); } if (databasesItem.getDatabaseType() != null) { Element databaseTypeElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "DatabaseType"); databaseTypeElement.appendChild(requestDoc.createTextNode(databasesItem.getDatabaseType())); databaseBackupSettingElement.appendChild(databaseTypeElement); } if (databasesItem.getName() != null) { Element nameElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "Name"); nameElement.appendChild(requestDoc.createTextNode(databasesItem.getName())); databaseBackupSettingElement.appendChild(nameElement); } } restoreRequestElement.appendChild(databasesSequenceElement); } } Element ignoreConflictingHostNamesElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "IgnoreConflictingHostNames"); ignoreConflictingHostNamesElement.appendChild(requestDoc .createTextNode(Boolean.toString(restoreRequest.isIgnoreConflictingHostNames()).toLowerCase())); restoreRequestElement.appendChild(ignoreConflictingHostNamesElement); Element overwriteElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Overwrite"); overwriteElement.appendChild( requestDoc.createTextNode(Boolean.toString(restoreRequest.isOverwrite()).toLowerCase())); restoreRequestElement.appendChild(overwriteElement); if (restoreRequest.getStorageAccountUrl() != null) { Element storageAccountUrlElement = requestDoc .createElementNS("http://schemas.microsoft.com/windowsazure", "StorageAccountUrl"); storageAccountUrlElement.appendChild(requestDoc.createTextNode(restoreRequest.getStorageAccountUrl())); restoreRequestElement.appendChild(storageAccountUrlElement); } DOMSource domSource = new DOMSource(requestDoc); StringWriter stringWriter = new StringWriter(); StreamResult streamResult = new StreamResult(stringWriter); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.transform(domSource, streamResult); requestContent = stringWriter.toString(); StringEntity entity = new StringEntity(requestContent); httpRequest.setEntity(entity); httpRequest.setHeader("Content-Type", "application/xml"); // Send Request HttpResponse httpResponse = null; try { if (shouldTrace) { CloudTracing.sendRequest(invocationId, httpRequest); } httpResponse = this.getClient().getHttpClient().execute(httpRequest); if (shouldTrace) { CloudTracing.receiveResponse(invocationId, httpResponse); } int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result WebSiteRestoreResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_OK) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new WebSiteRestoreResponse(); DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance(); documentBuilderFactory2.setNamespaceAware(true); DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder(); Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent)); Element restoreResponseElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "RestoreResponse"); if (restoreResponseElement != null) { Element operationIdElement = XmlUtility.getElementByTagNameNS(restoreResponseElement, "http://schemas.microsoft.com/windowsazure", "OperationId"); if (operationIdElement != null) { String operationIdInstance; operationIdInstance = operationIdElement.getTextContent(); result.setOperationId(operationIdInstance); } } } 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(); } } }