Search in sources :

Example 16 with SAXTransformerFactory

use of javax.xml.transform.sax.SAXTransformerFactory in project camel by apache.

the class TikaProducer method getTransformerHandler.

private TransformerHandler getTransformerHandler(OutputStream output, String method, boolean prettyPrint) throws TransformerConfigurationException, UnsupportedEncodingException {
    SAXTransformerFactory factory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
    TransformerHandler handler = factory.newTransformerHandler();
    handler.getTransformer().setOutputProperty(OutputKeys.METHOD, method);
    handler.getTransformer().setOutputProperty(OutputKeys.INDENT, prettyPrint ? "yes" : "no");
    if (this.encoding != null) {
        handler.getTransformer().setOutputProperty(OutputKeys.ENCODING, this.encoding);
    }
    handler.setResult(new StreamResult(new OutputStreamWriter(output, this.encoding)));
    return handler;
}
Also used : TransformerHandler(javax.xml.transform.sax.TransformerHandler) StreamResult(javax.xml.transform.stream.StreamResult) SAXTransformerFactory(javax.xml.transform.sax.SAXTransformerFactory) OutputStreamWriter(java.io.OutputStreamWriter)

Example 17 with SAXTransformerFactory

use of javax.xml.transform.sax.SAXTransformerFactory in project intellij-community by JetBrains.

the class XSLTReportConverter method convert.

@Override
public void convert(@NotNull final String rawDataDirectoryPath, @Nullable final String outputPath, @NotNull final Map<String, Tools> tools, @NotNull final List<File> inspectionsResults) throws InspectionsReportConverter.ConversionException {
    if (outputPath == null) {
        throw new ConversionException("Output path isn't specified.");
    }
    final SAXTransformerFactory transformerFactory = (SAXTransformerFactory) TransformerFactory.newInstance();
    final Source xslSource;
    final Transformer transformer;
    try {
        final File xsltSchemeFile = new File(myXSLTSchemePath);
        if (!xsltSchemeFile.exists()) {
            throw new ConversionException("Cannot find XSLT scheme: " + myXSLTSchemePath);
        }
        xslSource = new StreamSource(xsltSchemeFile);
        transformer = transformerFactory.newTransformer(xslSource);
    } catch (TransformerConfigurationException e) {
        throw new ConversionException("Fail to load XSLT scheme.");
    }
    final Writer w;
    final File outputFile = new File(outputPath);
    try {
        w = new FileWriter(outputFile);
    } catch (IOException e) {
        throw new ConversionException("Cannot edit file: " + outputFile.getPath());
    }
    try {
        for (File inspectionData : inspectionsResults) {
            if (inspectionData.isDirectory()) {
                warn("Folder isn't expected here: " + inspectionData.getName());
                continue;
            }
            final String fileNameWithoutExt = FileUtil.getNameWithoutExtension(inspectionData);
            if (InspectionApplication.DESCRIPTIONS.equals(fileNameWithoutExt)) {
                continue;
            }
            // Transform results:
            try {
                transformer.transform(new StreamSource(inspectionData), new StreamResult(w));
            } catch (TransformerException e) {
                throw new ConversionException("Cannot apply XSL transformation: " + e.getMessage());
            }
        }
    } finally {
        try {
            w.close();
        } catch (IOException e) {
            warn("Cannot save inspection results: " + e.getMessage());
        }
    }
}
Also used : StreamResult(javax.xml.transform.stream.StreamResult) StreamSource(javax.xml.transform.stream.StreamSource) FileWriter(java.io.FileWriter) SAXTransformerFactory(javax.xml.transform.sax.SAXTransformerFactory) IOException(java.io.IOException) StreamSource(javax.xml.transform.stream.StreamSource) File(java.io.File) FileWriter(java.io.FileWriter) Writer(java.io.Writer)

Example 18 with SAXTransformerFactory

use of javax.xml.transform.sax.SAXTransformerFactory in project intellij-community by JetBrains.

the class GeneralToSMTRunnerEventsConvertorTest method testPreserveFullOutputAfterImport.

