Search in sources :

Example 96 with Source

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

the class ExportTestResultsAction method getOutputText.

@Nullable
private String getOutputText(ExportTestResultsConfiguration config) throws IOException, TransformerException, SAXException {
    ExportTestResultsConfiguration.ExportFormat exportFormat = config.getExportFormat();
    SAXTransformerFactory transformerFactory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
    TransformerHandler handler;
    if (exportFormat == ExportTestResultsConfiguration.ExportFormat.Xml) {
        handler = transformerFactory.newTransformerHandler();
        handler.getTransformer().setOutputProperty(OutputKeys.INDENT, "yes");
        handler.getTransformer().setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
    } else {
        Source xslSource;
        if (config.getExportFormat() == ExportTestResultsConfiguration.ExportFormat.BundledTemplate) {
            URL bundledXsltUrl = getClass().getResource("intellij-export.xsl");
            xslSource = new StreamSource(URLUtil.openStream(bundledXsltUrl));
        } else {
            File xslFile = new File(config.getUserTemplatePath());
            if (!xslFile.isFile()) {
                showBalloon(myRunConfiguration.getProject(), MessageType.ERROR, ExecutionBundle.message("export.test.results.custom.template.not.found", xslFile.getPath()), null);
                return null;
            }
            xslSource = new StreamSource(xslFile);
        }
        handler = transformerFactory.newTransformerHandler(xslSource);
        handler.getTransformer().setParameter("TITLE", ExecutionBundle.message("export.test.results.filename", myRunConfiguration.getName(), myRunConfiguration.getType().getDisplayName()));
    }
    StringWriter w = new StringWriter();
    handler.setResult(new StreamResult(w));
    try {
        TestResultsXmlFormatter.execute(myModel.getRoot(), myRunConfiguration, myModel.getProperties(), handler);
    } catch (ProcessCanceledException e) {
        return null;
    }
    return w.toString();
}
Also used : TransformerHandler(javax.xml.transform.sax.TransformerHandler) StringWriter(java.io.StringWriter) StreamResult(javax.xml.transform.stream.StreamResult) StreamSource(javax.xml.transform.stream.StreamSource) SAXTransformerFactory(javax.xml.transform.sax.SAXTransformerFactory) VirtualFile(com.intellij.openapi.vfs.VirtualFile) File(java.io.File) StreamSource(javax.xml.transform.stream.StreamSource) Source(javax.xml.transform.Source) URL(java.net.URL) Nullable(org.jetbrains.annotations.Nullable)

Example 97 with Source

use of javax.xml.transform.Source in project uPortal by Jasig.

the class XSLTComponent method getEventReader.

/* (non-Javadoc)
     * @see org.apereo.portal.rendering.StAXPipelineComponent#getXmlStreamReader(java.lang.Object, java.lang.Object)
     */
