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:com.predic8.membrane.core.interceptor.schemavalidation.XMLSchemaValidator.java

@Override
protected Source getMessageBody(InputStream input) throws Exception {
    return new StreamSource(input);
}

From source file:com.edmunds.etm.common.xml.XmlValidator.java

/**
 * Validate configuration against XSD schema.
 *
 * @param configuration XML configuration as a string
 * @param schemaFile    XSD schema file name.
 * @throws XmlValidationException when validation fails
 */// w  ww .  j av  a 2 s  . c o m
public void validate(String configuration, String schemaFile) throws XmlValidationException {
    Source source = new StreamSource(new StringReader(configuration));
    validate(source, schemaFile);
}

From source file:be.fedict.eid.dss.model.bean.XmlSchemaManagerBean.java

public void add(String revision, InputStream xsdInputStream)
        throws InvalidXmlSchemaException, ExistingXmlSchemaException {
    byte[] xsd;//from w  w  w  . ja va  2s .c  om
    try {
        xsd = IOUtils.toByteArray(xsdInputStream);
    } catch (IOException e) {
        throw new RuntimeException("IO error: " + e.getMessage(), e);
    }
    ByteArrayInputStream schemaInputStream = new ByteArrayInputStream(xsd);
    SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    schemaFactory.setResourceResolver(new SignatureServiceLSResourceResolver(this.entityManager));
    StreamSource schemaSource = new StreamSource(schemaInputStream);
    try {
        schemaFactory.newSchema(schemaSource);
    } catch (SAXException e) {
        LOG.error("SAX error: " + e.getMessage(), e);
        throw new InvalidXmlSchemaException("SAX error: " + e.getMessage(), e);
    } catch (RuntimeException e) {
        LOG.error("Runtime exception: " + e.getMessage(), e);
        throw new InvalidXmlSchemaException(e.getMessage(), e);
    }

    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder documentBuilder;
    try {
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new RuntimeException("DOM error: " + e.getMessage(), e);
    }
    schemaInputStream = new ByteArrayInputStream(xsd);
    Document schemaDocument;
    try {
        schemaDocument = documentBuilder.parse(schemaInputStream);
    } catch (Exception e) {
        throw new RuntimeException("DOM error: " + e.getMessage(), e);
    }
    String namespace = schemaDocument.getDocumentElement().getAttribute("targetNamespace");
    LOG.debug("namespace: " + namespace);

    XmlSchemaEntity existingXmlSchemaEntity = this.entityManager.find(XmlSchemaEntity.class, namespace);
    if (null != existingXmlSchemaEntity) {
        throw new ExistingXmlSchemaException();
    }

    XmlSchemaEntity xmlSchemaEntity = new XmlSchemaEntity(namespace, revision, xsd);
    this.entityManager.persist(xmlSchemaEntity);
}

From source file:no.dusken.barweb.view.InvoiceView.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=faktura.pdf");

    Map<BarPerson, Integer> persons = (Map<BarPerson, Integer>) model.get("persons");
    Gjeng g = (Gjeng) model.get("gjeng");
    Invoice invoice = (Invoice) model.get("invoice");
    //Setup FOP//from w ww  .jav  a  2s  . c  o m
    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(persons, g, invoice));

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

}

From source file:io.github.kahowell.xformsvc.util.TransformUtil.java

public String transform(String transformationName, String source)
        throws TransformerConfigurationException, TransformerException, UnsupportedEncodingException {
    TransformerFactory factory = TransformerFactory.newInstance();
    factory.setURIResolver(getURIResolver());
    Transformer transformer = factory.newTransformer(lookupTransformer(transformationName));
    transformer.setOutputProperty(OutputKeys.INDENT, prettyPrint ? "yes" : "no");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    transformer.transform(new StreamSource(new ByteArrayInputStream(source.getBytes("UTF-8"))),
            new StreamResult(out));
    return out.toString("UTF-8");
}

From source file:edu.ku.brc.specify.utilapps.UIControlTOHTML.java

/**
 * @throws TransformerException//  w w  w .ja  va  2s. c  o  m
 * @throws TransformerConfigurationException
 * @throws FileNotFoundException
 * @throws IOException
 */
