Search in sources :

Example 56 with Result

use of javax.xml.transform.Result in project ACS by ACS-Community.

the class ScriptFilter method writeStatusFile.

private void writeStatusFile(String filename) throws ParserConfigurationException, TransformerException, FileNotFoundException {
    status = new ArrayList<SerializableProperty>();
    samplingGroups = new HashSet<String>();
    // Nuevo XML
    // BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
    String root = "SamplingStatus";
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document document = documentBuilder.newDocument();
    Element rootElement = document.createElement(root);
    rootElement.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
    rootElement.setAttribute("xsi:noNamespaceSchemaLocation", "status.xsd");
    document.appendChild(rootElement);
    int i = 0;
    for (BeanGrouper bg : BeanGrouperList) {
        for (SerializableProperty sp : bg.getSerializableProperty()) {
            status.add(i, sp);
            samplingGroups.add(sp.getSamplingGroup());
            i++;
        }
    }
    int index = 0;
    for (int l = 0; l < samplingGroups.size(); l++) {
        for (i = 0; i < status.size(); i++) {
            if (samplingGroups.toArray(new String[0])[l] == status.get(i).getSamplingGroup()) {
                index = i;
                break;
            }
        }
        String groupName = "SamplingGroup";
        Element groupElement = document.createElement(groupName);
        rootElement.appendChild(groupElement);
        String name = "SamplingGroupName";
        String name_data = status.get(index).getSamplingGroup();
        Element name_element = document.createElement(name);
        name_element.appendChild(document.createTextNode(name_data));
        groupElement.appendChild(name_element);
        String manName = "SamplingManagerName";
        String manName_data = MAN_NAME;
        Element manName_element = document.createElement(manName);
        manName_element.appendChild(document.createTextNode(manName_data));
        groupElement.appendChild(manName_element);
        String freq = "Frequency";
        String freq_data = Double.toString(status.get(index).getFrequency());
        Element freq_element = document.createElement(freq);
        freq_element.appendChild(document.createTextNode(freq_data));
        groupElement.appendChild(freq_element);
        String st = "SamplingTime";
        String st_data = Integer.toString(status.get(index).getSamplingTime());
        Element st_element = document.createElement(st);
        st_element.appendChild(document.createTextNode(st_data));
        groupElement.appendChild(st_element);
        String tw = "TimeWindow";
        String tw_data = Integer.toString(status.get(index).getTimeWindow());
        Element tw_element = document.createElement(tw);
        tw_element.appendChild(document.createTextNode(tw_data));
        groupElement.appendChild(tw_element);
        for (i = 0; i < status.size(); i++) {
            if (samplingGroups.toArray(new String[0])[l] == status.get(i).getSamplingGroup()) {
                /* Properties */
                String propertiesName = "Sample";
                Element propertiesElement = document.createElement(propertiesName);
                groupElement.appendChild(propertiesElement);
                String comp = "component";
                String comp_data = status.get(i).getComponent();
                Element comp_element = document.createElement(comp);
                comp_element.appendChild(document.createTextNode(comp_data));
                propertiesElement.appendChild(comp_element);
                String prop = "property";
                String prop_data = status.get(i).getProperty();
                Element prop_element = document.createElement(prop);
                prop_element.appendChild(document.createTextNode(prop_data));
                propertiesElement.appendChild(prop_element);
            }
        }
    }
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    if (status.size() == 0)
        return;
    File file = new File(filename);
    if (file.exists())
        file.delete();
    DOMSource source = new DOMSource(document);
    Result result = new StreamResult(new FileOutputStream(filename));
    transformer.transform(source, result);
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) Element(org.w3c.dom.Element) Document(org.w3c.dom.Document) StreamResult(javax.xml.transform.stream.StreamResult) Result(javax.xml.transform.Result) DocumentBuilder(javax.xml.parsers.DocumentBuilder) FileOutputStream(java.io.FileOutputStream) File(java.io.File)

Example 57 with Result

use of javax.xml.transform.Result in project OpenClinica by OpenClinica.

the class PdfProcessingFunction method run.

/*
     * The run() method.  Note that we will assume that all variables (i.e. file
     * paths) are set here.
     * 
     * Running this will open a file stream, perform a transform with the *.fo 
     * file (note, does not necessarily have to have a *.fo suffix) and then 
     * return a success/fail message.
     * (non-Javadoc)
     * @see org.akaza.openclinica.bean.service.ProcessingInterface#run()
     */
