Search in sources :

Example 11 with XMLEventReader

use of javax.xml.stream.XMLEventReader in project bazel by bazelbuild.

the class AndroidManifestProcessor method writeManifestPackage.

/**
   * Overwrite the package attribute of {@code <manifest>} in an AndroidManifest.xml file.
   *
   * @param manifest The input manifest.
   * @param customPackage The package to write to the manifest.
   * @param output The output manifest to generate.
   * @return The output manifest if generated or the input manifest if no overwriting is required.
   */
/* TODO(apell): switch from custom xml parsing to Gradle merger with NO_PLACEHOLDER_REPLACEMENT
   * set when android common is updated to version 2.5.0.
   */
public Path writeManifestPackage(Path manifest, String customPackage, Path output) {
    if (Strings.isNullOrEmpty(customPackage)) {
        return manifest;
    }
    try {
        Files.createDirectories(output.getParent());
        XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(Files.newInputStream(manifest), UTF_8.name());
        XMLEventWriter writer = XMLOutputFactory.newInstance().createXMLEventWriter(Files.newOutputStream(output), UTF_8.name());
        XMLEventFactory eventFactory = XMLEventFactory.newInstance();
        while (reader.hasNext()) {
            XMLEvent event = reader.nextEvent();
            if (event.isStartElement() && event.asStartElement().getName().toString().equalsIgnoreCase("manifest")) {
                StartElement element = event.asStartElement();
                @SuppressWarnings("unchecked") Iterator<Attribute> attributes = element.getAttributes();
                ImmutableList.Builder<Attribute> newAttributes = ImmutableList.builder();
                while (attributes.hasNext()) {
                    Attribute attr = attributes.next();
                    if (attr.getName().toString().equalsIgnoreCase("package")) {
                        newAttributes.add(eventFactory.createAttribute("package", customPackage));
                    } else {
                        newAttributes.add(attr);
                    }
                }
                writer.add(eventFactory.createStartElement(element.getName(), newAttributes.build().iterator(), element.getNamespaces()));
            } else {
                writer.add(event);
            }
        }
        writer.flush();
    } catch (XMLStreamException | FactoryConfigurationError | IOException e) {
        throw new RuntimeException(e);
    }
    return output;
}
Also used : Attribute(javax.xml.stream.events.Attribute) XMLEventFactory(javax.xml.stream.XMLEventFactory) ImmutableList(com.google.common.collect.ImmutableList) IOException(java.io.IOException) StartElement(javax.xml.stream.events.StartElement) XMLStreamException(javax.xml.stream.XMLStreamException) XMLEventWriter(javax.xml.stream.XMLEventWriter) XMLEvent(javax.xml.stream.events.XMLEvent) XMLEventReader(javax.xml.stream.XMLEventReader) FactoryConfigurationError(javax.xml.stream.FactoryConfigurationError)

Example 12 with XMLEventReader

use of javax.xml.stream.XMLEventReader in project hibernate-orm by hibernate.

the class MappingBinder method doBind.

@Override
protected Binding doBind(XMLEventReader staxEventReader, StartElement rootElementStartEvent, Origin origin) {
    final String rootElementLocalName = rootElementStartEvent.getName().getLocalPart();
    if ("hibernate-mapping".equals(rootElementLocalName)) {
        log.debugf("Performing JAXB binding of hbm.xml document : %s", origin.toString());
        XMLEventReader hbmReader = new HbmEventReader(staxEventReader, xmlEventFactory);
        JaxbHbmHibernateMapping hbmBindings = jaxb(hbmReader, LocalSchema.HBM.getSchema(), hbmJaxbContext(), origin);
        return new Binding<JaxbHbmHibernateMapping>(hbmBindings, origin);
    } else {
        try {
            final XMLEventReader reader = new JpaOrmXmlEventReader(staxEventReader, xmlEventFactory);
            return new Binding<Document>(toDom4jDocument(reader, origin), origin);
        } catch (JpaOrmXmlEventReader.BadVersionException e) {
            throw new UnsupportedOrmXsdVersionException(e.getRequestedVersion(), origin);
        }
    }
}
Also used : Binding(org.hibernate.boot.jaxb.spi.Binding) HbmEventReader(org.hibernate.boot.jaxb.internal.stax.HbmEventReader) XMLEventReader(javax.xml.stream.XMLEventReader) JaxbHbmHibernateMapping(org.hibernate.boot.jaxb.hbm.spi.JaxbHbmHibernateMapping) JpaOrmXmlEventReader(org.hibernate.boot.jaxb.internal.stax.JpaOrmXmlEventReader) UnsupportedOrmXsdVersionException(org.hibernate.boot.UnsupportedOrmXsdVersionException)

Example 13 with XMLEventReader

use of javax.xml.stream.XMLEventReader in project midpoint by Evolveum.

the class MidpointFunctionsImpl method parseXmlToMap.