protected void process()
        throws TransformerException, TransformerConfigurationException, FileNotFoundException, IOException {
    boolean doUIControls = true;
    boolean doForeign = false;
    String outFileName = "UIControls.html";

    TransformerFactory tFactory = TransformerFactory.newInstance();
    if (doUIControls) {

        Transformer transformer = tFactory
                .newTransformer(new StreamSource("src/edu/ku/brc/specify/utilapps/uicontrols.xslt"));
        transformer.transform(new StreamSource("UIControls.xml"),
                new StreamResult(new FileOutputStream("UIControls.html")));

    } else {
        String xsltFileName = doForeign ? foreignXSLT : englishXSLT;

        outFileName = doForeign ? foreignOUT : englishOUT;

        String filePath = "src/edu/ku/brc/specify/utilapps/" + xsltFileName;
        File transFile = new File(filePath);
        if (!transFile.exists()) {
            System.err.println("File path[" + filePath + "] doesn't exist!");
            System.exit(1);
        }
        System.out.println(filePath);

        Transformer transformer = tFactory.newTransformer(new StreamSource(filePath));
        try {
            // Need to read it in as a string because of the embedded German characters
            String xmlStr = FileUtils.readFileToString(new File("config/specify_datamodel.xml"));
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = factory.newDocumentBuilder();
            InputSource inStream = new InputSource();
            inStream.setCharacterStream(new StringReader(xmlStr));
            Document doc1 = db.parse(inStream);

            transformer.transform(new DOMSource(doc1), new StreamResult(new FileOutputStream(outFileName)));

        } catch (Exception ex) {
            edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
            edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(UIControlTOHTML.class, ex);
            ex.printStackTrace();
        }
    }
    System.out.println("** The output file[" + outFileName + "] is written.");

}

From source file:com.thoughtworks.go.domain.UnitTestReportGenerator.java

public Properties generate(File[] allTestFiles, String uploadDestPath) {
    FileOutputStream transformedHtml = null;
    File mergedResults = new File(
            folderToUpload.getAbsolutePath() + FileUtil.fileseparator() + TEST_RESULTS_FILE);
    File mergedResource = null;// www.  ja  v a 2s .co m
    FileInputStream mergedFileStream = null;
    try {
        mergedResource = mergeAllTestResultToSingleFile(allTestFiles);
        transformedHtml = new FileOutputStream(mergedResults);

        try {
            mergedFileStream = new FileInputStream(mergedResource);
            Source xmlSource = new StreamSource(mergedFileStream);
            StreamResult result = new StreamResult(transformedHtml);
            templates.newTransformer().transform(xmlSource, result);
        } catch (Exception e) {
            publisher.reportErrorMessage("Unable to publish test properties. Error was " + e.getMessage(), e);
        }

        extractProperties(mergedResults);
        publisher.upload(mergedResults, uploadDestPath);

        return null;
    } catch (Exception e) {
        publisher.reportErrorMessage("Unable to publish test properties. Error was " + e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(mergedFileStream);
        IOUtils.closeQuietly(transformedHtml);
        if (mergedResource != null) {
            mergedResource.delete();
        }
    }
    return new Properties();
}

From source file:com.stratumsoft.xmlgen.SchemaUtilTest.java

@Test
public void testGetNamesFromSchemaWithImport() throws Exception {
    final InputStream is = getClass().getResourceAsStream(elementFormXsd);
    assertNotNull(is);//from   ww w. j  av a  2  s  .com

    final StreamSource source = new StreamSource(is);
    final XmlSchemaCollection schemaColl = new XmlSchemaCollection();
    final URL baseUrl = SchemaUtilTest.class.getResource(elementFormXsd);
    final String baseUri = baseUrl.toURI().toString();

    schemaColl.setBaseUri(baseUri);

    final XmlSchema schema = schemaColl.read(source);
    assertNotNull(schema);

    System.out.println("There are " + schemaColl.getXmlSchemas().length + " schemas present");

    final Collection<QName> elements = SchemaUtil.getElements(schema);
    assertNotNull(elements);
    assertFalse(elements.isEmpty());

    System.out.println("Got the following elements from schema:");
    CollectionUtils.forAllDo(elements, new Closure() {
        @Override
        public void execute(Object input) {
            System.out.println(input);
        }
    });

}

From source file:com.elsevier.xml.XPathProcessor.java

/**
 * Apply the xpathExpression to the specified string and return a serialized
 * response./*from  w  w  w .  j  a v  a2  s .c  om*/
 * 
 * @param content
 *            String to which the xpathExpression will be applied
 * @param xpathExpression
 *            XPath expression to apply to the content
 * @return Serialized response from the evaluation.  If an error, the response will be "<error/>".
 */
public static String evaluateString(String content, String xpathExpression) {

    try {

        return evaluate(new StreamSource(IOUtils.toInputStream(content, CharEncoding.UTF_8)), xpathExpression);

    } catch (IOException e) {

        log.error("Problems processing the content.  " + e.getMessage(), e);
        return "<error/>";

    }

}

From source file:Main.java

/**
 *
 * @param source//  www . j  a v a2  s.  c om
 * @param xsltSource
 * @return
 * @throws TransformerConfigurationException
 * @throws JAXBException
 * @throws TransformerException
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 */
public static synchronized Document deserializeToDom(InputStream source, InputStream xsltSource)
        throws TransformerConfigurationException, JAXBException, TransformerException,
        ParserConfigurationException, SAXException, IOException {
    Document obj;
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    if (xsltSource != null) {
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer(new StreamSource(xsltSource));
        obj = dbf.newDocumentBuilder().newDocument();
        Result result = new DOMResult(obj);
        transformer.transform(new StreamSource(source), result);
    } else {
        obj = dbf.newDocumentBuilder().parse(source);

    }
    return obj;
}