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.idiominc.ws.opentopic.fo.i18n.PreprocessorTask.java

@Override
public void execute() throws BuildException {
    checkParameters();//from w  ww.j  a v a 2 s . c  om

    log("Processing " + input + " to " + output, Project.MSG_INFO);
    OutputStream out = null;
    try {
        final DocumentBuilder documentBuilder = XMLUtils.getDocumentBuilder();
        documentBuilder.setEntityResolver(xmlcatalog);

        final Document doc = documentBuilder.parse(input);
        final Document conf = documentBuilder.parse(config);
        final MultilanguagePreprocessor preprocessor = new MultilanguagePreprocessor(new Configuration(conf));
        final Document document = preprocessor.process(doc);

        final TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setURIResolver(xmlcatalog);
        final Transformer transformer;
        if (style != null) {
            log("Loading stylesheet " + style, Project.MSG_INFO);
            transformer = transformerFactory.newTransformer(new StreamSource(style));
        } else {
            transformer = transformerFactory.newTransformer();
        }
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        transformer.setOutputProperty(OutputKeys.INDENT, "no");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        if (doc.getDoctype() != null) {
            transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, doc.getDoctype().getPublicId());
            transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, doc.getDoctype().getSystemId());
        }

        out = new FileOutputStream(output);
        final StreamResult streamResult = new StreamResult(out);
        transformer.transform(new DOMSource(document), streamResult);
    } catch (final RuntimeException e) {
        throw e;
    } catch (final Exception e) {
        throw new BuildException(e);
    } finally {
        IOUtils.closeQuietly(out);
    }
}

From source file:com.swordlord.gozer.renderer.fop.FopFactoryHelper.java

public void transform(String strSource, Result result)
        throws TransformerConfigurationException, TransformerException {
    StringReader sr = new StringReader(strSource);
    // Setup input stream
    Source src = new StreamSource(sr);

    try {//from  w  w  w .  j  a va2s  .  c om
        // Setup JAXP using identity transformer
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer();

        transformer.setErrorListener(new FopTransformerErrorListener());

        String strEncoding = getCharset();
        transformer.setOutputProperty(OutputKeys.ENCODING, strEncoding);

        //System.setProperty("java.awt.headless", "true");
        //LOG.info("Headless mode before FOPing: " + GraphicsEnvironment.isHeadless());

        // Start XSLT transformation and FOP processing
        transformer.transform(src, result);
    } catch (TransformerConfigurationException e) {
        LOG.error(
                MessageFormat.format("FOP transformation finalisation crashed: {0}", e.getLocalizedMessage()));
        throw (e);
    } catch (TransformerException e) {
        LOG.error(
                MessageFormat.format("FOP transformation finalisation crashed: {0}", e.getLocalizedMessage()));
        throw (e);
    }
}

From source file:Main.java

/**
 *
 * @param source/*from   w ww.  jav a  2s.c o m*/
 * @param xsltSource
 * @param cls
 * @return
 * @throws TransformerConfigurationException
 * @throws JAXBException
 * @throws TransformerException
 */
public static synchronized Object deserialize(InputStream source, InputStream xsltSource, Class cls)
        throws TransformerConfigurationException, JAXBException, TransformerException {
    Object obj = null;
    JAXBContext jc = JAXBContext.newInstance(cls);

    if (xsltSource != null) {
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer;
        transformer = factory.newTransformer(new StreamSource(xsltSource));

        JAXBResult result = new JAXBResult(jc);
        transformer.transform(new StreamSource(source), result);
        obj = result.getResult();
    } else {
        obj = jc.createUnmarshaller().unmarshal(source);
    }
    return obj;
}

From source file:edu.wisc.hrs.dao.tlpayable.SoapTimeLeavePayableDaoTest.java

@Test
public void testDataMapping() throws Exception {
    final InputStream xmlStream = this.getClass().getResourceAsStream("/hrs/tlpaybl.xml");
    assertNotNull(xmlStream);/*ww  w .  j a  va 2 s  .c  om*/

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

    final List<TimeSheet> timeSheets = client.convertTimeSheets(response, Collections.<Integer, Job>emptyMap());
    verifyMappedData(timeSheets);
}

From source file:com.feedzai.fos.impl.r.RandomForestPMMLProducerConsumerTest.java

