List of usage examples for javax.xml.transform Templates newTransformer
Transformer newTransformer() throws TransformerConfigurationException;
From source file:fedora.server.rest.BaseRestResource.java
protected void transform(String xml, String xslt, Writer out) throws TransformerFactoryConfigurationError, TransformerConfigurationException, TransformerException { File xslFile = new File(fedoraServer.getHomeDir(), xslt); TransformerFactory factory = TransformerFactory.newInstance(); if (factory.getClass().getName().equals("net.sf.saxon.TransformerFactoryImpl")) { factory.setAttribute(FeatureKeys.VERSION_WARNING, Boolean.FALSE); }//from w w w .java 2 s. c o m Templates template = factory.newTemplates(new StreamSource(xslFile)); Transformer transformer = template.newTransformer(); String appContext = getContext().getEnvironmentValue(Constants.FEDORA_APP_CONTEXT_NAME); transformer.setParameter("fedora", appContext); transformer.transform(new StreamSource(new StringReader(xml)), new StreamResult(out)); }
From source file:net.sf.taverna.t2.activities.soaplab.views.SoaplabActivityContextualView.java
private String getMetadata() { try {//from w w w.j a v a2 s . c om Configuration configuration = getConfigBean(); JsonNode json = configuration.getJson(); String endpoint = json.get("endpoint").textValue(); Call call = (Call) new Service().createCall(); call.setTimeout(new Integer(0)); call.setTargetEndpointAddress(endpoint); call.setOperationName(new QName("describe")); String metadata = (String) call.invoke(new Object[0]); logger.info(metadata); // Old impl, returns a tree of the XML // ColXMLTree tree = new ColXMLTree(metadata); URL sheetURL = SoaplabActivityContextualView.class.getResource("/analysis_metadata_2_html.xsl"); TransformerFactory transformerFactory = TransformerFactory.newInstance(); logger.info(sheetURL.toString()); Templates stylesheet = transformerFactory.newTemplates(new StreamSource(sheetURL.openStream())); Transformer transformer = stylesheet.newTransformer(); StreamSource inputStream = new StreamSource(new ByteArrayInputStream(metadata.getBytes())); ByteArrayOutputStream transformedStream = new ByteArrayOutputStream(); StreamResult result = new StreamResult(transformedStream); transformer.transform(inputStream, result); transformedStream.flush(); transformedStream.close(); // String summaryText = "<html><head>" // + WorkflowSummaryAsHTML.STYLE_NOBG + "</head>" // + transformedStream.toString() + "</html>"; // JEditorPane metadataPane = new ColJEditorPane("text/html", // summaryText); // metadataPane.setText(transformedStream.toString()); // // logger.info(transformedStream.toString()); // JScrollPane jsp = new JScrollPane(metadataPane, // JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, // JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); // jsp.setPreferredSize(new Dimension(0, 0)); // jsp.getVerticalScrollBar().setValue(0); return transformedStream.toString(); } catch (Exception ex) { return "<font color=\"red\">Error</font><p>An exception occured while trying to fetch Soaplab metadata from the server. The error was :<pre>" + ex.getMessage() + "</pre>"; } }
From source file:com.esri.geoportal.commons.csw.client.impl.Profile.java
@Override public String generateCSWGetRecordsRequest(ICriteria criteria) { String internalRequestXml = createInternalXmlRequest(criteria); try (ByteArrayInputStream internalRequestInputStream = new ByteArrayInputStream( internalRequestXml.getBytes("UTF-8")); InputStream reqXsltInputStream = Thread.currentThread().getContextClassLoader() .getResourceAsStream(Constants.CONFIG_FOLDER_PATH + "/" + getGetRecordsReqXslt())) { // create internal request DOM DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = builderFactory.newDocumentBuilder(); Document internalRequestDOM = builder.parse(new InputSource(internalRequestInputStream)); // create transformer TransformerFactory transformerFactory = TransformerFactory.newInstance(); Templates template = transformerFactory.newTemplates(new StreamSource(reqXsltInputStream)); Transformer transformer = template.newTransformer(); // perform transformation StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(internalRequestDOM), new StreamResult(writer)); return writer.toString(); } catch (Exception ex) { LOG.warn("Error creating CSW get records request.", ex); return ""; }// w ww . j ava 2s.c o m }
From source file:edu.duke.cabig.c3pr.rules.common.adapter.CaAERSJBossXSLTRuleAdapter.java
public Package adapt(RuleSet ruleSet) throws RuleException { /*/*w w w . j a va 2 s .c o m*/ * Add adverseEventEvaluationResult here and remove it from everywhere else since this is a * hidden column, it should not be used for authoring. It is used only at runtime. So it * make sense to add to the condition here. IMP: This is only required for caAERS project. */ List<Rule> rules = ruleSet.getRule(); for (Rule r : rules) { Column column_fixed = new Column(); column_fixed.setObjectType("edu.duke.cabig.c3pr.rules.common.AdverseEventEvaluationResult"); column_fixed.setIdentifier("adverseEventEvaluationResult"); r.getCondition().getColumn().add(column_fixed); } List<String> imports = ruleSet.getImport(); if (log.isDebugEnabled()) { log.debug("Size of imports:" + imports.size()); for (String s : imports) { log.debug("each import :" + s); } } // marshal and transform String xml1 = XMLUtil.marshal(ruleSet); log.debug("Marshalled, Before transforming using [jboss-rules-intermediate.xsl]:\r\n" + xml1); XsltTransformer xsltTransformer = new XsltTransformer(); String xml = ""; try { xml = xsltTransformer.toXml(xml1, "jboss-rules-intermediate.xsl"); log.debug("After transforming using [jboss-rules-intermediate.xsl] :\n\r" + xml); } catch (Exception e) { log.error("Exception while transforming to New Scheme: " + e.getMessage(), e); } StringWriter writer = new StringWriter(); System.setProperty("javax.xml.transform.TransformerFactory", "org.apache.xalan.processor.TransformerFactoryImpl"); TransformerFactory transformerFactory = TransformerFactory.newInstance(); try { Templates translet = transformerFactory.newTemplates(new StreamSource( Thread.currentThread().getContextClassLoader().getResourceAsStream("new_jobss_rules.xsl"))); Transformer transformer = translet.newTransformer(); if (log.isDebugEnabled()) { log.debug("Before transforming using [new_jobss_rules.xsl] :\r\n" + xml); StringWriter strWriter = new StringWriter(); transformer.transform(new StreamSource(new StringReader(xml)), new StreamResult(strWriter)); log.debug("After transforming using [new_jboss_rules.xsl]:\r\n" + strWriter.toString()); } transformer.transform(new StreamSource(new StringReader(xml)), new StreamResult(writer)); } catch (Exception e) { log.error("Error while transforming using new_jboss_rules.xsl", e); throw new RuleException("Unable to transform using new_jboss_rules.xsl", e); } // create the rules package return XMLUtil.unmarshalToPackage(writer.toString()); }
From source file:org.fcrepo.localservices.saxon.SaxonServlet.java
/** * Apply stylesheet to source document//from w ww . ja va2 s. co m */ private void apply(String style, String source, HttpServletRequest req, HttpServletResponse res) throws Exception { // Validate parameters if (style == null) { throw new TransformerException("No style parameter supplied"); } if (source == null) { throw new TransformerException("No source parameter supplied"); } InputStream sourceStream = null; try { // Load the stylesheet (adding to cache if necessary) Templates pss = tryCache(style); Transformer transformer = pss.newTransformer(); Enumeration<?> p = req.getParameterNames(); while (p.hasMoreElements()) { String name = (String) p.nextElement(); if (!(name.equals("style") || name.equals("source"))) { String value = req.getParameter(name); transformer.setParameter(name, new StringValue(value)); } } // Start loading the document to be transformed sourceStream = getInputStream(source); // Set the appropriate output mime type String mime = pss.getOutputProperties().getProperty(OutputKeys.MEDIA_TYPE); if (mime == null) { res.setContentType("text/html"); } else { res.setContentType(mime); } // Transform StreamSource ss = new StreamSource(sourceStream); ss.setSystemId(source); transformer.transform(ss, new StreamResult(res.getOutputStream())); } finally { if (sourceStream != null) { try { sourceStream.close(); } catch (Exception e) { } } } }
From source file:Examples.java
/** * Show how to transform a DOM tree into another DOM tree. * This uses the javax.xml.parsers to parse an XML file into a * DOM, and create an output DOM.//from w w w. java 2s . c o m */ public static Node exampleDOM2DOM(String sourceID, String xslID) throws TransformerException, TransformerConfigurationException, SAXException, IOException, ParserConfigurationException { TransformerFactory tfactory = TransformerFactory.newInstance(); if (tfactory.getFeature(DOMSource.FEATURE)) { Templates templates; { DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); dfactory.setNamespaceAware(true); DocumentBuilder docBuilder = dfactory.newDocumentBuilder(); org.w3c.dom.Document outNode = docBuilder.newDocument(); Node doc = docBuilder.parse(new InputSource(xslID)); DOMSource dsource = new DOMSource(doc); // If we don't do this, the transformer won't know how to // resolve relative URLs in the stylesheet. dsource.setSystemId(xslID); templates = tfactory.newTemplates(dsource); } Transformer transformer = templates.newTransformer(); DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); // Note you must always setNamespaceAware when building .xsl stylesheets dfactory.setNamespaceAware(true); DocumentBuilder docBuilder = dfactory.newDocumentBuilder(); org.w3c.dom.Document outNode = docBuilder.newDocument(); Node doc = docBuilder.parse(new InputSource(sourceID)); transformer.transform(new DOMSource(doc), new DOMResult(outNode)); Transformer serializer = tfactory.newTransformer(); serializer.transform(new DOMSource(outNode), new StreamResult(new OutputStreamWriter(System.out))); return outNode; } else { throw new org.xml.sax.SAXNotSupportedException("DOM node processing not supported!"); } }
From source file:org.LexGrid.LexBIG.caCore.web.util.LexEVSHTTPQuery.java
/** * Generates an XML or HTML document based on a given stylesheet * @param xmlDoc Specifies the xml document * @param styleIn specifies the stylesheet * @return//from ww w .j a va 2 s. com * @throws Exception */ public void transform(Document xmlDoc, InputStream styleIn, OutputStream out) throws Exception { if (styleIn == null) throw new ServletException("No stylesheet configued"); JDOMSource source = new JDOMSource(xmlDoc); StreamResult result = new StreamResult(out); try { TransformerFactory tFactory = TransformerFactory.newInstance(); Templates stylesheet = tFactory.newTemplates(new StreamSource(styleIn)); Transformer processor = stylesheet.newTransformer(); processor.transform(source, result); } catch (Exception ex) { log.error(ex.getMessage()); throw new Exception("XSLTTransformer Exception: " + ex.getMessage()); } }
From source file:org.LexGrid.LexBIG.caCore.web.util.LexEVSHTTPQuery.java
/** * Generates an XML or HTML document based on a given stylesheet * @param xmlDoc Specifies the xml document * @param styleIn specifies the stylesheet * @return/*w w w . j a va 2 s . c o m*/ * @throws Exception */ public Document XSLTTransformer(Document xmlDoc, InputStream styleIn) throws Exception { JDOMSource source = new JDOMSource(xmlDoc); JDOMResult result = new JDOMResult(); try { if (styleIn != null) { TransformerFactory tFactory = TransformerFactory.newInstance(); Templates stylesheet = tFactory.newTemplates(new StreamSource(styleIn)); Transformer processor = stylesheet.newTransformer(); processor.transform(source, result); } } catch (Exception ex) { log.error(ex.getMessage()); throw new Exception("XSLTTransformer Exception: " + ex.getMessage()); } return result.getDocument(); }
From source file:eu.semaine.util.XMLTool.java
/** * Merge two XML files using XSLT//from w w w . j av a 2 s .c o m * @param xmlFileContent1, first XML file content * @param xmlFileContent2, second XML file content * @param xmlStyleSheet, XSL style sheet as a inputstream * @param refCodeName, code name used in xsl sheet to refer xmlFile2 (example: semaine.mary.intonation ) * @return output of merged xml file * @throws Exception * @throws FileNotFoundException */ public static String mergeTwoXMLFiles(String xmlFileContent1, final String xmlFileContent2, InputStream xmlStyleSheet, final String refCodeName) throws Exception, FileNotFoundException { Templates mergeXML2IntoStylesheet; TransformerFactory tFactory = TransformerFactory.newInstance(); //StreamSource stylesheetStream = new StreamSource(new FileReader(xmlStyleSheet)); StreamSource stylesheetStream = new StreamSource(xmlStyleSheet); mergeXML2IntoStylesheet = tFactory.newTemplates(stylesheetStream); StreamSource xml1Source = new StreamSource(new StringReader(xmlFileContent1)); StringWriter mergedWriter = new StringWriter(); StreamResult mergedResult = new StreamResult(mergedWriter); // Transformer is not guaranteed to be thread-safe -- therefore, we // need one per thread. Transformer mergingTransformer = mergeXML2IntoStylesheet.newTransformer(); mergingTransformer.setURIResolver(new URIResolver() { public Source resolve(String href, String base) { if (href == null) { return null; } else if (href.equals(refCodeName)) { return (new StreamSource(new StringReader(xmlFileContent2))); } else { return null; } } }); mergingTransformer.transform(xml1Source, mergedResult); return mergedWriter.toString(); }