Search in sources :

Example 56 with TransformerHandler

use of javax.xml.transform.sax.TransformerHandler in project knime-core by knime.

the class WorkflowSetMetaInfoEditor method doSave.

/**
 * {@inheritDoc}
 */
@Override
public void doSave(final IProgressMonitor monitor) {
    try {
        URI path = ((IURIEditorInput) getEditorInput()).getURI();
        File inputFile = new File(path);
        SAXTransformerFactory fac = (SAXTransformerFactory) TransformerFactory.newInstance();
        TransformerHandler handler = fac.newTransformerHandler();
        Transformer t = handler.getTransformer();
        t.setOutputProperty(OutputKeys.METHOD, "xml");
        t.setOutputProperty(OutputKeys.INDENT, "yes");
        OutputStream out = new FileOutputStream(inputFile);
        handler.setResult(new StreamResult(out));
        handler.startDocument();
        AttributesImpl atts = new AttributesImpl();
        atts.addAttribute(null, null, "nrOfElements", "CDATA", "" + m_elements.size());
        handler.startElement(null, null, "KNIMEMetaInfo", atts);
        monitor.beginTask("Saving meta information...", m_elements.size());
        for (MetaGUIElement element : m_elements) {
            element.saveTo(handler);
            monitor.worked(1);
        }
        handler.endElement(null, null, "KNIMEMetaInfo");
        handler.endDocument();
        out.close();
        setDirty(false);
    } catch (Exception e) {
        LOGGER.error("An error ocurred while saving " + getEditorInput().toString(), e);
    } finally {
        monitor.done();
    }
}
Also used : MetaGUIElement(org.knime.workbench.ui.metainfo.model.MetaGUIElement) IURIEditorInput(org.eclipse.ui.IURIEditorInput) TransformerHandler(javax.xml.transform.sax.TransformerHandler) Transformer(javax.xml.transform.Transformer) AttributesImpl(org.xml.sax.helpers.AttributesImpl) StreamResult(javax.xml.transform.stream.StreamResult) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) FileOutputStream(java.io.FileOutputStream) SAXTransformerFactory(javax.xml.transform.sax.SAXTransformerFactory) URI(java.net.URI) File(java.io.File) PartInitException(org.eclipse.ui.PartInitException)

Example 57 with TransformerHandler

use of javax.xml.transform.sax.TransformerHandler in project knime-core by knime.

the class PMMLDiscretizePreprocPortObjectSpec method createTransformerHandlerForSave.

static TransformerHandler createTransformerHandlerForSave(final OutputStream out) throws TransformerConfigurationException, SAXException {
    SAXTransformerFactory fac = (SAXTransformerFactory) TransformerFactory.newInstance();
    TransformerHandler handler = fac.newTransformerHandler();
    Transformer t = handler.getTransformer();
    // t.setOutputProperty(OutputKeys.METHOD, "xml");
    t.setOutputProperty(OutputKeys.INDENT, "yes");
    handler.setResult(new StreamResult(out));
    handler.startDocument();
    return handler;
}
Also used : TransformerHandler(javax.xml.transform.sax.TransformerHandler) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) SAXTransformerFactory(javax.xml.transform.sax.SAXTransformerFactory)

Example 58 with TransformerHandler

use of javax.xml.transform.sax.TransformerHandler in project sqlite-jna by gwenn.

the class SQLXMLImpl method setResult.

