List of usage examples for javax.xml.transform.stream StreamResult getWriter
public Writer getWriter()
From source file:org.openmrs.module.metadatasharing.converter.BaseConverter.java
protected static String toString(Node doc) throws SerializationException { try {/* w w w. j av a 2 s . co m*/ Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); StreamResult result = new StreamResult(new StringWriter()); transformer.transform(new DOMSource(doc), result); return result.getWriter().toString(); } catch (Exception e) { throw new SerializationException(e); } }
From source file:org.opentox.jaqpot3.qsar.util.PMMLProcess.java
private static String getNodeFromXML(String xml) throws JaqpotException { String res = ""; try {// w w w . j a v a 2 s . c o m DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); ByteArrayInputStream bis = new ByteArrayInputStream(xml.getBytes()); Document doc = docBuilder.parse(bis); // XPath to retrieve the content of the <FamilyAnnualDeductibleAmount> tag XPath xpath = XPathFactory.newInstance().newXPath(); String expression = "/PMML/TransformationDictionary"; Node node = (Node) xpath.compile(expression).evaluate(doc, XPathConstants.NODE); StreamResult xmlOutput = new StreamResult(new StringWriter()); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.transform(new DOMSource(node), xmlOutput); res = xmlOutput.getWriter().toString(); } catch (Exception ex) { String message = "Unexpected exception was caught while generating" + " the PMML representaition of a trained model."; logger.error(message, ex); throw new JaqpotException(message, ex); } return res; }
From source file:org.pentaho.di.trans.steps.xslt.Xslt.java
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException { meta = (XsltMeta) smi;//from w w w.j a v a2 s . c o m data = (XsltData) sdi; Object[] row = getRow(); if (row == null) { // no more input to be expected... setOutputDone(); return false; } if (first) { first = false; data.outputRowMeta = getInputRowMeta().clone(); meta.getFields(data.outputRowMeta, getStepname(), null, null, this, repository, metaStore); // Check if The result field is given if (Const.isEmpty(meta.getResultfieldname())) { // Result Field is missing ! logError(BaseMessages.getString(PKG, "Xslt.Log.ErrorResultFieldMissing")); throw new KettleStepException( BaseMessages.getString(PKG, "Xslt.Exception.ErrorResultFieldMissing")); } // Check if The XML field is given if (Const.isEmpty(meta.getFieldname())) { // Result Field is missing ! logError(BaseMessages.getString(PKG, "Xslt.Exception.ErrorXMLFieldMissing")); throw new KettleStepException(BaseMessages.getString(PKG, "Xslt.Exception.ErrorXMLFieldMissing")); } // Try to get XML Field index data.fieldposition = getInputRowMeta().indexOfValue(meta.getFieldname()); // Let's check the Field if (data.fieldposition < 0) { // The field is unreachable ! logError(BaseMessages.getString(PKG, "Xslt.Log.ErrorFindingField") + "[" + meta.getFieldname() + "]"); throw new KettleStepException( BaseMessages.getString(PKG, "Xslt.Exception.CouldnotFindField", meta.getFieldname())); } // Check if the XSL Filename is contained in a column if (meta.useXSLField()) { if (Const.isEmpty(meta.getXSLFileField())) { // The field is missing // Result field is missing ! logError(BaseMessages.getString(PKG, "Xslt.Log.ErrorXSLFileFieldMissing")); throw new KettleStepException( BaseMessages.getString(PKG, "Xslt.Exception.ErrorXSLFileFieldMissing")); } // Try to get Field index data.fielxslfiledposition = getInputRowMeta().indexOfValue(meta.getXSLFileField()); // Let's check the Field if (data.fielxslfiledposition < 0) { // The field is unreachable ! logError(BaseMessages.getString(PKG, "Xslt.Log.ErrorXSLFileFieldFinding") + "[" + meta.getXSLFileField() + "]"); throw new KettleStepException(BaseMessages.getString(PKG, "Xslt.Exception.ErrorXSLFileFieldFinding", meta.getXSLFileField())); } } else { if (Const.isEmpty(meta.getXslFilename())) { logError(BaseMessages.getString(PKG, "Xslt.Log.ErrorXSLFile")); throw new KettleStepException(BaseMessages.getString(PKG, "Xslt.Exception.ErrorXSLFile")); } // Check if XSL File exists! data.xslfilename = environmentSubstitute(meta.getXslFilename()); FileObject file = null; try { file = KettleVFS.getFileObject(data.xslfilename); if (!file.exists()) { logError(BaseMessages.getString(PKG, "Xslt.Log.ErrorXSLFileNotExists", data.xslfilename)); throw new KettleStepException(BaseMessages.getString(PKG, "Xslt.Exception.ErrorXSLFileNotExists", data.xslfilename)); } if (file.getType() != FileType.FILE) { logError(BaseMessages.getString(PKG, "Xslt.Log.ErrorXSLNotAFile", data.xslfilename)); throw new KettleStepException( BaseMessages.getString(PKG, "Xslt.Exception.ErrorXSLNotAFile", data.xslfilename)); } } catch (Exception e) { throw new KettleStepException(e); } finally { try { if (file != null) { file.close(); } } catch (Exception e) { /* Ignore */ } } } // Check output parameters int nrOutputProps = meta.getOutputPropertyName() == null ? 0 : meta.getOutputPropertyName().length; if (nrOutputProps > 0) { data.outputProperties = new Properties(); for (int i = 0; i < nrOutputProps; i++) { data.outputProperties.put(meta.getOutputPropertyName()[i], environmentSubstitute(meta.getOutputPropertyValue()[i])); } data.setOutputProperties = true; } // Check parameters data.nrParams = meta.getParameterField() == null ? 0 : meta.getParameterField().length; if (data.nrParams > 0) { data.indexOfParams = new int[data.nrParams]; data.nameOfParams = new String[data.nrParams]; for (int i = 0; i < data.nrParams; i++) { String name = environmentSubstitute(meta.getParameterName()[i]); String field = environmentSubstitute(meta.getParameterField()[i]); if (Const.isEmpty(field)) { throw new KettleStepException( BaseMessages.getString(PKG, "Xslt.Exception.ParameterFieldMissing", name, i)); } data.indexOfParams[i] = getInputRowMeta().indexOfValue(field); if (data.indexOfParams[i] < 0) { throw new KettleStepException( BaseMessages.getString(PKG, "Xslt.Exception.ParameterFieldNotFound", name)); } data.nameOfParams[i] = name; } data.useParameters = true; } data.factory = TransformerFactory.newInstance(); if (meta.getXSLFactory().equals("SAXON")) { // Set the TransformerFactory to the SAXON implementation. data.factory = new net.sf.saxon.TransformerFactoryImpl(); } } // end if first // Get the field value String xmlValue = getInputRowMeta().getString(row, data.fieldposition); if (meta.useXSLField()) { // Get the value data.xslfilename = getInputRowMeta().getString(row, data.fielxslfiledposition); if (log.isDetailed()) { logDetailed(BaseMessages.getString(PKG, "Xslt.Log.XslfileNameFromFied", data.xslfilename, meta.getXSLFileField())); } } try { if (log.isDetailed()) { if (meta.isXSLFieldIsAFile()) { logDetailed(BaseMessages.getString(PKG, "Xslt.Log.Filexsl") + data.xslfilename); } else { logDetailed(BaseMessages.getString(PKG, "Xslt.Log.XslStream", data.xslfilename)); } } // Get the template from the cache Transformer transformer = data.getTemplate(data.xslfilename, data.xslIsAfile); // Do we need to set output properties? if (data.setOutputProperties) { transformer.setOutputProperties(data.outputProperties); } // Do we need to pass parameters? if (data.useParameters) { for (int i = 0; i < data.nrParams; i++) { transformer.setParameter(data.nameOfParams[i], row[data.indexOfParams[i]]); } } Source source = new StreamSource(new StringReader(xmlValue)); // Prepare output stream StreamResult result = new StreamResult(new StringWriter()); // transform xml source transformer.transform(source, result); String xmlString = result.getWriter().toString(); if (log.isDetailed()) { logDetailed(BaseMessages.getString(PKG, "Xslt.Log.FileResult")); logDetailed(xmlString); } Object[] outputRowData = RowDataUtil.addValueData(row, getInputRowMeta().size(), xmlString); if (log.isRowLevel()) { logRowlevel( BaseMessages.getString(PKG, "Xslt.Log.ReadRow") + " " + getInputRowMeta().getString(row)); } // add new values to the row. putRow(data.outputRowMeta, outputRowData); // copy row to output rowset(s); } catch (Exception e) { String errorMessage = e.getMessage(); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); DefaultErrorHandler.printLocation(pw, e); pw.close(); errorMessage = sw.toString() + "\n" + errorMessage; if (getStepMeta().isDoingErrorHandling()) { // Simply add this row to the error row putError(getInputRowMeta(), row, 1, errorMessage, meta.getResultfieldname(), "XSLT01"); } else { logError(BaseMessages.getString(PKG, "Xslt.ErrorProcesing" + " : " + errorMessage)); throw new KettleStepException(BaseMessages.getString(PKG, "Xslt.ErrorProcesing"), e); } } return true; }
From source file:org.pentaho.platform.util.xml.dom4j.XmlDom4JHelper.java
public static org.dom4j.Document convertToDom4JDoc(final org.w3c.dom.Document doc) throws TransformerConfigurationException, TransformerException, TransformerFactoryConfigurationError, DocumentException {//from w w w. j av a2s. co m DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new StringWriter()); TransformerFactory.newInstance().newTransformer().transform(source, result); String theXML = result.getWriter().toString(); org.dom4j.Document dom4jDoc = DocumentHelper.parseText(theXML); return dom4jDoc; }
From source file:org.pentaho.platform.web.servlet.SolutionEngineInteractivityService.java
protected void handleActionRequest(final HttpServletRequest request, final HttpServletResponse response, final HttpOutputHandler outputHandler, final HttpServletRequestHandler requestHandler, IParameterProvider requestParameters, ByteArrayOutputStream outputStream, final IContentItem contentItem) throws ServletException, IOException { IRuntimeContext runtime = null;//from w w w. ja v a 2 s . c om try { final org.w3c.dom.Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder() .newDocument(); final org.w3c.dom.Element root = document.createElement("action_sequence_info"); document.appendChild(root); requestHandler.setCreateFeedbackParameterCallback(new ICreateFeedbackParameterCallback() { public void createFeedbackParameter(IRuntimeContext runtimeContext, String fieldName, String displayName, String hint, Object defaultValues, List values, Map dispNames, String displayStyle, boolean optional, boolean visible) { org.w3c.dom.Element parameterElement = document.createElement("parameter"); parameterElement.setAttribute("name", fieldName); parameterElement.setAttribute("display-name", displayName); parameterElement.setAttribute("display-style", displayStyle); parameterElement.setAttribute("hint", "" + hint); parameterElement.setAttribute("optional", "" + optional); parameterElement.setAttribute("visible", "" + visible); try { IActionParameter actionParameter = runtimeContext.getInputParameter(fieldName); if (actionParameter != null) { List variables = actionParameter.getVariables(); for (int i = 0; variables != null && i < variables.size(); i++) { Object var = variables.get(i); if (var instanceof ActionParameterSource) { String sourceName = ((ActionParameterSource) var).getSourceName(); String sourceValue = ((ActionParameterSource) var).getValue(); parameterElement.setAttribute("source-name", "" + sourceName); parameterElement.setAttribute("source-value", "" + sourceValue); } else { System.out.println(var); } } } } catch (Exception npe) { //ignore } root.appendChild(parameterElement); if (values != null) { org.w3c.dom.Element valuesElement = document.createElement("values"); for (Object value : values) { org.w3c.dom.Element valueElement = document.createElement("value"); valueElement.setAttribute("value", "" + value); if (dispNames != null && dispNames.containsKey(value)) { valueElement.setAttribute("display-name", "" + dispNames.get(value)); } valuesElement.appendChild(valueElement); } parameterElement.appendChild(valuesElement); } if (defaultValues != null) { org.w3c.dom.Element valuesElement = document.createElement("selected-values"); if (defaultValues instanceof List) { for (Object value : (List) defaultValues) { org.w3c.dom.Element valueElement = document.createElement("value"); valueElement.setAttribute("value", "" + value); valuesElement.appendChild(valueElement); } } else { org.w3c.dom.Element valueElement = document.createElement("value"); valueElement.setAttribute("value", "" + defaultValues); valuesElement.appendChild(valueElement); } parameterElement.appendChild(valuesElement); } } }); runtime = requestHandler.handleActionRequest(0, 0); root.setAttribute("is-prompt-pending", "" + runtime.isPromptPending()); DOMSource source = new DOMSource(document); StreamResult result = new StreamResult(new StringWriter()); TransformerFactory.newInstance().newTransformer().transform(source, result); String theXML = result.getWriter().toString(); response.setContentType("text/xml"); response.getOutputStream().write(theXML.getBytes()); response.getOutputStream().close(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (TransformerConfigurationException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } catch (TransformerFactoryConfigurationError e) { e.printStackTrace(); } finally { if (runtime != null) { runtime.dispose(); } } if (contentItem != null) { contentItem.closeOutputStream(); } }
From source file:org.springframework.oxm.support.AbstractMarshaller.java
/** * Template method for handling {@code StreamResult}s. * <p>This implementation delegates to {@code marshalOutputStream} or {@code marshalWriter}, * depending on what is contained in the {@code StreamResult} * @param graph the root of the object graph to marshal * @param streamResult the {@code StreamResult} * @throws IOException if an I/O Exception occurs * @throws XmlMappingException if the given object cannot be marshalled to the result * @throws IllegalArgumentException if {@code streamResult} does neither * contain an {@code OutputStream} nor a {@code Writer} *//*from ww w . ja v a 2 s . com*/ protected void marshalStreamResult(Object graph, StreamResult streamResult) throws XmlMappingException, IOException { if (streamResult.getOutputStream() != null) { marshalOutputStream(graph, streamResult.getOutputStream()); } else if (streamResult.getWriter() != null) { marshalWriter(graph, streamResult.getWriter()); } else { throw new IllegalArgumentException("StreamResult contains neither OutputStream nor Writer"); } }
From source file:org.teiid.spring.autoconfigure.TeiidServer.java
private static String prettyFormat(String xml) { try {//from ww w.j a v a 2 s . co m Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); StreamResult result = new StreamResult(new StringWriter()); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); InputSource is = new InputSource(new StringReader(xml)); DOMSource source = new DOMSource(db.parse(is)); transformer.transform(source, result); return result.getWriter().toString(); } catch (IllegalArgumentException | TransformerFactoryConfigurationError | ParserConfigurationException | SAXException | IOException | TransformerException e) { return xml; } }
From source file:org.vivoweb.harvester.fetch.WOSFetch.java
/** * @param documentNode a DOM node to be changed into a properly indented string * @return The indented string containing the node and sub-nodes *///from w w w . ja va 2s . c om private String nodeToString(Node documentNode) { StreamResult result = null; try { Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); result = new StreamResult(new StringWriter()); DOMSource domSource = new DOMSource(documentNode); transformer.transform(domSource, result); } catch (TransformerException e) { e.printStackTrace(); } catch (TransformerFactoryConfigurationError e1) { e1.printStackTrace(); } return result.getWriter().toString(); }
From source file:org.vivoweb.harvester.util.SOAPMessenger.java
/** * Take an XML string and ensure there are line breaks and indentation. * @param inputXml the input XML string//from w w w . j a va2 s. c o m * @return the formatted XML string */ public String formatResult(String inputXml) { try { StringReader reader = new StringReader(inputXml); InputSource source = new InputSource(reader); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(source); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); StreamResult result = new StreamResult(new StringWriter()); DOMSource domSource = new DOMSource(document); transformer.transform(domSource, result); return result.getWriter().toString(); } catch (Exception e) { log.error(e.getMessage(), e); return inputXml; //log error and then just don't format the result } }
From source file:org.yestech.jmlnitrate.transformation.outbound.HttpServletXSLTOutboundTransformation.java
/** * Transforms a {@link ResponseHandler} to a valid output format. * * @param response The Response to transform * @throws Exception if an error happens *//*ww w .ja v a 2 s. com*/ public void transform(ResponseHandler response) throws Exception { Object xml = ((HttpServletResponseHandler) response).getValue(HttpServletResponseHandler.KEY_RESULT); String xsl = (String) (((HttpServletResponseHandler) response) .getValue(HttpServletResponseHandler.KEY_VIEW)); //only transform if we are dealing with an xsl response view. if (xsl != null && !xsl.equals("") && xsl.endsWith(".xsl")) { StreamResult result = xsltTransform.transform(xml, xsl); setTransformationResult(result.getWriter().toString()); } }