@Override
public PipelineEventReader<XMLEventReader, XMLEvent> getEventReader(HttpServletRequest request, HttpServletResponse response) {
    final PipelineEventReader<XMLEventReader, XMLEvent> pipelineEventReader = this.wrappedComponent.getEventReader(request, response);
    final Transformer transformer = this.transformerSource.getTransformer(request, response);
    //Setup a URIResolver based on the current resource loader
    transformer.setURIResolver(this.uriResolver);
    //Configure the Transformer via injected class
    if (this.xsltParameterSource != null) {
        final Map<String, Object> transformerParameters = this.xsltParameterSource.getParameters(request, response);
        if (transformerParameters != null) {
            this.logger.debug("{} - Setting Transformer Parameters: ", this.beanName, transformerParameters);
            for (final Map.Entry<String, Object> transformerParametersEntry : transformerParameters.entrySet()) {
                final String name = transformerParametersEntry.getKey();
                final Object value = transformerParametersEntry.getValue();
                if (value != null) {
                    transformer.setParameter(name, value);
                }
            }
        }
        final Properties outputProperties = this.xsltParameterSource.getOutputProperties(request, response);
        if (outputProperties != null) {
            this.logger.debug("{} - Setting Transformer Output Properties: ", this.beanName, outputProperties);
            transformer.setOutputProperties(outputProperties);
        }
    }
    //The event reader from the previous component in the pipeline
    final XMLEventReader eventReader = pipelineEventReader.getEventReader();
    //Wrap the event reader in a stream reader to avoid a JDK bug
    final XMLStreamReader streamReader;
    try {
        streamReader = new FixedXMLEventStreamReader(eventReader);
    } catch (XMLStreamException e) {
        throw new RuntimeException("Failed to create XMLStreamReader from XMLEventReader", e);
    }
    final Source xmlReaderSource = new StAXSource(streamReader);
    //Setup logging for the transform
    transformer.setErrorListener(this.errorListener);
    //Transform to a SAX ContentHandler to avoid JDK bug: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6775588
    final XMLEventBufferWriter eventWriterBuffer = new XMLEventBufferWriter();
    final ContentHandler contentHandler = StaxUtils.createLexicalContentHandler(eventWriterBuffer);
    contentHandler.setDocumentLocator(new LocatorImpl());
    final SAXResult outputTarget = new SAXResult(contentHandler);
    try {
        this.logger.debug("{} - Begining XML Transformation", this.beanName);
        transformer.transform(xmlReaderSource, outputTarget);
        this.logger.debug("{} - XML Transformation complete", this.beanName);
    } catch (TransformerException e) {
        throw new RuntimeException("Failed to transform document", e);
    }
    final String mediaType = transformer.getOutputProperty(OutputKeys.MEDIA_TYPE);
    final List<XMLEvent> eventBuffer = eventWriterBuffer.getEventBuffer();
    final XMLEventReader outputEventReader = new XMLEventBufferReader(eventBuffer.listIterator());
    final Map<String, String> outputProperties = pipelineEventReader.getOutputProperties();
    final PipelineEventReaderImpl<XMLEventReader, XMLEvent> pipelineEventReaderImpl = new PipelineEventReaderImpl<XMLEventReader, XMLEvent>(outputEventReader, outputProperties);
    pipelineEventReaderImpl.setOutputProperty(OutputKeys.MEDIA_TYPE, mediaType);
    return pipelineEventReaderImpl;
}
Also used : XMLEventBufferWriter(org.apereo.portal.xml.stream.XMLEventBufferWriter) Transformer(javax.xml.transform.Transformer) XMLStreamReader(javax.xml.stream.XMLStreamReader) FixedXMLEventStreamReader(org.springframework.util.xml.FixedXMLEventStreamReader) Properties(java.util.Properties) Source(javax.xml.transform.Source) StAXSource(javax.xml.transform.stax.StAXSource) ContentHandler(org.xml.sax.ContentHandler) XMLEventReader(javax.xml.stream.XMLEventReader) LocatorImpl(org.xml.sax.helpers.LocatorImpl) TransformerException(javax.xml.transform.TransformerException) StAXSource(javax.xml.transform.stax.StAXSource) XMLStreamException(javax.xml.stream.XMLStreamException) SAXResult(javax.xml.transform.sax.SAXResult) XMLEventBufferReader(org.apereo.portal.xml.stream.XMLEventBufferReader) PipelineEventReaderImpl(org.apereo.portal.rendering.PipelineEventReaderImpl) XMLEvent(javax.xml.stream.events.XMLEvent) Map(java.util.Map)

Example 98 with Source

use of javax.xml.transform.Source in project uPortal by Jasig.

the class BaseXsltDataUpgraderTest method loadSchema.

private Schema loadSchema(Resource[] resources, String schemaLanguage) throws IOException, SAXException {
    Assert.notEmpty(resources, "No resources given");
    Assert.hasLength(schemaLanguage, "No schema language provided");
    Source[] schemaSources = new Source[resources.length];
    XMLReader xmlReader = XMLReaderFactory.createXMLReader();
    xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
    for (int i = 0; i < resources.length; i++) {
        Assert.notNull(resources[i], "Resource is null");
        Assert.isTrue(resources[i].exists(), "Resource " + resources[i] + " does not exist");
        InputSource inputSource = SaxResourceUtils.createInputSource(resources[i]);
        schemaSources[i] = new SAXSource(xmlReader, inputSource);
    }
    SchemaFactory schemaFactory = SchemaFactory.newInstance(schemaLanguage);
    return schemaFactory.newSchema(schemaSources);
}
Also used : SchemaFactory(javax.xml.validation.SchemaFactory) InputSource(org.xml.sax.InputSource) SAXSource(javax.xml.transform.sax.SAXSource) DOMSource(javax.xml.transform.dom.DOMSource) StreamSource(javax.xml.transform.stream.StreamSource) Source(javax.xml.transform.Source) InputSource(org.xml.sax.InputSource) SAXSource(javax.xml.transform.sax.SAXSource) XMLReader(org.xml.sax.XMLReader)

Example 99 with Source

use of javax.xml.transform.Source in project uPortal by Jasig.

the class SitemapTest method testStylesheetCompilation.

