List of usage examples for javax.xml.transform.stream StreamSource setSystemId
public void setSystemId(File f)
From source file:org.fcrepo.localservices.saxon.SaxonServlet.java
/** * Maintain prepared stylesheets in memory for reuse *///w ww .j a v a2 s . c om private Templates tryCache(String url) throws Exception { Templates x = (Templates) m_cache.get(url); if (x == null) { synchronized (m_cache) { if (!m_cache.containsKey(url)) { TransformerFactory factory = TransformerFactory.newInstance(); if (factory.getClass().getName().equals("net.sf.saxon.TransformerFactoryImpl")) { factory.setAttribute(FeatureKeys.VERSION_WARNING, Boolean.FALSE); } StreamSource ss = new StreamSource(getInputStream(url)); ss.setSystemId(url); x = factory.newTemplates(ss); m_cache.put(url, x); } } } return x; }
From source file:org.fcrepo.localservices.saxon.SaxonServlet.java
/** * Apply stylesheet to source document/* ww w . j a v a 2s .c om*/ */ 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:com.wooki.services.parsers.XHTMLToFormattingObjects.java
public InputStream performTransformation(Resource xmlDocument) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); StreamResult toReturn = new StreamResult(baos); // Use the TransformerFactory to instantiate a Transformer that will // work with the stylesheet you specify. This method call also processes // the stylesheet into // a compiled Templates object. try {/*from ww w . ja v a 2 s .c o m*/ URL url = this.xslStylesheet.getURL(); Element processedStylesheet = cache.get(url); if (processedStylesheet == null) { if (url.getProtocol().equals("http")) { GetMethod method = new GetMethod(url.toString()); this.httpClient.executeMethod(method); byte[] body = method.getResponseBody(); StreamSource input = new StreamSource(new ByteArrayInputStream(body)); input.setSystemId(url.toString()); tFactory.setURIResolver(this); transformer = tFactory.newTransformer(input); transformer.setURIResolver(this); processedStylesheet = new Element(this.xslStylesheet.getURL(), transformer); } else { StreamSource input = new StreamSource(this.xslStylesheet.getInputStream()); input.setSystemId(this.xslStylesheet.getFile()); transformer = tFactory.newTransformer(input); transformer.setURIResolver(this); processedStylesheet = new Element(this.xslStylesheet.getURL(), transformer); } cache.put(processedStylesheet); } else { transformer = (Transformer) processedStylesheet.getObjectValue(); } XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setEntityResolver(this); // transformer. // Use the Transformer to apply the associated Templates object to // an // XML document (foo.xml) and write the output to a file. transformer.transform(new SAXSource(reader, new InputSource(xmlDocument.getInputStream())), toReturn); String result = new String(baos.toByteArray()); return new ByteArrayInputStream(baos.toByteArray()); } catch (TransformerConfigurationException e) { e.printStackTrace(); logger.error(e.getLocalizedMessage()); return null; } catch (IOException e) { e.printStackTrace(); logger.error(e.getLocalizedMessage()); return null; } catch (TransformerException e) { e.printStackTrace(); logger.error(e.getLocalizedMessage()); return null; } catch (SAXException e) { e.printStackTrace(); logger.error(e.getLocalizedMessage()); return null; } catch (Error e) { e.printStackTrace(); logger.error(e.getLocalizedMessage()); } return new ByteArrayInputStream(baos.toByteArray()); }
From source file:lux.Evaluator.java
/** * Build a document as a Saxon {@link XdmNode}. The document will be given a generated id outside * the space of ids reserved for indexed documents. * @param xml the document content/*w w w.ja v a 2s .co m*/ * @param uri the document uri * @return the constructed document * @throws LuxException if any error occurs (such as an XML parse error). */ public XdmNode build(Reader xml, String uri) { StreamSource source = new StreamSource(xml); source.setSystemId(uri); try { return builder.build(source); } catch (SaxonApiException e) { throw new LuxException(e); } }
From source file:lux.Evaluator.java
/** * Build a document as a Saxon {@link XdmNode}. The document will be given a generated id outside * the space of ids reserved for indexed documents. * @param xml the document content/*from w w w . ja va2s.co m*/ * @param uri the document uri * @return the constructed document * @throws LuxException if any error occurs (such as an XML parse error). */ public XdmNode build(InputStream xml, String uri) { StreamSource source = new StreamSource(xml); source.setSystemId(uri); try { return builder.build(source); } catch (SaxonApiException e) { throw new LuxException(e); } }
From source file:fr.efl.chaine.xslt.GauloisPipe.java
private XsltTransformer getXsltTransformer(String href, HashMap<QName, ParameterValue> parameters) throws MalformedURLException, SaxonApiException, URISyntaxException, FileNotFoundException, IOException {// w ww.java 2 s.c o m // TODO : rewrite this, as cp: and jar: protocols are availabe and one can use new URL(cp:/...).getInputStream() String __href = ParametersMerger.processParametersReplacement(href, parameters); LOGGER.debug("loading " + __href); XsltExecutable xsl = xslCache.get(__href); if (xsl == null) { LOGGER.trace(__href + " not in cache"); try { InputStream input; if (__href.startsWith("file:")) { File f = new File(new URI(__href)); input = new FileInputStream(f); } else if (__href.startsWith("jar:")) { input = new URL(__href).openStream(); } else if (__href.startsWith("cp:")) { input = GauloisPipe.class.getResourceAsStream(__href.substring(3)); } else { File f = new File(__href); input = new FileInputStream(f); } LOGGER.trace("input is " + input); StreamSource source = new StreamSource(input); source.setSystemId(__href); xsl = xsltCompiler.compile(source); xslCache.put(__href, xsl); } catch (SaxonApiException ex) { LOGGER.error("while compiling " + __href); LOGGER.error("SaxonAPIException: " + href + ": [" + ex.getErrorCode() + "]:" + ex.getMessage()); if (ex.getCause() != null) { LOGGER.error(ex.getCause().getMessage()); } throw ex; } catch (URISyntaxException | FileNotFoundException ex) { LOGGER.error("while compiling " + __href); throw ex; } } return xsl.load(); }
From source file:org.mycore.common.xml.MCRURIResolver.java
/** * URI Resolver that resolves XSL document() or xsl:include calls. * * @see javax.xml.transform.URIResolver// w w w .ja v a2 s.com */ public Source resolve(String href, String base) throws TransformerException { if (LOGGER.isDebugEnabled()) { if (base != null) { LOGGER.debug("Including " + href + " from " + base); addDebugInfo(href, base); } else { LOGGER.debug("Including " + href); addDebugInfo(href, null); } } if (!href.contains(":")) { return tryResolveXSL(href, base); } String scheme = getScheme(href, base); URIResolver uriResolver = SUPPORTED_SCHEMES.get(scheme); if (uriResolver != null) { return uriResolver.resolve(href, base); } else { // try to handle as URL, use default resolver for file:// and try { InputSource entity = MCREntityResolver.instance().resolveEntity(null, href); if (entity != null) { LOGGER.debug("Resolved via EntityResolver: " + entity.getSystemId()); return new MCRLazyStreamSource(entity::getByteStream, entity.getSystemId()); } } catch (SAXException | IOException e) { LOGGER.debug("Error while resolving uri: " + href); } // http:// if (href.endsWith("/") && scheme.equals("file")) { //cannot stream directories return null; } StreamSource streamSource = new StreamSource(); streamSource.setSystemId(href); return streamSource; } }
From source file:com.enonic.vertical.adminweb.UserHandlerServlet.java
private StreamSource buildXSL(HttpSession session, Source xslFile, Source source) throws VerticalAdminException { StreamSource result = null; HashMap<String, Object> xslParams = new HashMap<String, Object>(); xslParams.put("xslpath", ""); // xslParams.put("xslpath", AdminStore.getAdminXSLPath()); try {//w w w . ja v a2s. c o m StringWriter swriter = new StringWriter(); transformXML(session, swriter, source, xslFile, xslParams); result = new StreamSource(new StringReader(swriter.toString())); result.setSystemId(xslFile.getSystemId()); } catch (Exception e) { VerticalAdminLogger.errorAdmin(this.getClass(), 50, "XSLT error: %t", e); } return result; }
From source file:nl.nn.adapterframework.util.XmlUtils.java
public static synchronized Transformer createTransformer(URL url, boolean xslt2) throws TransformerConfigurationException, IOException { StreamSource stylesource = new StreamSource(url.openStream(), Misc.DEFAULT_INPUT_STREAM_ENCODING); stylesource.setSystemId(url.toString()); return createTransformer(stylesource, xslt2); }
From source file:org.ambraproject.service.xml.XMLServiceImpl.java
private StreamSource getResourceAsStreamSource(String filename) throws IOException { log.debug("Loading: {}", filename); URL loc = getClass().getClassLoader().getResource(filename); //If Loading resource fails, try getting the physical file if (loc == null) { File xsl = new File(filename); log.debug("Found File: {}", xsl.getPath()); return new StreamSource(xsl); } else {/*from ww w . j a v a 2 s .c o m*/ InputStream is = getClass().getClassLoader().getResourceAsStream(filename); StreamSource source = new StreamSource(is); log.debug("Found Resource: {}", loc.getFile()); //Note: http://stackoverflow.com/questions/7236291/saxon-error-with-xslt-import-statement source.setSystemId(loc.getFile()); return source; } }