List of usage examples for javax.xml.transform.stream StreamResult getWriter
public Writer getWriter()
From source file:org.fireflow.clientwidget.FpdlExporter.java
public static String getXml(Node node, String encoding) { try {//w w w . j a v a2 s.c om Transformer tf = TransformerFactory.newInstance().newTransformer(); tf.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); tf.setOutputProperty(OutputKeys.ENCODING, encoding); tf.setOutputProperty(OutputKeys.INDENT, "yes"); tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); StreamResult dest = new StreamResult(new StringWriter()); tf.transform(new DOMSource(node), dest); return dest.getWriter().toString(); } catch (Exception e) { // ignore } return ""; }
From source file:org.fireflow.webdesigner.transformer.AbstractFpdlDiagramSerializer.java
public String serializeDiagramToStr(WorkflowProcess workflowProcess, String subProcessName, String encoding, boolean omitXmlDeclaration) { try {// w w w.j a v a 2 s . c o m Document doc = this.serializeDiagramToDoc(workflowProcess, subProcessName); Transformer tf = TransformerFactory.newInstance().newTransformer(); if (omitXmlDeclaration) { tf.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); } tf.setOutputProperty(OutputKeys.ENCODING, encoding); tf.setOutputProperty(OutputKeys.INDENT, "yes"); tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); StreamResult dest = new StreamResult(new StringWriter()); tf.transform(new DOMSource(doc), dest); return dest.getWriter().toString(); } catch (Exception e) { //TODO e.printStackTrace(); } return ""; }
From source file:org.giavacms.base.common.util.HtmlUtils.java
public static String prettyXml(String code) { if (code == null) { code = ""; }/* w ww . j a va2 s .co m*/ try { TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformerFactory.setAttribute("indent-number", 4); Transformer transformer; transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); StreamResult result = new StreamResult(new StringWriter()); StreamSource source = new StreamSource(new StringReader(code)); transformer.transform(source, result); return result.getWriter().toString(); } catch (TransformerConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerException e) { // TODO Auto-generated catch block e.printStackTrace(); } return ""; }
From source file:org.mule.service.soap.SoapTestUtils.java
private static String prettyPrint(String a) throws Exception { DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(a)); Document doc = db.parse(is);/* w w w . j a va 2 s . c o m*/ Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); // initialize StreamResult with File object to save to file StreamResult result = new StreamResult(new StringWriter()); DOMSource source = new DOMSource(doc); transformer.transform(source, result); return result.getWriter().toString(); }
From source file:ORG.oclc.os.SRW.xml2jsonTransformer.java
@Override public void transform(Source xmlSource, Result outputTarget) throws TransformerException { StreamSource source = (StreamSource) xmlSource; BufferedReader br = new BufferedReader(source.getReader()); StringBuilder sb = new StringBuilder(); String line;/*w w w . jav a2s.co m*/ try { while ((line = br.readLine()) != null) sb.append(line); } catch (IOException ex) { throw new TransformerException(ex); } String xmlRecord = sb.toString(); if (log.isDebugEnabled()) log.debug("xmlSource: " + xmlRecord); XMLSerializer xmlSerializer = new XMLSerializer(); try { JSON json = xmlSerializer.read(xmlRecord); StreamResult sr = (StreamResult) outputTarget; json.write(sr.getWriter()); if (log.isDebugEnabled()) log.debug("convertedJSON: " + sr.toString()); } catch (Exception e) { log.error("Unable to transform to JSON: " + xmlRecord); throw new TransformerException(e); } }
From source file:org.ojbc.web.portal.controllers.PortalController.java
private void debugPrintAssertion(Element assertionElement) throws Exception { if (assertionElement == null) { log.info("assertionElement was null, skipping debug output"); return;//from w ww.ja v a 2 s .c o m } Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); StreamResult result = new StreamResult(new StringWriter()); DOMSource source = new DOMSource(assertionElement); transformer.transform(source, result); String xmlString = result.getWriter().toString(); log.info(xmlString); }
From source file:org.okbqa.disambiguation.client.DBpediaSpotlightClient.java
public TemplateInterpretations extract(PseudoSPARQLTemplate pst) throws SpotlightException { TemplateInterpretations ret = new TemplateInterpretations(); TemplateInterpretation ti = new TemplateInterpretation(); ret.getInterpretations().add(ti);//from w w w .j a v a 2s . c o m List<EntityBinding> bindings = ti.getEntityBindings(); // obtain variables that are rdf:Resource and their verbalizations List<String> resourceVariables = new ArrayList<String>(); for (EntitySlot es : pst.getSlots()) { if (es.getPredicate().equals("is") && es.getObject().equals("rdf:Resource")) resourceVariables.add(es.getSubject()); } Map<String, String> varToVerbalization = new HashMap<String, String>(); for (EntitySlot es : pst.getSlots()) { if (es.getPredicate().equals("verbalization") && resourceVariables.contains(es.getSubject())) { varToVerbalization.put(es.getSubject(), es.getObject()); } } // build a query for just the rdf:Resource variables String query = null; DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); try { DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); // root element Document doc = docBuilder.newDocument(); Element annotation = doc.createElement("annotation"); doc.appendChild(annotation); annotation.setAttribute("text", pst.getQuestion().replace("\"", """)); // surface forms for (String verbalization : varToVerbalization.values()) { Element surfaceForm = doc.createElement("surfaceForm"); annotation.appendChild(surfaceForm); surfaceForm.setAttribute("name", verbalization); surfaceForm.setAttribute("offset", String.valueOf(pst.getQuestion().indexOf(verbalization))); } Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); StreamResult result = new StreamResult(new StringWriter()); transformer.transform(new DOMSource(doc), result); query = result.getWriter().toString(); } catch (Exception e) { e.printStackTrace(); query = ""; } try { String spotlightResponse = getResponse(API_URL + "rest/annotate/?" + "spotter=SpotXmlParser" + "&text=" + URLEncoder.encode(query, "utf-8")); JSONObject resultJSON = null; JSONArray entities = null; try { resultJSON = new JSONObject(spotlightResponse); ti.setScore(resultJSON.getDouble("@confidence")); entities = resultJSON.getJSONArray("Resources"); } catch (JSONException e) { throw new AnnotationException(e); } for (int i = 0; i < entities.length(); i++) { JSONObject entityJSON = entities.getJSONObject(i); Entity entity = Entity.fromJSON(entityJSON); bindings.add(new EntityBinding(entityJSON.getString("@surfaceForm"), entity)); } } catch (Exception e) { e.printStackTrace(); } return ret; }
From source file:org.opencastproject.manager.core.MetadataDocumentHandler.java
/** * Sets data in a XML-file.//from w w w . j av a 2s . com * * @throws TransformerFactoryConfigurationError * @throws TransformerException */ public synchronized void writeNewPluginNodesInFile(File file, Document doc) throws TransformerFactoryConfigurationError, TransformerException { Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //initialize StreamResult with File object to save to file StreamResult result = new StreamResult(new StringWriter()); DOMSource source = new DOMSource(doc); transformer.transform(source, result); String xmlString = result.getWriter().toString(); //writing to file FileOutputStream fop = null; try { fop = new FileOutputStream(file); byte[] contentInBytes = xmlString.getBytes(); fop.write(contentInBytes); fop.flush(); fop.close(); } catch (IOException e) { logger.error("Workflow editor could not add notes to XML file."); } finally { try { if (fop != null) { fop.close(); } } catch (IOException e) { logger.error("Workflow editor could not add notes to XML file."); } } }
From source file:org.openehealth.ipf.platform.camel.core.support.transform.min.TestConverter.java
public Result render(String model, Result result, Object... params) throws IOException { StreamResult r = (StreamResult) result; IOUtils.write(model, r.getWriter()); return r;//from w w w. j a v a2 s . co m }
From source file:org.openmrs.module.DeIdentifiedPatientDataExportModule.api.impl.DeIdentifiedExportServiceImpl.java
public void generatePatientXML(HttpServletResponse response, List<PersonAttributeType> pat, List<Integer> ids, Integer pid) {//from w ww . j ava 2 s . c o m response.setHeader("Content-Disposition", "attachment;filename=" + "patientExportSummary" + ".xml"); try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement("patient-export-summary"); doc.appendChild(rootElement); Element patients = doc.createElement("patients"); rootElement.appendChild(patients); for (int k = 0; k < ids.size(); k++) { Element pp = doc.createElement("patient-" + ids.get(k).toString()); patients.appendChild(pp); Element pes1 = doc.createElement("patient-demographic-data"); pp.appendChild(pes1); Element name1 = doc.createElement("name"); PatientService ps = Context.getPatientService(); Patient patient1 = ps.getPatient(ids.get(k)); patient1 = setRandomPatientNames(patient1); name1.appendChild(doc.createTextNode( patient1.getGivenName() + " " + patient1.getMiddleName() + " " + patient1.getFamilyName())); pes1.appendChild(name1); patient1 = setPatientDOB(patient1.getBirthdate(), patient1); Element DOB1 = doc.createElement("DOB"); DOB1.appendChild(doc.createTextNode(patient1.getBirthdate().toString())); pes1.appendChild(DOB1); for (int i = 0; i < pat.size(); i++) { PersonAttribute pa = patient1.getAttribute(pat.get(i)); String personAttributeType = pat.get(i).getName().toLowerCase().replaceAll("\\s", ""); if (personAttributeType.contains("mother's")) { personAttributeType = "mother-name"; } Element personAttribute1 = doc.createElement(personAttributeType); personAttribute1.appendChild(doc.createTextNode(pa.getValue().toString())); pes1.appendChild(personAttribute1); } List<Obs> obs1 = new ArrayList<Obs>(); Context.clearSession(); ObsService obsService = Context.getObsService(); Patient p1 = ps.getPatient(ids.get(k)); List<Obs> ob = getOriginalObsList(p1, obsService); obs1 = getEncountersOfPatient(p1, ob, pid); //New obs list - updated Element encounters = doc.createElement("encounters"); pp.appendChild(encounters); List<ConceptSource> cs = getConceptMapping(obs1); for (int i = 0; i < obs1.size(); i++) { Element encounter = doc.createElement("encounter"); encounters.appendChild(encounter); Element location = doc.createElement("encounter-location"); location.appendChild(doc.createTextNode(obs1.get(i).getLocation().getAddress1())); encounter.appendChild(location); Element date = doc.createElement("encounter-date"); date.appendChild(doc.createTextNode( obs1.get(i).getEncounter().getEncounterDatetime().toLocaleString().toString())); encounter.appendChild(date); Element observation = doc.createElement("observation"); encounter.appendChild(observation); Element concept = doc.createElement("concept"); observation.appendChild(concept); Element conceptId = doc.createElement("concept-id"); conceptId.appendChild(doc.createTextNode(obs1.get(i).getConcept().toString())); concept.appendChild(conceptId); for (int j = 0; j < cs.size(); j++) { Element conceptSourceId = doc.createElement("concept-source-id"); conceptSourceId.appendChild(doc.createTextNode(cs.get(j).getHl7Code().toString())); concept.appendChild(conceptSourceId); Element conceptSource = doc.createElement("concept-source"); conceptSource.appendChild(doc.createTextNode(cs.get(j).getName().toString())); concept.appendChild(conceptSource); } Element value = doc.createElement("value"); observation.appendChild(value); if (obs1.get(i).getValueCoded() != null) { Element valueCoded = doc.createElement("value-coded"); valueCoded.appendChild(doc.createTextNode(obs1.get(i).getValueCoded().toString())); value.appendChild(valueCoded); } if (obs1.get(i).getValueNumeric() != null) { Element valueNumeric = doc.createElement("value-numeric"); valueNumeric.appendChild(doc.createTextNode(obs1.get(i).getValueNumeric().toString())); value.appendChild(valueNumeric); } if (obs1.get(i).getValueBoolean() != null) { Element valueBoolean = doc.createElement("value-boolean"); valueBoolean.appendChild(doc.createTextNode(obs1.get(i).getValueBoolean().toString())); value.appendChild(valueBoolean); } } } // Then write the doc into a StringWriter Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //initialize StreamResult with StringWriter object to save to string StreamResult result = new StreamResult(new StringWriter()); DOMSource source = new DOMSource(doc); transformer.transform(source, result); String xmlString = result.getWriter().toString(); System.out.println(xmlString); // Finally, send the response byte[] res = xmlString.getBytes(Charset.forName("UTF-8")); response.setCharacterEncoding("UTF-8"); response.getOutputStream().write(res); response.flushBuffer(); } catch (IOException e) { // TODO Auto-generated catch block log.error("IO Exception in generating XML", e); } catch (Exception e) { // TODO Auto-generated catch block log.error("Exception in generating XML", e); } }