@Test
public void testStylesheetCompilation() throws IOException {
    final MockHttpServletRequest request = new MockHttpServletRequest();
    Resource resource = new ClassPathResource(STYLESHEET_LOCATION);
    Source source = new StreamSource(resource.getInputStream(), resource.getURI().toASCIIString());
    try {
        Transformer transformer = TransformerFactory.newInstance().newTransformer(source);
        transformer.setParameter(SitemapPortletController.USE_TAB_GROUPS, useTabGroups);
        transformer.setParameter(SitemapPortletController.USER_LANG, "en_US");
        transformer.setParameter(XsltPortalUrlProvider.CURRENT_REQUEST, request);
        transformer.setParameter(XsltPortalUrlProvider.XSLT_PORTAL_URL_PROVIDER, this.xsltPortalUrlProvider);
        Source xmlSource = new StreamSource(new ClassPathResource(XML_LOCATION).getFile());
        CharArrayWriter buffer = new CharArrayWriter();
        TransformerUtils.enableIndenting(transformer);
        transformer.transform(xmlSource, new StreamResult(buffer));
        if (logger.isTraceEnabled()) {
            logger.trace("XML: " + new String(buffer.toCharArray()));
        }
    } catch (TransformerConfigurationException e) {
        logger.error(e.getMessage(), e);
        throw new RuntimeException(e);
    } catch (TransformerException e) {
        logger.error(e.getMessage(), e);
        throw new RuntimeException(e);
    }
}
Also used : Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) StreamSource(javax.xml.transform.stream.StreamSource) ClassPathResource(org.springframework.core.io.ClassPathResource) Resource(org.springframework.core.io.Resource) ClassPathResource(org.springframework.core.io.ClassPathResource) StreamSource(javax.xml.transform.stream.StreamSource) Source(javax.xml.transform.Source) MessageSource(org.springframework.context.MessageSource) StaticMessageSource(org.springframework.context.support.StaticMessageSource) CharArrayWriter(java.io.CharArrayWriter) TransformerException(javax.xml.transform.TransformerException) Test(org.junit.Test)

Example 100 with Source

use of javax.xml.transform.Source in project uPortal by Jasig.

the class TemplateDataTenantOperationsListener method importQueue.

/** Imports the specified entities in the proper order. */
private void importQueue(final ITenant tenant, final Map<PortalDataKey, Set<BucketTuple>> queue, final StringBuilder importReport) throws Exception {
    final StandardEvaluationContext ctx = new StandardEvaluationContext();
    ctx.setRootObject(new RootObjectImpl(tenant));
    IDataTemplatingStrategy templating = new SpELDataTemplatingStrategy(portalSpELService, ctx);
    Document doc = null;
    try {
        for (PortalDataKey pdk : dataKeyImportOrder) {
            Set<BucketTuple> bucket = queue.get(pdk);
            if (bucket != null) {
                log.debug("Importing the specified PortalDataKey tenant '{}':  {}", tenant.getName(), pdk.getName());
                for (BucketTuple tuple : bucket) {
                    doc = tuple.getDocument();
                    Source data = templating.processTemplates(doc, tuple.getResource().getURL().toString());
                    dataHandlerService.importData(data, pdk);
                    importReport.append(createImportReportLineItem(pdk, tuple));
                }
            }
        }
    } catch (Exception e) {
        log.error("Failed to process the specified template document:\n{}", (doc != null ? doc.asXML() : "null"), e);
        throw e;
    }
}
Also used : StandardEvaluationContext(org.springframework.expression.spel.support.StandardEvaluationContext) SpELDataTemplatingStrategy(org.apereo.portal.io.xml.SpELDataTemplatingStrategy) IDataTemplatingStrategy(org.apereo.portal.io.xml.IDataTemplatingStrategy) PortalDataKey(org.apereo.portal.io.xml.PortalDataKey) Document(org.dom4j.Document) Source(javax.xml.transform.Source) URISyntaxException(java.net.URISyntaxException)

Aggregations

Source (javax.xml.transform.Source)238 StreamSource (javax.xml.transform.stream.StreamSource)161 DOMSource (javax.xml.transform.dom.DOMSource)108 Transformer (javax.xml.transform.Transformer)76 StreamResult (javax.xml.transform.stream.StreamResult)74 InputSource (org.xml.sax.InputSource)67 SAXSource (javax.xml.transform.sax.SAXSource)56 StringReader (java.io.StringReader)52 IOException (java.io.IOException)46 TransformerException (javax.xml.transform.TransformerException)45 Result (javax.xml.transform.Result)42 TransformerFactory (javax.xml.transform.TransformerFactory)41 Test (org.junit.Test)39 StringWriter (java.io.StringWriter)35 InputStream (java.io.InputStream)32 SAXException (org.xml.sax.SAXException)32 Schema (javax.xml.validation.Schema)29 Validator (javax.xml.validation.Validator)29 SchemaFactory (javax.xml.validation.SchemaFactory)28 ByteArrayInputStream (java.io.ByteArrayInputStream)26