List of usage examples for org.w3c.dom Document createTextNode
public Text createTextNode(String data);
Text
node given the specified string. From source file:conf.Configuration.java
/** * Write out the non-default properties in this configuration to the given * {@link Writer}./*from w w w . ja v a 2 s . c o m*/ * * @param out the writer to write to. */ public synchronized void writeXml(Writer out) throws IOException { Properties properties = getProps(); try { Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Element conf = doc.createElement("configuration"); doc.appendChild(conf); conf.appendChild(doc.createTextNode("\n")); for (Enumeration e = properties.keys(); e.hasMoreElements();) { String name = (String) e.nextElement(); Object object = properties.get(name); String value = null; if (object instanceof String) { value = (String) object; } else { continue; } Element propNode = doc.createElement("property"); conf.appendChild(propNode); if (updatingResource != null) { Comment commentNode = doc.createComment("Loaded from " + updatingResource.get(name)); propNode.appendChild(commentNode); } Element nameNode = doc.createElement("name"); nameNode.appendChild(doc.createTextNode(name)); propNode.appendChild(nameNode); Element valueNode = doc.createElement("value"); valueNode.appendChild(doc.createTextNode(value)); propNode.appendChild(valueNode); conf.appendChild(doc.createTextNode("\n")); } DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(out); TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer = transFactory.newTransformer(); transformer.transform(source, result); } catch (TransformerException te) { throw new IOException(te); } catch (ParserConfigurationException pe) { throw new IOException(pe); } }
From source file:com.sap.research.roo.addon.nwcloud.NWCloudOperationsImpl.java
/** * This is the command "nwcloud enable-jpa". It will configure the JPA persistence layer in a * way that will use the HANA Cloud persistence service. *//*from w w w.j a va 2 s . c o m*/ public void nwcloudEnableJPA() { // TODO // One could check here if ECLIPSELINK is used as JPA provider in persistence.xml // and abort, if something else is used. // 1. Copy the "persistence.xml" from the addon resources to the directory // "src\main\resources\META-INF\persistence.xml" of the project. // -> the existing "persistence.xml" will be overwritten, so we will do // a backup before to be able to revert this operation. // Get the META-INF dir of the current project ("src\main\resources\META-INF") // (Later in the packaged WAR this directory will reside in "WEB-INF\classes\META-INF".) String dirWebMetaInf = this.getPathResolved(Path.SRC_MAIN_RESOURCES, "META-INF"); // Backup "persistence.xml" which is located in this folder this.backup(dirWebMetaInf + File.separatorChar + "persistence.xml", null); // Overwrite the existing "persistence.xml" with the one included in the resources of our addon copyFileFromAddonToProject(dirWebMetaInf, "persistence.xml", "HANA Cloud JPA persistency config (needs EclipseLink)"); // -------------------------------------------------------------------------------- // 2. Backup "src\main\webapp\WEB-INF\web.xml" first, and then modify it by inserting // the following to declare the DataSource which the application server should // fetch from the environment and provide to the web app through JNDI. // <resource-ref> // <res-ref-name>jdbc/DefaultDB</res-ref-name> // <res-type>javax.sql.DataSource</res-type> // </resource-ref> // Get the WEB-INF dir ("src\main\webapp\WEB-INF"), where the "web.xml" is located. String dirWebInf = this.getPathResolved(Path.SRC_MAIN_WEBAPP, "WEB-INF"); String fileWebXml = dirWebInf + File.separatorChar + "web.xml"; // Backup "src\main\webapp\META-INF\web.xml" this.backup(fileWebXml, null); // Insert declaration for app server in "web.xml" to import DataSource from environment to JNDI // Read "web.xml" and store reference to root Element Document document = XmlUtils.readXml(fileManager.getInputStream(fileWebXml)); Element root = document.getDocumentElement(); // Add JNDI ressource definition for JPA data source to use (if it does not yet exist) if (XmlUtils.findFirstElement("/web-app/resource-ref/resource-ref-name[text()='jdbc/DefaultDB']", root) == null) { // Create needed DOM elements String elemNamespace = "http://java.sun.com/xml/ns/javaee"; Element resRefElement = document.createElementNS(elemNamespace, "resource-ref"); Element resRefNameElement = document.createElementNS(elemNamespace, "res-ref-name"); Node resRefNameElementText = document.createTextNode("jdbc/DefaultDB"); Element resRefTypeElement = document.createElementNS(elemNamespace, "res-type"); Node resRefTypeElementText = document.createTextNode("javax.sql.DataSource"); // Connect and insert elements in XML document resRefNameElement.appendChild(resRefNameElementText); resRefTypeElement.appendChild(resRefTypeElementText); resRefElement.appendChild(resRefNameElement); resRefElement.appendChild(resRefTypeElement); root.appendChild(resRefElement); // Update "web.xml" String descriptionOfChange = "Added JNDI ressource for JPA datasource"; fileManager.createOrUpdateTextFileIfRequired(fileWebXml, XmlUtils.nodeToString(document), descriptionOfChange, true); } // -------------------------------------------------------------------------------- // 3. Modify "src\main\resources\META-INF\spring\applicationContext.xml" // - Remove the existing declaration of the "dataSource" bean // <bean class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" id="dataSource"> // [...] // </bean> // - Insert statement to fetch dataSource from JNDI (as created by application server) // <jee:jndi-lookup id="dataSource" jndi-name="jdbc/DefaultDB" /> // Get the Spring config file of the current project ("src\main\resources\META-INF\spring\applicationContext.xml") // and create a backup of it, so we're able to revert the changes. String fileSpringConf = this.getPathResolved(Path.SPRING_CONFIG_ROOT, "applicationContext.xml"); this.backup(fileSpringConf, null); // Read "applicationContext.xml" and store reference to root Element document = XmlUtils.readXml(fileManager.getInputStream(fileSpringConf)); root = document.getDocumentElement(); // Loop through all bean elements and remove all beans having id "dataSource" String descriptionOfChange = ""; List<Element> beanElements = XmlUtils.findElements("/beans/bean", root); for (Element beanElement : beanElements) { // Did we find the bean with the id "dataSource"? if (beanElement.getAttribute("id").equalsIgnoreCase("dataSource")) { Node parent = beanElement.getParentNode(); parent.removeChild(beanElement); DomUtils.removeTextNodes(parent); descriptionOfChange = "Removed bean storing static datasource"; // We will not break the loop (even though we could theoretically), just in case there is more than one such bean declared } } // Update "applicationContext.xml" file if something has changed fileManager.createOrUpdateTextFileIfRequired(fileSpringConf, XmlUtils.nodeToString(document), descriptionOfChange, true); // Add bean for dynamic JNDI lookup of datasource (if it does not yet exist) if (XmlUtils.findFirstElement("/beans/jndi-lookup[@id='dataSource']", root) == null) { Element newJndiElement = document.createElementNS("http://www.springframework.org/schema/jee", "jee:jndi-lookup"); newJndiElement.setAttribute("id", "dataSource"); newJndiElement.setAttribute("jndi-name", "jdbc/DefaultDB"); root.appendChild(newJndiElement); descriptionOfChange = "Added bean for dynamic JNDI lookup of datasource"; // Update "applicationContext.xml" fileManager.createOrUpdateTextFileIfRequired(fileSpringConf, XmlUtils.nodeToString(document), descriptionOfChange, true); } }
From source file:jef.tools.XMLUtils.java
/** * ?//from w ww .j av a 2 s . c om * * @param node * * @param data * * @return DOM */ public static Text setText(Node node, String data) { Document doc = null; if (node.getNodeType() == Node.DOCUMENT_NODE) { doc = (Document) node; } else { doc = node.getOwnerDocument(); } clearChildren(node, Node.TEXT_NODE); Text t = doc.createTextNode(data); node.appendChild(t); return t; }
From source file:com.ToResultSet.java
@Path("/input") @GET/*from www. j a va 2 s . co m*/ @Produces(MediaType.APPLICATION_JSON) public String toResultSet(@QueryParam("budget") String x, @QueryParam("maxbudget") String y, @QueryParam("location") String location, @QueryParam("date") String minDateString) throws ParserConfigurationException, TransformerException, ParseException { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { System.out.println("Fehler bei MySQL-JDBC-Bridge" + e); } //SQL Query wird hier erzeugt je nach dem Daten, die angegeben werden try { int minBudget = 0; int maxBudget = 0; try { minBudget = Integer.valueOf(x); } catch (NumberFormatException e) { if (x.length() > 0) { return "Ihre Budget soll aus Zahlen bestehen"; } } try { maxBudget = Integer.valueOf(y); } catch (NumberFormatException e) { if (y.length() > 0) { return "Ihre Budget soll aus Zahlen bestehen"; } } try { test = Integer.valueOf(location); if (test >= 0) { return "Location soll aus String bestehen"; } } catch (Exception e) { } try { if (minDateString.substring(2, 3).contains("-") && minDateString.length() > 0) { return "Date Format soll yyyy-MM-dd"; } else { java.util.Date date1 = sdf.parse(minDateString); minDate = new java.sql.Date(date1.getTime()); } } catch (Exception e) { if (minDateString.length() > 0) return "Date Format soll yyyy-MM-dd"; } //Connection mit dem SQL wird erzeugt String url = "jdbc:mysql://" + host + "/" + dbName; connection = DriverManager.getConnection( "jdbc:mysql://localhost:3306/location?autoReconnect=true&useSSL=false", "root", "dreamhigh"); statement = connection.createStatement(); String sqlQuery = "Select * FROM " + dbTable; List<String> whereClause = new ArrayList<>(); if (minBudget > 0) { whereClause.add("Budget >= " + minBudget); } if (maxBudget > 0) { whereClause.add("Budget <= " + maxBudget); } if (minBudget > maxBudget && maxBudget > 0 && minBudget > 0) { return "Minimal Budget soll kleiner als Maximal Budget"; } if (minDate != null) { whereClause.add("Date >= '" + minDate + "'"); } if (location != null && !location.isEmpty()) { whereClause.add("Location = '" + location + "'"); } //Die Daten werden nach dem Budget absteigend sortiert if (whereClause.size() > 0) { sqlQuery += " WHERE " + StringUtils.join(whereClause, " AND ") + " ORDER BY Budget DESC"; } if (whereClause.size() == 0) { sqlQuery += " ORDER BY Budget DESC"; } resultSet = statement.executeQuery(sqlQuery); int spalten = resultSet.getMetaData().getColumnCount(); System.out.println("Anzahl Spalten: " + spalten); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.newDocument(); Element results = doc.createElement("Results"); doc.appendChild(results); connection = DriverManager.getConnection( "jdbc:mysql://localhost:3306/location?autoReconnect=true&useSSL=false", "root", "dreamhigh"); ResultSetMetaData rsmd = resultSet.getMetaData(); int colCount = rsmd.getColumnCount(); while (resultSet.next()) { String[] str = new String[8]; for (int k = 1; k <= spalten; k++) { str[k - 1] = resultSet.getString(k); result.add(resultSet.getString(k)); } //Result wird hier als XML zuerst erzeugt und dann Json Element row = doc.createElement("Row"); results.appendChild(row); for (int ii = 1; ii <= colCount; ii++) { String columnName = rsmd.getColumnName(ii); Object value = resultSet.getObject(ii); Element node = doc.createElement(columnName); if (value != null) { node.appendChild(doc.createTextNode(value.toString())); row.appendChild(node); } } } System.out.println(getDocumentAsXml(doc)); try { xmlJSONObj = XML.toJSONObject(getDocumentAsXml(doc)); outPut = xmlJSONObj.toString(4); System.out.println(outPut); return outPut; } catch (JSONException je) { } } catch (SQLException e) { System.out.println("Fehler bei Tabellenabfrage: " + e); } return outPut; }
From source file:com.microsoft.windowsazure.management.scheduler.CloudServiceOperationsImpl.java
/** * Create a cloud service.// ww w . ja v a 2 s . c o m * * @param cloudServiceName Required. The cloud service name. * @param parameters Required. Parameters supplied to the Create cloud * service operation. * @throws ParserConfigurationException Thrown if there was an error * configuring the parser for the response body. * @throws SAXException Thrown if there was an error parsing the response * body. * @throws TransformerException Thrown if there was an error creating the * DOM transformer. * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations. * @throws ServiceException Thrown if an unexpected response is found. * @return A standard service response including an HTTP status code and * request ID. */ @Override public OperationResponse beginCreating(String cloudServiceName, CloudServiceCreateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { // Validate if (cloudServiceName == null) { throw new NullPointerException("cloudServiceName"); } if (cloudServiceName.length() > 100) { throw new IllegalArgumentException("cloudServiceName"); } if (parameters == null) { throw new NullPointerException("parameters"); } if (parameters.getDescription() == null) { throw new NullPointerException("parameters.Description"); } if (parameters.getDescription().length() > 1024) { throw new IllegalArgumentException("parameters.Description"); } if (parameters.getGeoRegion() == null) { throw new NullPointerException("parameters.GeoRegion"); } if (parameters.getLabel() == null) { throw new NullPointerException("parameters.Label"); } if (parameters.getLabel().length() > 100) { throw new IllegalArgumentException("parameters.Label"); } // 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("cloudServiceName", cloudServiceName); tracingParameters.put("parameters", parameters); CloudTracing.enter(invocationId, this, "beginCreatingAsync", tracingParameters); } // Construct URL String url = ""; if (this.getClient().getCredentials().getSubscriptionId() != null) { url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8"); } url = url + "/CloudServices/"; url = url + URLEncoder.encode(cloudServiceName, "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", "2013-03-01"); // Serialize Request String requestContent = null; DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document requestDoc = documentBuilder.newDocument(); Element cloudServiceElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "CloudService"); requestDoc.appendChild(cloudServiceElement); Element labelElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Label"); labelElement.appendChild(requestDoc.createTextNode(parameters.getLabel())); cloudServiceElement.appendChild(labelElement); Element descriptionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Description"); descriptionElement.appendChild(requestDoc.createTextNode(parameters.getDescription())); cloudServiceElement.appendChild(descriptionElement); Element geoRegionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "GeoRegion"); geoRegionElement.appendChild(requestDoc.createTextNode(parameters.getGeoRegion())); cloudServiceElement.appendChild(geoRegionElement); if (parameters.getEmail() != null) { Element emailElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Email"); emailElement.appendChild(requestDoc.createTextNode(parameters.getEmail())); cloudServiceElement.appendChild(emailElement); } 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.mediaservices.AccountOperationsImpl.java
/** * The Create Media Services Account operation creates a new media services * account in Windows Azure. (see/*from ww w. jav a 2 s. c o m*/ * http://msdn.microsoft.com/en-us/library/windowsazure/dn194267.aspx for * more information) * * @param parameters Required. Parameters supplied to the Create Media * Services Account operation. * @throws ParserConfigurationException Thrown if there was an error * configuring the parser for the response body. * @throws SAXException Thrown if there was an error parsing the response * body. * @throws TransformerException Thrown if there was an error creating the * DOM transformer. * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations. * @throws ServiceException Thrown if an unexpected response is found. * @return The Create Media Services Account operation response. */ @Override public MediaServicesAccountCreateResponse create(MediaServicesAccountCreateParameters parameters) throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException { // Validate if (parameters == null) { throw new NullPointerException("parameters"); } if (parameters.getAccountName() == null) { throw new NullPointerException("parameters.AccountName"); } if (parameters.getAccountName().length() < 3) { throw new IllegalArgumentException("parameters.AccountName"); } if (parameters.getAccountName().length() > 24) { throw new IllegalArgumentException("parameters.AccountName"); } if (parameters.getBlobStorageEndpointUri() == null) { throw new NullPointerException("parameters.BlobStorageEndpointUri"); } if (parameters.getRegion() == null) { throw new NullPointerException("parameters.Region"); } if (parameters.getRegion().length() < 3) { throw new IllegalArgumentException("parameters.Region"); } if (parameters.getRegion().length() > 256) { throw new IllegalArgumentException("parameters.Region"); } if (parameters.getStorageAccountKey() == null) { throw new NullPointerException("parameters.StorageAccountKey"); } if (parameters.getStorageAccountKey().length() < 14) { throw new IllegalArgumentException("parameters.StorageAccountKey"); } if (parameters.getStorageAccountKey().length() > 256) { throw new IllegalArgumentException("parameters.StorageAccountKey"); } if (parameters.getStorageAccountName() == null) { throw new NullPointerException("parameters.StorageAccountName"); } if (parameters.getStorageAccountName().length() < 3) { throw new IllegalArgumentException("parameters.StorageAccountName"); } if (parameters.getStorageAccountName().length() > 24) { throw new IllegalArgumentException("parameters.StorageAccountName"); } for (char storageAccountNameChar : parameters.getStorageAccountName().toCharArray()) { if (Character.isLowerCase(storageAccountNameChar) == false && Character.isDigit(storageAccountNameChar) == false) { throw new IllegalArgumentException("parameters.StorageAccountName"); } } // 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/mediaservices/Accounts"; 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", "2011-10-01"); // Serialize Request String requestContent = null; DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document requestDoc = documentBuilder.newDocument(); Element accountCreationRequestElement = requestDoc.createElementNS( "http://schemas.datacontract.org/2004/07/Microsoft.Cloud.Media.Management.ResourceProvider.Models", "AccountCreationRequest"); requestDoc.appendChild(accountCreationRequestElement); Element accountNameElement = requestDoc.createElementNS( "http://schemas.datacontract.org/2004/07/Microsoft.Cloud.Media.Management.ResourceProvider.Models", "AccountName"); accountNameElement.appendChild(requestDoc.createTextNode(parameters.getAccountName())); accountCreationRequestElement.appendChild(accountNameElement); Element blobStorageEndpointUriElement = requestDoc.createElementNS( "http://schemas.datacontract.org/2004/07/Microsoft.Cloud.Media.Management.ResourceProvider.Models", "BlobStorageEndpointUri"); blobStorageEndpointUriElement .appendChild(requestDoc.createTextNode(parameters.getBlobStorageEndpointUri().toString())); accountCreationRequestElement.appendChild(blobStorageEndpointUriElement); Element regionElement = requestDoc.createElementNS( "http://schemas.datacontract.org/2004/07/Microsoft.Cloud.Media.Management.ResourceProvider.Models", "Region"); regionElement.appendChild(requestDoc.createTextNode(parameters.getRegion())); accountCreationRequestElement.appendChild(regionElement); Element storageAccountKeyElement = requestDoc.createElementNS( "http://schemas.datacontract.org/2004/07/Microsoft.Cloud.Media.Management.ResourceProvider.Models", "StorageAccountKey"); storageAccountKeyElement.appendChild(requestDoc.createTextNode(parameters.getStorageAccountKey())); accountCreationRequestElement.appendChild(storageAccountKeyElement); Element storageAccountNameElement = requestDoc.createElementNS( "http://schemas.datacontract.org/2004/07/Microsoft.Cloud.Media.Management.ResourceProvider.Models", "StorageAccountName"); storageAccountNameElement.appendChild(requestDoc.createTextNode(parameters.getStorageAccountName())); accountCreationRequestElement.appendChild(storageAccountNameElement); 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.createFromJson(httpRequest, requestContent, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result MediaServicesAccountCreateResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_CREATED) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new MediaServicesAccountCreateResponse(); ObjectMapper objectMapper = new ObjectMapper(); JsonNode responseDoc = null; String responseDocContent = IOUtils.toString(responseContent); if (responseDocContent == null == false && responseDocContent.length() > 0) { responseDoc = objectMapper.readTree(responseDocContent); } if (responseDoc != null && responseDoc instanceof NullNode == false) { MediaServicesCreatedAccount accountInstance = new MediaServicesCreatedAccount(); result.setAccount(accountInstance); JsonNode accountIdValue = responseDoc.get("AccountId"); if (accountIdValue != null && accountIdValue instanceof NullNode == false) { String accountIdInstance; accountIdInstance = accountIdValue.getTextValue(); accountInstance.setAccountId(accountIdInstance); } JsonNode accountNameValue = responseDoc.get("AccountName"); if (accountNameValue != null && accountNameValue instanceof NullNode == false) { String accountNameInstance; accountNameInstance = accountNameValue.getTextValue(); accountInstance.setAccountName(accountNameInstance); } JsonNode subscriptionValue = responseDoc.get("Subscription"); if (subscriptionValue != null && subscriptionValue instanceof NullNode == false) { String subscriptionInstance; subscriptionInstance = subscriptionValue.getTextValue(); accountInstance.setSubscriptionId(subscriptionInstance); } } } 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:de.fuberlin.wiwiss.marbles.MarblesServlet.java
/** * Enhances source data with consistently colored icons; * adds detailed source list to Fresnel output * /* w w w . j ava 2s . co m*/ * @param doc The Fresnel tree */ private void addSources(Document doc, List<org.apache.commons.httpclient.URI> retrievedURLs) { int colorIndex = 0; HashMap<String, Source> sources = new HashMap<String, Source>(); NodeList nodeList = doc.getElementsByTagName("source"); int numNodes = nodeList.getLength(); for (int i = 0; i < numNodes; i++) { Node node = nodeList.item(i); String uri = node.getFirstChild().getFirstChild().getNodeValue(); Source source; /* Get source, create it if necessary */ if (null == (source = sources.get(uri))) { source = new Source(uri); colorIndex = source.determineIcon(colorIndex); sources.put(uri, source); } /* Enhance source reference with icon */ Element sourceIcon = doc.createElementNS(Constants.nsFresnelView, "sourceIcon"); sourceIcon.appendChild(doc.createTextNode(source.getIcon())); node.appendChild(sourceIcon); } /* Supplement source list with retrieved URLs */ if (retrievedURLs != null) for (org.apache.commons.httpclient.URI uri : retrievedURLs) { Source source; if (null == (source = sources.get(uri.toString()))) { source = new Source(uri.toString()); colorIndex = source.determineIcon(colorIndex); sources.put(uri.toString(), source); } } /* Provide list of sources */ RepositoryConnection metaDataConn = null; try { metaDataConn = metaDataRepository.getConnection(); Element sourcesElement = doc.createElementNS(Constants.nsFresnelView, "sources"); for (String uri : sources.keySet()) { Source source = sources.get(uri); sourcesElement.appendChild(source.toElement(doc, cacheController, metaDataConn)); } Node results = doc.getFirstChild(); results.appendChild(sourcesElement); } catch (RepositoryException e) { e.printStackTrace(); } finally { try { if (metaDataConn != null) metaDataConn.close(); } catch (RepositoryException e) { e.printStackTrace(); } } }
From source file:com.centeractive.ws.builder.soap.XmlUtils.java
public static Document addResultSetXmlPart(Element resultsElement, ResultSet rs, Document xmlDocumentResult) throws SQLException { // resultSet = statement.getResultSet(); // connection to an ACCESS MDB ResultSetMetaData rsmd = rs.getMetaData(); Element resultSetElement = xmlDocumentResult.createElement("ResultSet"); resultSetElement.setAttribute("fetchSize", String.valueOf(rs.getFetchSize())); resultsElement.appendChild(resultSetElement); int colCount = rsmd.getColumnCount(); while (rs.next()) { Element rowElement = xmlDocumentResult.createElement("Row"); rowElement.setAttribute("rowNumber", String.valueOf(rs.getRow())); resultsElement.appendChild(rowElement); for (int ii = 1; ii <= colCount; ii++) { String columnName = ""; if (!StringUtils.isBlank(rsmd.getTableName(ii))) { columnName += (rsmd.getTableName(ii)).toUpperCase() + "."; }//from w w w . j a v a 2 s. co m columnName += (rsmd.getColumnName(ii)).toUpperCase(); String value = rs.getString(ii); Element node = xmlDocumentResult.createElement(createXmlName(columnName)); if (!StringUtils.isBlank(value)) { Text textNode = xmlDocumentResult.createTextNode(value.toString()); node.appendChild(textNode); } rowElement.appendChild(node); } resultSetElement.appendChild(rowElement); } return xmlDocumentResult; }
From source file:org.openmrs.web.controller.report.CohortReportFormController.java
/** * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse, java.lang.Object, * org.springframework.validation.BindException) *//*w ww . j a v a2 s . co m*/ @Override protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object commandObj, BindException errors) throws Exception { CommandObject command = (CommandObject) commandObj; // do simpleframework serialization of everything but 'rows', and add those via handcoded xml, since // serializing them is not reversible ReportSchema rs = new ReportSchema(); rs.setReportSchemaId(command.getReportId()); rs.setName(command.getName()); rs.setDescription(command.getDescription()); rs.setReportParameters(command.getParameters()); rs.setDataSetDefinitions(new ArrayList<DataSetDefinition>()); Serializer serializer = OpenmrsUtil.getSerializer(); StringWriter sw = new StringWriter(); serializer.write(rs, sw); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(false); DocumentBuilder db = dbf.newDocumentBuilder(); Document xml = db.parse(new InputSource( new StringReader("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>" + sw.toString()))); Node node = findChild(xml, "reportSchema"); node = findChild(node, "dataSets"); Element dsd = xml.createElement("dataSetDefinition"); dsd.setAttribute("name", "cohorts"); dsd.setAttribute("class", "org.openmrs.report.CohortDataSetDefinition"); node.appendChild(dsd); Element strategies = xml.createElement("strategies"); strategies.setAttribute("class", "java.util.LinkedHashMap"); dsd.appendChild(strategies); Element descriptions = xml.createElement("descriptions"); descriptions.setAttribute("class", "java.util.LinkedHashMap"); dsd.appendChild(descriptions); for (CohortReportRow row : command.getRows()) { if (StringUtils.hasText(row.getQuery())) { Element entry = xml.createElement("entry"); strategies.appendChild(entry); Element nameEl = xml.createElement("string"); Text val = xml.createTextNode(row.getName()); val.setNodeValue(row.getName()); nameEl.appendChild(val); entry.appendChild(nameEl); Element cohort = xml.createElement("cohort"); entry.appendChild(cohort); cohort.setAttribute("class", "org.openmrs.reporting.PatientSearch"); Element strategyEl = xml.createElement("specification"); val = xml.createTextNode(row.getQuery()); val.setNodeValue(row.getQuery()); strategyEl.appendChild(val); cohort.appendChild(strategyEl); } if (StringUtils.hasText(row.getDescription())) { Element entry = xml.createElement("entry"); descriptions.appendChild(entry); Element el = xml.createElement("string"); Text val = xml.createTextNode(row.getName()); val.setNodeValue(row.getName()); el.appendChild(val); entry.appendChild(el); el = xml.createElement("string"); val = xml.createTextNode(row.getDescription()); val.setNodeValue(row.getDescription()); el.appendChild(val); entry.appendChild(el); } } // now turn this into an xml string System.setProperty("javax.xml.transform.TransformerFactory", "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl"); TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans = transfac.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); trans.setOutputProperty(OutputKeys.INDENT, "yes"); trans.setOutputProperty(OutputKeys.METHOD, "xml"); StringWriter out = new StringWriter(); StreamResult result = new StreamResult(out); DOMSource source = new DOMSource(xml); trans.transform(source, result); String schemaXml = out.toString(); ReportSchemaXml rsx = new ReportSchemaXml(); rsx.populateFromReportSchema(rs); rsx.setXml(schemaXml); rsx.updateXmlFromAttributes(); rsx.setUuid(request.getParameter("parentUUID")); ReportService rptSvc = (ReportService) Context.getService(ReportService.class); if (rsx.getReportSchemaId() != null) { rptSvc.saveReportSchemaXml(rsx); } else { rptSvc.saveReportSchemaXml(rsx); } return new ModelAndView(new RedirectView(getSuccessView() + "?reportId=" + rsx.getReportSchemaId())); }
From source file:com.dinochiesa.edgecallouts.EditXmlNode.java
private void execute0(Document document, MessageContext msgCtxt) throws Exception { String xpath = getXpath(msgCtxt); XPathEvaluator xpe = getXpe(msgCtxt); NodeList nodes = (NodeList) xpe.evaluate(xpath, document, XPathConstants.NODESET); validate(nodes);//from w w w . j a va2 s . c om EditAction action = getAction(msgCtxt); if (action == EditAction.Remove) { remove(nodes); return; } short newNodeType = getNewNodeType(msgCtxt); String text = getNewNodeText(msgCtxt); Node newNode = null; switch (newNodeType) { case Node.ELEMENT_NODE: // Create a duplicate node and transfer ownership of the // new node into the destination document. Document temp = XmlUtils.parseXml(text); newNode = document.importNode(temp.getDocumentElement(), true); break; case Node.ATTRIBUTE_NODE: if (text.indexOf("=") < 1) { throw new IllegalStateException("attribute spec must be name=value"); } String[] parts = text.split("=", 2); if (parts.length != 2) throw new IllegalStateException("attribute spec must be name=value"); Attr attr = document.createAttribute(parts[0]); attr.setValue(parts[1]); newNode = attr; break; case Node.TEXT_NODE: newNode = document.createTextNode(text); break; } switch (action) { case InsertBefore: insertBefore(nodes, newNode, newNodeType); break; case Append: append(nodes, newNode, newNodeType); break; case Replace: replace(nodes, newNode, newNodeType); break; } }