Example usage for javax.xml.transform TransformerFactory setAttribute

List of usage examples for javax.xml.transform TransformerFactory setAttribute

Introduction

In this page you can find the example usage for javax.xml.transform TransformerFactory setAttribute.

Prototype

public abstract void setAttribute(String name, Object value);

Source Link

Document

Allows the user to set specific attributes on the underlying implementation.

Usage

From source file:org.toobsframework.transformpipeline.domain.ChainedXSLTransletTransformer.java

public String transform(List inputXSLs, String inputXML, Map inputParams,
        IXMLTransformerHelper transformerHelper) throws XMLTransformerException {

    String outputXML = null;//  ww w. ja v  a  2s. co m
    ByteArrayInputStream xmlInputStream = null;
    ByteArrayOutputStream xmlOutputStream = null;
    try {
        TransformerFactory tFactory = new org.apache.xalan.xsltc.trax.TransformerFactoryImpl();
        try {
            //tFactory.setAttribute("use-classpath", Boolean.TRUE);
            tFactory.setAttribute("auto-translet", Boolean.TRUE);
        } catch (IllegalArgumentException iae) {
            log.error("Error setting XSLTC specific attribute", iae);
            throw new XMLTransformerException(iae);
        }
        setFactoryResolver(tFactory);

        TransformerFactoryImpl traxFactory = (TransformerFactoryImpl) tFactory;

        // Create a TransformerHandler for each stylesheet.
        ArrayList tHandlers = new ArrayList();
        TransformerHandler tHandler = null;

        // Create a SAX XMLReader.
        XMLReader reader = new org.apache.xerces.parsers.SAXParser();

        // transformer3 outputs SAX events to the serializer.
        if (outputProperties == null) {
            outputProperties = OutputPropertiesFactory.getDefaultMethodProperties("html");
        }
        Serializer serializer = SerializerFactory.getSerializer(outputProperties);
        for (int it = 0; it < inputXSLs.size(); it++) {
            String xslTranslet = (String) inputXSLs.get(it);
            Source source = uriResolver.resolve(xslTranslet + ".xsl", "");

            String tPkg = source.getSystemId().substring(0, source.getSystemId().lastIndexOf("/"))
                    .replaceAll("/", ".").replaceAll("-", "_");

            // Package name needs to be set for each TransformerHandler instance
            tFactory.setAttribute("package-name", tPkg);
            tHandler = traxFactory.newTransformerHandler(source);

            // Set parameters and output encoding on each handlers transformer
            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;
        // Link the handlers to each other and to the reader
        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"));
        xmlSource = new InputSource(xmlInputStream);
        xmlOutputStream = new ByteArrayOutputStream();
        serializer.setOutputStream(xmlOutputStream);
        // Link the last handler to the serializer
        ((TransformerHandler) tHandlers.get(tHandlers.size() - 1))
                .setResult(new SAXResult(serializer.asContentHandler()));
        reader.parse(xmlSource);
        outputXML = xmlOutputStream.toString("UTF-8");
    } catch (Exception ex) {
        log.error("Error performing chained transformation: " + ex.getMessage(), 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;
}

From source file:org.toobsframework.transformpipeline.domain.TransletTransformer.java

@SuppressWarnings("unchecked")
protected void doTransform(String xslTranslet, StreamSource xmlSource, Map params,
        IXMLTransformerHelper transformerHelper, StreamResult xmlResult) throws XMLTransformerException {

    try {/* w  w  w  .  j a v a 2  s. co  m*/
        // Dont rely on the system property to get the right transformer
        TransformerFactory tFactory = new org.apache.xalan.xsltc.trax.TransformerFactoryImpl();
        // set the URI Resolver for the transformer factory      
        setFactoryResolver(tFactory);

        Source source = uriResolver.resolve(xslTranslet + ".xsl", "");

        String tPkg = source.getSystemId().substring(0, source.getSystemId().lastIndexOf("/"))
                .replaceAll("/", ".").replaceAll("-", "_");

        try {
            //tFactory.setAttribute("use-classpath", Boolean.TRUE);
            tFactory.setAttribute("auto-translet", Boolean.TRUE);
            tFactory.setAttribute("package-name", tPkg);
        } catch (IllegalArgumentException iae) {
            log.error("Error setting XSLTC specific attribute", iae);
            throw new XMLTransformerException(iae);
        }

        Transformer transformer = tFactory.newTransformer(source);

        // 2.2 Set character encoding for all transforms to UTF-8.
        transformer.setOutputProperty("encoding", "UTF-8");
        transformer.setErrorListener(tFactory.getErrorListener());

        // 2.5 Set Parameters necessary for transformation.
        if (params != null) {
            Iterator paramIt = params.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);
        }

        // 3. Use the Transformer to transform an XML Source and send the
        //    output to a Result object.
        transformer.transform(xmlSource, xmlResult);
    } catch (TransformerConfigurationException tce) {
        log.error(tce.toString(), tce);
        throw new XMLTransformerException(tce);
    } catch (TransformerException te) {
        log.error(te.toString(), te);
        throw new XMLTransformerException(te);
    }

}

From source file:org.usergrid.tools.ApiDoc.java

public void output(ApiListing listing, String section) throws IOException, TransformerException {
    Document doc = listing.createWADLApplication();

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    transformerFactory.setAttribute("indent-number", 4);
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(new File(section + ".wadl"));
    transformer.transform(source, result);

    File file = new File(section + ".json");
    listing.setBasePath("${basePath}");
    FileUtils.write(file, JsonUtils.mapToFormattedJsonString(listing));

}

From source file:org.zaproxy.zap.extension.saml.SAMLMessage.java

/**
 * Get the saml message as a formatted XML
 *
 * @return/*from w ww  .  j  a  va2 s.  c o m*/
 */
public String getSamlMessageString() {
    try {
        Source xmlInput;
        xmlInput = new StreamSource(new StringReader(samlMessageString));

        StringWriter stringWriter = new StringWriter();
        StreamResult xmlOutput = new StreamResult(stringWriter);
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setAttribute("indent-number", 4);
        Transformer transformer = transformerFactory.newTransformer();

        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.transform(xmlInput, xmlOutput);
        return xmlOutput.getWriter().toString();
    } catch (Exception e) {
        log.warn("error in parsing saml message.", e);
        return samlMessageString;
    }
}

From source file:telecom.sudparis.eu.paas.client.APIClient.java

private static String prettyFormat(String input, int indent) {
    try {// w w  w  . j a va  2s  .  com
        Source xmlInput = new StreamSource(new StringReader(input));
        StringWriter stringWriter = new StringWriter();
        StreamResult xmlOutput = new StreamResult(stringWriter);
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setAttribute("indent-number", indent);
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");
        transformer.transform(xmlInput, xmlOutput);
        return xmlOutput.getWriter().toString();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}