Example usage for javax.xml.transform.stream StreamSource StreamSource

List of usage examples for javax.xml.transform.stream StreamSource StreamSource

Introduction

In this page you can find the example usage for javax.xml.transform.stream StreamSource StreamSource.

Prototype

public StreamSource(File f) 

Source Link

Document

Construct a StreamSource from a File.

Usage

From source file:edu.duke.cabig.c3pr.rules.common.adapter.CaAERSJBossXSLTRuleAdapter.java

public Package adapt(RuleSet ruleSet) throws RuleException {

    /*//from   ww  w  . jav  a  2s .  c  om
     * Add adverseEventEvaluationResult here and remove it from everywhere else since this is a
     * hidden column, it should not be used for authoring. It is used only at runtime. So it
     * make sense to add to the condition here. IMP: This is only required for caAERS project.
     */
    List<Rule> rules = ruleSet.getRule();
    for (Rule r : rules) {
        Column column_fixed = new Column();
        column_fixed.setObjectType("edu.duke.cabig.c3pr.rules.common.AdverseEventEvaluationResult");
        column_fixed.setIdentifier("adverseEventEvaluationResult");
        r.getCondition().getColumn().add(column_fixed);

    }

    List<String> imports = ruleSet.getImport();
    if (log.isDebugEnabled()) {
        log.debug("Size of imports:" + imports.size());
        for (String s : imports) {
            log.debug("each import :" + s);
        }
    }

    // marshal and transform
    String xml1 = XMLUtil.marshal(ruleSet);
    log.debug("Marshalled, Before transforming using [jboss-rules-intermediate.xsl]:\r\n" + xml1);

    XsltTransformer xsltTransformer = new XsltTransformer();
    String xml = "";

    try {
        xml = xsltTransformer.toXml(xml1, "jboss-rules-intermediate.xsl");
        log.debug("After transforming using [jboss-rules-intermediate.xsl] :\n\r" + xml);
    } catch (Exception e) {
        log.error("Exception while transforming to New Scheme: " + e.getMessage(), e);
    }

    StringWriter writer = new StringWriter();

    System.setProperty("javax.xml.transform.TransformerFactory",
            "org.apache.xalan.processor.TransformerFactoryImpl");
    TransformerFactory transformerFactory = TransformerFactory.newInstance();

    try {

        Templates translet = transformerFactory.newTemplates(new StreamSource(
                Thread.currentThread().getContextClassLoader().getResourceAsStream("new_jobss_rules.xsl")));
        Transformer transformer = translet.newTransformer();

        if (log.isDebugEnabled()) {
            log.debug("Before transforming using [new_jobss_rules.xsl] :\r\n" + xml);
            StringWriter strWriter = new StringWriter();
            transformer.transform(new StreamSource(new StringReader(xml)), new StreamResult(strWriter));
            log.debug("After transforming using [new_jboss_rules.xsl]:\r\n" + strWriter.toString());
        }

        transformer.transform(new StreamSource(new StringReader(xml)), new StreamResult(writer));

    } catch (Exception e) {
        log.error("Error while transforming using new_jboss_rules.xsl", e);
        throw new RuleException("Unable to transform using new_jboss_rules.xsl", e);
    }

    // create the rules package
    return XMLUtil.unmarshalToPackage(writer.toString());
}

From source file:com.wandrell.example.swss.test.unit.endpoint.password.plain.wss4j.TestEntityEndpointRequestPasswordPlainWss4j.java