@Override
public Map<String, String> parseXmlToMap(String xml) {
    Map<String, String> resultingMap = new HashMap<String, String>();
    if (xml != null && !xml.isEmpty()) {
        XMLInputFactory factory = XMLInputFactory.newInstance();
        String value = "";
        String startName = "";
        InputStream stream = new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8));
        boolean isRootElement = true;
        try {
            XMLEventReader eventReader = factory.createXMLEventReader(stream);
            while (eventReader.hasNext()) {
                XMLEvent event = eventReader.nextEvent();
                Integer code = event.getEventType();
                if (code == XMLStreamConstants.START_ELEMENT) {
                    StartElement startElement = event.asStartElement();
                    startName = startElement.getName().getLocalPart();
                    if (!isRootElement) {
                        resultingMap.put(startName, null);
                    } else {
                        isRootElement = false;
                    }
                } else if (code == XMLStreamConstants.CHARACTERS) {
                    Characters characters = event.asCharacters();
                    if (!characters.isWhiteSpace()) {
                        StringBuilder valueBuilder;
                        if (value != null) {
                            valueBuilder = new StringBuilder(value).append(" ").append(characters.getData().toString());
                        } else {
                            valueBuilder = new StringBuilder(characters.getData().toString());
                        }
                        value = valueBuilder.toString();
                    }
                } else if (code == XMLStreamConstants.END_ELEMENT) {
                    EndElement endElement = event.asEndElement();
                    String endName = endElement.getName().getLocalPart();
                    if (endName.equals(startName)) {
                        if (value != null) {
                            resultingMap.put(endName, value);
                            value = null;
                        }
                    } else {
                        LOGGER.trace("No value between xml tags, tag name : {0}", endName);
                    }
                } else if (code == XMLStreamConstants.END_DOCUMENT) {
                    isRootElement = true;
                }
            }
        } catch (XMLStreamException e) {
            StringBuilder error = new StringBuilder("Xml stream exception wile parsing xml string").append(e.getLocalizedMessage());
            throw new SystemException(error.toString());
        }
    } else {
        LOGGER.trace("Input xml string null or empty.");
    }
    return resultingMap;
}
Also used : EndElement(javax.xml.stream.events.EndElement) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Characters(javax.xml.stream.events.Characters) PolyString(com.evolveum.midpoint.prism.polystring.PolyString) StartElement(javax.xml.stream.events.StartElement) XMLStreamException(javax.xml.stream.XMLStreamException) ByteArrayInputStream(java.io.ByteArrayInputStream) XMLEvent(javax.xml.stream.events.XMLEvent) XMLEventReader(javax.xml.stream.XMLEventReader) XMLInputFactory(javax.xml.stream.XMLInputFactory)

Example 14 with XMLEventReader

use of javax.xml.stream.XMLEventReader in project opennms by OpenNMS.

the class HypericAckProcessor method parseHypericAlerts.

/**
     * <p>parseHypericAlerts</p>
     *
     * @param reader a {@link java.io.Reader} object.
     * @return a {@link java.util.List} object.
     * @throws javax.xml.bind.JAXBException if any.
     * @throws javax.xml.stream.XMLStreamException if any.
     */
public static List<HypericAlertStatus> parseHypericAlerts(Reader reader) throws JAXBException, XMLStreamException {
    List<HypericAlertStatus> retval = new ArrayList<HypericAlertStatus>();
    // Instantiate a JAXB context to parse the alert status
    JAXBContext context = JAXBContext.newInstance(new Class[] { HypericAlertStatuses.class, HypericAlertStatus.class });
    XMLInputFactory xmlif = XMLInputFactory.newInstance();
    XMLEventReader xmler = xmlif.createXMLEventReader(reader);
    EventFilter filter = new EventFilter() {

        @Override
        public boolean accept(XMLEvent event) {
            return event.isStartElement();
        }
    };
    XMLEventReader xmlfer = xmlif.createFilteredReader(xmler, filter);
    // Read up until the beginning of the root element
    StartElement startElement = (StartElement) xmlfer.nextEvent();
    // Fetch the root element name for {@link HypericAlertStatus} objects
    String rootElementName = context.createJAXBIntrospector().getElementName(new HypericAlertStatuses()).getLocalPart();
    if (rootElementName.equals(startElement.getName().getLocalPart())) {
        Unmarshaller unmarshaller = context.createUnmarshaller();
        // Use StAX to pull parse the incoming alert statuses
        while (xmlfer.peek() != null) {
            Object object = unmarshaller.unmarshal(xmler);
            if (object instanceof HypericAlertStatus) {
                HypericAlertStatus alertStatus = (HypericAlertStatus) object;
                retval.add(alertStatus);
            }
        }
    } else {
        // Try to pull in the HTTP response to give the user a better idea of what went wrong
        StringBuffer errorContent = new StringBuffer();
        LineNumberReader lineReader = new LineNumberReader(reader);
        try {
            String line;
            while (true) {
                line = lineReader.readLine();
                if (line == null) {
                    break;
                } else {
                    errorContent.append(line.trim());
                }
            }
        } catch (IOException e) {
            errorContent.append("Exception while trying to print out message content: " + e.getMessage());
        }
        // Throw an exception and include the erroneous HTTP response in the exception text
        throw new JAXBException("Found wrong root element in Hyperic XML document, expected: \"" + rootElementName + "\", found \"" + startElement.getName().getLocalPart() + "\"\n" + errorContent.toString());
    }
    return retval;
}
Also used : JAXBException(javax.xml.bind.JAXBException) ArrayList(java.util.ArrayList) JAXBContext(javax.xml.bind.JAXBContext) IOException(java.io.IOException) EventFilter(javax.xml.stream.EventFilter) LineNumberReader(java.io.LineNumberReader) StartElement(javax.xml.stream.events.StartElement) XMLEvent(javax.xml.stream.events.XMLEvent) XMLEventReader(javax.xml.stream.XMLEventReader) Unmarshaller(javax.xml.bind.Unmarshaller) XMLInputFactory(javax.xml.stream.XMLInputFactory)

