Search in sources :

Example 26 with StartElement

use of javax.xml.stream.events.StartElement in project uPortal by Jasig.

the class StAXSerializingComponentTest method testSerializing.

@Test
public void testSerializing() throws Exception {
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final MockHttpServletResponse response = new MockHttpServletResponse();
    final IPortletWindowRegistry portletWindowRegistry = mock(IPortletWindowRegistry.class);
    when(xmlUtilities.getHtmlOutputFactory()).thenReturn(XMLOutputFactory.newFactory());
    //Setup a simple pass-through parent
    staxSerializingComponent.setWrappedComponent(new SimpleStAXSource());
    staxSerializingComponent.setXmlUtilities(xmlUtilities);
    final IPortletWindow portletWindow = mock(IPortletWindow.class);
    when(portletWindowRegistry.getPortletWindow(Matchers.eq(request), Matchers.any(StartElement.class))).thenReturn(new Tuple<IPortletWindow, StartElement>(portletWindow, null));
    when(portletWindowRegistry.getOrCreateDefaultPortletWindowByLayoutNodeId(Matchers.eq(request), Matchers.anyString())).thenReturn(portletWindow);
    final PortletContentPlaceholderEventSource contentPlaceholderEventSource = new PortletContentPlaceholderEventSource();
    contentPlaceholderEventSource.setPortletWindowRegistry(portletWindowRegistry);
    final PortletHeaderPlaceholderEventSource headerPlaceholderEventSource = new PortletHeaderPlaceholderEventSource();
    headerPlaceholderEventSource.setPortletWindowRegistry(portletWindowRegistry);
    final PortletTitlePlaceholderEventSource portletTitlePlaceholderEventSource = new PortletTitlePlaceholderEventSource();
    portletTitlePlaceholderEventSource.setPortletWindowRegistry(portletWindowRegistry);
    final PortletHelpPlaceholderEventSource portletHelpPlaceholderEventSource = new PortletHelpPlaceholderEventSource();
    portletHelpPlaceholderEventSource.setPortletWindowRegistry(portletWindowRegistry);
    final Map<String, CharacterEventSource> chunkingElements = new LinkedHashMap<String, CharacterEventSource>();
    chunkingElements.put("portlet", contentPlaceholderEventSource);
    chunkingElements.put("portlet-header", headerPlaceholderEventSource);
    staxSerializingComponent.setChunkingElements(chunkingElements);
    final Map<String, CharacterEventSource> chunkingPatterns = new LinkedHashMap<String, CharacterEventSource>();
    chunkingPatterns.put("\\{up-portlet-title\\(([^\\)]+)\\)\\}", portletTitlePlaceholderEventSource);
    chunkingPatterns.put("\\{up-portlet-help\\(([^\\)]+)\\)\\}", portletHelpPlaceholderEventSource);
    staxSerializingComponent.setChunkingPatterns(chunkingPatterns);
    final PipelineEventReader<CharacterEventReader, CharacterEvent> eventReader = staxSerializingComponent.getEventReader(request, response);
    //Expected events structure, leaving the data out to make it at least a little simpler
    final List<? extends CharacterEvent> expectedEvents = this.getExpectedEvents();
    final Iterator<CharacterEvent> eventItr = eventReader.iterator();
    final Iterator<? extends CharacterEvent> expectedEventsItr = expectedEvents.iterator();
    int eventCount = 0;
    while (expectedEventsItr.hasNext()) {
        eventCount++;
        assertTrue("The number of events returned by the eventReader less than the expected event count of: " + expectedEvents.size() + " was: " + eventCount, eventItr.hasNext());
        final CharacterEvent expectedEvent = expectedEventsItr.next();
        final CharacterEvent event = eventItr.next();
        assertEquals("Events at index " + eventCount + " do not match\n" + expectedEvent + "\n" + event, expectedEvent, event);
    }
    assertFalse("The number of events returned by the eventReader is more than the expected event count of: " + expectedEvents.size(), eventItr.hasNext());
}
Also used : PortletHeaderPlaceholderEventSource(org.apereo.portal.character.stream.PortletHeaderPlaceholderEventSource) IPortletWindowRegistry(org.apereo.portal.portlet.registry.IPortletWindowRegistry) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) IPortletWindow(org.apereo.portal.portlet.om.IPortletWindow) LinkedHashMap(java.util.LinkedHashMap) StartElement(javax.xml.stream.events.StartElement) CharacterEventReader(org.apereo.portal.character.stream.CharacterEventReader) PortletHelpPlaceholderEventSource(org.apereo.portal.character.stream.PortletHelpPlaceholderEventSource) CharacterEvent(org.apereo.portal.character.stream.events.CharacterEvent) PortletTitlePlaceholderEventSource(org.apereo.portal.character.stream.PortletTitlePlaceholderEventSource) CharacterEventSource(org.apereo.portal.character.stream.CharacterEventSource) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) PortletContentPlaceholderEventSource(org.apereo.portal.character.stream.PortletContentPlaceholderEventSource) Test(org.junit.Test)

