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.wfu.inotado.helper.MarshalHelper.java

@SuppressWarnings("unchecked")
public <T> T unmarshal(String xml) {
    T obj = null;/*from w  ww  . j av  a  2s.  c o m*/
    Source source = null;
    if (StringUtils.isNotEmpty(xml)) {
        source = new StreamSource(new StringReader(xml));
        try {
            obj = (T) this.marshaller.unmarshal(source);
        } catch (UnmarshallingFailureException e) {
            log.warn("Unable to unmarshal the xml: " + xml);
        }
    }
    return obj;
}

From source file:edu.wisc.hrs.dao.person.SoapContactInfoDaoTest.java

@Test
@Override/*from   ww w  . ja v  a  2s  .c o  m*/
public void testGetPersonInformation() throws Exception {
    final WebServiceMessage webServiceMessage = setupWebServiceMessageSender();

    when(webServiceMessage.getPayloadSource())
            .thenReturn(new StreamSource(this.getClass().getResourceAsStream("/hrs/person.xml")));

    super.testGetPersonInformation();
}

From source file:no.dusken.barweb.view.XListView.java

protected void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    response.setContentType("application/pdf");
    response.setCharacterEncoding("UTF-8");
    response.setHeader("Content-Disposition", "attachment; filename=xlist.pdf");

    List<BarPerson> barPersons = (List<BarPerson>) model.get("barPersons");
    Gjeng g = (Gjeng) model.get("gjeng");
    List<Vare> varer = (List<Vare>) model.get("varer");
    Integer lowlimit = (Integer) model.get("lowLimit");
    Boolean panger = (Boolean) model.get("panger");
    //Setup FOP/*from w w  w  . j a va2s  .  com*/
    Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, response.getOutputStream());

    //Setup Transformer
    Source xsltSrc = new StreamSource(
            this.getClass().getResourceAsStream("/no/dusken/barweb/stylesheets/" + styleSheet));
    Transformer transformer = tFactory.newTransformer(xsltSrc);

    //Make sure the XSL transformation's result is piped through to FOP
    Result res = new SAXResult(fop.getDefaultHandler());

    //Setup input
    DOMSource src = new DOMSource(generateXml(barPersons, g, varer, lowlimit, panger));

    //Start the transformation and rendering process
    transformer.transform(src, res);
    response.getOutputStream().flush();

}

From source file:edu.wisc.hrs.dao.url.SoapHrsUrlDaoTest.java

@Test
public void testDataMapping() throws Exception {
    final InputStream xmlStream = this.getClass().getResourceAsStream("/hrs/url.xml");
    assertNotNull(xmlStream);//from  w w w  .j  a  v a 2s  . c o m

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

    final Map<String, String> urlMap = client.convertUrlMap(response);
    verifyMappedData(urlMap);
}

From source file:com.seajas.search.attender.validator.TemplateValidator.java

/**
 * Validate the given command object./*  w w  w .j  av a  2  s.com*/
 * 
 * @param command
 * @param errors
 */
@Override
public void validate(final Object command, final Errors errors) {
    TemplateCommand template = (TemplateCommand) command;

    if (template.getAction().equals("edit")) {
        if (StringUtils.isEmpty(template.getLanguage()))
            errors.rejectValue("language", "templates.error.language.empty");
        else if (!attenderService.getAvailableSearchLanguages().contains(template.getLanguage()))
            errors.rejectValue("language", "templates.error.language.invalid");

        // Now validate the content

        if (StringUtils.isEmpty(template.getResultsHtmlContent()))
            errors.rejectValue("resultsHtmlContent", "templates.error.results.html.content.empty");
        else {
            StreamSource source = new StreamSource(new StringReader(template.getResultsHtmlContent()));

            try {
                TransformerFactory.newInstance().newTransformer(source);
            } catch (Exception e) {
                errors.rejectValue("resultsHtmlContent", "templates.error.results.html.content.invalid");
            }
        }

        if (StringUtils.isEmpty(template.getResultsTextContent()))
            errors.rejectValue("resultsTextContent", "templates.error.results.text.content.empty");
        else {
            StreamSource source = new StreamSource(new StringReader(template.getResultsTextContent()));

            try {
                TransformerFactory.newInstance().newTransformer(source);
            } catch (Exception e) {
                errors.rejectValue("resultsTextContent", "templates.error.results.text.content.invalid");
            }
        }

        if (StringUtils.isEmpty(template.getConfirmationHtmlContent()))
            errors.rejectValue("confirmationHtmlContent", "templates.error.confirmation.html.content.empty");
        else {
            StreamSource source = new StreamSource(new StringReader(template.getConfirmationHtmlContent()));

            try {
                TransformerFactory.newInstance().newTransformer(source);
            } catch (Exception e) {
                errors.rejectValue("confirmationHtmlContent",
                        "templates.error.confirmation.html.content.invalid");
            }
        }

        if (StringUtils.isEmpty(template.getConfirmationTextContent()))
            errors.rejectValue("confirmationTextContent", "templates.error.confirmation.text.content.empty");
        else {
            StreamSource source = new StreamSource(new StringReader(template.getConfirmationTextContent()));

            try {
                TransformerFactory.newInstance().newTransformer(source);
            } catch (Exception e) {
                errors.rejectValue("confirmationTextContent",
                        "templates.error.confirmation.text.content.invalid");
            }
        }
    }
}

