Search in sources :

Example 31 with XMLEventReader

use of javax.xml.stream.XMLEventReader 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.createContentHandler(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 32 with XMLEventReader

use of javax.xml.stream.XMLEventReader in project uPortal by Jasig.

the class ChunkingEventReader method tryChunking.

private XMLEvent tryChunking(StartElement startElement) throws XMLStreamException {
    QName elementName = startElement.getName();
    CharacterEventSource characterEventSource = this.chunkingElements.get(elementName.getLocalPart());
    while (characterEventSource != null) {
        final XMLEvent previousEvent = this.getPreviousEvent();
        if (previousEvent != null && previousEvent.isStartElement()) {
            this.captureEvent = startElement;
            // It is left open since ATTRIBUTE events can follow a START_ELEMENT event.
            return EVENT_FACTORY.createCharacters("");
        }
        // Capture the characters written out to this point then clear the buffer
        this.captureCharacterDataEvent();
        // Get the generated events for the element
        final XMLEventReader parent = this.getParent();
        characterEventSource.generateCharacterEvents(this.request, parent, startElement, this.characterEvents);
        // Read the next event off the reader
        final XMLEvent nextEvent = parent.nextEvent();
        if (nextEvent.isStartElement()) {
            startElement = nextEvent.asStartElement();
            elementName = startElement.getName();
            characterEventSource = this.chunkingElements.get(elementName.getLocalPart());
        } else {
            return nextEvent;
        }
    }
    return startElement;
}
Also used : QName(javax.xml.namespace.QName) XMLEvent(javax.xml.stream.events.XMLEvent) XMLEventReader(javax.xml.stream.XMLEventReader) CharacterEventSource(org.apereo.portal.character.stream.CharacterEventSource)

Example 33 with XMLEventReader

use of javax.xml.stream.XMLEventReader in project uPortal by Jasig.

the class WindowStateSettingsStAXComponent method getEventReader.

/* (non-Javadoc)
     * @see org.apereo.portal.rendering.PipelineComponent#getEventReader(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
@Override
public PipelineEventReader<XMLEventReader, XMLEvent> getEventReader(HttpServletRequest request, HttpServletResponse response) {
    final PipelineEventReader<XMLEventReader, XMLEvent> pipelineEventReader = this.wrappedComponent.getEventReader(request, response);
    final XMLEventReader eventReader = pipelineEventReader.getEventReader();
    final IStylesheetDescriptor stylesheetDescriptor = stylesheetAttributeSource.getStylesheetDescriptor(request);
    final IPortalRequestInfo portalRequestInfo = this.urlSyntaxProvider.getPortalRequestInfo(request);
    final XMLEventReader filteredEventReader;
    if (portalRequestInfo.getTargetedPortletWindowId() == null) {
        final IStylesheetParameterDescriptor defaultWindowStateParam = stylesheetDescriptor.getStylesheetParameterDescriptor("dashboardForcedWindowState");
        if (defaultWindowStateParam != null) {
            // Set all window states to the specified default
            final WindowState windowState = PortletUtils.getWindowState(defaultWindowStateParam.getDefaultValue());
            filteredEventReader = new SinglePortletWindowStateSettingXMLEventReader(request, eventReader, windowState);
        } else {
            // Make sure there aren't any portlets in a "targeted" window state
            filteredEventReader = new NonTargetedPortletWindowStateSettingXMLEventReader(request, eventReader);
        }
    } else {
        // Not mobile, don't bother filtering
        filteredEventReader = eventReader;
    }
    final Map<String, String> outputProperties = pipelineEventReader.getOutputProperties();
    return new PipelineEventReaderImpl<XMLEventReader, XMLEvent>(filteredEventReader, outputProperties);
}
Also used : WindowState(javax.portlet.WindowState) IStylesheetParameterDescriptor(org.apereo.portal.layout.om.IStylesheetParameterDescriptor) IPortalRequestInfo(org.apereo.portal.url.IPortalRequestInfo) XMLEvent(javax.xml.stream.events.XMLEvent) XMLEventReader(javax.xml.stream.XMLEventReader) FilteringXMLEventReader(org.apereo.portal.xml.stream.FilteringXMLEventReader) IStylesheetDescriptor(org.apereo.portal.layout.om.IStylesheetDescriptor)

Example 34 with XMLEventReader

use of javax.xml.stream.XMLEventReader in project uPortal by Jasig.

the class BaseXsltDataUpgraderTest method testXsltUpgrade.

protected void testXsltUpgrade(final Resource xslResource, final PortalDataKey dataKey, final Resource inputResource, final Resource expectedResultResource, final Resource xsdResource) throws Exception {
    final XmlUtilities xmlUtilities = new XmlUtilitiesImpl() {

        @Override
        public Templates getTemplates(Resource stylesheet) throws TransformerConfigurationException, IOException {
            final TransformerFactory transformerFactory = TransformerFactory.newInstance();
            return transformerFactory.newTemplates(new StreamSource(stylesheet.getInputStream()));
        }
    };
    final XsltDataUpgrader xsltDataUpgrader = new XsltDataUpgrader();
    xsltDataUpgrader.setPortalDataKey(dataKey);
    xsltDataUpgrader.setXslResource(xslResource);
    xsltDataUpgrader.setXmlUtilities(xmlUtilities);
    xsltDataUpgrader.afterPropertiesSet();
    // Create XmlEventReader (what the JaxbPortalDataHandlerService has)
    final XMLInputFactory xmlInputFactory = xmlUtilities.getXmlInputFactory();
    final XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(inputResource.getInputStream());
    final Node sourceNode = xmlUtilities.convertToDom(xmlEventReader);
    final DOMSource source = new DOMSource(sourceNode);
    final DOMResult result = new DOMResult();
    xsltDataUpgrader.upgradeData(source, result);
    // XSD Validation
    final String resultString = XmlUtilitiesImpl.toString(result.getNode());
    if (xsdResource != null) {
        final Schema schema = this.loadSchema(new Resource[] { xsdResource }, XMLConstants.W3C_XML_SCHEMA_NS_URI);
        final Validator validator = schema.newValidator();
        try {
            validator.validate(new StreamSource(new StringReader(resultString)));
        } catch (Exception e) {
            throw new XmlTestException("Failed to validate XSLT output against provided XSD", resultString, e);
        }
    }
    XMLUnit.setIgnoreWhitespace(true);
    XMLUnit.setNormalizeWhitespace(true);
    try {
        Diff d = new Diff(new InputStreamReader(expectedResultResource.getInputStream()), new StringReader(resultString));
        assertTrue("Upgraded data doesn't match expected data: " + d, d.similar());
    } catch (Exception e) {
        throw new XmlTestException("Failed to assert similar between XSLT output and expected XML", resultString, e);
    } catch (Error e) {
        throw new XmlTestException("Failed to assert similar between XSLT output and expected XML", resultString, e);
    }
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) TransformerFactory(javax.xml.transform.TransformerFactory) DOMResult(javax.xml.transform.dom.DOMResult) InputStreamReader(java.io.InputStreamReader) Diff(org.custommonkey.xmlunit.Diff) StreamSource(javax.xml.transform.stream.StreamSource) Node(org.w3c.dom.Node) Schema(javax.xml.validation.Schema) Resource(org.springframework.core.io.Resource) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) IOException(java.io.IOException) SAXException(org.xml.sax.SAXException) XmlUtilitiesImpl(org.apereo.portal.xml.XmlUtilitiesImpl) XmlUtilities(org.apereo.portal.xml.XmlUtilities) StringReader(java.io.StringReader) XMLEventReader(javax.xml.stream.XMLEventReader) XMLInputFactory(javax.xml.stream.XMLInputFactory) Validator(javax.xml.validation.Validator)

Example 35 with XMLEventReader

use of javax.xml.stream.XMLEventReader in project uPortal by Jasig.

the class AbstractDom4jImporterExporterTest method testDom4jRoundTripWithComment.

@Test
public void testDom4jRoundTripWithComment() throws Exception {
    final TestDom4jImporter importer = new TestDom4jImporter();
    final TestDom4jExporter exporter = new TestDom4jExporter();
    exporter.setXmlUtilities(new XmlUtilitiesImpl());
    final XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
    final InputStream resource = this.getClass().getResourceAsStream("/org/apereo/portal/io/xml/crn/pilot-lo.fragment-layout.xml");
    final XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(resource);
    final Tuple<String, Element> result = importer.unmarshal(new StAXSource(xmlEventReader));
    assertNotNull(result);
    final StringWriter writer = new StringWriter();
    exporter.marshal(result, new StreamResult(writer));
    final String marshalResult = writer.toString();
    assertNotNull(marshalResult);
    XMLUnit.setIgnoreWhitespace(true);
    try {
        Diff d = new Diff(new InputStreamReader(this.getClass().getResourceAsStream("/org/apereo/portal/io/xml/crn/pilot-lo.fragment-layout.xml")), new StringReader(marshalResult));
        assertTrue("Upgraded data doesn't match expected data: " + d, d.similar());
    } catch (Exception e) {
        throw new XmlTestException("Failed to assert similar between marshall output and expected XML", marshalResult, e);
    } catch (Error e) {
        throw new XmlTestException("Failed to assert similar between marshall output and expected XML", marshalResult, e);
    }
}
Also used : StreamResult(javax.xml.transform.stream.StreamResult) InputStreamReader(java.io.InputStreamReader) Diff(org.custommonkey.xmlunit.Diff) InputStream(java.io.InputStream) Element(org.dom4j.Element) StAXSource(javax.xml.transform.stax.StAXSource) XmlTestException(org.apereo.portal.io.xml.XmlTestException) XmlUtilitiesImpl(org.apereo.portal.xml.XmlUtilitiesImpl) StringWriter(java.io.StringWriter) StringReader(java.io.StringReader) XMLEventReader(javax.xml.stream.XMLEventReader) XmlTestException(org.apereo.portal.io.xml.XmlTestException) XMLInputFactory(javax.xml.stream.XMLInputFactory) Test(org.junit.Test)

Aggregations

XMLEventReader (javax.xml.stream.XMLEventReader)71 XMLInputFactory (javax.xml.stream.XMLInputFactory)36 XMLEvent (javax.xml.stream.events.XMLEvent)34 XMLStreamException (javax.xml.stream.XMLStreamException)23 StringReader (java.io.StringReader)18 Test (org.junit.Test)17 InputStream (java.io.InputStream)15 StAXSource (javax.xml.transform.stax.StAXSource)13 StartElement (javax.xml.stream.events.StartElement)12 IOException (java.io.IOException)10 Unmarshaller (javax.xml.bind.Unmarshaller)9 Attribute (javax.xml.stream.events.Attribute)8 ByteArrayInputStream (java.io.ByteArrayInputStream)6 StringWriter (java.io.StringWriter)6 ArrayList (java.util.ArrayList)6 QName (javax.xml.namespace.QName)6 Document (org.w3c.dom.Document)6 ByteArrayOutputStream (java.io.ByteArrayOutputStream)5 InputStreamReader (java.io.InputStreamReader)5 JAXBContext (javax.xml.bind.JAXBContext)5