Example 27 with StartElement

use of javax.xml.stream.events.StartElement in project uPortal by Jasig.

the class TransientUserLayoutXMLEventReader method getAdditionalEvents.

/**
     * Examines the current token and when appropriate creates and returns dynamically created
     * content. If dynamic content is not created, return null.
     *
     * @param event The current event
     * @return Dynamic content to inject into document, else null if no additional dynamic content
     *     was created.
     */
@Override
protected Deque<XMLEvent> getAdditionalEvents(XMLEvent event) {
    if (event.isStartElement()) {
        final StartElement startElement = event.asStartElement();
        //All following logic requires an ID attribute, ignore any element without one
        final Attribute idAttribute = startElement.getAttributeByName(IUserLayoutManager.ID_ATTR_NAME);
        if (idAttribute == null) {
            return null;
        }
        // Create and return a transient (dynamically created) folder that includes a transient channel
        // if we are processing the tart element of the root node
        // iff the subscribeId is present and describes a transient channel and not a regular layout channel.
        final String subscribeId = this.userLayoutManager.getFocusedId();
        if (this.rootFolderId.equals(idAttribute.getValue()) && subscribeId != null && !subscribeId.equals("") && this.userLayoutManager.isTransientChannel(subscribeId)) {
            IPortletDefinition chanDef = null;
            try {
                chanDef = this.userLayoutManager.getChannelDefinition(subscribeId);
            } catch (Exception e) {
                logger.error("Could not obtain IChannelDefinition for subscribe id: {}", subscribeId, e);
            }
            if (chanDef != null) {
                final QName name = startElement.getName();
                final String namespaceURI = name.getNamespaceURI();
                final String prefix = name.getPrefix();
                final Deque<XMLEvent> transientEventBuffer = new LinkedList<XMLEvent>();
                final Collection<Attribute> transientFolderAttributes = new LinkedList<Attribute>();
                transientFolderAttributes.add(EVENT_FACTORY.createAttribute("ID", TransientUserLayoutManagerWrapper.TRANSIENT_FOLDER_ID));
                transientFolderAttributes.add(EVENT_FACTORY.createAttribute("name", chanDef != null ? chanDef.getTitle() : "Temporary"));
                transientFolderAttributes.add(EVENT_FACTORY.createAttribute("type", "regular"));
                transientFolderAttributes.add(EVENT_FACTORY.createAttribute("hidden", "false"));
                transientFolderAttributes.add(EVENT_FACTORY.createAttribute("unremovable", "true"));
                transientFolderAttributes.add(EVENT_FACTORY.createAttribute("immutable", "true"));
                transientFolderAttributes.add(EVENT_FACTORY.createAttribute("unremovable", "true"));
                transientFolderAttributes.add(EVENT_FACTORY.createAttribute("dlm:addChildAllowed", "false"));
                transientFolderAttributes.add(EVENT_FACTORY.createAttribute("dlm:deleteAllowed", "false"));
                transientFolderAttributes.add(EVENT_FACTORY.createAttribute("dlm:editAllowed", "false"));
                transientFolderAttributes.add(EVENT_FACTORY.createAttribute("dlm:moveAllowed", "false"));
                transientFolderAttributes.add(EVENT_FACTORY.createAttribute("dlm:precedence", "100.0"));
                transientFolderAttributes.add(EVENT_FACTORY.createAttribute("transient", "true"));
                final StartElement transientFolder = EVENT_FACTORY.createStartElement(prefix, namespaceURI, IUserLayoutManager.FOLDER, transientFolderAttributes.iterator(), null);
                transientEventBuffer.add(transientFolder);
                //TODO Move IChannelDefinition/IPortletDefinition -> StAX events code somewhere reusable
                final Collection<Attribute> channelAttrs = new LinkedList<Attribute>();
                channelAttrs.add(EVENT_FACTORY.createAttribute("ID", subscribeId));
                channelAttrs.add(EVENT_FACTORY.createAttribute("typeID", Integer.toString(chanDef.getType().getId())));
                channelAttrs.add(EVENT_FACTORY.createAttribute("hidden", "false"));
                channelAttrs.add(EVENT_FACTORY.createAttribute("unremovable", "true"));
                channelAttrs.add(EVENT_FACTORY.createAttribute("dlm:deleteAllowed", "false"));
                channelAttrs.add(EVENT_FACTORY.createAttribute("dlm:moveAllowed", "false"));
                channelAttrs.add(EVENT_FACTORY.createAttribute("name", chanDef.getName()));
                channelAttrs.add(EVENT_FACTORY.createAttribute("description", chanDef.getDescription()));
                channelAttrs.add(EVENT_FACTORY.createAttribute("title", chanDef.getTitle()));
                channelAttrs.add(EVENT_FACTORY.createAttribute("chanID", chanDef.getPortletDefinitionId().getStringId()));
                channelAttrs.add(EVENT_FACTORY.createAttribute("fname", chanDef.getFName()));
                channelAttrs.add(EVENT_FACTORY.createAttribute("timeout", Integer.toString(chanDef.getTimeout())));
                channelAttrs.add(EVENT_FACTORY.createAttribute("transient", "true"));
                final StartElement startChannel = EVENT_FACTORY.createStartElement(prefix, namespaceURI, IUserLayoutManager.CHANNEL, channelAttrs.iterator(), null);
                transientEventBuffer.offer(startChannel);
                // add channel parameter elements
                for (final IPortletDefinitionParameter parm : chanDef.getParameters()) {
                    final Collection<Attribute> parameterAttrs = new LinkedList<Attribute>();
                    parameterAttrs.add(EVENT_FACTORY.createAttribute("name", parm.getName()));
                    parameterAttrs.add(EVENT_FACTORY.createAttribute("value", parm.getValue()));
                    final StartElement startParameter = EVENT_FACTORY.createStartElement(prefix, namespaceURI, IUserLayoutManager.PARAMETER, parameterAttrs.iterator(), null);
                    transientEventBuffer.offer(startParameter);
                    final EndElement endParameter = EVENT_FACTORY.createEndElement(prefix, namespaceURI, IUserLayoutManager.PARAMETER, null);
                    transientEventBuffer.offer(endParameter);
                }
                final EndElement endChannel = EVENT_FACTORY.createEndElement(prefix, namespaceURI, IUserLayoutManager.CHANNEL, null);
                transientEventBuffer.offer(endChannel);
                final EndElement endFolder = EVENT_FACTORY.createEndElement(prefix, namespaceURI, IUserLayoutManager.FOLDER, null);
                transientEventBuffer.offer(endFolder);
                return transientEventBuffer;
            } else {
                // I don't think subscribeId could be null, but log warning if so.
                logger.warn("Unable to resolve portlet definition for subscribe ID {}", subscribeId);
            }
        }
    }
    return null;
}
Also used : StartElement(javax.xml.stream.events.StartElement) Attribute(javax.xml.stream.events.Attribute) EndElement(javax.xml.stream.events.EndElement) QName(javax.xml.namespace.QName) IPortletDefinitionParameter(org.apereo.portal.portlet.om.IPortletDefinitionParameter) XMLEvent(javax.xml.stream.events.XMLEvent) LinkedList(java.util.LinkedList) IPortletDefinition(org.apereo.portal.portlet.om.IPortletDefinition)

