/** * Returns properly configured (e.g. security features) factory * - securityProcessing == is set based on security processing property, default is true */ public static TransformerFactory createTransformerFactory(boolean disableSecureProcessing) throws IllegalStateException { try { TransformerFactory factory = TransformerFactory.newInstance(); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "TransformerFactory instance: {0}", factory); } factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, !isXMLSecurityDisabled(disableSecureProcessing)); return factory; } catch (TransformerConfigurationException ex) { LOGGER.log(Level.SEVERE, null, ex); throw new IllegalStateException( ex); } catch (AbstractMethodError er) { LOGGER.log(Level.SEVERE, null, er); throw new IllegalStateException(Messages.INVALID_JAXP_IMPLEMENTATION.format(), er); } }
public void xsltprocess(String[] args) throws TransformerException, TransformerConfigurationException, FileNotFoundException, IOException { // 1. Instantiate a TransformerFactory. SAXTransformerFactory tFactory = (SAXTransformerFactory) TransformerFactory.newInstance(); // 2. Use the TransformerFactory to process the stylesheet Source and // generate a Transformer. InputStream is = getClass().getResourceAsStream("xmg2pol.xsl"); Transformer transformer = tFactory.newTransformer (new StreamSource(is)); transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "polarities.dtd,xml"); transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8"); // 3. Use the Transformer to transform an XML Source and send the // output to a Result object. try { String input = args[0]; String output= args[1]; SAXSource saxs = new SAXSource(new InputSource(input)); XMLReader saxReader = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser"); saxReader.setEntityResolver(new MyEntityResolver()); saxs.setXMLReader(saxReader); transformer.transform(saxs, new StreamResult(new OutputStreamWriter(new FileOutputStream(output), "utf-8"))); } catch (Exception e) { e.printStackTrace(); } }
@Override protected TransformerHandler getTransformerHandler(String xslFileName) throws SAXException, ParserConfigurationException, TransformerConfigurationException, IOException { SAXTransformerFactory factory = (SAXTransformerFactory) TransformerFactory.newInstance(); factory.setURIResolver(uriResolver); TemplatesHandler templatesHandler = factory.newTemplatesHandler(); SAXParserFactory pFactory = SAXParserFactory.newInstance(); pFactory.setNamespaceAware(true); XMLReader xmlreader = pFactory.newSAXParser().getXMLReader(); // create the stylesheet input source InputSource xslSrc = new InputSource(xslFileName); xslSrc.setSystemId(filenameToURL(xslFileName)); // hook up the templates handler as the xsl content handler xmlreader.setContentHandler(templatesHandler); // call parse on the xsl input source xmlreader.parse(xslSrc); // extract the Templates object created from the xsl input source return factory.newTransformerHandler(templatesHandler.getTemplates()); }
@Override public TransformerHandler getSerializer() { try { SAXTransformerFactory transformerFactory = buildTransformerFactory(); configure(transformerFactory); TransformerHandler transformer = buildTransformer(transformerFactory); configure(transformer.getTransformer()); return transformer; } catch (TransformerConfigurationException ex) { throw new FluentXmlConfigurationException(ex); } }
private Result buildSingleTransformerPipeline(Result result) { try { SAXTransformerFactory saxTransformerFactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); TransformerHandler transformerHandler = saxTransformerFactory.newTransformerHandler(); if (result != null) { transformerHandler.setResult(result); } return new SAXResult(transformerHandler); } catch (TransformerConfigurationException ex) { throw new FluentXmlConfigurationException(ex); } }
private SAXResult toSAXResult(Result result) { if (result instanceof SAXResult) { return (SAXResult) result; } try { SAXTransformerFactory transformerFactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); TransformerHandler transformerHandler = transformerFactory.newTransformerHandler(); transformerHandler.setResult(result); return new SAXResult(transformerHandler); } catch (TransformerConfigurationException ex) { throw new FluentXmlConfigurationException(ex); } }
public SchemaToXML(Schema schema, StreamResult streamResult) { final SAXTransformerFactory stf = (SAXTransformerFactory) TransformerFactory.newInstance(); try { xmlOut = stf.newTransformerHandler(); } catch (TransformerConfigurationException error) { throw new RuntimeException("Unable to create TransformerHandler.", error); } final Transformer t = xmlOut.getTransformer(); try { t.setOutputProperty("{http://xml.apache.org/xalan}indent-amount", "2"); } catch (final IllegalArgumentException e) { // It was worth a try } t.setOutputProperty(OutputKeys.INDENT, "yes"); t.setOutputProperty(OutputKeys.ENCODING, SchemaComparator.CHAR_SET); xmlOut.setResult(streamResult); this.schema = schema; }
String colorizeXML(String xml, String xsltFilename) throws TransformerConfigurationException, TransformerException { // Get the XSLT file as a resource InputStream xslt = getClass().getResourceAsStream(xsltFilename); // Create and configure XSLT Transformer TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(new StreamSource(xslt)); transformer.setParameter("indent-elements", "yes"); OutputStream outputStream = new ByteArrayOutputStream(); InputStream inputStream = new ByteArrayInputStream(xml.getBytes()); // Convert the XML into HTML per the XSLT file transformer.transform(new StreamSource(inputStream), new StreamResult(outputStream)); return new String(((ByteArrayOutputStream)outputStream).toByteArray()); }
@Test public final void testXMLStackOverflowBug() throws TransformerConfigurationException, IOException, SAXException { try { SAXTransformerFactory stf = (SAXTransformerFactory) TransformerFactory.newInstance(); TransformerHandler ser = stf.newTransformerHandler(); ser.setResult(new StreamResult(System.out)); StringBuilder sb = new StringBuilder(4096); for (int x = 4096; x > 0; x--) { sb.append((char) x); } ser.characters(sb.toString().toCharArray(), 0, sb.toString().toCharArray().length); ser.endDocument(); } catch (StackOverflowError se) { se.printStackTrace(); Assert.fail("StackOverflow"); } }
/** * Pass warning messages from the compiler to the error listener */ private void passWarningsToListener(ArrayList<ErrorMsg> messages) throws TransformerException { if (_errorListener == null || messages == null) { return; } // Pass messages to listener, one by one final int count = messages.size(); for (int pos = 0; pos < count; pos++) { ErrorMsg msg = messages.get(pos); // Workaround for the TCK failure ErrorListener.errorTests.error001. if (msg.isWarningError()) _errorListener.error( new TransformerConfigurationException(msg.toString())); else _errorListener.warning( new TransformerConfigurationException(msg.toString())); } }
/** * Implements JAXP's Templates.newTransformer() * * @throws TransformerConfigurationException */ public synchronized Transformer newTransformer() throws TransformerConfigurationException { TransformerImpl transformer; transformer = new TransformerImpl(getTransletInstance(), _outputProperties, _indentNumber, _tfactory); if (_uriResolver != null) { transformer.setURIResolver(_uriResolver); } if (_tfactory.getFeature(XMLConstants.FEATURE_SECURE_PROCESSING)) { transformer.setSecureProcessing(true); } return transformer; }
public static String toString(SOAPMessage soapMessage, String encoding) throws TransformerConfigurationException, TransformerException, SOAPException, IOException, ParserConfigurationException, SAXException { soapMessage.saveChanges(); if (encoding == null) { // #3803 Engine.logEngine.warn("(SOAPUtils) encoding is null. Set encoding to UTF-8 for toString."); encoding = "UTF-8"; } ByteArrayOutputStream out = new ByteArrayOutputStream(); soapMessage.writeTo(out); String s = new String(out.toByteArray(), encoding); s = XMLUtils.prettyPrintDOMWithEncoding(s, encoding); // Ticket #2678: fix empty "xmlns" s = s.replaceAll("\\sxmlns=\"\"", ""); return s; }
/** * 获取一个Transformer对象,由于使用时都做相同的初始化,所以提取出来作为公共方法。 * * @return a Transformer encoding gb2312 */ public static Transformer newTransformer() { try { Transformer transformer = TransformerFactory.newInstance() .newTransformer(); Properties properties = transformer.getOutputProperties(); properties.setProperty(OutputKeys.ENCODING, "gb2312"); properties.setProperty(OutputKeys.METHOD, "xml"); properties.setProperty(OutputKeys.VERSION, "1.0"); properties.setProperty(OutputKeys.INDENT, "no"); transformer.setOutputProperties(properties); return transformer; } catch (TransformerConfigurationException tce) { throw new RuntimeException(tce.getMessage()); } }
public PomModifier(final Path projectDirectory, final Path gitDirectory) { if (builderFactory == null) { builderFactory = DocumentBuilderFactory.newInstance(); transformerFactory = TransformerFactory.newInstance(); try { builder = builderFactory.newDocumentBuilder(); transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); } catch (ParserConfigurationException | TransformerConfigurationException e) { throw new IllegalStateException(e); } } this.projectPomFile = gitDirectory.resolve("pom.xml"); this.projectDirectory = projectDirectory; this.gitDirectory = gitDirectory; }
/** * Pass warning messages from the compiler to the error listener */ private void passWarningsToListener(Vector messages) throws TransformerException { if (_errorListener == null || messages == null) { return; } // Pass messages to listener, one by one final int count = messages.size(); for (int pos = 0; pos < count; pos++) { ErrorMsg msg = (ErrorMsg)messages.elementAt(pos); // Workaround for the TCK failure ErrorListener.errorTests.error001. if (msg.isWarningError()) _errorListener.error( new TransformerConfigurationException(msg.toString())); else _errorListener.warning( new TransformerConfigurationException(msg.toString())); } }
/** * javax.xml.transform.sax.SAXTransformerFactory implementation. * Create an XMLFilter that uses the given source as the * transformation instructions. * * @param templates The source of the transformation instructions. * @return An XMLFilter object, or null if this feature is not supported. * @throws TransformerConfigurationException */ @Override public XMLFilter newXMLFilter(Templates templates) throws TransformerConfigurationException { try { return new com.sun.org.apache.xalan.internal.xsltc.trax.TrAXFilter(templates); } catch (TransformerConfigurationException e1) { if (_errorListener != null) { try { _errorListener.fatalError(e1); return null; } catch (TransformerException e2) { new TransformerConfigurationException(e2); } } throw e1; } }
/** * Create a Transformer object that copies the input document to the * result. Uses the com.sun.org.apache.xalan.internal.processor.TransformerFactory. * @return A Transformer object. */ public Transformer newTransformer() throws TransformerConfigurationException { if (_xalanFactory == null) { createXalanTransformerFactory(); } if (_errorlistener != null) { _xalanFactory.setErrorListener(_errorlistener); } if (_uriresolver != null) { _xalanFactory.setURIResolver(_uriresolver); } _currFactory = _xalanFactory; return _currFactory.newTransformer(); }
/** * javax.xml.transform.sax.TransformerFactory implementation. * Create a Transformer object that copies the input document to the result. * * @return A Transformer object that simply copies the source to the result. * @throws TransformerConfigurationException */ @Override public Transformer newTransformer() throws TransformerConfigurationException { // create CatalogFeatures that is accessible by the Transformer // through the factory instance buildCatalogFeatures(); TransformerImpl result = new TransformerImpl(new Properties(), _indentNumber, this); if (_uriResolver != null) { result.setURIResolver(_uriResolver); } if (!_isNotSecureProcessing) { result.setSecureProcessing(true); } return result; }
/** * Create a Templates object that from the input stylesheet * Uses the com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactory. * @param source the stylesheet. * @return A Templates object. */ public Templates newTemplates(Source source) throws TransformerConfigurationException { if (_xsltcFactory == null) { createXSLTCTransformerFactory(); } if (_errorlistener != null) { _xsltcFactory.setErrorListener(_errorlistener); } if (_uriresolver != null) { _xsltcFactory.setURIResolver(_uriresolver); } _currFactory = _xsltcFactory; return _currFactory.newTemplates(source); }
public TransformerHandler getRAFilter(double min, double max) throws TransformerConfigurationException, SAXException, ParserConfigurationException, IOException { double raMin = RA_MIN; // hours double raMax = RA_MAX; // hours if (min < max) { if ((min >= RA_MIN && min <= RA_MAX) && (max >= RA_MIN && max <= RA_MAX)) { raMin = min; // set value of query raMax = max; // set value of query } } else { throw new IllegalArgumentException("min must be less than max.\n" + "min=" + min + ", max=" + max); } return ffact.newRAFilter(raMin, raMax); }
public XMLFilter newXMLFilter(Templates templates) throws TransformerConfigurationException { try { return new com.sun.org.apache.xalan.internal.xsltc.trax.TrAXFilter(templates); } catch(TransformerConfigurationException e1) { if (_xsltcFactory == null) { createXSLTCTransformerFactory(); } ErrorListener errorListener = _xsltcFactory.getErrorListener(); if(errorListener != null) { try { errorListener.fatalError(e1); return null; } catch( TransformerException e2) { new TransformerConfigurationException(e2); } } throw e1; } }
public static XSLTransformer loadFromFile(File fSS, boolean bForCache) { try { Source stylesheet = new StreamSource(fSS) ; if (bForCache) { // if this processor is cached, use XALAN XSLTCompiler, instead of XALAN interpretor System.setProperty("javax.xml.transform.TransformerFactory", "org.apache.xalan.xsltc.trax.TransformerFactoryImpl") ; } Templates templ = TransformerFactory.newInstance().newTemplates(stylesheet) ; return new XSLTransformer(templ); } catch (TransformerConfigurationException e) { return null ; } }
private QrdaGenerator() throws IOException, TransformerConfigurationException { MustacheFactory mf = new DefaultMustacheFactory(); submission = mf.compile("submission-template.xml"); subpopulation = mf.compile("subpopulation-template.xml"); performanceRate = mf.compile("performance-rate-template.xml"); quality = filterQualityMeasures(); aci = filterAciMeasures(); ia = filterIaMeasures(); }
public static void main(String... args) throws IOException, TransformerConfigurationException { MustacheFactory mf = new DefaultMustacheFactory(); Mustache mdTemplate = mf.compile("error-code/error-code-tempate.md"); try (FileWriter fw = new FileWriter("./ERROR_MESSAGES.md")) { List<ErrorCode> errorCodes = Arrays.asList(ErrorCode.values()); mdTemplate.execute(fw, errorCodes).flush(); fw.flush(); } }
AnnotationParserImpl(boolean disableSecureProcessing) { try { SAXTransformerFactory factory = stf.get(); factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, disableSecureProcessing); transformer = factory.newTransformerHandler(); } catch (TransformerConfigurationException e) { throw new Error(e); // impossible } }
TransformerFactory getTransformerFactory() throws TransformerConfigurationException { if (tfactory == null) { tfactory = TransformerFactory.newInstance(); } return tfactory; }
/** * Sets the service description name. * * @param serviceDescriptionFile the service description file * @param serviceName the service name */ private void setServiceDescriptionName(File serviceDescriptionFile) { String newServiceName = this.getSymbolicBundleName() + "." + CLASS_LOAD_SERVICE_NAME; try { // --- Open the XML document ------------------ DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse(serviceDescriptionFile); // --- Get the XML root/component element ----- Node component = doc.getFirstChild(); NamedNodeMap componentAttr = component.getAttributes(); Node nameAttr = componentAttr.getNamedItem("name"); nameAttr.setTextContent(newServiceName); // --- Save document in XML file -------------- TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(serviceDescriptionFile); transformer.transform(source, result); } catch (ParserConfigurationException pcEx) { pcEx.printStackTrace(); } catch (SAXException saxEx) { saxEx.printStackTrace(); } catch (IOException ioEx) { ioEx.printStackTrace(); } catch (TransformerConfigurationException tcEx) { tcEx.printStackTrace(); } catch (TransformerException tEx) { tEx.printStackTrace(); } }
/** * @return used to perform identity transforms * @throws java.sql.SQLException when unable to obtain the instance. */ protected static Transformer getIdentityTransformer() throws SQLException { if (JDBCSQLXML.identityTransformer == null) { try { JDBCSQLXML.identityTransformer = getTransformerFactory().newTransformer(); } catch (TransformerConfigurationException ex) { throw Exceptions.transformFailed(ex); } } return JDBCSQLXML.identityTransformer; }
protected Transformer buildTransformer(ToolParams params, ProcessorConfig procConfig) { Path scriptPath = Paths.get(procConfig.getValidatorPath()); if (!scriptPath.isAbsolute()) { scriptPath = params.getProcessorConfPath().getParent().resolve(scriptPath); } if (!Files.exists(scriptPath)) { throw new IllegalArgumentException("Unable to find validation script "+scriptPath); } try { return params.getFactory().newTransformer(new StreamSource(scriptPath.toFile())) ; } catch (TransformerConfigurationException e) { throw new UpgradeConfigException(e); } }
/** * Creates a new identity transformer. * @return */ public static Transformer newTransformer() { try { return transformerFactory.get().newTransformer(); } catch (TransformerConfigurationException tex) { throw new IllegalStateException("Unable to create a JAXP transformer"); } }
/** * This method generates an instance of the translet class that is * wrapped inside this Template. The translet instance will later * be wrapped inside a Transformer object. */ private Translet getTransletInstance() throws TransformerConfigurationException { try { if (_name == null) return null; if (_class == null) defineTransletClasses(); // The translet needs to keep a reference to all its auxiliary // class to prevent the GC from collecting them AbstractTranslet translet = (AbstractTranslet) _class[_transletIndex].getConstructor().newInstance(); translet.postInitialization(); translet.setTemplates(this); translet.setServicesMechnism(_useServicesMechanism); translet.setAllowedProtocols(_accessExternalStylesheet); if (_auxClasses != null) { translet.setAuxiliaryClasses(_auxClasses); } return translet; } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) { ErrorMsg err = new ErrorMsg(ErrorMsg.TRANSLET_OBJECT_ERR, _name); throw new TransformerConfigurationException(err.toString(), e); } }
public TransformerHandler getDecFilter(double min, double max) throws TransformerConfigurationException, SAXException, ParserConfigurationException, IOException { double decMin = DEC_MIN; // degrees double decMax = DEC_MAX; // degrees if (min < max) { if ((min >= DEC_MIN && min <= DEC_MAX) && (max >= DEC_MIN && max <= DEC_MAX)) { decMin = min; // set value of query decMax = max; // set value of query } } else { throw new IllegalArgumentException("min must be less than max.\n" + "min=" + min + ", max=" + max); } return ffact.newDECFilter(decMin, decMax); }
/** * Obtains transformer's parameter with a short name that set with an integer * object before. Value should be same as the set integer object. * @throws TransformerConfigurationException If for some reason the * TransformerHandler can not be created. */ @Test public void clear04() throws TransformerConfigurationException { Transformer transformer = TransformerFactory.newInstance().newTransformer(); int intObject = 5; transformer.setParameter(SHORT_PARAM_NAME, intObject); assertEquals(transformer.getParameter(SHORT_PARAM_NAME), intObject); }
@Override public TransformerHandler newRADECFilter(double rmin, double rmax, double dmin, double dmax) throws TransformerConfigurationException, SAXException, ParserConfigurationException, IOException { TransformerHandler retval = getTransformerHandler(getRADECXsl()); Transformer xformer = retval.getTransformer(); xformer.setParameter("ra_min_hr", String.valueOf(rmin)); xformer.setParameter("ra_max_hr", String.valueOf(rmax)); xformer.setParameter("dec_min_deg", String.valueOf(dmin)); xformer.setParameter("dec_max_deg", String.valueOf(dmax)); return retval; }
@Override protected ContentHandler getContentHandler(String targetMimeType, Writer output) throws TransformerConfigurationException { if(MimetypeMap.MIMETYPE_TEXT_CSV.equals(targetMimeType)) { return new CsvContentHandler(output); } // Otherwise use the normal Tika rules return super.getContentHandler(targetMimeType, output); }
/** * javax.xml.transform.sax.SAXTransformerFactory implementation. * Get a TemplatesHandler object that can process SAX ContentHandler * events into a Templates object. * * @return A TemplatesHandler object that can handle SAX events * @throws TransformerConfigurationException */ @Override public TemplatesHandler newTemplatesHandler() throws TransformerConfigurationException { // create CatalogFeatures that is accessible by the Handler // through the factory instance buildCatalogFeatures(); final TemplatesHandlerImpl handler = new TemplatesHandlerImpl(_indentNumber, this); if (_uriResolver != null) { handler.setURIResolver(_uriResolver); } return handler; }