List of usage examples for javax.xml.parsers DocumentBuilder newDocument
public abstract Document newDocument();
From source file:de.mpg.escidoc.services.tools.scripts.person_grants.Util.java
/** * Queries an eSciDoc instance//from ww w . j ava 2 s . c o m * * @param url * @param query * @param adminUserName * @param adminPassword * @param frameworkUrl * @return */ public static Document queryFramework(String url, String query, String adminUserName, String adminPassword, String frameworkUrl) { try { DocumentBuilder documentBuilder; DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactoryImpl.newInstance(); documentBuilderFactory.setNamespaceAware(true); documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.newDocument(); HttpClient client = new HttpClient(); client.getParams().setParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true); GetMethod getMethod = new GetMethod(url + "?query=" + (query != null ? URLEncoder.encode(query, "UTF-8") : "") + "&eSciDocUserHandle=" + Base64.encode( getAdminUserHandle(adminUserName, adminPassword, frameworkUrl).getBytes("UTF-8"))); System.out.println("Querying <" + url + "?query=" + (query != null ? URLEncoder.encode(query, "UTF-8") : "") + "&eSciDocUserHandle=" + Base64.encode( getAdminUserHandle(adminUserName, adminPassword, frameworkUrl).getBytes("UTF-8"))); client.executeMethod(getMethod); if (getMethod.getStatusCode() == 200) { document = documentBuilder.parse(getMethod.getResponseBodyAsStream()); } else { System.out.println("Error querying: Status " + getMethod.getStatusCode() + "\n" + getMethod.getResponseBodyAsString()); } return document; } catch (Exception e) { try { System.out.println("Error querying Framework <" + url + "?query=" + (query != null ? URLEncoder.encode(query, "UTF-8") : "") + "&eSciDocUserHandle=" + Base64.encode( getAdminUserHandle(adminUserName, adminPassword, frameworkUrl).getBytes("UTF-8")) + ">"); } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } e.printStackTrace(); } return null; }
From source file:eu.stork.peps.test.simple.SSETestUtils.java
/** * Marshall.//from w ww .j a v a 2 s . co m * * @param samlToken the SAML token * * @return the byte[] * * @throws MarshallingException the marshalling exception * @throws ParserConfigurationException the parser configuration exception * @throws TransformerException the transformer exception */ public static byte[] marshall(final XMLObject samlToken) throws MarshallingException, ParserConfigurationException, TransformerException { final javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance(); dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); dbf.setNamespaceAware(true); dbf.setIgnoringComments(true); final javax.xml.parsers.DocumentBuilder docBuild = dbf.newDocumentBuilder(); // Get the marshaller factory final MarshallerFactory marshallerFactory = Configuration.getMarshallerFactory(); // Get the Subject marshaller final Marshaller marshaller = marshallerFactory.getMarshaller(samlToken); final Document doc = docBuild.newDocument(); // Marshall the SAML token marshaller.marshall(samlToken, doc); // Obtain a byte array representation of the marshalled SAML object final DOMSource domSource = new DOMSource(doc); final StringWriter writer = new StringWriter(); final StreamResult result = new StreamResult(writer); final TransformerFactory transFact = TransformerFactory.newInstance(); final Transformer transformer = transFact.newTransformer(); transformer.transform(domSource, result); return writer.toString().getBytes(); }
From source file:eu.eidas.engine.test.simple.SSETestUtils.java
/** * Marshall./*from w ww. j a v a2 s . co m*/ * * @param samlToken the SAML token * * @return the byte[] * * @throws MarshallingException the marshalling exception * @throws ParserConfigurationException the parser configuration exception * @throws TransformerException the transformer exception */ public static byte[] marshall(final XMLObject samlToken) throws MarshallingException, ParserConfigurationException, TransformerException { final javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance(); dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); dbf.setNamespaceAware(true); dbf.setIgnoringComments(true); final javax.xml.parsers.DocumentBuilder docBuild = dbf.newDocumentBuilder(); // Get the marshaller factory final MarshallerFactory marshallerFactory = Configuration.getMarshallerFactory(); // Get the Subject marshaller final Marshaller marshaller = marshallerFactory.getMarshaller(samlToken); final Document doc = docBuild.newDocument(); // Marshall the SAML token marshaller.marshall(samlToken, doc); // Obtain a byte array representation of the marshalled SAML object final DOMSource domSource = new DOMSource(doc); ByteArrayOutputStream baos = new ByteArrayOutputStream(); final StreamResult result = new StreamResult(new OutputStreamWriter(baos, Constants.UTF8)); final TransformerFactory transFact = TransformerFactory.newInstance(); final Transformer transformer = transFact.newTransformer(); transformer.transform(domSource, result); return baos.toByteArray(); }
From source file:com.hpe.application.automation.tools.octane.executor.TestExecutionJobCreatorService.java
private static String prepareMtbxData(List<TestExecutionInfo> tests) throws IOException { /*<Mtbx>//from w w w. j a va 2 s. co m <Test name="test1" path="${WORKSPACE}\${CHECKOUT_SUBDIR}\APITest1"> <Parameter name="A" value="abc" type="string"/> <DataTable path="${WORKSPACE}\aa\bbb.xslx"/> . </Test> <Test name="test2" path="${WORKSPACE}\${CHECKOUT_SUBDIR}\test2"> <Parameter name="p1" value="123" type="int"/> <Parameter name="p4" value="123.4" type="float"/> . </Test> </Mtbx>*/ try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement("Mtbx"); doc.appendChild(rootElement); for (TestExecutionInfo test : tests) { Element testElement = doc.createElement("Test"); String packageAndTestName = (StringUtils.isNotEmpty(test.getPackageName()) ? test.getPackageName() + "\\" : "") + test.getTestName(); testElement.setAttribute("name", packageAndTestName); String path = "${WORKSPACE}\\${CHECKOUT_SUBDIR}" + (StringUtils.isEmpty(test.getPackageName()) ? "" : OctaneConstants.General.WINDOWS_PATH_SPLITTER + test.getPackageName()) + OctaneConstants.General.WINDOWS_PATH_SPLITTER + test.getTestName(); testElement.setAttribute("path", path); if (StringUtils.isNotEmpty(test.getDataTable())) { Element dataTableElement = doc.createElement("DataTable"); dataTableElement.setAttribute("path", "${WORKSPACE}\\${CHECKOUT_SUBDIR}" + OctaneConstants.General.WINDOWS_PATH_SPLITTER + test.getDataTable()); testElement.appendChild(dataTableElement); } rootElement.appendChild(testElement); } TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(doc), new StreamResult(writer)); return writer.toString(); } catch (Exception e) { throw new IOException("Failed to build MTBX content : " + e.getMessage()); } }
From source file:com.hangum.tadpole.engine.sql.util.QueryUtils.java
/** * query to xml//from w w w .j av a 2s. com * * @param userDB * @param strQuery * @param listParam */ @SuppressWarnings("deprecation") public static String selectToXML(final UserDBDAO userDB, final String strQuery, final List<Object> listParam) throws Exception { final StringWriter stWriter = new StringWriter(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); final Document doc = builder.newDocument(); final Element results = doc.createElement("Results"); doc.appendChild(results); SqlMapClient client = TadpoleSQLManager.getInstance(userDB); QueryRunner qr = new QueryRunner(client.getDataSource()); qr.query(strQuery, listParam.toArray(), new ResultSetHandler<Object>() { @Override public Object handle(ResultSet rs) throws SQLException { ResultSetMetaData metaData = rs.getMetaData(); while (rs.next()) { Element row = doc.createElement("Row"); results.appendChild(row); for (int i = 1; i <= metaData.getColumnCount(); i++) { String columnName = metaData.getColumnName(i); Object value = rs.getObject(i) == null ? "" : rs.getObject(i); Element node = doc.createElement(columnName); node.appendChild(doc.createTextNode(value.toString())); row.appendChild(node); } } return stWriter.toString(); } }); DOMSource domSource = new DOMSource(doc); TransformerFactory tf = TransformerFactory.newInstance(); tf.setAttribute("indent-number", 4); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");//"ISO-8859-1"); StreamResult sr = new StreamResult(stWriter); transformer.transform(domSource, sr); return stWriter.toString(); }
From source file:com.hangum.tadpole.engine.sql.util.QueryUtils.java
/** * execute DML/*from ww w. j ava 2 s .co m*/ * * @param userDB * @param strQuery * @param listParam * @param resultType * @throws Exception */ public static String executeDML(final UserDBDAO userDB, final String strQuery, final List<Object> listParam, final String resultType) throws Exception { SqlMapClient client = TadpoleSQLManager.getInstance(userDB); Object effectObject = runSQLOther(userDB, strQuery, listParam); String strReturn = ""; if (resultType.equals(RESULT_TYPE.CSV.name())) { final StringWriter stWriter = new StringWriter(); CSVWriter csvWriter = new CSVWriter(stWriter, ','); String[] arryString = new String[2]; arryString[0] = "effectrow"; arryString[1] = String.valueOf(effectObject); csvWriter.writeNext(arryString); strReturn = stWriter.toString(); } else if (resultType.equals(RESULT_TYPE.JSON.name())) { final JsonArray jsonArry = new JsonArray(); JsonObject jsonObj = new JsonObject(); jsonObj.addProperty("effectrow", String.valueOf(effectObject)); jsonArry.add(jsonObj); strReturn = JSONUtil.getPretty(jsonArry.toString()); } else {//if(resultType.equals(RESULT_TYPE.XML.name())) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); final Document doc = builder.newDocument(); final Element results = doc.createElement("Results"); doc.appendChild(results); Element row = doc.createElement("Row"); results.appendChild(row); Element node = doc.createElement("effectrow"); node.appendChild(doc.createTextNode(String.valueOf(effectObject))); row.appendChild(node); DOMSource domSource = new DOMSource(doc); TransformerFactory tf = TransformerFactory.newInstance(); tf.setAttribute("indent-number", 4); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); final StringWriter stWriter = new StringWriter(); StreamResult sr = new StreamResult(stWriter); transformer.transform(domSource, sr); strReturn = stWriter.toString(); } return strReturn; }
From source file:sep.gaia.resources.poi.POILoaderWorker.java
/** * Generates a Overpass API-request in XML-format. The request complies to the limitations and the * bounding box in <code>query</code> and is designed to retrieve both nodes and recursed ways. * @param query The query to generate XML for. * @return The generated XML-query./*from w ww.j ava2 s . c o m*/ */ private static String generateQueryXML(POIQuery query) { try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.newDocument(); // The root of a OSM-query is always osm-script: Element script = doc.createElement("osm-script"); doc.appendChild(script); // First element is the union containing the queries: Element unionElement = doc.createElement("union"); script.appendChild(unionElement); // Second element says that the recused union of the prior results should be formed: Element recurseUnion = doc.createElement("union"); Element itemElement = doc.createElement("item"); recurseUnion.appendChild(itemElement); Element recurseElement = doc.createElement("recurse"); recurseElement.setAttribute("type", "down"); recurseUnion.appendChild(recurseElement); script.appendChild(recurseUnion); // The last element means, that the results (of the recursed union) // should be written as response: Element printElement = doc.createElement("print"); script.appendChild(printElement); // First query (in the query union) askes for nodes conforming the given attributes: Element queryNodeElement = doc.createElement("query"); queryNodeElement.setAttribute("type", "node"); // The second element does the same for ways: Element queryWayElement = doc.createElement("query"); queryWayElement.setAttribute("type", "way"); // Add them to the first union: unionElement.appendChild(queryNodeElement); unionElement.appendChild(queryWayElement); // Now iterate all key-value-pairs and add "has-kv"-pairs to both queries: POIFilter filter = query.getLimitations(); Map<String, String> attributes = filter.getLimitations(); for (String key : attributes.keySet()) { String value = attributes.get(key); // The values returned by POIFilter are regular expressions, so use regv instead of v: Element currentKVNode = doc.createElement("has-kv"); currentKVNode.setAttribute("k", key); currentKVNode.setAttribute("regv", value); queryNodeElement.appendChild(currentKVNode); Element currentKVWay = doc.createElement("has-kv"); currentKVWay.setAttribute("k", key); currentKVWay.setAttribute("regv", value); queryWayElement.appendChild(currentKVWay); } // We don't want the data of the whole earth, so add bounding-boxes to the queries: Element nodeBBoxElement = createBBoxElement(doc, query.getBoundingBox()); queryNodeElement.appendChild(nodeBBoxElement); Element wayBBoxElement = createBBoxElement(doc, query.getBoundingBox()); queryWayElement.appendChild(wayBBoxElement); // Now the XML-tree is built, so transform it to a string and return it: TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); ByteArrayOutputStream stream = new ByteArrayOutputStream(); StreamResult result = new StreamResult(stream); transformer.transform(source, result); return stream.toString(); } catch (ParserConfigurationException | TransformerException e) { Logger.getInstance().error("Cannot write cache-index: " + e.getMessage()); return null; } }
From source file:com.portfolio.data.utils.DomUtils.java
private static Document newDOM() throws Exception { // ======================================= DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder domBuilder = domFactory.newDocumentBuilder(); return domBuilder.newDocument(); }
From source file:com.photon.phresco.service.util.ServerUtil.java
/** * To create pom.xml file for artifact upload * /*from ww w .j av a2 s . c o m*/ * @param info * @return * @throws PhrescoException */ public static File createPomFile(ArtifactGroup info) throws PhrescoException { FileWriter writer = null; File pomFile = getPomFile(); DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); try { DocumentBuilder domBuilder = domFactory.newDocumentBuilder(); org.w3c.dom.Document newDoc = domBuilder.newDocument(); Element rootElement = newDoc.createElement(ServerConstants.POM_PROJECT); newDoc.appendChild(rootElement); Element modelVersion = newDoc.createElement(ServerConstants.POM_MODELVERSION); modelVersion.setTextContent(ServerConstants.POM_MODELVERSION_VAL); rootElement.appendChild(modelVersion); Element groupId = newDoc.createElement(ServerConstants.POM_GROUPID); groupId.setTextContent(info.getGroupId()); rootElement.appendChild(groupId); Element artifactId = newDoc.createElement(ServerConstants.POM_ARTIFACTID); artifactId.setTextContent(info.getArtifactId()); rootElement.appendChild(artifactId); Element version = newDoc.createElement(ServerConstants.POM_VERSION); version.setTextContent(info.getVersions().get(0).getVersion()); rootElement.appendChild(version); Element packaging = newDoc.createElement(ServerConstants.POM_PACKAGING); packaging.setTextContent(info.getPackaging()); rootElement.appendChild(packaging); Element description = newDoc.createElement(ServerConstants.POM_DESC); description.setTextContent(ServerConstants.POM_DESC_VAL); rootElement.appendChild(description); TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans = transfac.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, ServerConstants.POM_OMMIT); trans.setOutputProperty(OutputKeys.INDENT, ServerConstants.POM_DESC); StringWriter sw = new StringWriter(); StreamResult result = new StreamResult(sw); DOMSource source = new DOMSource(newDoc); trans.transform(source, result); String xmlString = sw.toString(); writer = new FileWriter(pomFile); writer.write(xmlString); writer.close(); } catch (Exception e) { throw new PhrescoException(e); } finally { Utility.closeStream(writer); } return pomFile; }
From source file:com.msopentech.odatajclient.engine.data.json.GeospatialJSONHandler.java
public static void serialize(final JsonGenerator jgen, final Element node, final String type) throws IOException { final EdmSimpleType edmSimpleType = EdmSimpleType.fromValue(type); if (edmSimpleType.equals(EdmSimpleType.GeographyCollection) || edmSimpleType.equals(EdmSimpleType.GeometryCollection)) { jgen.writeStringField(ODataConstants.ATTR_TYPE, EdmSimpleType.GeometryCollection.name()); } else {/*from w ww . ja va2s.c o m*/ final int yIdx = edmSimpleType.name().indexOf('y'); final String itemType = edmSimpleType.name().substring(yIdx + 1); jgen.writeStringField(ODataConstants.ATTR_TYPE, itemType); } Element root = null; switch (edmSimpleType) { case GeographyPoint: case GeometryPoint: root = XMLUtils.getChildElements(node, ODataConstants.ELEM_POINT).get(0); jgen.writeArrayFieldStart(ODataConstants.JSON_COORDINATES); serializePoint(jgen, XMLUtils.getChildElements(root, ODataConstants.ELEM_POS).get(0)); jgen.writeEndArray(); break; case GeographyMultiPoint: case GeometryMultiPoint: root = XMLUtils.getChildElements(node, ODataConstants.ELEM_MULTIPOINT).get(0); jgen.writeArrayFieldStart(ODataConstants.JSON_COORDINATES); final List<Element> pMembs = XMLUtils.getChildElements(root, ODataConstants.ELEM_POINTMEMBERS); if (pMembs != null && !pMembs.isEmpty()) { for (Element point : XMLUtils.getChildElements(pMembs.get(0), ODataConstants.ELEM_POINT)) { jgen.writeStartArray(); serializePoint(jgen, XMLUtils.getChildElements(point, ODataConstants.ELEM_POS).get(0)); jgen.writeEndArray(); } } jgen.writeEndArray(); break; case GeographyLineString: case GeometryLineString: root = XMLUtils.getChildElements(node, ODataConstants.ELEM_LINESTRING).get(0); jgen.writeArrayFieldStart(ODataConstants.JSON_COORDINATES); serializeLineString(jgen, root); jgen.writeEndArray(); break; case GeographyMultiLineString: case GeometryMultiLineString: root = XMLUtils.getChildElements(node, ODataConstants.ELEM_MULTILINESTRING).get(0); jgen.writeArrayFieldStart(ODataConstants.JSON_COORDINATES); final List<Element> lMembs = XMLUtils.getChildElements(root, ODataConstants.ELEM_LINESTRINGMEMBERS); if (lMembs != null && !lMembs.isEmpty()) { for (Element lineStr : XMLUtils.getChildElements(lMembs.get(0), ODataConstants.ELEM_LINESTRING)) { jgen.writeStartArray(); serializeLineString(jgen, lineStr); jgen.writeEndArray(); } } jgen.writeEndArray(); break; case GeographyPolygon: case GeometryPolygon: root = XMLUtils.getChildElements(node, ODataConstants.ELEM_POLYGON).get(0); jgen.writeArrayFieldStart(ODataConstants.JSON_COORDINATES); serializePolygon(jgen, root); jgen.writeEndArray(); break; case GeographyMultiPolygon: case GeometryMultiPolygon: root = XMLUtils.getChildElements(node, ODataConstants.ELEM_MULTIPOLYGON).get(0); jgen.writeArrayFieldStart(ODataConstants.JSON_COORDINATES); final List<Element> mpMembs = XMLUtils.getChildElements(root, ODataConstants.ELEM_SURFACEMEMBERS); if (mpMembs != null & !mpMembs.isEmpty()) { for (Element pol : XMLUtils.getChildElements(mpMembs.get(0), ODataConstants.ELEM_POLYGON)) { jgen.writeStartArray(); serializePolygon(jgen, pol); jgen.writeEndArray(); } } jgen.writeEndArray(); break; case GeographyCollection: case GeometryCollection: root = XMLUtils.getChildElements(node, ODataConstants.ELEM_GEOCOLLECTION).get(0); final List<Element> cMembs = XMLUtils.getChildElements(root, ODataConstants.ELEM_GEOMEMBERS); if (cMembs != null && !cMembs.isEmpty()) { jgen.writeArrayFieldStart(ODataConstants.JSON_GEOMETRIES); for (Node geom : XMLUtils.getChildNodes(cMembs.get(0), Node.ELEMENT_NODE)) { try { final DocumentBuilder builder = ODataConstants.DOC_BUILDER_FACTORY.newDocumentBuilder(); final Document doc = builder.newDocument(); final Element fakeParent = doc.createElementNS(ODataConstants.NS_DATASERVICES, ODataConstants.PREFIX_DATASERVICES + "fake"); fakeParent.appendChild(doc.importNode(geom, true)); final EdmSimpleType callAsType = XMLUtils.simpleTypeForNode( edmSimpleType == EdmSimpleType.GeographyCollection ? Geospatial.Dimension.GEOGRAPHY : Geospatial.Dimension.GEOMETRY, geom); jgen.writeStartObject(); serialize(jgen, fakeParent, callAsType.toString()); jgen.writeEndObject(); } catch (Exception e) { LOG.warn("While serializing {}", XMLUtils.getSimpleName(geom), e); } } jgen.writeEndArray(); } break; default: } if (root != null) { serializeCrs(jgen, root); } }