public ProcessingResultType run() {
    // FopFactory fopFactory = FopFactory.newInstance(); 
    FopFactory fopFactory = FopFactory.newInstance();
    //   FopFactory fopFactory = FopFactory.newInstance(new File(".").toURI());
    OutputStream out = null;
    File outputFile = null;
    String zipName = "_";
    File xslFile = null;
    try {
        FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
        //set the renderer to be PDF
        // the expected sequence here will be xml -> xslt -> fo -> pdf
        // where fo is the transformed file
        File procExportDirectory;
        File[] oldFiles = null;
        if (this.getExportFileName() != null && this.getLocation() != null) {
            procExportDirectory = new File(this.getLocation());
            if (!procExportDirectory.isDirectory()) {
                procExportDirectory.mkdir();
            }
            outputFile = new File(procExportDirectory + File.separator + this.getExportFileName() + ".pdf");
            zipName = (procExportDirectory + File.separator + this.getExportFileName() + ".zip");
        } else {
            //getODMFILENAme is a path of .fo object
            outputFile = new File(this.getODMXMLFileName() + ".pdf");
            zipName = this.getODMXMLFileName() + ".zip";
        }
        //transformfilename is abs path+file name(.fo) transformFileName and odmxmlfile name are same?
        xslFile = new File(this.getTransformFileName());
        out = new FileOutputStream(outputFile);
        out = new BufferedOutputStream(out);
        Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out);
        TransformerFactory factory = TransformerFactory.newInstance();
        // identity transformer
        Transformer transformer = factory.newTransformer();
        Source src = new StreamSource(xslFile);
        // Resulting SAX events (the generated FO) must be piped through to FOP
        Result res = new SAXResult(fop.getDefaultHandler());
        // Start XSLT transformation and FOP processing
        transformer.transform(src, res);
        // Result processing
        FormattingResults foResults = fop.getResults();
        java.util.List pageSequences = foResults.getPageSequences();
        for (java.util.Iterator it = pageSequences.iterator(); it.hasNext(); ) {
            PageSequenceResults pageSequenceResults = (PageSequenceResults) it.next();
            logger.debug("PageSequence " + (String.valueOf(pageSequenceResults.getID()).length() > 0 ? pageSequenceResults.getID() : "<no id>") + " generated " + pageSequenceResults.getPageCount() + " pages.");
        }
        logger.debug("Generated " + foResults.getPageCount() + " pages in total.");
        out.close();
        if (isZip()) {
            if (outputFile != null) {
                ZipOutputStream zipOut = null;
                FileInputStream fis = null;
                try {
                    fis = new FileInputStream(outputFile);
                    zipOut = new ZipOutputStream(new FileOutputStream(new File(zipName)));
                    zipOut.putNextEntry(new ZipEntry(outputFile.getName()));
                    int bytesRead;
                    byte[] buff = new byte[512];
                    while ((bytesRead = fis.read(buff)) != -1) {
                        zipOut.write(buff, 0, bytesRead);
                    }
                    zipOut.closeEntry();
                    zipOut.finish();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (zipOut != null)
                        zipOut.close();
                    if (fis != null)
                        fis.close();
                }
            }
            setArchivedFileName(new File(zipName).getName());
        } else
            setArchivedFileName(outputFile.getName());
    } catch (Exception e) {
        e.printStackTrace();
        ProcessingResultType resultError = ProcessingResultType.FAIL;
        // view datasets page
        resultError.setUrl(CoreResources.getField("sysURL.base") + "ViewDatasets");
        resultError.setArchiveMessage("Failure thrown: " + e.getMessage());
        resultError.setDescription("Your job failed with the message of: " + e.getMessage());
        return resultError;
    } finally {
    }
    if (isDeleteOld()) {
        deleteOldFiles(this.getOldFiles(), outputFile, zipName);
    }
    if (isZip()) {
        outputFile.delete();
    }
    //delete intermediatory .fo file
    if (xslFile != null)
        xslFile.delete();
    // otherwise return a success with the URL link
    ProcessingResultType resultSuccess = ProcessingResultType.SUCCESS;
    resultSuccess.setUrl(CoreResources.getField("sysURL.base") + // to the pdf
    "AccessFile?fileId=");
    resultSuccess.setArchiveMessage("Success");
    resultSuccess.setDescription("Your job succeeded please find the URL below");
    return resultSuccess;
}
Also used : Transformer(javax.xml.transform.Transformer) FOUserAgent(org.apache.fop.apps.FOUserAgent) ZipOutputStream(java.util.zip.ZipOutputStream) BufferedOutputStream(java.io.BufferedOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) ZipEntry(java.util.zip.ZipEntry) PageSequenceResults(org.apache.fop.apps.PageSequenceResults) FopFactory(org.apache.fop.apps.FopFactory) StreamSource(javax.xml.transform.stream.StreamSource) Source(javax.xml.transform.Source) Result(javax.xml.transform.Result) SAXResult(javax.xml.transform.sax.SAXResult) BufferedOutputStream(java.io.BufferedOutputStream) TransformerFactory(javax.xml.transform.TransformerFactory) Fop(org.apache.fop.apps.Fop) StreamSource(javax.xml.transform.stream.StreamSource) FormattingResults(org.apache.fop.apps.FormattingResults) FileInputStream(java.io.FileInputStream) FOPException(org.apache.fop.apps.FOPException) SAXResult(javax.xml.transform.sax.SAXResult) ZipOutputStream(java.util.zip.ZipOutputStream) FileOutputStream(java.io.FileOutputStream) File(java.io.File)