@Override
public <T extends Result> T setResult(Class<T> resultClass) throws SQLException {
    checkAndSwitchWritable();
    if (resultClass == null || DOMResult.class.equals(resultClass)) {
        final DOMResult domResult = new DOMResult();
        src = new DOMSrc(domResult);
        return (T) domResult;
    } else if (SAXResult.class.equals(resultClass)) {
        try {
            SAXTransformerFactory transformerFactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
            TransformerHandler transformerHandler = transformerFactory.newTransformerHandler();
            transformerHandler.setResult(new StreamResult(createWriter()));
            return resultClass.cast(new SAXResult(transformerHandler));
        } catch (TransformerException e) {
            throw new SQLiteException(null, "Unable to create SAXResult.", ErrCodes.WRAPPER_SPECIFIC, e);
        }
    } else if (StreamResult.class.equals(resultClass)) {
        return resultClass.cast(new StreamResult(createWriter()));
    } else if (StAXResult.class.equals(resultClass)) {
        try {
            XMLOutputFactory xof = XMLOutputFactory.newInstance();
            XMLStreamWriter xsw = xof.createXMLStreamWriter(createWriter());
            return resultClass.cast(new StAXResult(xsw));
        } catch (XMLStreamException e) {
            throw new SQLiteException(null, "Unable to create StAXResult.", ErrCodes.WRAPPER_SPECIFIC, e);
        }
    }
    throw new SQLiteException("Unknown XML Result class: " + resultClass, ErrCodes.WRAPPER_SPECIFIC);
}
Also used : StAXResult(javax.xml.transform.stax.StAXResult) TransformerHandler(javax.xml.transform.sax.TransformerHandler) XMLOutputFactory(javax.xml.stream.XMLOutputFactory) DOMResult(javax.xml.transform.dom.DOMResult) StreamResult(javax.xml.transform.stream.StreamResult) SAXTransformerFactory(javax.xml.transform.sax.SAXTransformerFactory) SQLiteException(org.sqlite.SQLiteException) SAXResult(javax.xml.transform.sax.SAXResult) XMLStreamException(javax.xml.stream.XMLStreamException) XMLStreamWriter(javax.xml.stream.XMLStreamWriter) TransformerException(javax.xml.transform.TransformerException)

Example 59 with TransformerHandler

use of javax.xml.transform.sax.TransformerHandler in project syncope by apache.

the class DefaultReportJobDelegate method execute.

@Transactional
@Override
public void execute(final String reportKey) throws JobExecutionException {
    Report report = reportDAO.find(reportKey);
    if (report == null) {
        throw new JobExecutionException("Report " + reportKey + " not found");
    }
    if (!report.isActive()) {
        LOG.info("Report {} not active, aborting...", reportKey);
        return;
    }
    // 1. create execution
    ReportExec execution = entityFactory.newEntity(ReportExec.class);
    execution.setStatus(ReportExecStatus.STARTED);
    execution.setStart(new Date());
    execution.setReport(report);
    execution = reportExecDAO.save(execution);
    report.add(execution);
    report = reportDAO.save(report);
    // 2. define a SAX handler for generating result as XML
    TransformerHandler handler;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);
    zos.setLevel(Deflater.BEST_COMPRESSION);
    try {
        handler = TRANSFORMER_FACTORY.newTransformerHandler();
        Transformer serializer = handler.getTransformer();
        serializer.setOutputProperty(OutputKeys.ENCODING, StandardCharsets.UTF_8.name());
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        // a single ZipEntry in the ZipOutputStream
        zos.putNextEntry(new ZipEntry(report.getName()));
        // streaming SAX handler in a compressed byte array stream
        handler.setResult(new StreamResult(zos));
    } catch (Exception e) {
        throw new JobExecutionException("While configuring for SAX generation", e, true);
    }
    execution.setStatus(ReportExecStatus.RUNNING);
    execution = reportExecDAO.save(execution);
    status.set("Starting");
    // 3. actual report execution
    StringBuilder reportExecutionMessage = new StringBuilder();
    try {
        // report header
        handler.startDocument();
        AttributesImpl atts = new AttributesImpl();
        atts.addAttribute("", "", ReportXMLConst.ATTR_NAME, ReportXMLConst.XSD_STRING, report.getName());
        handler.startElement("", "", ReportXMLConst.ELEMENT_REPORT, atts);
        status.set("Generating report header");
        // iterate over reportlet instances defined for this report
        for (int i = 0; i < report.getReportlets().size() && !interrupt; i++) {
            Optional<Reportlet> reportlet = ImplementationManager.buildReportlet(report.getReportlets().get(i));
            if (reportlet.isPresent()) {
                try {
                    status.set("Invoking reportlet " + report.getReportlets().get(i).getKey());
                    reportlet.get().extract(handler, status);
                } catch (Throwable t) {
                    LOG.error("While executing reportlet {} for report {}", reportlet, reportKey, t);
                    execution.setStatus(ReportExecStatus.FAILURE);
                    Throwable effective = t instanceof ReportException ? t.getCause() : t;
                    reportExecutionMessage.append(ExceptionUtils2.getFullStackTrace(effective)).append("\n==================\n");
                }
            }
        }
        if (interrupt) {
            LOG.debug("Report job {} interrupted", reportKey);
            interrupted = true;
        }
        // report footer
        status.set("Generating report footer");
        handler.endElement("", "", ReportXMLConst.ELEMENT_REPORT);
        handler.endDocument();
        if (!ReportExecStatus.FAILURE.name().equals(execution.getStatus())) {
            execution.setStatus(ReportExecStatus.SUCCESS);
        }
    } catch (Exception e) {
        execution.setStatus(ReportExecStatus.FAILURE);
        reportExecutionMessage.append(ExceptionUtils2.getFullStackTrace(e));
        throw new JobExecutionException(e, true);
    } finally {
        status.set("Completed");
        try {
            zos.closeEntry();
            zos.close();
            baos.close();
        } catch (IOException e) {
            LOG.error("While closing StreamResult's backend", e);
        }
        execution.setExecResult(baos.toByteArray());
        execution.setMessage(reportExecutionMessage.toString());
        execution.setEnd(new Date());
        reportExecDAO.save(execution);
    }
}
Also used : TransformerHandler(javax.xml.transform.sax.TransformerHandler) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) Report(org.apache.syncope.core.persistence.api.entity.Report) Reportlet(org.apache.syncope.core.persistence.api.dao.Reportlet) ZipEntry(java.util.zip.ZipEntry) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) ReportExec(org.apache.syncope.core.persistence.api.entity.ReportExec) Date(java.util.Date) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) IOException(java.io.IOException) JobExecutionException(org.quartz.JobExecutionException) JobExecutionException(org.quartz.JobExecutionException) AttributesImpl(org.xml.sax.helpers.AttributesImpl) ZipOutputStream(java.util.zip.ZipOutputStream) Transactional(org.springframework.transaction.annotation.Transactional)

