Example usage for javax.xml.transform.sax TransformerHandler startDocument

List of usage examples for javax.xml.transform.sax TransformerHandler startDocument

Introduction

In this page you can find the example usage for javax.xml.transform.sax TransformerHandler startDocument.

Prototype

public void startDocument() throws SAXException;

Source Link

Document

Receive notification of the beginning of a document.

Usage

From source file:Main.java

/**
 * Creates a {@link TransformerHandler}.
 * /*from   w w w .  j  av a 2 s .com*/
 * @param commentHeader the comment header
 * @param rootTag the root tag
 * @param streamResult stream result
 */
public static TransformerHandler createTransformerHandler(String commentHeader, String rootTag,
        StreamResult streamResult, Charset charset)
        throws TransformerFactoryConfigurationError, TransformerConfigurationException, SAXException {
    SAXTransformerFactory tf = (SAXTransformerFactory) TransformerFactory.newInstance();
    try {
        tf.setAttribute("indent-number", new Integer(2));
    } catch (Exception e) {
        // ignore, workaround for JDK 1.5 bug, see http://forum.java.sun.com/thread.jspa?threadID=562510
    }
    TransformerHandler transformerHandler = tf.newTransformerHandler();
    Transformer serializer = transformerHandler.getTransformer();
    serializer.setOutputProperty(OutputKeys.ENCODING, charset.name());
    serializer.setOutputProperty(OutputKeys.METHOD, "xml");
    serializer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformerHandler.setResult(streamResult);
    transformerHandler.startDocument();
    String newline = System.getProperty("line.separator");
    if (newline == null) {
        newline = "\n";
    }
    commentHeader = (newline + commentHeader).replaceAll("\\n--", newline + " ");
    transformerHandler.characters("\n".toCharArray(), 0, 1);
    transformerHandler.comment(commentHeader.toCharArray(), 0, commentHeader.toCharArray().length);
    transformerHandler.characters("\n".toCharArray(), 0, 1);
    if (rootTag.length() > 0) {
        transformerHandler.startElement("", "", rootTag, null);
    }
    return transformerHandler;
}

From source file:IOUtils.java

/**
 * Checks if the used Trax implementation correctly handles namespaces set using
 * <code>startPrefixMapping()</code>, but wants them also as 'xmlns:' attributes.
 * <p>//from  w  w  w  .jav  a 2  s.co  m
 * The check consists in sending SAX events representing a minimal namespaced document
 * with namespaces defined only with calls to <code>startPrefixMapping</code> (no
 * xmlns:xxx attributes) and check if they are present in the resulting text.
 */
protected static boolean needsNamespacesAsAttributes(Properties format)
        throws TransformerException, SAXException {
    // Serialize a minimal document to check how namespaces are handled.
    final StringWriter writer = new StringWriter();

    final String uri = "namespaceuri";
    final String prefix = "nsp";
    final String check = "xmlns:" + prefix + "='" + uri + "'";

    final TransformerHandler handler = FACTORY.newTransformerHandler();

    handler.getTransformer().setOutputProperties(format);
    handler.setResult(new StreamResult(writer));

    // Output a single element
    handler.startDocument();
    handler.startPrefixMapping(prefix, uri);
    handler.startElement(uri, "element", "element", new AttributesImpl());
    handler.endElement(uri, "element", "element");
    handler.endPrefixMapping(prefix);
    handler.endDocument();

    final String text = writer.toString();

    // Check if the namespace is there (replace " by ' to be sure of what we search in)
    boolean needsIt = (text.replace('"', '\'').indexOf(check) == -1);

    return needsIt;
}

From source file:it.polito.tellmefirst.web.rest.interfaces.AbsResponseInterface.java

public TransformerHandler initXMLDoc(ByteArrayOutputStream out) throws TMFOutputException {
    LOG.debug("[initXMLDoc] - BEGIN");
    TransformerHandler hd;
    try {//from w ww.  j a  va 2 s .  c o m
        StreamResult streamResult = new StreamResult(out);
        SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
        hd = tf.newTransformerHandler();
        Transformer serializer = hd.getTransformer();
        serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        hd.setResult(streamResult);
        hd.startDocument();
    } catch (Exception e) {
        throw new TMFOutputException("Error initializing XML.", e);
    }
    LOG.debug("[initXMLDoc] - END");
    return hd;
}

From source file:org.syncope.core.util.ImportExport.java