Example 58 with Result

use of javax.xml.transform.Result in project camel by apache.

the class XsltBuilder method process.

public void process(Exchange exchange) throws Exception {
    notNull(getTemplate(), "template");
    if (isDeleteOutputFile()) {
        // add on completion so we can delete the file when the Exchange is done
        String fileName = ExchangeHelper.getMandatoryHeader(exchange, Exchange.XSLT_FILE_NAME, String.class);
        exchange.addOnCompletion(new XsltBuilderOnCompletion(fileName));
    }
    Transformer transformer = getTransformer();
    configureTransformer(transformer, exchange);
    ResultHandler resultHandler = resultHandlerFactory.createResult(exchange);
    Result result = resultHandler.getResult();
    // let's copy the headers before we invoke the transform in case they modify them
    Message out = exchange.getOut();
    out.copyFrom(exchange.getIn());
    // the underlying input stream, which we need to close to avoid locking files or other resources
    InputStream is = null;
    try {
        Source source;
        // only convert to input stream if really needed
        if (isInputStreamNeeded(exchange)) {
            is = exchange.getIn().getBody(InputStream.class);
            source = getSource(exchange, is);
        } else {
            Object body = exchange.getIn().getBody();
            source = getSource(exchange, body);
        }
        if (source instanceof StAXSource) {
            // Always convert StAXSource to SAXSource.
            // * Xalan and Saxon-B don't support StAXSource.
            // * The JDK default implementation (XSLTC) doesn't handle CDATA events
            //   (see com.sun.org.apache.xalan.internal.xsltc.trax.StAXStream2SAX).
            // * Saxon-HE/PE/EE seem to support StAXSource, but don't advertise this
            //   officially (via TransformerFactory.getFeature(StAXSource.FEATURE))
            source = new StAX2SAXSource(((StAXSource) source).getXMLStreamReader());
        }
        LOG.trace("Using {} as source", source);
        transformer.transform(source, result);
        LOG.trace("Transform complete with result {}", result);
        resultHandler.setBody(out);
    } finally {
        releaseTransformer(transformer);
        // IOHelper can handle if is is null
        IOHelper.close(is);
    }
}
Also used : Transformer(javax.xml.transform.Transformer) Message(org.apache.camel.Message) InputStream(java.io.InputStream) StAX2SAXSource(org.apache.camel.converter.jaxp.StAX2SAXSource) StAXSource(javax.xml.transform.stax.StAXSource) DOMSource(javax.xml.transform.dom.DOMSource) StreamSource(javax.xml.transform.stream.StreamSource) StAX2SAXSource(org.apache.camel.converter.jaxp.StAX2SAXSource) Source(javax.xml.transform.Source) SAXSource(javax.xml.transform.sax.SAXSource) StAXSource(javax.xml.transform.stax.StAXSource) Result(javax.xml.transform.Result)

Example 59 with Result

use of javax.xml.transform.Result in project jackrabbit by apache.

the class ClientSession method exportSystemView.

/**
     * Exports the XML system view of the specified repository location
     * to the given XML content handler. This method first requests the
     * raw XML data from the remote session, and then uses an identity
     * transformation to feed the data to the given XML content handler.
     * Possible IO and transformer exceptions are thrown as SAXExceptions.
     *
     * {@inheritDoc}
     */
public void exportSystemView(String path, ContentHandler handler, boolean binaryAsLink, boolean noRecurse) throws SAXException, RepositoryException {
    try {
        byte[] xml = remote.exportSystemView(path, binaryAsLink, noRecurse);
        Source source = new StreamSource(new ByteArrayInputStream(xml));
        Result result = new SAXResult(handler);
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer();
        transformer.transform(source, result);
    } catch (RemoteException ex) {
        throw new RemoteRepositoryException(ex);
    } catch (IOException ex) {
        throw new SAXException(ex);
    } catch (TransformerConfigurationException ex) {
        throw new SAXException(ex);
    } catch (TransformerException ex) {
        throw new SAXException(ex);
    }
}
Also used : TransformerFactory(javax.xml.transform.TransformerFactory) Transformer(javax.xml.transform.Transformer) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) StreamSource(javax.xml.transform.stream.StreamSource) IOException(java.io.IOException) StreamSource(javax.xml.transform.stream.StreamSource) Source(javax.xml.transform.Source) Result(javax.xml.transform.Result) SAXResult(javax.xml.transform.sax.SAXResult) SAXException(org.xml.sax.SAXException) SAXResult(javax.xml.transform.sax.SAXResult) ByteArrayInputStream(java.io.ByteArrayInputStream) RemoteException(java.rmi.RemoteException) TransformerException(javax.xml.transform.TransformerException)