public void testPreserveFullOutputAfterImport() throws Exception {
    mySuite.addChild(mySimpleTest);
    for (int i = 0; i < 550; i++) {
        String message = "line" + i + "\n";
        mySimpleTest.addLast(printer -> printer.print(message, ConsoleViewContentType.NORMAL_OUTPUT));
    }
    mySimpleTest.setFinished();
    mySuite.setFinished();
    SAXTransformerFactory transformerFactory = (SAXTransformerFactory) TransformerFactory.newInstance();
    TransformerHandler handler = transformerFactory.newTransformerHandler();
    handler.getTransformer().setOutputProperty(OutputKeys.INDENT, "yes");
    handler.getTransformer().setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
    File output = FileUtil.createTempFile("output", "");
    try {
        FileUtilRt.createParentDirs(output);
        handler.setResult(new StreamResult(new FileWriter(output)));
        MockRuntimeConfiguration configuration = new MockRuntimeConfiguration(getProject());
        TestResultsXmlFormatter.execute(mySuite, configuration, new SMTRunnerConsoleProperties(configuration, "framework", new DefaultRunExecutor()), handler);
        String savedText = FileUtil.loadFile(output);
        assertTrue(savedText.split("\n").length > 550);
        myEventsProcessor.onStartTesting();
        ImportedToGeneralTestEventsConverter.parseTestResults(() -> new StringReader(savedText), myEventsProcessor);
        myEventsProcessor.onFinishTesting();
        List<? extends SMTestProxy> children = myResultsViewer.getTestsRootNode().getChildren();
        assertSize(1, children);
        SMTestProxy testProxy = children.get(0);
        MockPrinter mockPrinter = new MockPrinter();
        testProxy.printOn(mockPrinter);
        assertSize(550, mockPrinter.getAllOut().split("\n"));
    } finally {
        FileUtil.delete(output);
    }
}
Also used : TransformerHandler(javax.xml.transform.sax.TransformerHandler) StreamResult(javax.xml.transform.stream.StreamResult) FileWriter(java.io.FileWriter) SAXTransformerFactory(javax.xml.transform.sax.SAXTransformerFactory) StringReader(java.io.StringReader) MockPrinter(com.intellij.execution.testframework.sm.runner.ui.MockPrinter) File(java.io.File) DefaultRunExecutor(com.intellij.execution.executors.DefaultRunExecutor)

Example 19 with SAXTransformerFactory

use of javax.xml.transform.sax.SAXTransformerFactory in project bytecode-viewer by Konloch.

the class Processor method process.

public int process() throws TransformerException, IOException, SAXException {
    ZipInputStream zis = new ZipInputStream(input);
    final ZipOutputStream zos = new ZipOutputStream(output);
    final OutputStreamWriter osw = new OutputStreamWriter(zos);
    Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
    TransformerFactory tf = TransformerFactory.newInstance();
    if (!tf.getFeature(SAXSource.FEATURE) || !tf.getFeature(SAXResult.FEATURE)) {
        return 0;
    }
    SAXTransformerFactory saxtf = (SAXTransformerFactory) tf;
    Templates templates = null;
    if (xslt != null) {
        templates = saxtf.newTemplates(xslt);
    }
    // configuring outHandlerFactory
    // ///////////////////////////////////////////////////////
    EntryElement entryElement = getEntryElement(zos);
    ContentHandler outDocHandler = null;
    switch(outRepresentation) {
        case BYTECODE:
            outDocHandler = new OutputSlicingHandler(new ASMContentHandlerFactory(zos), entryElement, false);
            break;
        case MULTI_XML:
            outDocHandler = new OutputSlicingHandler(new SAXWriterFactory(osw, true), entryElement, true);
            break;
        case SINGLE_XML:
            ZipEntry outputEntry = new ZipEntry(SINGLE_XML_NAME);
            zos.putNextEntry(outputEntry);
            outDocHandler = new SAXWriter(osw, false);
            break;
    }
    // configuring inputDocHandlerFactory
    // /////////////////////////////////////////////////
    ContentHandler inDocHandler;
    if (templates == null) {
        inDocHandler = outDocHandler;
    } else {
        inDocHandler = new InputSlicingHandler("class", outDocHandler, new TransformerHandlerFactory(saxtf, templates, outDocHandler));
    }
    ContentHandlerFactory inDocHandlerFactory = new SubdocumentHandlerFactory(inDocHandler);
    if (inDocHandler != null && inRepresentation != SINGLE_XML) {
        inDocHandler.startDocument();
        inDocHandler.startElement("", "classes", "classes", new AttributesImpl());
    }
    int i = 0;
    ZipEntry ze;
    while ((ze = zis.getNextEntry()) != null) {
        update(ze.getName(), n++);
        if (isClassEntry(ze)) {
            processEntry(zis, ze, inDocHandlerFactory);
        } else {
            OutputStream os = entryElement.openEntry(getName(ze));
            copyEntry(zis, os);
            entryElement.closeEntry();
        }
        i++;
    }
    if (inDocHandler != null && inRepresentation != SINGLE_XML) {
        inDocHandler.endElement("", "classes", "classes");
        inDocHandler.endDocument();
    }
    if (outRepresentation == SINGLE_XML) {
        zos.closeEntry();
    }
    zos.flush();
    zos.close();
    return i;
}
Also used : SAXTransformerFactory(javax.xml.transform.sax.SAXTransformerFactory) ZipEntry(java.util.zip.ZipEntry) ZipOutputStream(java.util.zip.ZipOutputStream) SAXTransformerFactory(javax.xml.transform.sax.SAXTransformerFactory) ZipInputStream(java.util.zip.ZipInputStream) AttributesImpl(org.xml.sax.helpers.AttributesImpl) ZipOutputStream(java.util.zip.ZipOutputStream)