public void export(final OutputStream os)
        throws SAXException, TransformerConfigurationException, CycleInMultiParentTreeException {

    StreamResult streamResult = new StreamResult(os);
    SAXTransformerFactory transformerFactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();

    TransformerHandler handler = transformerFactory.newTransformerHandler();
    Transformer serializer = handler.getTransformer();
    serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    serializer.setOutputProperty(OutputKeys.INDENT, "yes");
    handler.setResult(streamResult);//from   w w  w . j a  v a  2  s . c  om
    handler.startDocument();
    handler.startElement("", "", ROOT_ELEMENT, new AttributesImpl());

    Connection conn = DataSourceUtils.getConnection(dataSource);
    ResultSet rs = null;
    try {
        // first read all tables...
        rs = conn.getMetaData().getTables(null, null, null, new String[] { "TABLE" });
        Set<String> tableNames = new HashSet<String>();
        while (rs.next()) {
            String tableName = rs.getString("TABLE_NAME");
            // these tables must be ignored
            if (!tableName.toUpperCase().startsWith("QRTZ_")
                    && !tableName.toUpperCase().equals("ACT_GE_PROPERTY")) {

                tableNames.add(tableName);
            }
        }
        // then sort tables based on foreign keys and dump
        for (String tableName : sortByForeignKeys(conn, tableNames)) {

            doExportTable(handler, conn, tableName);
        }
    } catch (SQLException e) {
        LOG.error("While exporting database content", e);
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                LOG.error("While closing tables result set", e);
            }
        }
        DataSourceUtils.releaseConnection(conn, dataSource);
    }

    handler.endElement("", "", ROOT_ELEMENT);
    handler.endDocument();
}

From source file:org.apache.syncope.core.util.ImportExport.java

public void export(final OutputStream os) throws SAXException, TransformerConfigurationException {

    StreamResult streamResult = new StreamResult(os);
    final SAXTransformerFactory transformerFactory = (SAXTransformerFactory) SAXTransformerFactory
            .newInstance();/*from ww w . java2  s  . c  om*/

    TransformerHandler handler = transformerFactory.newTransformerHandler();
    Transformer serializer = handler.getTransformer();
    serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    serializer.setOutputProperty(OutputKeys.INDENT, "yes");
    handler.setResult(streamResult);
    handler.startDocument();
    handler.startElement("", "", ROOT_ELEMENT, new AttributesImpl());

    final Connection conn = DataSourceUtils.getConnection(dataSource);

    ResultSet rs = null;

    try {
        final DatabaseMetaData meta = conn.getMetaData();

        final String schema = readSchema();

        rs = meta.getTables(null, schema, null, new String[] { "TABLE" });

        final Set<String> tableNames = new HashSet<String>();

        while (rs.next()) {
            String tableName = rs.getString("TABLE_NAME");

            // these tables must be ignored
            if (!tableName.toUpperCase().startsWith("QRTZ_")
                    && !tableName.toUpperCase().startsWith("LOGGING_")) {
                tableNames.add(tableName);
            }
        }

        // then sort tables based on foreign keys and dump
        for (String tableName : sortByForeignKeys(conn, tableNames, schema)) {
            doExportTable(handler, conn, tableName);
        }
    } catch (SQLException e) {
        LOG.error("While exporting database content", e);
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                LOG.error("While closing tables result set", e);
            }
        }
        DataSourceUtils.releaseConnection(conn, dataSource);
    }

    handler.endElement("", "", ROOT_ELEMENT);
    handler.endDocument();
}

From source file:dicoogle.ua.dim.DIMGeneric.java

