List of usage examples for javax.xml.transform TransformerFactory getFeature
public abstract boolean getFeature(String name);
From source file:ValidateXMLInput.java
void validate() throws Exception { // Since we're going to use a SAX feature, the transformer must support // input in the form of a SAXSource. TransformerFactory tfactory = TransformerFactory.newInstance(); if (tfactory.getFeature(SAXSource.FEATURE)) { // Standard way of creating an XMLReader in JAXP 1.1. SAXParserFactory pfactory = SAXParserFactory.newInstance(); pfactory.setNamespaceAware(true); // Very important! // Turn on validation. pfactory.setValidating(true);/*from www. jav a 2s .c o m*/ // Get an XMLReader. XMLReader reader = pfactory.newSAXParser().getXMLReader(); // Instantiate an error handler (see the Handler inner class below) that will report any // errors or warnings that occur as the XMLReader is parsing the XML input. Handler handler = new Handler(); reader.setErrorHandler(handler); // Standard way of creating a transformer from a URL. Transformer t = tfactory.newTransformer(new StreamSource("birds.xsl")); // Specify a SAXSource that takes both an XMLReader and a URL. SAXSource source = new SAXSource(reader, new InputSource("birds.xml")); // Transform to a file. try { t.transform(source, new StreamResult("birds.out")); } catch (TransformerException te) { // The TransformerException wraps someting other than a SAXParseException // warning or error, either of which should be "caught" by the Handler. System.out.println("Not a SAXParseException warning or error: " + te.getMessage()); } System.out.println("=====Done====="); } else System.out.println("tfactory does not support SAX features!"); }
From source file:de.gbv.ole.Marc21ToOleBulk.java
/** * Set the <code>Result</code> associated with this * <code>TransformerHandler</code> to be used for the transformation. * * @param result the Result to be used for the transformation *//*w w w .j av a 2 s .com*/ protected final void setHandler(final Result result) { try { TransformerFactory factory = TransformerFactory.newInstance(); if (!factory.getFeature(SAXTransformerFactory.FEATURE)) { throw new UnsupportedOperationException("SAXTransformerFactory is not supported"); } SAXTransformerFactory saxFactory = (SAXTransformerFactory) factory; handler = saxFactory.newTransformerHandler(); handler.getTransformer().setOutputProperty(OutputKeys.METHOD, "xml"); handler.setResult(result); } catch (Exception e) { throw new MarcException(e.getMessage(), e); } }
From source file:org.eclipse.smila.search.servlet.SMILASearchServlet.java
/** * create XSL transformer for stylesheet. * * @param xslDoc/*ww w.j a va 2s. co m*/ * XSL DOM document * @return XSL transformer * @throws ServletException * error. */ protected Transformer getXSLTransformer(final Document xslDoc) throws ServletException { final TransformerFactory tFactory = TransformerFactory.newInstance(); if (tFactory.getFeature(DOMSource.FEATURE) && tFactory.getFeature(StreamResult.FEATURE)) { final DOMSource xslDomSource = new DOMSource(xslDoc); try { return tFactory.newTransformer(xslDomSource); } catch (final TransformerConfigurationException e) { throw new ServletException("error while creating the transformer", e); } } else { throw new ServletException("the transformer [" + tFactory.getClass().getName() + "] doesn't support the used DOMSource or StreamResult"); } }
From source file:org.lilyproject.runtime.tools.plugin.genclassloader.ClassloaderMojo.java
/** * Create a project file containing the dependencies. * * @throws IOException/*from w w w. j a v a2s .com*/ * @throws SAXException */ private void createDependencyListing(File classloaderTemplate) throws IOException, SAXException { if (classloaderTemplate != null && classloaderTemplate.exists()) { getLog().info("Found classloader template, trying to parse it..."); parseClassloaderTemplate(classloaderTemplate); } final boolean hasEntries = entryMap.size() > 0; // fill in file with all dependencies FileOutputStream fos = new FileOutputStream(projectDescriptorFile); TransformerHandler ch = null; TransformerFactory factory = TransformerFactory.newInstance(); if (factory.getFeature(SAXTransformerFactory.FEATURE)) { try { ch = ((SAXTransformerFactory) factory).newTransformerHandler(); // set properties Transformer serializer = ch.getTransformer(); serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); // set result Result result = new StreamResult(fos); ch.setResult(result); // start file generation ch.startDocument(); AttributesImpl atts = new AttributesImpl(); if (this.shareSelf != null) { atts.addAttribute("", "share-self", "share-self", "CDATA", this.shareSelf); } ch.startElement("", "classloader", "classloader", atts); atts.clear(); ch.startElement("", "classpath", "classpath", atts); SortedSet<Artifact> sortedArtifacts = new TreeSet<Artifact>(dependenciesToList); Entry entry; String entryShare; String entryVersion; for (Artifact artifact : sortedArtifacts) { atts.addAttribute("", "groupId", "groupId", "CDATA", artifact.getGroupId()); atts.addAttribute("", "artifactId", "artifactId", "CDATA", artifact.getArtifactId()); if (artifact.getClassifier() != null) { atts.addAttribute("", "classifier", "classifier", "CDATA", artifact.getClassifier()); } if (!artifact.getGroupId().equals("org.lilyproject")) { atts.addAttribute("", "version", "version", "CDATA", artifact.getBaseVersion()); } entry = new Entry(artifact.getGroupId(), artifact.getArtifactId(), artifact.getClassifier()); if (hasEntries && entryMap.containsKey(entry)) { entryVersion = extractAttVal(entryMap.get(entry).getAttributes(), "version"); entryShare = extractAttVal(entryMap.get(entry).getAttributes(), "share"); entryMap.remove(entry); if (entryVersion != null && !entryVersion.equals("") && !entryVersion.equals(artifact.getBaseVersion())) { getLog().warn( "version conflict between entry in template and artifact on classpath for " + entry); } if (entryShare != null) { atts.addAttribute("", "", "share", "CDATA", entryShare); } } else { // atts.addAttribute("", "", "share", "CDATA", SHARE_DEFAULT); } ch.startElement("", "artifact", "artifact", atts); ch.endElement("", "artifact", "artifact"); atts.clear(); } ch.endElement("", "classpath", "classpath"); ch.endElement("", "classloader", "classloader"); ch.endDocument(); fos.close(); if (entryMap.size() > 0) { getLog().warn("Classloader template contains entries that could not be resolved."); } } catch (TransformerConfigurationException ex) { ex.printStackTrace(); throw new SAXException("Unable to get a TransformerHandler."); } } else { throw new RuntimeException("Could not load SAXTransformerFactory."); } }
From source file:org.lilyproject.runtime.tools.plugin.genclassloader.ClassloaderMojo.java
private void parseClassloaderTemplate(File file) { DOMResult domResult = null;/*from www . ja va 2s. c o m*/ Transformer transformer = null; try { Source xmlSource = new StreamSource(file); TransformerFactory tfFactory = TransformerFactory.newInstance(); if (tfFactory.getFeature(DOMResult.FEATURE)) { transformer = tfFactory.newTransformer(); domResult = new DOMResult(); transformer.transform(xmlSource, domResult); } } catch (TransformerException ex) { throw new RuntimeException("Error parsing file '" + file + "'."); } if (domResult != null && transformer != null) { Document docu = (Document) domResult.getNode(); Element classpath; NodeList list; String shareSelf = docu.getDocumentElement().getAttribute("share-self").trim(); if (shareSelf.length() > 0) { this.shareSelf = shareSelf; } try { classpath = (Element) docu.getElementsByTagName("classpath").item(0); list = classpath.getElementsByTagName("artifact"); } catch (NullPointerException npex) { throw new RuntimeException("Classloader template is invalid."); } NamedNodeMap map; Entry entry; String groupId; String classifier; String artifactId; Element domArtifact; for (int i = 0; i < list.getLength(); i++) { domArtifact = (Element) list.item(i); map = domArtifact.getAttributes(); groupId = extractAttVal(map, "groupId"); artifactId = extractAttVal(map, "artifactId"); classifier = extractAttVal(map, "classifier"); entry = new Entry(groupId, artifactId, classifier); entryMap.put(entry, domArtifact); } } }
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 {//ww w . j a v a 2 s .co m throw new MCRConfigurationException("Transformer Factory " + transformerFactory.getClass().getName() + " does not implement SAXTransformerFactory"); } }
From source file:org.pepstock.jem.ant.validator.transformer.TransformerValidator.java
/** * Inits the transformer, load the xslt and validate it, load jem properties * During the transformation, the transformer onbject is locked, so the file * listner is inhibited to do a refresh. * /*from w w w. j ava2s.c om*/ * @param xsltvalidatorFile the xslt file * @return the transformer * @throws ValidationException the validation exception */ private Transformer createTransformer(String xsltvalidatorFile) throws ValidationException { Transformer t = null; // Instantiate a TransformerFactory TransformerFactory tFactory = TransformerFactory.newInstance(); // add error listner to capture validation error. ErrorListener tfel = new TransformerFactoryErrorListener(); tFactory.setErrorListener(tfel); // check the transformer compliant if (!tFactory.getFeature(SAXTransformerFactory.FEATURE)) { throw new ValidationException(AntMessage.JEMA050E.toMessage().getFormattedMessage()); } // activate xalan extension NodeInfo to map source xml code position tFactory.setAttribute(TransformerFactoryImpl.FEATURE_SOURCE_LOCATION, Boolean.TRUE); StreamSource ss = new StreamSource(xsltvalidatorFile); try { // A Transformer may be used multiple times. // Parameters and output properties are preserved across // transformations. t = tFactory.newTransformer(ss); } catch (TransformerConfigurationException e) { throw new ValidationException(AntMessage.JEMA047E.toMessage().getFormattedMessage(e.getMessage()), e); } // add custom error listener, necessary to avoid internal catch // of exception throwed by xslt ErrorListener el = new TransformerErrorListener(); t.setErrorListener(el); // pass the parameter list to the xslt for (Object key : System.getProperties().keySet()) { String keyString = key.toString(); String value = System.getProperty(keyString); t.setParameter(keyString, value); } for (String key : System.getenv().keySet()) { String value = System.getenv().get(key); t.setParameter(key, value); } return t; }
From source file:org.toobsframework.transformpipeline.domain.BaseXMLTransformer.java
public void init() { if (uriResolver == null) { throw new RuntimeException("uriResolver property must be set"); }/* w w w .j a v a 2 s. c o m*/ TransformerFactory tFactory = TransformerFactory.newInstance(); setFactoryResolver(tFactory); tFactory.setAttribute("http://xml.apache.org/xalan/features/incremental", java.lang.Boolean.TRUE); if (tFactory.getFeature(SAXSource.FEATURE) && tFactory.getFeature(SAXResult.FEATURE)) { // Cast the TransformerFactory to SAXTransformerFactory. saxTFactory = ((SAXTransformerFactory) tFactory); } if (outputProperties == null) { outputProperties = OutputPropertiesFactory.getDefaultMethodProperties("html"); } templateCache = new ConcurrentHashMap<String, Templates>(); }
From source file:org.toobsframework.transformpipeline.domain.ChainedXSLTransformer.java
private String transform(List inputXSLs, String inputXML, Map inputParams, IXMLTransformerHelper transformerHelper) throws XMLTransformerException { String outputXML = null;/*from ww w. jav a 2s.com*/ ByteArrayInputStream xmlInputStream = null; ByteArrayOutputStream xmlOutputStream = null; try { TransformerFactory tFactory = TransformerFactory.newInstance(); setFactoryResolver(tFactory); if (tFactory.getFeature(SAXSource.FEATURE) && tFactory.getFeature(SAXResult.FEATURE)) { // Cast the TransformerFactory to SAXTransformerFactory. SAXTransformerFactory saxTFactory = ((SAXTransformerFactory) tFactory); // Create a TransformerHandler for each stylesheet. ArrayList tHandlers = new ArrayList(); TransformerHandler tHandler = null; // Create an XMLReader. XMLReader reader = new SAXParser(); // transformer3 outputs SAX events to the serializer. if (outputProperties == null) { outputProperties = OutputPropertiesFactory.getDefaultMethodProperties("html"); } Serializer serializer = SerializerFactory.getSerializer(outputProperties); String xslFile = null; for (int it = 0; it < inputXSLs.size(); it++) { Object source = inputXSLs.get(it); if (source instanceof StreamSource) { tHandler = saxTFactory.newTransformerHandler((StreamSource) source); if (xslFile == null) xslFile = ((StreamSource) source).getSystemId(); } else { //tHandler = saxTFactory.newTransformerHandler(new StreamSource(getXSLFile((String) source))); tHandler = saxTFactory .newTransformerHandler(uriResolver.resolve((String) source + ".xsl", "")); if (xslFile == null) xslFile = (String) source; } Transformer transformer = tHandler.getTransformer(); transformer.setOutputProperty("encoding", "UTF-8"); transformer.setErrorListener(tFactory.getErrorListener()); if (inputParams != null) { Iterator paramIt = inputParams.entrySet().iterator(); while (paramIt.hasNext()) { Map.Entry thisParam = (Map.Entry) paramIt.next(); transformer.setParameter((String) thisParam.getKey(), (String) thisParam.getValue()); } } if (transformerHelper != null) { transformer.setParameter(TRANSFORMER_HELPER, transformerHelper); } tHandlers.add(tHandler); } tHandler = null; for (int th = 0; th < tHandlers.size(); th++) { tHandler = (TransformerHandler) tHandlers.get(th); if (th == 0) { reader.setContentHandler(tHandler); reader.setProperty("http://xml.org/sax/properties/lexical-handler", tHandler); } else { ((TransformerHandler) tHandlers.get(th - 1)).setResult(new SAXResult(tHandler)); } } // Parse the XML input document. The input ContentHandler and output ContentHandler // work in separate threads to optimize performance. InputSource xmlSource = null; xmlInputStream = new ByteArrayInputStream((inputXML).getBytes("UTF-8")); if (log.isTraceEnabled()) { log.trace("Input XML:\n" + inputXML); } xmlSource = new InputSource(xmlInputStream); xmlOutputStream = new ByteArrayOutputStream(); serializer.setOutputStream(xmlOutputStream); ((TransformerHandler) tHandlers.get(tHandlers.size() - 1)) .setResult(new SAXResult(serializer.asContentHandler())); Date timer = new Date(); reader.parse(xmlSource); Date timer2 = new Date(); outputXML = xmlOutputStream.toString("UTF-8"); if (log.isDebugEnabled()) { long diff = timer2.getTime() - timer.getTime(); log.debug("Time to transform: " + diff + " mS XSL: " + xslFile); if (log.isTraceEnabled()) { log.trace("Output XML:\n" + outputXML); } } } } catch (IOException ex) { throw new XMLTransformerException(ex); } catch (IllegalArgumentException ex) { throw new XMLTransformerException(ex); } catch (SAXException ex) { throw new XMLTransformerException(ex); } catch (TransformerConfigurationException ex) { throw new XMLTransformerException(ex); } catch (TransformerFactoryConfigurationError ex) { throw new XMLTransformerException(ex); } catch (TransformerException ex) { throw new XMLTransformerException(ex); } finally { try { if (xmlInputStream != null) { xmlInputStream.close(); xmlInputStream = null; } if (xmlOutputStream != null) { xmlOutputStream.close(); xmlOutputStream = null; } } catch (IOException ex) { } } return outputXML; }