Example 28 with StartElement

use of javax.xml.stream.events.StartElement in project poi by apache.

the class DrawSimpleShape method getCustomGeometry.

protected static CustomGeometry getCustomGeometry(String name, Graphics2D graphics) {
    @SuppressWarnings("unchecked") Map<String, CustomGeometry> presets = (graphics == null) ? null : (Map<String, CustomGeometry>) graphics.getRenderingHint(Drawable.PRESET_GEOMETRY_CACHE);
    if (presets == null) {
        presets = new HashMap<String, CustomGeometry>();
        if (graphics != null) {
            graphics.setRenderingHint(Drawable.PRESET_GEOMETRY_CACHE, presets);
        }
        String packageName = "org.apache.poi.sl.draw.binding";
        InputStream presetIS = Drawable.class.getResourceAsStream("presetShapeDefinitions.xml");
        // StAX:
        EventFilter startElementFilter = new EventFilter() {

            @Override
            public boolean accept(XMLEvent event) {
                return event.isStartElement();
            }
        };
        try {
            XMLInputFactory staxFactory = XMLInputFactory.newInstance();
            XMLEventReader staxReader = staxFactory.createXMLEventReader(presetIS);
            XMLEventReader staxFiltRd = staxFactory.createFilteredReader(staxReader, startElementFilter);
            // Ignore StartElement:
            staxFiltRd.nextEvent();
            // JAXB:
            JAXBContext jaxbContext = JAXBContext.newInstance(packageName);
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            while (staxFiltRd.peek() != null) {
                StartElement evRoot = (StartElement) staxFiltRd.peek();
                String cusName = evRoot.getName().getLocalPart();
                // XMLEvent ev = staxReader.nextEvent();
                JAXBElement<org.apache.poi.sl.draw.binding.CTCustomGeometry2D> el = unmarshaller.unmarshal(staxReader, CTCustomGeometry2D.class);
                CTCustomGeometry2D cusGeom = el.getValue();
                presets.put(cusName, new CustomGeometry(cusGeom));
            }
            staxFiltRd.close();
            staxReader.close();
        } catch (Exception e) {
            throw new RuntimeException("Unable to load preset geometries.", e);
        } finally {
            IOUtils.closeQuietly(presetIS);
        }
    }
    return presets.get(name);
}
Also used : InputStream(java.io.InputStream) CTCustomGeometry2D(org.apache.poi.sl.draw.binding.CTCustomGeometry2D) JAXBContext(javax.xml.bind.JAXBContext) EventFilter(javax.xml.stream.EventFilter) StartElement(javax.xml.stream.events.StartElement) XMLEvent(javax.xml.stream.events.XMLEvent) XMLEventReader(javax.xml.stream.XMLEventReader) CustomGeometry(org.apache.poi.sl.draw.geom.CustomGeometry) Unmarshaller(javax.xml.bind.Unmarshaller) XMLInputFactory(javax.xml.stream.XMLInputFactory)

