List of usage examples for javax.xml.transform TransformerFactory setErrorListener
public abstract void setErrorListener(ErrorListener listener);
From source file:org.apache.fop.cli.InputHandler.java
/** * Transforms the input document to the input format expected by FOP using XSLT. * @param result the Result object where the result of the XSL transformation is sent to * @throws FOPException in case of an error during processing *///from w w w .ja va 2 s .com protected void transformTo(Result result) throws FOPException { try { // Setup XSLT TransformerFactory factory = TransformerFactory.newInstance(); if (uriResolver != null) { factory.setURIResolver(uriResolver); } factory.setErrorListener(this); Transformer transformer; Source xsltSource = createXSLTSource(); if (xsltSource == null) { // FO Input transformer = factory.newTransformer(); } else { // XML/XSLT input transformer = factory.newTransformer(xsltSource); // Set the value of parameters, if any, defined for stylesheet if (xsltParams != null) { for (int i = 0; i < xsltParams.size(); i += 2) { transformer.setParameter((String) xsltParams.elementAt(i), (String) xsltParams.elementAt(i + 1)); } } } transformer.setErrorListener(this); // Create a SAXSource from the input Source file Source src = createMainSource(); // Start XSLT transformation and FOP processing transformer.transform(src, result); } catch (Exception e) { throw new FOPException(e); } }
From source file:org.apache.fop.plan.PreloaderPlan.java
private Document getDocument(InputStream in) throws TransformerException { TransformerFactory tFactory = TransformerFactory.newInstance(); //Custom error listener to minimize output to console ErrorListener errorListener = new DefaultErrorListener(log); tFactory.setErrorListener(errorListener); Transformer transformer = tFactory.newTransformer(); transformer.setErrorListener(errorListener); Source source = new StreamSource(in); DOMResult res = new DOMResult(); transformer.transform(source, res);//from w w w.j a va2s.co m Document doc = (Document) res.getNode(); return doc; }
From source file:org.apache.solr.handler.dataimport.processor.XPathEntityProcessor.java
private void initXpathReader() { useSolrAddXml = Boolean.parseBoolean(context.getEntityAttribute(USE_SOLR_ADD_SCHEMA)); streamRows = Boolean.parseBoolean(context.getEntityAttribute(STREAM)); if (context.getResolvedEntityAttribute("batchSize") != null) { blockingQueueSize = Integer.parseInt(context.getEntityAttribute("batchSize")); }//from www . ja v a2 s . c o m if (context.getResolvedEntityAttribute("readTimeOut") != null) { blockingQueueTimeOut = Integer.parseInt(context.getEntityAttribute("readTimeOut")); } String xslt = context.getEntityAttribute(XSL); if (xslt != null) { xslt = context.replaceTokens(xslt); try { // create an instance of TransformerFactory final TransformerFactory transFact = TransformerFactory.newInstance(); final SolrCore core = context.getSolrCore(); final StreamSource xsltSource; if (core != null) { // Solr cut off //final ResourceLoader loader = core.getResourceLoader(); //transFact.setURIResolver(new SystemIdResolver(loader).asURIResolver()); //xsltSource = new StreamSource(loader.openResource(xslt), // SystemIdResolver.createSystemIdFromResourceName(xslt)); xsltSource = new StreamSource(xslt); } else { // fallback for tests xsltSource = new StreamSource(xslt); } transFact.setErrorListener(xmllog); try { xslTransformer = transFact.newTransformer(xsltSource); } finally { // some XML parsers are broken and don't close the byte stream (but they should according to spec) IOUtils.closeQuietly(xsltSource.getInputStream()); } LOG.info("Using xslTransformer: " + xslTransformer.getClass().getName()); } catch (final Exception e) { throw new DataImportHandlerException(SEVERE, "Error initializing XSL ", e); } } if (useSolrAddXml) { // Support solr add documents xpathReader = new XPathRecordReader("/add/doc"); xpathReader.addField("name", "/add/doc/field/@name", true); xpathReader.addField("value", "/add/doc/field", true); } else { final String forEachXpath = context.getEntityAttribute(FOR_EACH); if (forEachXpath == null) throw new DataImportHandlerException(SEVERE, "Entity : " + context.getEntityAttribute("name") + " must have a 'forEach' attribute"); try { xpathReader = new XPathRecordReader(forEachXpath); for (final Map<String, String> field : context.getAllEntityFields()) { if (field.get(XPATH) == null) continue; int flags = 0; if ("true".equals(field.get("flatten"))) { flags = XPathRecordReader.FLATTEN; } String xpath = field.get(XPATH); xpath = context.replaceTokens(xpath); xpathReader.addField(field.get(DataImporter.COLUMN), xpath, Boolean.parseBoolean(field.get(DataImporter.MULTI_VALUED)), flags); } } catch (final RuntimeException e) { throw new DataImportHandlerException(SEVERE, "Exception while reading xpaths for fields", e); } } final String url = context.getEntityAttribute(URL); final List<String> l = url == null ? Collections.EMPTY_LIST : TemplateString.getVariables(url); for (final String s : l) { if (s.startsWith(entityName + ".")) { if (placeHolderVariables == null) placeHolderVariables = new ArrayList<String>(); placeHolderVariables.add(s.substring(entityName.length() + 1)); } } for (final Map<String, String> fld : context.getAllEntityFields()) { if (fld.get(COMMON_FIELD) != null && "true".equals(fld.get(COMMON_FIELD))) { if (commonFields == null) commonFields = new ArrayList<String>(); commonFields.add(fld.get(DataImporter.COLUMN)); } } }
From source file:org.apache.solr.handler.dataimport.XPathEntityProcessor.java
private void initXpathReader(VariableResolver resolver) { reinitXPathReader = false;//from ww w . jav a2s. c o m useSolrAddXml = Boolean.parseBoolean(context.getEntityAttribute(USE_SOLR_ADD_SCHEMA)); streamRows = Boolean.parseBoolean(context.getEntityAttribute(STREAM)); if (context.getResolvedEntityAttribute("batchSize") != null) { blockingQueueSize = Integer.parseInt(context.getEntityAttribute("batchSize")); } if (context.getResolvedEntityAttribute("readTimeOut") != null) { blockingQueueTimeOut = Integer.parseInt(context.getEntityAttribute("readTimeOut")); } String xslt = context.getEntityAttribute(XSL); if (xslt != null) { xslt = context.replaceTokens(xslt); try { // create an instance of TransformerFactory TransformerFactory transFact = TransformerFactory.newInstance(); final SolrCore core = context.getSolrCore(); final StreamSource xsltSource; if (core != null) { final ResourceLoader loader = core.getResourceLoader(); transFact.setURIResolver(new SystemIdResolver(loader).asURIResolver()); xsltSource = new StreamSource(loader.openResource(xslt), SystemIdResolver.createSystemIdFromResourceName(xslt)); } else { // fallback for tests xsltSource = new StreamSource(xslt); } transFact.setErrorListener(xmllog); try { xslTransformer = transFact.newTransformer(xsltSource); } finally { // some XML parsers are broken and don't close the byte stream (but they should according to spec) IOUtils.closeQuietly(xsltSource.getInputStream()); } LOG.info("Using xslTransformer: " + xslTransformer.getClass().getName()); } catch (Exception e) { throw new DataImportHandlerException(SEVERE, "Error initializing XSL ", e); } } if (useSolrAddXml) { // Support solr add documents xpathReader = new XPathRecordReader("/add/doc"); xpathReader.addField("name", "/add/doc/field/@name", true); xpathReader.addField("value", "/add/doc/field", true); } else { String forEachXpath = context.getResolvedEntityAttribute(FOR_EACH); if (forEachXpath == null) throw new DataImportHandlerException(SEVERE, "Entity : " + context.getEntityAttribute("name") + " must have a 'forEach' attribute"); if (forEachXpath.equals(context.getEntityAttribute(FOR_EACH))) reinitXPathReader = true; try { xpathReader = new XPathRecordReader(forEachXpath); for (Map<String, String> field : context.getAllEntityFields()) { if (field.get(XPATH) == null) continue; int flags = 0; if ("true".equals(field.get("flatten"))) { flags = XPathRecordReader.FLATTEN; } String xpath = field.get(XPATH); xpath = context.replaceTokens(xpath); //!xpath.equals(field.get(XPATH) means the field xpath has a template //in that case ensure that the XPathRecordReader is reinitialized //for each xml if (!xpath.equals(field.get(XPATH)) && !context.isRootEntity()) reinitXPathReader = true; xpathReader.addField(field.get(DataImporter.COLUMN), xpath, Boolean.parseBoolean(field.get(DataImporter.MULTI_VALUED)), flags); } } catch (RuntimeException e) { throw new DataImportHandlerException(SEVERE, "Exception while reading xpaths for fields", e); } } String url = context.getEntityAttribute(URL); List<String> l = url == null ? Collections.EMPTY_LIST : resolver.getVariables(url); for (String s : l) { if (s.startsWith(entityName + ".")) { if (placeHolderVariables == null) placeHolderVariables = new ArrayList<>(); placeHolderVariables.add(s.substring(entityName.length() + 1)); } } for (Map<String, String> fld : context.getAllEntityFields()) { if (fld.get(COMMON_FIELD) != null && "true".equals(fld.get(COMMON_FIELD))) { if (commonFields == null) commonFields = new ArrayList<>(); commonFields.add(fld.get(DataImporter.COLUMN)); } } }
From source file:org.apache.solr.util.xslt.TransformerProvider.java
/** Return a Templates object for the given filename */ private Templates getTemplates(ResourceLoader loader, String filename, int cacheLifetimeSeconds) throws IOException { Templates result = null;/*ww w. ja v a 2s . c o m*/ lastFilename = null; try { if (log.isDebugEnabled()) { log.debug("compiling XSLT templates:" + filename); } final String fn = "xslt/" + filename; final TransformerFactory tFactory = TransformerFactory.newInstance(); tFactory.setURIResolver(new SystemIdResolver(loader).asURIResolver()); tFactory.setErrorListener(xmllog); final StreamSource src = new StreamSource(loader.openResource(fn), SystemIdResolver.createSystemIdFromResourceName(fn)); try { result = tFactory.newTemplates(src); } finally { // some XML parsers are broken and don't close the byte stream (but they should according to spec) IOUtils.closeQuietly(src.getInputStream()); } } catch (Exception e) { log.error(getClass().getName(), "newTemplates", e); final IOException ioe = new IOException("Unable to initialize Templates '" + filename + "'"); ioe.initCause(e); throw ioe; } lastFilename = filename; lastTemplates = result; cacheExpires = System.currentTimeMillis() + (cacheLifetimeSeconds * 1000); return result; }
From source file:org.apache.struts2.views.xslt.XSLTResult.java
protected Templates getTemplates(final String path) throws TransformerException, IOException { if (path == null) throw new TransformerException("Stylesheet path is null"); Templates templates = templatesCache.get(path); if (noCache || (templates == null)) { synchronized (templatesCache) { URL resource = ServletActionContext.getServletContext().getResource(path); if (resource == null) { throw new TransformerException("Stylesheet " + path + " not found in resources."); }//from ww w . j a v a2 s . c o m LOG.debug("Preparing XSLT stylesheet templates: {}", path); TransformerFactory factory = TransformerFactory.newInstance(); factory.setURIResolver(getURIResolver()); factory.setErrorListener(buildErrorListener()); templates = factory.newTemplates(new StreamSource(resource.openStream())); templatesCache.put(path, templates); } } return templates; }
From source file:org.dhatim.templating.xslt.XslTemplateProcessor.java
@Override protected void loadTemplate(SmooksResourceConfiguration resourceConfig) throws IOException, TransformerConfigurationException { TransformerFactory transformerFactory = TransformerFactory.newInstance(); StreamSource xslStreamSource; boolean isInlineXSL = resourceConfig.isInline(); byte[] xslBytes = resourceConfig.getBytes(); xslString = new String(xslBytes, getEncoding().name()); // If it's not a full XSL template, we need to make it so by wrapping it... isTemplatelet = isTemplatelet(isInlineXSL, new String(xslBytes)); if (isTemplatelet) { String templateletWrapper = new String( StreamUtils.readStream(ClassUtil.getResourceAsStream("doc-files/templatelet.xsl", getClass()))); String templatelet = new String(xslBytes); templateletWrapper = StringUtils.replace(templateletWrapper, "@@@templatelet@@@", templatelet); xslBytes = templateletWrapper.getBytes(); xslString = new String(xslBytes, getEncoding().name()); }/*from www . ja va 2s.c o m*/ boolean failOnWarning = resourceConfig.getBoolParameter("failOnWarning", true); xslStreamSource = new StreamSource(new StringReader(xslString)); transformerFactory.setErrorListener(new XslErrorListener(failOnWarning)); xslTemplate = transformerFactory.newTemplates(xslStreamSource); }
From source file:org.ikasan.filetransfer.xml.transform.DefaultXSLTransformer.java
/** * Creates a new <code>TransformerFactory</code> instance, * sets the default error listener, sets debugging flag on if necessary * and finally returns the instance./*w w w . j a va 2s .co m*/ * * @return new TransformerFactory instance */ private TransformerFactory newTransformerFactory() { // Get a new TransformerFactory instance TransformerFactory tFactory = TransformerFactory.newInstance(); //logger.debug("Setting auto-translet to true..."); //tFactory.setAttribute("auto-translet", Boolean.TRUE); if (System.getProperty(XSLT_DEBUG, "false").equalsIgnoreCase("true")) tFactory.setAttribute("debug", Boolean.TRUE); logger.debug("Setting error event listener to ErrorListener..."); tFactory.setErrorListener(new DefaultErrorListener()); return tFactory; }
From source file:org.mycore.common.content.transformer.MCRXSLTransformer.java
public synchronized void setTransformerFactory(String factoryClass) throws TransformerFactoryConfigurationError { TransformerFactory transformerFactory = Optional.ofNullable(factoryClass) .map(c -> TransformerFactory.newInstance(c, null)).orElseGet(TransformerFactory::newInstance); LOGGER.info("Transformerfactory: " + transformerFactory.getClass().getName()); transformerFactory.setURIResolver(URI_RESOLVER); transformerFactory.setErrorListener(MCRErrorListener.getInstance()); if (transformerFactory.getFeature(SAXSource.FEATURE) && transformerFactory.getFeature(SAXResult.FEATURE)) { this.tFactory = (SAXTransformerFactory) transformerFactory; } else {//from w w w . j av a2 s . c o m throw new MCRConfigurationException("Transformer Factory " + transformerFactory.getClass().getName() + " does not implement SAXTransformerFactory"); } }
From source file:org.openadaptor.auxil.processor.xml.XsltProcessor.java
/** * Trys to load the XSLT from the file defined in the properties (will also try to find the file on the classpath if * it can).//from w w w .j ava 2s . com * * @throws ValidationException * if the XSLT file is not defined in the properties, the file cannot be found or there was an error parsing * it */ private void loadXSLT() { if (xsltFile == null) throw new ValidationException("xsltFile property not set", this); // if the file doesn't exist try to get it via the classpath URL url = FileUtils.toURL(xsltFile); if (url == null) throw new ValidationException("File not found: " + xsltFile, this); // load the transform try { TransformerFactory factory = TransformerFactory.newInstance(); ErrorListener errorListener = new ErrorListener() { public void warning(TransformerException exception) throws TransformerException { log.warn(exception.getMessage(), exception); } public void fatalError(TransformerException exception) throws TransformerException { throw exception; } public void error(TransformerException exception) throws TransformerException { throw exception; } }; factory.setErrorListener(errorListener); transform = factory.newTransformer(new StreamSource(url.getPath())); log.info("Loaded XSLT [" + xsltFile + "] successfully"); } catch (TransformerConfigurationException e) { throw new ValidationException("Failed to load XSLT: " + e.getMessage(), this); } }