Example 15 with XMLEventReader

use of javax.xml.stream.XMLEventReader in project voltdb by VoltDB.

the class JDBCSQLXML method createStAXSource.

/**
     * Retrieves a new StAXSource for reading the XML value designated by this
     * SQLXML instance. <p>
     *
     * @param sourceClass The class of the source
     * @throws java.sql.SQLException if there is an error processing the XML
     *      value or if the given <tt>sourceClass</tt> is not supported.
     * @return a new StAXSource for reading the XML value designated by this
     *      SQLXML instance
     */
@SuppressWarnings("unchecked")
protected <T extends Source> T createStAXSource(Class<T> sourceClass) throws SQLException {
    StAXSource source = null;
    Constructor sourceCtor = null;
    Reader reader = null;
    XMLInputFactory factory = null;
    XMLEventReader eventReader = null;
    try {
        factory = XMLInputFactory.newInstance();
    } catch (FactoryConfigurationError ex) {
        throw Exceptions.sourceInstantiation(ex);
    }
    try {
        sourceCtor = (sourceClass == null) ? StAXSource.class.getConstructor(XMLEventReader.class) : sourceClass.getConstructor(XMLEventReader.class);
    } catch (SecurityException ex) {
        throw Exceptions.sourceInstantiation(ex);
    } catch (NoSuchMethodException ex) {
        throw Exceptions.sourceInstantiation(ex);
    }
    reader = getCharacterStreamImpl();
    try {
        eventReader = factory.createXMLEventReader(reader);
    } catch (XMLStreamException ex) {
        throw Exceptions.sourceInstantiation(ex);
    }
    try {
        source = (StAXSource) sourceCtor.newInstance(eventReader);
    } catch (SecurityException ex) {
        throw Exceptions.sourceInstantiation(ex);
    } catch (IllegalArgumentException ex) {
        throw Exceptions.sourceInstantiation(ex);
    } catch (IllegalAccessException ex) {
        throw Exceptions.sourceInstantiation(ex);
    } catch (InstantiationException ex) {
        throw Exceptions.sourceInstantiation(ex);
    } catch (InvocationTargetException ex) {
        throw Exceptions.sourceInstantiation(ex.getTargetException());
    } catch (ClassCastException ex) {
        throw Exceptions.sourceInstantiation(ex);
    }
    return (T) source;
}
Also used : Constructor(java.lang.reflect.Constructor) CharArrayReader(java.io.CharArrayReader) Reader(java.io.Reader) XMLEventReader(javax.xml.stream.XMLEventReader) InputStreamReader(java.io.InputStreamReader) StringReader(java.io.StringReader) StAXSource(javax.xml.transform.stax.StAXSource) InvocationTargetException(java.lang.reflect.InvocationTargetException) XMLStreamException(javax.xml.stream.XMLStreamException) XMLEventReader(javax.xml.stream.XMLEventReader) TransformerFactoryConfigurationError(javax.xml.transform.TransformerFactoryConfigurationError) FactoryConfigurationError(javax.xml.parsers.FactoryConfigurationError) XMLInputFactory(javax.xml.stream.XMLInputFactory)

Aggregations

XMLEventReader (javax.xml.stream.XMLEventReader)62 XMLInputFactory (javax.xml.stream.XMLInputFactory)30 XMLEvent (javax.xml.stream.events.XMLEvent)30 XMLStreamException (javax.xml.stream.XMLStreamException)21 StringReader (java.io.StringReader)18 InputStream (java.io.InputStream)15 Test (org.junit.Test)14 StAXSource (javax.xml.transform.stax.StAXSource)13 StartElement (javax.xml.stream.events.StartElement)10 IOException (java.io.IOException)8 StringWriter (java.io.StringWriter)6 Unmarshaller (javax.xml.bind.Unmarshaller)6 Attribute (javax.xml.stream.events.Attribute)6 Document (org.w3c.dom.Document)6 ArrayList (java.util.ArrayList)5 JAXBContext (javax.xml.bind.JAXBContext)5 Diff (org.custommonkey.xmlunit.Diff)5 InputSource (org.xml.sax.InputSource)5 JAXBException (javax.xml.bind.JAXBException)4 DOMSource (javax.xml.transform.dom.DOMSource)4