Example usage for javax.xml.transform Transformer setParameter

List of usage examples for javax.xml.transform Transformer setParameter

Introduction

In this page you can find the example usage for javax.xml.transform Transformer setParameter.

Prototype

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

Source Link

Document

Add a parameter for the transformation.

Usage

From source file:dk.defxws.fedoragsearch.server.GTransformer.java

public StringBuffer transform(String xsltName, Source sourceStream, URIResolver uriResolver,
        HashMap<String, String> params, boolean checkInHome) throws Exception {
    logger.fine("xsltName=" + xsltName);
    Transformer transformer = getTransformer(xsltName, uriResolver, checkInHome);
    //logger.info(params);
    Iterator it = params.keySet().iterator();
    String key = "";
    String value = "";
    while (it.hasNext()) {
        key = (String) it.next();
        value = params.get(key);//from ww w. ja v  a  2  s .c  o  m
        if (value == null) {
            value = "";
        }
        transformer.setParameter(key, value);

    }
    transformer.setParameter("DATETIME", new Date());
    StreamResult destStream = new StreamResult(new StringWriter());
    try {
        transformer.transform(sourceStream, destStream);
    } catch (TransformerException e) {
        logger.log(Level.SEVERE, "transform " + xsltName + ":\n", e);
        throw new Exception("transform " + xsltName + ":\n", e);
    }
    StringWriter sw = (StringWriter) destStream.getWriter();
    //      if (logger.isDebugEnabled())
    //      logger.debug("sw="+sw.getBuffer().toString());
    return sw.getBuffer();
}

From source file:eu.scape_project.planning.xml.ProjectExportAction.java

/**
 * Performs XSLT transformation to get the data into the plans.
 * /*from  www .  j  a  v a  2  s .co m*/
 * @param doc
 *            the plan document
 * @param out
 *            output stream to write the transformed plan XML
 * @param tempDir
 *            temporary directory where the data files are located
 * @throws TransformerException
 *             if an error occured during transformation
 */
private void addBinaryData(Document doc, OutputStream out, String tempDir) throws TransformerException {
    InputStream xsl = Thread.currentThread().getContextClassLoader()
            .getResourceAsStream("data/xslt/bytestreams.xsl");

    TransformerFactory transformerFactory = TransformerFactory.newInstance();

    Transformer transformer = transformerFactory.newTransformer(new StreamSource(xsl));
    transformer.setParameter("tempDir", tempDir);

    Source xmlSource = new DocumentSource(doc);

    Result outputTarget = new StreamResult(out); // new
                                                 // FileWriter(outFile));

    log.debug("starting bytestream transformation ...");
    transformer.transform(xmlSource, outputTarget);
    log.debug("FINISHED bytestream transformation!");
}

From source file:de.interactive_instruments.ShapeChange.Target.FeatureCatalogue.XsltWriter.java

public void xsltWrite(File transformationSource, URI xsltMainFileUri, File transformationTarget) {

    try {/* ww  w  .j  ava 2 s.  c o  m*/

        // Set up input and output files

        InputStream stream = null;

        if (xsltMainFileUri.getScheme().startsWith("http")) {
            URL url = xsltMainFileUri.toURL();
            URLConnection urlConnection = url.openConnection();
            stream = urlConnection.getInputStream();
        } else {
            File xsl = new File(xsltMainFileUri);
            // FeatureCatalogue.java already checked that file exists
            stream = new FileInputStream(xsl);
        }

        Source xsltSource = new StreamSource(stream);
        xsltSource.setSystemId(xsltMainFileUri.toString());
        Source xmlSource = new StreamSource(transformationSource);
        Result res = new StreamResult(transformationTarget);

        // create an instance of TransformerFactory
        if (xslTransformerFactory != null) {
            // use TransformerFactory specified in configuration
            System.setProperty("javax.xml.transform.TransformerFactory", xslTransformerFactory);
        } else {
            // use TransformerFactory determined by system
        }
        TransformerFactory transFact = TransformerFactory.newInstance();

        /*
         * Set URI resolver for transformation, configured with standard
         * mappings (e.g. for the localization files) and possibly other
         * mappings.
         */
        transFact.setURIResolver(new XsltUriResolver(hrefMappings));

        Transformer trans = transFact.newTransformer(xsltSource);

        /*
         * Specify any standard transformation parameters (e.g. for
         * localization).
         */
        for (String key : transformationParameters.keySet()) {
            trans.setParameter(key, transformationParameters.get(key));
        }

        /* Execute the transformation. */
        trans.transform(xmlSource, res);

    } catch (Exception e) {

        String m = e.getMessage();
        if (m != null) {
            if (result != null) {
                result.addError(m);
            } else {
                System.err.println(m);
            }
        } else {
            String msg = "Exception occurred while processing the XSL transformation.";
            if (result != null) {
                result.addError(msg);
            } else {
                System.err.println(msg);
            }
        }
    }

}