public String getXML() {

    StringWriter writer = new StringWriter();

    StreamResult streamResult = new StreamResult(writer);
    SAXTransformerFactory tf = (SAXTransformerFactory) TransformerFactory.newInstance();
    //      SAX2.0 ContentHandler.
    TransformerHandler hd = null;
    try {/*from   w w  w .  ja  va  2 s . c o  m*/
        hd = tf.newTransformerHandler();
    } catch (TransformerConfigurationException ex) {
        Logger.getLogger(DIMGeneric.class.getName()).log(Level.SEVERE, null, ex);
    }
    Transformer serializer = hd.getTransformer();
    serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    serializer.setOutputProperty(OutputKeys.METHOD, "xml");
    serializer.setOutputProperty(OutputKeys.INDENT, "yes");
    serializer.setOutputProperty(OutputKeys.STANDALONE, "yes");
    hd.setResult(streamResult);
    try {
        hd.startDocument();

        AttributesImpl atts = new AttributesImpl();
        hd.startElement("", "", "DIM", atts);

        for (Patient p : this.patients) {
            atts.clear();
            atts.addAttribute("", "", "name", "", p.getPatientName().trim());
            atts.addAttribute("", "", "id", "", p.getPatientID().trim());
            hd.startElement("", "", "Patient", atts);

            for (Study s : p.getStudies()) {
                atts.clear();
                atts.addAttribute("", "", "date", "", s.getStudyData().trim());
                atts.addAttribute("", "", "id", "", s.getStudyInstanceUID().trim());

                hd.startElement("", "", "Study", atts);

                for (Serie serie : s.getSeries()) {
                    atts.clear();
                    atts.addAttribute("", "", "modality", "", serie.getModality().trim());
                    atts.addAttribute("", "", "id", "", serie.getSerieInstanceUID().trim());

                    hd.startElement("", "", "Serie", atts);

                    ArrayList<URI> img = serie.getImageList();
                    ArrayList<String> uid = serie.getSOPInstanceUIDList();
                    int size = img.size();
                    for (int i = 0; i < size; i++) {
                        atts.clear();
                        atts.addAttribute("", "", "path", "", img.get(i).toString().trim());
                        atts.addAttribute("", "", "uid", "", uid.get(i).trim());

                        hd.startElement("", "", "Image", atts);
                        hd.endElement("", "", "Image");
                    }
                    hd.endElement("", "", "Serie");
                }
                hd.endElement("", "", "Study");
            }
            hd.endElement("", "", "Patient");
        }
        hd.endElement("", "", "DIM");

    } catch (SAXException ex) {
        Logger.getLogger(DIMGeneric.class.getName()).log(Level.SEVERE, null, ex);
    }

    return writer.toString();
}

From source file:org.syncope.core.scheduling.ReportJob.java

@Override
public void execute(final JobExecutionContext context) throws JobExecutionException {

    Report report = reportDAO.find(reportId);
    if (report == null) {
        throw new JobExecutionException("Report " + reportId + " not found");
    }//from  w  w  w .jav a2 s. c  o  m

    // 1. create execution
    ReportExec execution = new ReportExec();
    execution.setStatus(ReportExecStatus.STARTED);
    execution.setStartDate(new Date());
    execution.setReport(report);
    execution = reportExecDAO.save(execution);

    // 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 {
        SAXTransformerFactory transformerFactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
        handler = transformerFactory.newTransformerHandler();
        Transformer serializer = handler.getTransformer();
        serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        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);

    ConfigurableListableBeanFactory beanFactory = ApplicationContextManager.getApplicationContext()
            .getBeanFactory();

    // 3. actual report execution
    StringBuilder reportExecutionMessage = new StringBuilder();
    StringWriter exceptionWriter = new StringWriter();
    try {
        // report header
        handler.startDocument();
        AttributesImpl atts = new AttributesImpl();
        atts.addAttribute("", "", ATTR_NAME, XSD_STRING, report.getName());
        handler.startElement("", "", ELEMENT_REPORT, atts);

        // iterate over reportlet instances defined for this report
        for (ReportletConf reportletConf : report.getReportletConfs()) {
            Class reportletClass = null;
            try {
                reportletClass = Class.forName(reportletConf.getReportletClassName());
            } catch (ClassNotFoundException e) {
                LOG.error("Reportlet class not found: {}", reportletConf.getReportletClassName(), e);

            }

            if (reportletClass != null) {
                Reportlet autowired = (Reportlet) beanFactory.createBean(reportletClass,
                        AbstractBeanDefinition.AUTOWIRE_BY_TYPE, false);
                autowired.setConf(reportletConf);

                // invoke reportlet
                try {
                    autowired.extract(handler);
                } catch (Exception e) {
                    execution.setStatus(ReportExecStatus.FAILURE);

                    Throwable t = e instanceof ReportException ? e.getCause() : e;
                    exceptionWriter.write(t.getMessage() + "\n\n");
                    t.printStackTrace(new PrintWriter(exceptionWriter));
                    reportExecutionMessage.append(exceptionWriter.toString()).append("\n==================\n");
                }
            }
        }

        // report footer
        handler.endElement("", "", ELEMENT_REPORT);
        handler.endDocument();

        if (!ReportExecStatus.FAILURE.name().equals(execution.getStatus())) {

            execution.setStatus(ReportExecStatus.SUCCESS);
        }
    } catch (Exception e) {
        execution.setStatus(ReportExecStatus.FAILURE);

        exceptionWriter.write(e.getMessage() + "\n\n");
        e.printStackTrace(new PrintWriter(exceptionWriter));
        reportExecutionMessage.append(exceptionWriter.toString());

        throw new JobExecutionException(e, true);
    } finally {
        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.setEndDate(new Date());
        reportExecDAO.save(execution);
    }
}