Example 60 with TransformerHandler

use of javax.xml.transform.sax.TransformerHandler in project syncope by apache.

the class XSLTTransformer method setSAXConsumer.

/**
 * {@inheritDoc}
 */
@Override
protected void setSAXConsumer(final SAXConsumer consumer) {
    TransformerHandler transformerHandler;
    try {
        transformerHandler = TRAX_FACTORY.newTransformerHandler(this.templates);
    } catch (Exception e) {
        throw new SetupException("Could not initialize transformer handler.", e);
    }
    if (this.parameters != null) {
        final Transformer transformer = transformerHandler.getTransformer();
        this.parameters.forEach((name, values) -> {
            // is valid XSLT parameter name
            if (XSLT_PARAMETER_NAME_PATTERN.matcher(name).matches()) {
                transformer.setParameter(name, values);
            }
        });
    }
    final SAXResult result = new SAXResult();
    result.setHandler(consumer);
    // According to TrAX specs, all TransformerHandlers are LexicalHandlers
    result.setLexicalHandler(consumer);
    transformerHandler.setResult(result);
    final SAXConsumerAdapter saxConsumerAdapter = new SAXConsumerAdapter();
    saxConsumerAdapter.setContentHandler(transformerHandler);
    super.setSAXConsumer(saxConsumerAdapter);
}
Also used : TransformerHandler(javax.xml.transform.sax.TransformerHandler) SetupException(org.apache.cocoon.pipeline.SetupException) Transformer(javax.xml.transform.Transformer) AbstractSAXTransformer(org.apache.cocoon.sax.AbstractSAXTransformer) SAXResult(javax.xml.transform.sax.SAXResult) SAXConsumerAdapter(org.apache.cocoon.sax.util.SAXConsumerAdapter) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) SetupException(org.apache.cocoon.pipeline.SetupException)

Aggregations

TransformerHandler (javax.xml.transform.sax.TransformerHandler)84 StreamResult (javax.xml.transform.stream.StreamResult)57 SAXTransformerFactory (javax.xml.transform.sax.SAXTransformerFactory)51 TransformerConfigurationException (javax.xml.transform.TransformerConfigurationException)33 Transformer (javax.xml.transform.Transformer)29 IOException (java.io.IOException)23 SAXException (org.xml.sax.SAXException)22 AttributesImpl (org.xml.sax.helpers.AttributesImpl)17 StringWriter (java.io.StringWriter)13 SAXResult (javax.xml.transform.sax.SAXResult)13 File (java.io.File)11 XMLReader (org.xml.sax.XMLReader)11 FileOutputStream (java.io.FileOutputStream)10 Test (org.junit.Test)10 InputStream (java.io.InputStream)9 ByteArrayOutputStream (java.io.ByteArrayOutputStream)8 OutputStream (java.io.OutputStream)8 ContentHandler (org.xml.sax.ContentHandler)8 InputSource (org.xml.sax.InputSource)8 Metadata (org.apache.tika.metadata.Metadata)7