From source file:com.spoledge.audao.generator.GeneratorFlow.java

public void generateDtos() throws IOException, TransformerException {
    Transformer transformer = getTransformer(ResourceType.DTO);
    String path = dirName + "dto/";

    for (String tableName : getTableNames()) {
        if (hasDto(tableName)) {
            transformer.setParameter("table_name", tableName);
            transformer.transform(getSource(), output.addResult(file(path, tableName, "")));
        }/*www  . j  av a 2s.co  m*/
    }
}

From source file:com.spoledge.audao.generator.GeneratorFlow.java

private Transformer getTransformer(String resourceKey) {
    try {/*from w w  w . ja  v a2s. com*/
        TemplatesCache tc = generator.getTemplatesCache();
        Templates templates = tc.getTemplates(resourceKey);

        if (templates == null) {
            InputStream is = getClass().getResourceAsStream(resourceKey);
            templates = tc.getTemplates(resourceKey, new StreamSource(is, resourceKey));
        }

        Transformer ret = templates.newTransformer();
        ret.setURIResolver(generator.getResourceURIResolver()); // not auto copied from TrFactory
        ret.setErrorListener(this);
        ret.setParameter("pkg_db", pkgName);

        return ret;
    } catch (TransformerConfigurationException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.spoledge.audao.generator.GeneratorFlow.java

public void generateDtoGwtSerializers() throws IOException, TransformerException {
    Transformer transformer = getTransformer(ResourceType.DTO_GWT_SERIALIZER);
    String path = dirName + "dto/";

    for (String tableName : getTableNames()) {
        if (hasDto(tableName)) {
            transformer.setParameter("table_name", tableName);
            transformer.transform(getSource(),
                    output.addResult(file(path, tableName, "_CustomFieldSerializer")));
        }//from www.  j av  a 2 s  .  c o  m
    }
}

From source file:com.spoledge.audao.generator.GeneratorFlow.java

public void generateDaoImpls() throws IOException, TransformerException {
    Transformer transformer = getTransformer(ResourceType.DAO_IMPL);
    setDbType(transformer);// www.j  av  a 2s.  co  m

    String path = dirName + "dao/" + generator.getTarget().getIdentifier() + '/';

    for (String tableName : getTableNames()) {
        transformer.setParameter("table_name", tableName);
        transformer.transform(getSource(), output.addResult(file(path, tableName, "DaoImpl")));
    }
}

From source file:org.fcrepo.localservices.saxon.SaxonServlet.java

/**
 * Apply stylesheet to source document//w ww . j  a v a2 s. c  o  m
 */
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:it.cnr.icar.eric.server.cms.CanonicalXMLCatalogingService.java

public ServiceOutput invoke(ServerRequestContext context, ServiceInput input, ServiceType service,
        InvocationController invocationController, UserType user) throws RegistryException {
    if (log.isTraceEnabled()) {
        log.trace("CanonicalXMLCatalogingService.invoke()");
    }//w  w w .j a v a  2s .  c  o  m
    ServiceOutput so = new ServiceOutput();
    so.setOutput(context);
    RepositoryItem repositoryItem = input.getRepositoryItem();
    // The RI is optional per the [ebRS] spec. Return empty ServiceOutput.
    if (repositoryItem != null) {
        @SuppressWarnings("unused")
        String roId = input.getRegistryObject().getId();

        ServerRequestContext outputContext = null;

        try {
            outputContext = context; // new RequestContext(null);
            StreamSource inputSrc = getAsStreamSource((ExtrinsicObjectType) input.getRegistryObject());

            StreamSource invocationControlFileSrc = rm.getAsStreamSource(invocationController.getEoId());

            // dumpStream(invocationControlFileSrc);

            TransformerFactory tFactory = TransformerFactory.newInstance();
            Transformer transformer = initTransformer(tFactory, invocationControlFileSrc);
            // Use CatalogingService URIResolver to resolve RIs submitted in
            // the
            // ServiceInput object
            transformer.setURIResolver(getURIResolver(context));
            // Set respository item as parameter
            transformer.setParameter("repositoryItem", input.getRegistryObject().getId());

            // Create the output file with catalogedMetadata
            File outputFile = File.createTempFile("CanonicalXMLCatalogingService_OutputFile", ".xml");
            outputFile.deleteOnExit();

            log.debug("Tempfile= " + outputFile.getAbsolutePath());

            StreamResult sr = new StreamResult(outputFile);
            transformer.transform(inputSrc, sr);

            @SuppressWarnings("unchecked")
            JAXBElement<RegistryObjectListType> ebRegistryObjectList = (JAXBElement<RegistryObjectListType>) bu
                    .getJAXBContext().createUnmarshaller().unmarshal(outputFile);
            // take ComplexType from Element
            RegistryObjectListType catalogedMetadata = ebRegistryObjectList.getValue();

            //            RegistryObjectListType catalogedMetadata = (RegistryObjectListType) bu.getJAXBContext()
            //                  .createUnmarshaller().unmarshal(outputFile);

            // TODO: User should refer to "Service object for the
            // Content Management Service that generated the
            // Cataloged Content."
            outputContext.setUser(user);

            bu.getObjectRefsAndRegistryObjects(catalogedMetadata,
                    outputContext.getTopLevelRegistryObjectTypeMap(), outputContext.getObjectRefTypeMap());
        } catch (Exception e) {
            if (outputContext != context) {
                outputContext.rollback();
            }
            throw new RegistryException(e);
        }

        so.setOutput(outputContext);

        // Setting this error list is redundant, but Content Validation
        // Services
        // currently output a Boolean and a RegistryErrorList, so using
        // same mechanism to report errors from Content Cataloging Services.
        so.setErrorList(outputContext.getErrorList());

        if (outputContext != context) {
            outputContext.commit();
        }
    }
    return so;
}

From source file:facturas.PDF.InputHandler.java

/**
 * Transforms the input document to the input format expected by FOP using
 * XSLT.//from w  ww  .  j  av  a2  s .  c o m
 *
 * @param result
 *            the Result object where the result of the XSL transformation
 *            is sent to
 * @throws FOPException
 *             in case of an error during processing
 */
protected void transformTo(Result result) throws FOPException {
    try {
        // Setup XSLT
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer;

        if (stylesheet == null) { // FO Input
            transformer = factory.newTransformer();
        } else { // XML/XSLT input
            transformer = factory.newTransformer(new StreamSource(stylesheet));

            // 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 = new StreamSource(sourcefile);

        Source src = new StreamSource(new StringReader(_generador.createString()));

        // Start XSLT transformation and FOP processing
        transformer.transform(src, result);

    } catch (Exception e) {
        throw new FOPException(e);
    }
}