From source file:org.apache.cocoon.components.source.impl.WebDAVSource.java

private InputStream resourcesToXml(WebdavResource[] resources) throws Exception {
    TransformerFactory tf = TransformerFactory.newInstance();
    TransformerHandler th = ((SAXTransformerFactory) tf).newTransformerHandler();
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    StreamResult result = new StreamResult(bOut);
    th.setResult(result);/*from w w  w  . ja  va2s  .  com*/
    th.startDocument();
    th.startPrefixMapping(PREFIX, NAMESPACE);
    th.startElement(NAMESPACE, COLLECTION_NAME, PREFIX + ":" + COLLECTION_NAME, XMLUtils.EMPTY_ATTRIBUTES);
    resourcesToSax(resources, th);
    th.endElement(NAMESPACE, COLLECTION_NAME, PREFIX + ":" + COLLECTION_NAME);
    th.endPrefixMapping(PREFIX);
    th.endDocument();

    return new ByteArrayInputStream(bOut.toByteArray());
}

From source file:org.apache.cocoon.serialization.AbstractTextSerializer.java

/**
 * Checks if the used Trax implementation correctly handles namespaces set using
 * <code>startPrefixMapping()</code>, but wants them also as 'xmlns:' attributes.
 * <p>/* w ww.j  a v  a2  s .  com*/
 * The check consists in sending SAX events representing a minimal namespaced document
 * with namespaces defined only with calls to <code>startPrefixMapping</code> (no
 * xmlns:xxx attributes) and check if they are present in the resulting text.
 */
protected boolean needsNamespacesAsAttributes() throws Exception {

    SAXTransformerFactory factory = getTransformerFactory();

    Boolean cacheValue = (Boolean) needsNamespaceCache.get(factory.getClass().getName());
    if (cacheValue != null) {
        return cacheValue.booleanValue();
    } else {
        // Serialize a minimal document to check how namespaces are handled.
        StringWriter writer = new StringWriter();

        String uri = "namespaceuri";
        String prefix = "nsp";
        String check = "xmlns:" + prefix + "='" + uri + "'";

        TransformerHandler handler = this.getTransformerHandler();

        handler.getTransformer().setOutputProperties(format);
        handler.setResult(new StreamResult(writer));

        // Output a single element
        handler.startDocument();
        handler.startPrefixMapping(prefix, uri);
        handler.startElement(uri, "element", "element", XMLUtils.EMPTY_ATTRIBUTES);
        handler.endElement(uri, "element", "element");
        handler.endPrefixMapping(prefix);
        handler.endDocument();

        String text = writer.toString();

        // Check if the namespace is there (replace " by ' to be sure of what we search in)
        boolean needsIt = (text.replace('"', '\'').indexOf(check) == -1);

        String msg = needsIt ? " needs namespace attributes (will be slower)."
                : " handles correctly namespaces.";

        getLogger().debug("Trax handler " + handler.getClass().getName() + msg);

        needsNamespaceCache.put(factory.getClass().getName(), BooleanUtils.toBooleanObject(needsIt));

        return needsIt;
    }
}

From source file:org.apache.fop.events.model.EventModel.java

private void writeXMLizable(XMLizable object, File outputFile) throws IOException {
    //These two approaches do not seem to work in all environments:
    //Result res = new StreamResult(outputFile);
    //Result res = new StreamResult(outputFile.toURI().toURL().toExternalForm());
    //With an old Xalan version: file:/C:/.... --> file:\C:\.....
    OutputStream out = new java.io.FileOutputStream(outputFile);
    out = new java.io.BufferedOutputStream(out);
    Result res = new StreamResult(out);

    try {//from  ww  w  .  jav  a 2 s .co  m
        SAXTransformerFactory tFactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
        TransformerHandler handler = tFactory.newTransformerHandler();
        Transformer transformer = handler.getTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        handler.setResult(res);
        handler.startDocument();
        object.toSAX(handler);
        handler.endDocument();
    } catch (TransformerConfigurationException e) {
        throw new IOException(e.getMessage());
    } catch (TransformerFactoryConfigurationError e) {
        throw new IOException(e.getMessage());
    } catch (SAXException e) {
        throw new IOException(e.getMessage());
    } finally {
        IOUtils.closeQuietly(out);
    }
}