Example 29 with StartElement

use of javax.xml.stream.events.StartElement in project poi by apache.

the class PresetGeometries method init.

@SuppressWarnings("unused")
public void init(InputStream is) throws XMLStreamException, JAXBException {
    // StAX:
    EventFilter startElementFilter = new EventFilter() {

        @Override
        public boolean accept(XMLEvent event) {
            return event.isStartElement();
        }
    };
    XMLInputFactory staxFactory = XMLInputFactory.newFactory();
    XMLEventReader staxReader = staxFactory.createXMLEventReader(is);
    XMLEventReader staxFiltRd = staxFactory.createFilteredReader(staxReader, startElementFilter);
    // ignore StartElement:
    /* XMLEvent evDoc = */
    staxFiltRd.nextEvent();
    // JAXB:
    JAXBContext jaxbContext = JAXBContext.newInstance(BINDING_PACKAGE);
    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
    long cntElem = 0;
    while (staxFiltRd.peek() != null) {
        StartElement evRoot = (StartElement) staxFiltRd.peek();
        String name = evRoot.getName().getLocalPart();
        JAXBElement<CTCustomGeometry2D> el = unmarshaller.unmarshal(staxReader, CTCustomGeometry2D.class);
        CTCustomGeometry2D cus = el.getValue();
        cntElem++;
        if (containsKey(name)) {
            LOG.log(POILogger.WARN, "Duplicate definition of " + name);
        }
        put(name, new CustomGeometry(cus));
    }
}
Also used : StartElement(javax.xml.stream.events.StartElement) CTCustomGeometry2D(org.apache.poi.sl.draw.binding.CTCustomGeometry2D) XMLEvent(javax.xml.stream.events.XMLEvent) XMLEventReader(javax.xml.stream.XMLEventReader) JAXBContext(javax.xml.bind.JAXBContext) Unmarshaller(javax.xml.bind.Unmarshaller) EventFilter(javax.xml.stream.EventFilter) XMLInputFactory(javax.xml.stream.XMLInputFactory)