@Override
protected final Source getRequestEnvelope() {
    try {/*w  ww  . j a  v  a 2s  .  co  m*/
        return new StreamSource(SecureSoapMessages.getPlainPasswordStream(pathValid, username, password));
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.wandrell.example.swss.test.unit.endpoint.password.digest.wss4j.TestEntityEndpointRequestPasswordDigestWss4j.java

@Override
protected final Source getRequestEnvelope() {
    try {/*w  ww .jav  a 2  s .c  o  m*/
        return new StreamSource(SecureSoapMessages.getDigestedPasswordStream(pathValid, username, password));
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.benfante.minimark.blo.AssessmentPdfBuilder.java

/**
 * Build the PDF for an assessment.// w  ww. j  av  a2s. c om
 *
 * @param assessment The assessment
 * @param baseUrl The base URL for retrieving images and resource. If null it will not be set.
 * @param locale The locale for producing the document. Id null, the default locale will be used.
 * @return The PDF document.
 */
public byte[] buildPdf(AssessmentFilling assessment, String baseUrl, Locale locale) throws Exception {
    String xmlfo = assessmentXMLFOBuilder.makeXMLFO(assessment, locale != null ? locale : Locale.getDefault());
    ByteArrayOutputStream pdfos = new ByteArrayOutputStream();
    Reader foreader = null;
    try {
        foreader = new StringReader(xmlfo);
        FOUserAgent foua = fopFactory.newFOUserAgent();
        if (baseUrl != null) {
            foua.setBaseURL(baseUrl);
        }
        Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foua, pdfos);
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer(); // identity transformer
        Source src = new StreamSource(foreader);
        Result result = new SAXResult(fop.getDefaultHandler());
        transformer.transform(src, result);
    } finally {
        if (foreader != null) {
            try {
                foreader.close();
            } catch (IOException ioe) {
            }
        }
        if (pdfos != null) {
            try {
                pdfos.close();
            } catch (IOException ioe) {
            }
        }
    }
    return pdfos.toByteArray();
}

From source file:TransformServlet.java

/**
 * Main servlet entry point//w w w.  j  ava  2  s .com
 */
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    // Initialise the output writer
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    // Get the two paramters "class" and "source".
    String transletName = request.getParameter("class");
    String documentURI = request.getParameter("source");

    try {
        if ((transletName == null) || (documentURI == null)) {
            out.println("<h1>XSL transformation error</h1>");
            out.println(
                    "The parameters <b><tt>class</tt></b> and " + "<b><tt>source</tt></b> must be specified");
        } else {
            TransformerFactory tf = TransformerFactory.newInstance();
            try {
                tf.setAttribute("use-classpath", Boolean.TRUE);
            } catch (IllegalArgumentException iae) {
                System.err.println("Could not set XSLTC-specific TransformerFactory "
                        + "attributes.  Transformation failed.");
            }
            Transformer t = tf.newTransformer(new StreamSource(transletName));

            // Start the transformation
            final long start = System.currentTimeMillis();
            t.transform(new StreamSource(documentURI), new StreamResult(out));
            final long done = System.currentTimeMillis() - start;
            out.println("<!-- transformed by XSLTC in " + done + "msecs -->");
        }
    } catch (Exception e) {
        out.println("<h1>Error</h1>");
        out.println(e.toString());
    }
}

From source file:org.ambraproject.service.XMLServiceImpl.java

/**
 * Initialization method called by Spring.
 *
 * @throws org.ambraproject.ApplicationException On Template creation Exceptions.
 *///from   w  ww .j  a va2  s.com
public void init() throws ApplicationException {
    // set JAXP properties
    System.getProperties().putAll(xmlFactoryProperty);

    // Create a document builder factory and set the defaults
    factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setValidating(false);

    // set the Templates
    final TransformerFactory tFactory = TransformerFactory.newInstance();

    try {
        translet = tFactory.newTemplates(new StreamSource(xslDefaultTemplate));
    } catch (TransformerConfigurationException tce) {
        throw new ApplicationException(tce);
    }
}

From source file:com.sazneo.export.formatter.html.HtmlFormatter.java

/**
 * Transform the data file and output to the chosen output dir
 *//*from  ww w  . j a va2s .  com*/
public void transform() {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    try {
        DocumentBuilder builder = factory.newDocumentBuilder();
        document = builder.parse(dataFile);

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        StreamSource styleSource = new StreamSource(styleSheet);
        Transformer transformer = transformerFactory.newTransformer(styleSource);

        DOMSource source = new DOMSource(document);
        StreamResult result = new StreamResult(outputStream);
        transformer.transform(source, result);

    } catch (ParserConfigurationException e) {
        logger.error(e);
    } catch (SAXException e) {
        logger.error(e);
    } catch (IOException e) {
        logger.error(e);
    } catch (TransformerConfigurationException e) {
        logger.error(e);
    } catch (TransformerException e) {
        logger.error(e);
    }
}

From source file:PayHost.Utilities.java

/**
 * Make the http post response pretty with indentation
 *
 * @param input Response//from  www . j  a  v  a 2s . c  o m
 * @param indent Indentation level
 * @return String in pretty format
 */
public static String prettyFormat(String input, int indent) {
    try {
        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.transform(xmlInput, xmlOutput);
        return xmlOutput.getWriter().toString();
    } catch (IllegalArgumentException | TransformerException e) {
        throw new RuntimeException(e); // simple exception handling, please review it
    }
}

From source file:org.wiredwidgets.cow.server.web.ProcessesController.java

/**
 * For backward compatibility.  'cow' is preferred over 'v2'.
 * Calls getCowProcess/*  w ww  . j  ava2  s.  com*/
 * @param key
 * @return 
 * @see #getCowProcess(java.lang.String) 
 */
@RequestMapping(value = "/{key}", params = "format=v2")
@ResponseBody
public StreamSource getV2Process(@PathVariable("key") String key) {
    return new StreamSource(processService.getResourceAsStream(decode(key), ProcessService.V2_EXTENSION));
}

From source file:edu.wisc.hrs.dao.roles.SoapHrsRolesDaoTest.java

@Test
public void testDataMapping() throws Exception {
    final InputStream xmlStream = this.getClass().getResourceAsStream("/hrs/roles.xml");
    assertNotNull(xmlStream);/* w w  w.j  a  v  a2s. c om*/

    final GetCompIntfcUWPORTAL1ROLESResponse response = (GetCompIntfcUWPORTAL1ROLESResponse) this.unmarshaller
            .unmarshal(new StreamSource(xmlStream));

    final Set<String> roles = client.convertRoles(response);
    verifyMappedData(roles);
}