From source file:Main.java

public static String applyXSLT(Source xml, URL xsltFilename, Map params) {
    try {/*from   w  w w  .  j  a  v a  2s.  c  om*/
        TransformerFactory f = TransformerFactory.newInstance();
        StreamSource xsltSrc = new StreamSource(xsltFilename.openConnection().getInputStream());
        StringWriter out = new StringWriter();
        StreamResult res = new StreamResult(out);
        Transformer t = f.newTransformer(xsltSrc);

        if (params != null) {
            Iterator i = params.keySet().iterator();
            while (i.hasNext()) {
                Object obj = i.next();
                t.setParameter(obj.toString(), params.get(obj));
            }
        }
        t.transform(xml, res);

        return out.toString();
    } catch (Exception e) {
        return null;
    }
}

From source file:com.healthcit.cacure.export.ExportToExcel.java

@Test
public void export() throws JAXBException, TransformerException {
    JAXBContext jc = JAXBContext.newInstance("com.healthcit.cacure.export.model");
    File iFile = new File("C:\\temp\\moduleTest1.xml");
    //File iFile = new File("C:\\temp\\formExportTest.xml");
    //File iFile = new File("C:\\temp\\section1.1.xml");
    //File iFile = new File("C:\\temp\\complexSkip2.xml");
    //File iFile = new File("C:\\temp\\section3.1.xml");
    File oFile = new File("C:\\temp\\Book2.xml");
    Unmarshaller m = jc.createUnmarshaller();
    Cure xml = (Cure) m.unmarshal(iFile);
    StreamSource xslSource = new StreamSource("src//main//resources//xls.xsl");
    //long formId = 9979;

    //Cure xml = dataExporter.constructFormXML(formId);
    JAXBSource xmlSource = new JAXBSource(jc, xml);
    Transformer transformer = TransformerFactory.newInstance().newTransformer(xslSource);
    transformer.transform(xmlSource, new StreamResult(oFile));
}

From source file:org.jenkins.tools.test.model.MavenPom.java

public void transformPom(MavenCoordinates coreCoordinates) throws PomTransformationException {
    File pom = new File(rootDir.getAbsolutePath() + "/" + pomFileName);
    File backupedPom = new File(rootDir.getAbsolutePath() + "/" + pomFileName + ".backup");
    try {//from ww  w  .  j  av a2  s  .co  m
        FileUtils.rename(pom, backupedPom);

        Source xmlSource = new StreamSource(backupedPom);
        // TODO switch to DOM4J for simplicity and consistency
        Source xsltSource = new StreamSource(new ClassPathResource("mavenParentReplacer.xsl").getInputStream());
        Result result = new StreamResult(pom);

        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer(xsltSource);
        transformer.setParameter("parentArtifactId", coreCoordinates.artifactId);
        transformer.setParameter("parentGroupId", coreCoordinates.groupId);
        transformer.setParameter("parentVersion", coreCoordinates.version);
        transformer.transform(xmlSource, result);
    } catch (Exception e) {
        throw new PomTransformationException("Error while transforming pom : " + pom.getAbsolutePath(), e);
    }

}

From source file:com.amalto.core.schema.validation.XmlSchemaValidator.java

private javax.xml.validation.Validator getValidator() {
    javax.xml.validation.Validator validator;
    synchronized (schemaCache) {
        try {/*from w w w  .  j  av  a  2 s.co  m*/
            validator = (javax.xml.validation.Validator) validatorCache.get(dataModelName,
                    Thread.currentThread());
            if (validator != null) {
                return validator;
            }
            Schema parsedSchema = schemaCache.get(dataModelName);
            if (parsedSchema == null) {
                parsedSchema = schemaFactory.newSchema(new StreamSource(schemaAsStream));
                schemaCache.put(dataModelName, parsedSchema);
            }
            validator = parsedSchema.newValidator();
            validatorCache.put(dataModelName, Thread.currentThread(), validator);
        } catch (SAXException e) {
            throw new RuntimeException("Exception occurred during XML schema parsing.", e);
        }
    }
    return validator;
}

From source file:org.dataminx.dts.ws.jms.DtsWsMessageConverter.java

/**
 * Extracts the given JMS Message payload and returns it as an object.
 *
 * @param message the incoming JMS message
 * @return the message payload as an {@link Object}
 * @throws JMSException if the incoming message is not of a supported
 *         message type//from   ww w .j  av a 2s.c  om
 */
private Object extractMessagePayload(final Message message) throws JMSException {
    final Object payload;
    if (message instanceof TextMessage) {
        final TextMessage textMessage = (TextMessage) message;
        payload = textMessage.getText();
    } else if (message instanceof ObjectMessage) {
        final ObjectMessage objectMessage = (ObjectMessage) message;
        payload = objectMessage.getObject();
    } else if (message instanceof BytesMessage) {
        final BytesMessage bytesMessage = (BytesMessage) message;
        final byte[] bytes = new byte[(int) bytesMessage.getBodyLength()];
        bytesMessage.readBytes(bytes);
        final ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
        payload = new StreamSource(bis);
    } else {
        throw new MessageConversionException("Invalid message type...");
    }
    return payload;
}