Example 30 with StartElement

use of javax.xml.stream.events.StartElement in project tomee by apache.

the class StaxCompare method compare.

public static boolean compare(final XMLEventReader a, final XMLEventReader b, final StringBuilder message) {
    XMLEvent eventA;
    XMLEvent eventB;
    int eventType;
    try {
        while ((eventA = nextInterestingEvent(a)) != null & (eventB = nextInterestingEvent(b)) != null) {
            if ((eventType = eventA.getEventType()) != eventB.getEventType()) {
                message.append("events of different types: ").append(eventA).append(", ").append(eventB);
                return false;
            }
            if (eventType == XMLStreamConstants.START_ELEMENT) {
                final StartElement startA = eventA.asStartElement();
                final StartElement startB = eventB.asStartElement();
                if (!startA.getName().getLocalPart().equals(startB.getName().getLocalPart())) {
                    message.append("Different elements ").append(startA.getName()).append(", ").append(startB.getName()).append(" at location ").append(eventA.getLocation());
                    return false;
                }
            } else if (eventType == XMLStreamConstants.END_ELEMENT) {
                final EndElement endA = eventA.asEndElement();
                final EndElement endB = eventB.asEndElement();
                if (!endA.getName().getLocalPart().equals(endB.getName().getLocalPart())) {
                    message.append("Different elements ").append(endA.getName()).append(", ").append(endB.getName()).append(" at location ").append(eventA.getLocation());
                    return false;
                }
            } else if (eventType == XMLStreamConstants.CHARACTERS) {
                final Characters endA = eventA.asCharacters();
                final Characters endB = eventB.asCharacters();
                if (!endA.getData().equals(endB.getData())) {
                    message.append("Different content ").append(endA.getData()).append(", ").append(endB.getData()).append(" at location ").append(eventA.getLocation());
                    return false;
                }
            }
        }
        if (eventA != null) {
            message.append("A is longer: ").append(eventA.getLocation());
            return false;
        }
        if (eventB != null) {
            message.append("B is longer: ").append(eventB.getLocation());
            return false;
        }
    } catch (final XMLStreamException e) {
        message.append("Exception processing ").append(e.getMessage());
        return false;
    }
    return true;
}
Also used : StartElement(javax.xml.stream.events.StartElement) XMLStreamException(javax.xml.stream.XMLStreamException) EndElement(javax.xml.stream.events.EndElement) Characters(javax.xml.stream.events.Characters) XMLEvent(javax.xml.stream.events.XMLEvent)

Aggregations

StartElement (javax.xml.stream.events.StartElement)30 XMLEvent (javax.xml.stream.events.XMLEvent)20 QName (javax.xml.namespace.QName)11 XMLEventReader (javax.xml.stream.XMLEventReader)10 XMLStreamException (javax.xml.stream.XMLStreamException)9 Attribute (javax.xml.stream.events.Attribute)8 EndElement (javax.xml.stream.events.EndElement)8 XMLInputFactory (javax.xml.stream.XMLInputFactory)7 IOException (java.io.IOException)4 ArrayList (java.util.ArrayList)4 InputStream (java.io.InputStream)3 LinkedList (java.util.LinkedList)3 JAXBContext (javax.xml.bind.JAXBContext)3 Unmarshaller (javax.xml.bind.Unmarshaller)3 EventFilter (javax.xml.stream.EventFilter)3 Characters (javax.xml.stream.events.Characters)3 IPortletWindow (org.apereo.portal.portlet.om.IPortletWindow)3 AbstractGCEvent (com.tagtraum.perf.gcviewer.model.AbstractGCEvent)2 GCEvent (com.tagtraum.perf.gcviewer.model.GCEvent)2 BufferedInputStream (java.io.BufferedInputStream)2