@Test
public void testUncompressed() throws Exception {
    ModelConfig modelConfig = setupConfig();
    RManager rManager = setupManager();//from w  ww.  java2 s .  c o m

    UUID uuid = rManager.trainAndAdd(modelConfig, RIntegrationTest.getTrainingInstances());

    File targetFile = Files.createTempFile("targetPMML", ".xml").toFile();

    // Save the model as PMML and load it.
    rManager.saveAsPMML(uuid, targetFile.getAbsolutePath(), false);

    try (FileInputStream fis = new FileInputStream(targetFile)) {
        JAXBUtil.unmarshalPMML(new StreamSource(fis));
    }

    targetFile.delete();
}

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

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

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

    final PersonInformation contactInformation = client.mapPerson(response);
    verifyMappedData(contactInformation);
}

From source file:edu.wisc.hrs.dao.abshis.SoapAbsenceHistoryDaoTest.java

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

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

    final List<AbsenceHistory> absenceHistories = client.convertAbsenceHistory(response,
            Collections.<Integer, Job>emptyMap());
    this.verifyMappedData(absenceHistories);
}

From source file:it.tidalwave.northernwind.core.impl.util.CachedURIResolver.java

/*******************************************************************************************************************
 *
 ******************************************************************************************************************/
@Override/*from ww  w.  ja  va2s  .co m*/
public Source resolve(final String href, final String base) throws TransformerException {
    try {
        log.info("resolve({}, {})", href, base);

        final File cacheFolder = new File(cacheFolderPath);

        if (!cacheFolder.exists()) {
            mkdirs(cacheFolder);
        }

        final File cachedFile = new File(cacheFolder, encodedUtf8(href));
        final long elapsed = System.currentTimeMillis() - cachedFile.lastModified();

        log.debug(">>>> cached file is {} elapsed time is {} msec", cachedFile, elapsed);

        if (!cachedFile.exists() || (elapsed > expirationTime)) {
            cacheDocument(cachedFile, href);
        }

        return new StreamSource(new FileInputStream(cachedFile));
    } catch (IOException e) {
        throw new TransformerException(e);
    }
}

From source file:com.dalendev.meteotndata.servlet.UpdateStationDataServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  w w  w .  ja  va 2s .c  o m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    InputStream inputStream = request.getInputStream();
    ByteArrayOutputStream byteArrayStream = new ByteArrayOutputStream();

    int length;
    byte[] buffer = new byte[1024];
    while ((length = inputStream.read(buffer)) >= 0) {
        byteArrayStream.write(buffer, 0, length);
    }

    if (byteArrayStream.size() > 0) {
        Station station = SerializationUtils.deserialize(byteArrayStream.toByteArray());
        Logger.getLogger(UpdateStationDataServlet.class.getName()).log(Level.INFO, station.getCode());

        JAXBContext jc;
        try {
            jc = JAXBContext.newInstance(MeasurementList.class);
            Unmarshaller u = jc.createUnmarshaller();
            URL url = new URL(
                    "http://dati.meteotrentino.it/service.asmx/ultimiDatiStazione?codice=" + station.getCode());
            StreamSource src = new StreamSource(url.openStream());
            JAXBElement je = u.unmarshal(src, MeasurementList.class);
            MeasurementList measurementList = (MeasurementList) je.getValue();

            MeasurmentSamplerService mss = new MeasurmentSamplerService();
            mss.mergeMeasurment(station, measurementList);
            List<Measurement> sampledList = mss.getSampledMeasurementList();
            MeasurementDAO.storeStation(sampledList);

            if (sampledList.size() > 0) {
                Measurement lastMeasurement = sampledList.get(sampledList.size() - 1);
                station.setLastUpdate(lastMeasurement.getTimestamp());
                StationDAO.storeStation(station);
            }

            Logger.getLogger(UpdateStationDataServlet.class.getName()).log(Level.INFO,
                    "Station {0} has {1} new measurements",
                    new Object[] { station.getCode(), sampledList.size() });
        } catch (JAXBException ex) {
            Logger.getLogger(UpdateStationDataServlet.class.getName()).log(Level.SEVERE, null, ex);
        }

        response.setStatus(200);
    } else {
        Logger.getLogger(UpdateStationDataServlet.class.getName()).log(Level.INFO,
                "Cannot retrieve Station's serialization");
    }
}

From source file:edu.wisc.hrs.dao.absbal.SoapAbsenceBalanceDaoTest.java

@Test
public void testDataMapping() throws Exception {
    final InputStream xmlStream = this.getClass().getResourceAsStream("/hrs/absbal.xml");
    assertNotNull(xmlStream);// w w w. ja  v  a  2  s.  co m

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

    final List<AbsenceBalance> absenceBalance = client.convertAbsenceBalance(response,
            Collections.<Integer, Job>emptyMap());

    verifyMappedData(absenceBalance);
}