Example 20 with SAXTransformerFactory

use of javax.xml.transform.sax.SAXTransformerFactory in project jackrabbit by apache.

the class EventJournalResourceImpl method spool.

@Override
public void spool(OutputContext outputContext) throws IOException {
    Calendar cal = Calendar.getInstance(Locale.ENGLISH);
    try {
        outputContext.setContentType("application/atom+xml; charset=UTF-8");
        outputContext.setProperty("Vary", "If-None-Match");
        // TODO: Content-Encoding: gzip
        // find out where to start
        long prevts = -1;
        String inm = request.getHeader("If-None-Match");
        if (inm != null) {
            // TODO: proper parsing when comma-delimited
            inm = inm.trim();
            if (inm.startsWith("\"") && inm.endsWith("\"")) {
                String tmp = inm.substring(1, inm.length() - 1);
                try {
                    prevts = Long.parseLong(tmp, 16);
                    journal.skipTo(prevts);
                } catch (NumberFormatException ex) {
                // broken etag
                }
            }
        }
        boolean hasPersistEvents = false;
        if (outputContext.hasStream()) {
            long lastts = -1;
            long now = System.currentTimeMillis();
            boolean done = false;
            // collect events
            List<Event> events = new ArrayList<Event>(MAXEV);
            while (!done && journal.hasNext()) {
                Event e = journal.nextEvent();
                hasPersistEvents |= e.getType() == Event.PERSIST;
                if (e.getDate() != lastts) {
                    // consider stopping
                    if (events.size() > MAXEV) {
                        done = true;
                    }
                    if (e.getDate() > now + MAXWAIT) {
                        done = true;
                    }
                }
                if (!done && (prevts == -1 || e.getDate() >= prevts)) {
                    events.add(e);
                }
                lastts = e.getDate();
            }
            if (lastts >= 0) {
                // construct ETag from newest event
                outputContext.setETag("\"" + Long.toHexString(lastts) + "\"");
            }
            OutputStream os = outputContext.getOutputStream();
            StreamResult streamResult = new StreamResult(os);
            SAXTransformerFactory tf = (SAXTransformerFactory) TransformerFactory.newInstance();
            TransformerHandler th = tf.newTransformerHandler();
            Transformer s = th.getTransformer();
            s.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            s.setOutputProperty(OutputKeys.INDENT, "yes");
            s.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            th.setResult(streamResult);
            th.startDocument();
            th.startElement(ATOMNS, FEED, FEED, NOATTRS);
            writeAtomElement(th, TITLE, "EventJournal for " + getLocator().getWorkspaceName());
            th.startElement(ATOMNS, AUTHOR, AUTHOR, NOATTRS);
            writeAtomElement(th, NAME, "Jackrabbit Event Journal Feed Generator");
            th.endElement(ATOMNS, AUTHOR, AUTHOR);
            String id = getFullUri(request);
            writeAtomElement(th, ID, id);
            AttributesImpl linkattrs = new AttributesImpl();
            linkattrs.addAttribute(null, "self", "self", "CDATA", id);
            writeAtomElement(th, LINK, linkattrs, null);
            cal.setTimeInMillis(lastts >= 0 ? lastts : now);
            String upd = ISO8601.format(cal);
            writeAtomElement(th, UPDATED, upd);
            String lastDateString = "";
            long lastTimeStamp = 0;
            long index = 0;
            AttributesImpl contentatt = new AttributesImpl();
            contentatt.addAttribute(null, "type", "type", "CDATA", EVENTMEDIATYPE);
            while (!events.isEmpty()) {
                List<Event> bundle = null;
                String path = null;
                String op;
                if (hasPersistEvents) {
                    bundle = new ArrayList<Event>();
                    Event e = null;
                    op = "operations";
                    do {
                        e = events.remove(0);
                        bundle.add(e);
                        // compute common path
                        if (path == null) {
                            path = e.getPath();
                        } else {
                            if (e.getPath() != null && e.getPath().length() < path.length()) {
                                path = e.getPath();
                            }
                        }
                    } while (e.getType() != Event.PERSIST && !events.isEmpty());
                } else {
                    // no persist events
                    Event e = events.remove(0);
                    bundle = Collections.singletonList(e);
                    path = e.getPath();
                    op = EventUtil.getEventName(e.getType());
                }
                Event firstEvent = bundle.get(0);
                String entryupd = lastDateString;
                if (lastTimeStamp != firstEvent.getDate()) {
                    cal.setTimeInMillis(firstEvent.getDate());
                    entryupd = ISO8601.format(cal);
                    index = 0;
                } else {
                    index += 1;
                }
                th.startElement(ATOMNS, ENTRY, ENTRY, NOATTRS);
                String entrytitle = op + (path != null ? (": " + path) : "");
                writeAtomElement(th, TITLE, entrytitle);
                String entryid = id + "?type=journal&ts=" + Long.toHexString(firstEvent.getDate()) + "-" + index;
                writeAtomElement(th, ID, entryid);
                String author = firstEvent.getUserID() == null || firstEvent.getUserID().length() == 0 ? null : firstEvent.getUserID();
                if (author != null) {
                    th.startElement(ATOMNS, AUTHOR, AUTHOR, NOATTRS);
                    writeAtomElement(th, NAME, author);
                    th.endElement(ATOMNS, AUTHOR, AUTHOR);
                }
                writeAtomElement(th, UPDATED, entryupd);
                th.startElement(ATOMNS, CONTENT, CONTENT, contentatt);
                for (Event e : bundle) {
                    // serialize the event
                    th.startElement(EVNS, E_EVENT, E_EVENT, NOATTRS);
                    // DAV:href
                    if (e.getPath() != null) {
                        boolean isCollection = (e.getType() == Event.NODE_ADDED || e.getType() == Event.NODE_REMOVED);
                        String href = locator.getFactory().createResourceLocator(locator.getPrefix(), locator.getWorkspacePath(), e.getPath(), false).getHref(isCollection);
                        th.startElement(DavConstants.NAMESPACE.getURI(), DavConstants.XML_HREF, DavConstants.XML_HREF, NOATTRS);
                        th.characters(href.toCharArray(), 0, href.length());
                        th.endElement(DavConstants.NAMESPACE.getURI(), DavConstants.XML_HREF, DavConstants.XML_HREF);
                    }
                    // event type
                    String evname = EventUtil.getEventName(e.getType());
                    th.startElement(EVNS, E_EVENTTYPE, E_EVENTTYPE, NOATTRS);
                    th.startElement(EVNS, evname, evname, NOATTRS);
                    th.endElement(EVNS, evname, evname);
                    th.endElement(EVNS, E_EVENTTYPE, E_EVENTTYPE);
                    // date
                    writeObsElement(th, E_EVENTDATE, Long.toString(e.getDate()));
                    // user data
                    if (e.getUserData() != null && e.getUserData().length() > 0) {
                        writeObsElement(th, E_EVENTUSERDATA, firstEvent.getUserData());
                    }
                    // try to compute nodetype information
                    if (e instanceof AdditionalEventInfo) {
                        try {
                            Name pnt = ((AdditionalEventInfo) e).getPrimaryNodeTypeName();
                            if (pnt != null) {
                                writeObsElement(th, E_EVENTPRIMARNODETYPE, pnt.toString());
                            }
                            Set<Name> mixins = ((AdditionalEventInfo) e).getMixinTypeNames();
                            if (mixins != null) {
                                for (Name mixin : mixins) {
                                    writeObsElement(th, E_EVENTMIXINNODETYPE, mixin.toString());
                                }
                            }
                        } catch (UnsupportedRepositoryOperationException ex) {
                        // optional
                        }
                    }
                    // identifier
                    if (e.getIdentifier() != null) {
                        writeObsElement(th, E_EVENTIDENTIFIER, e.getIdentifier());
                    }
                    // info
                    if (!e.getInfo().isEmpty()) {
                        th.startElement(EVNS, E_EVENTINFO, E_EVENTINFO, NOATTRS);
                        Map<?, ?> m = e.getInfo();
                        for (Map.Entry<?, ?> entry : m.entrySet()) {
                            String key = entry.getKey().toString();
                            Object value = entry.getValue();
                            String t = value != null ? value.toString() : null;
                            writeElement(th, null, key, NOATTRS, t);
                        }
                        th.endElement(EVNS, E_EVENTINFO, E_EVENTINFO);
                    }
                    th.endElement(EVNS, E_EVENT, E_EVENT);
                    lastTimeStamp = e.getDate();
                    lastDateString = entryupd;
                }
                th.endElement(ATOMNS, CONTENT, CONTENT);
                th.endElement(ATOMNS, ENTRY, ENTRY);
            }
            th.endElement(ATOMNS, FEED, FEED);
            th.endDocument();
            os.flush();
        }
    } catch (Exception ex) {
        throw new IOException("error generating feed: " + ex.getMessage());
    }
}
Also used : UnsupportedRepositoryOperationException(javax.jcr.UnsupportedRepositoryOperationException) TransformerHandler(javax.xml.transform.sax.TransformerHandler) Transformer(javax.xml.transform.Transformer) OutputStream(java.io.OutputStream) AdditionalEventInfo(org.apache.jackrabbit.spi.commons.AdditionalEventInfo) ArrayList(java.util.ArrayList) Name(org.apache.jackrabbit.spi.Name) AttributesImpl(org.xml.sax.helpers.AttributesImpl) StreamResult(javax.xml.transform.stream.StreamResult) Calendar(java.util.Calendar) SAXTransformerFactory(javax.xml.transform.sax.SAXTransformerFactory) IOException(java.io.IOException) RepositoryException(javax.jcr.RepositoryException) IOException(java.io.IOException) UnsupportedRepositoryOperationException(javax.jcr.UnsupportedRepositoryOperationException) DavException(org.apache.jackrabbit.webdav.DavException) SAXException(org.xml.sax.SAXException) Event(javax.jcr.observation.Event) Map(java.util.Map)

Aggregations

SAXTransformerFactory (javax.xml.transform.sax.SAXTransformerFactory)27 TransformerHandler (javax.xml.transform.sax.TransformerHandler)22 StreamResult (javax.xml.transform.stream.StreamResult)22 AttributesImpl (org.xml.sax.helpers.AttributesImpl)7 InputStream (java.io.InputStream)6 StringWriter (java.io.StringWriter)6 Metadata (org.apache.tika.metadata.Metadata)6 File (java.io.File)5 IOException (java.io.IOException)5 Transformer (javax.xml.transform.Transformer)5 ParseContext (org.apache.tika.parser.ParseContext)5 OutputStream (java.io.OutputStream)4 OutputStreamWriter (java.io.OutputStreamWriter)4 TikaTest (org.apache.tika.TikaTest)4 AutoDetectParser (org.apache.tika.parser.AutoDetectParser)4 Test (org.junit.Test)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 FileOutputStream (java.io.FileOutputStream)3 Map (java.util.Map)3 TransformerConfigurationException (javax.xml.transform.TransformerConfigurationException)3