Example 60 with Result

use of javax.xml.transform.Result in project adempiere by adempiere.

the class MArchive method saveBinaryDataIntoFileSystem.

/**
	 * Save to file system. If the MArchive is not saved yet (id==0) it will
	 * first save the MArchive object because it uses the id as filename.
	 * @param inflatedData
	 */
private void saveBinaryDataIntoFileSystem(byte[] inflatedData) {
    if ("".equals(m_archivePathRoot)) {
        throw new IllegalArgumentException("no attachmentPath defined");
    }
    if (inflatedData == null || inflatedData.length == 0) {
        throw new IllegalArgumentException("InflatedData is NULL");
    }
    if (this.get_ID() == 0) {
        //set binary data otherwise save will fail
        super.setBinaryData(new byte[] { '0' });
        if (!this.save()) {
            throw new IllegalArgumentException("unable to save MArchive");
        }
    }
    final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    BufferedOutputStream out = null;
    try {
        // create destination folder
        final File destFolder = new File(m_archivePathRoot + File.separator + getArchivePathSnippet());
        if (!destFolder.exists()) {
            if (!destFolder.mkdirs()) {
                log.warning("unable to create folder: " + destFolder.getPath());
            }
        }
        // write to pdf
        final File destFile = new File(m_archivePathRoot + File.separator + getArchivePathSnippet() + this.get_ID() + ".pdf");
        out = new BufferedOutputStream(new FileOutputStream(destFile));
        out.write(inflatedData);
        out.flush();
        //create xml entry
        final DocumentBuilder builder = factory.newDocumentBuilder();
        final Document document = builder.newDocument();
        final Element root = document.createElement("archive");
        document.appendChild(root);
        document.setXmlStandalone(true);
        final Element entry = document.createElement("entry");
        entry.setAttribute("file", ARCHIVE_FOLDER_PLACEHOLDER + getArchivePathSnippet() + this.get_ID() + ".pdf");
        root.appendChild(entry);
        final Source source = new DOMSource(document);
        final ByteArrayOutputStream bos = new ByteArrayOutputStream();
        final Result result = new StreamResult(bos);
        final Transformer xformer = TransformerFactory.newInstance().newTransformer();
        xformer.transform(source, result);
        final byte[] xmlData = bos.toByteArray();
        log.fine(bos.toString());
        //store xml in db
        super.setBinaryData(xmlData);
    } catch (Exception e) {
        log.log(Level.SEVERE, "saveLOBData", e);
        m_deflated = null;
        super.setBinaryData(null);
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (Exception e) {
            }
        }
    }
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) Element(org.w3c.dom.Element) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Document(org.w3c.dom.Document) DOMSource(javax.xml.transform.dom.DOMSource) Source(javax.xml.transform.Source) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SAXException(org.xml.sax.SAXException) StreamResult(javax.xml.transform.stream.StreamResult) Result(javax.xml.transform.Result) DocumentBuilder(javax.xml.parsers.DocumentBuilder) FileOutputStream(java.io.FileOutputStream) BufferedOutputStream(java.io.BufferedOutputStream) File(java.io.File)

Aggregations

Result (javax.xml.transform.Result)80 StreamResult (javax.xml.transform.stream.StreamResult)72 Source (javax.xml.transform.Source)52 Transformer (javax.xml.transform.Transformer)52 DOMSource (javax.xml.transform.dom.DOMSource)42 TransformerFactory (javax.xml.transform.TransformerFactory)33 StringWriter (java.io.StringWriter)24 TransformerException (javax.xml.transform.TransformerException)21 IOException (java.io.IOException)20 StreamSource (javax.xml.transform.stream.StreamSource)20 SAXResult (javax.xml.transform.sax.SAXResult)16 ByteArrayOutputStream (java.io.ByteArrayOutputStream)15 File (java.io.File)15 Document (org.w3c.dom.Document)14 TransformerConfigurationException (javax.xml.transform.TransformerConfigurationException)11 DOMResult (javax.xml.transform.dom.DOMResult)11 InputSource (org.xml.sax.InputSource)11 SAXException (org.xml.sax.SAXException)10 ByteArrayInputStream (java.io.ByteArrayInputStream)9 DocumentBuilder (javax.xml.parsers.DocumentBuilder)9