Example usage for javax.xml.stream XMLStreamException XMLStreamException

List of usage examples for javax.xml.stream XMLStreamException XMLStreamException

Introduction

In this page you can find the example usage for javax.xml.stream XMLStreamException XMLStreamException.

Prototype

public XMLStreamException(String msg, Location location) 

Source Link

Document

Construct an exception with the assocated message, exception and location.

Usage

From source file:Main.java

/**
 * Skip current element, including all its content.
 * Precondition: the current event is START_ELEMENT.
 * Postcondition: the current event is the corresponding END_ELEMENT.
 * Similar to {@link XMLStreamReader#nextTag()}, but also skips text content.
 * @param reader must not be {@code null}
 * @throws XMLStreamException if the current event is not START_ELEMENT or there is an error processing the underlying XML source
 *//*from   w w  w .ja v  a2s  .  c o  m*/
public static void skipElement(XMLStreamReader reader) throws XMLStreamException {
    if (reader.getEventType() != START_ELEMENT)
        throw new XMLStreamException("expected start of element", reader.getLocation());

    int depth = 0;
    while (reader.hasNext()) {
        int event = reader.next();
        if (event == START_ELEMENT) {
            ++depth;
        } else if (event == END_ELEMENT) {
            --depth;
            if (depth == -1)
                break;
        }
    }
}

From source file:Main.java

/**
 * Test if the current event is an element tag with the given namespace and name.
 * If the namespace URI is null it is not checked for equality,
 * if the local name is null it is not checked for equality.
 * @param reader must not be {@code null}
 * @param event START_ELEMENT or END_ELEMENT
 * @param uri the namespace URI of the element, may be null
 * @param name the local name of the element, may be null
 * @param slash "" or "/", for error message
 * @throws XMLStreamException if the required values are not matched.
 *//*from   w  w w.  j a  v a  2 s  . co m*/
private static void requireElement(XMLStreamReader reader, int event, String uri, String name, String slash)
        throws XMLStreamException {
    // Note: reader.require(event, uri, name) has a lousy error message

    if (reader.getEventType() != event)
        throw new XMLStreamException("expected <" + slash + name + ">", reader.getLocation());

    if (uri != null) {
        String found = reader.getNamespaceURI();
        if (!found.equals(uri))
            throw new XMLStreamException(
                    "expected <" + slash + name + "> with namespace [" + uri + "], found [" + found + "]",
                    reader.getLocation());
    }

    if (name != null) {
        String found = reader.getLocalName();
        if (!found.equals(name))
            throw new XMLStreamException("expected <" + slash + name + ">, found <" + slash + found + ">",
                    reader.getLocation());
    }
}

From source file:dk.statsbiblioteket.util.xml.XMLUnicodeStreamWriter.java

@Override
public void writeCharacters(String text) throws XMLStreamException {
    outXML.flush();//www.ja v a  2 s.c  o m
    try {
        out.write(extendedUnicodeEscape(text, false));
    } catch (IOException e) {
        throw new XMLStreamException("Unable to write to underlying Writer " + out, e);
    }
}

From source file:org.javelin.sws.ext.bind.internal.model.SimpleTypePattern.java

@Override
public T consumeValue(XMLEventReader eventReader, UnmarshallingContext context) throws XMLStreamException {
    String value = this.consumeNonNullString(eventReader, context);
    if (this.formatter == null) {
        @SuppressWarnings("unchecked")
        T v = (T) value;// www  .  j  ava  2  s .  c  o  m
        return v;
    }
    try {
        return this.formatter.parse(value, Locale.getDefault());
    } catch (ParseException e) {
        throw new XMLStreamException(e.getMessage(), e);
    }
}

From source file:de.huxhorn.sulky.plist.impl.PropertyListReader.java

private Object readDate(XMLStreamReader reader) throws XMLStreamException {
    reader.require(XMLStreamConstants.START_ELEMENT, null, DATE_NODE);
    String text = StaxUtilities.readSimpleTextNodeIfAvailable(reader, null, DATE_NODE);
    try {/* www  . ja v  a2s. c om*/
        return format.parse(text);
    } catch (ParseException e) {
        throw new XMLStreamException("Invalid date: '" + text + "'", e);
    }
}

From source file:at.gv.egiz.slbinding.SLUnmarshaller.java

/**
 * @param source a StreamSource wrapping a Reader (!) for the marshalled Object
 * @return the unmarshalled Object// w w w .j a  v a 2s  .c om
 * @throws XMLStreamException
 * @throws JAXBException
 */
public Object unmarshal(StreamSource source) throws XMLStreamException, JAXBException {
    Reader inputReader = source.getReader();

    /* Validate XML against XXE, XEE, and SSRF
     * 
     * This pre-validation step is required because com.sun.xml.stream.sjsxp-1.0.2 XML stream parser library does not 
     * support all XML parser features to prevent these types of attacks  
     */
    if (inputReader instanceof InputStreamReader) {
        try {
            //create copy of input stream
            InputStreamReader isReader = (InputStreamReader) inputReader;
            String encoding = isReader.getEncoding();
            byte[] backup = IOUtils.toByteArray(isReader, encoding);

            //validate input stream
            DOMUtils.validateXMLAgainstXXEAndSSRFAttacks(new ByteArrayInputStream(backup));

            //create new inputStreamReader for reak processing
            inputReader = new InputStreamReader(new ByteArrayInputStream(backup), encoding);

        } catch (XMLStreamException e) {
            log.error("XML data validation FAILED with msg: " + e.getMessage(), e);
            throw new XMLStreamException("XML data validation FAILED with msg: " + e.getMessage(), e);

        } catch (IOException e) {
            log.error("XML data validation FAILED with msg: " + e.getMessage(), e);
            throw new XMLStreamException("XML data validation FAILED with msg: " + e.getMessage(), e);

        }

    } else {
        log.error("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
        log.error(
                "Reader is not of type InputStreamReader -> can not make a copy of the InputStream --> extended XML validation is not possible!!! ");
        log.error("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");

    }

    /* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
     * parse XML with original functionality
     * 
     * This code implements the the original mocca XML processing by using 
     *  com.sun.xml.stream.sjsxp-1.0.2 XML stream parser library. Currently, this library is required to get full 
     *  security-layer specific XML processing. However, this lib does not fully support XXE, XEE and SSRF
     *  prevention mechanisms (e.g.: XMLInputFactory.SUPPORT_DTD flag is not used)    
     * 
     * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
     */
    XMLInputFactory inputFactory = XMLInputFactory.newInstance();

    //disallow DTD and external entities
    inputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
    inputFactory.setProperty("javax.xml.stream.isSupportingExternalEntities", false);

    XMLEventReader eventReader = inputFactory.createXMLEventReader(inputReader);
    RedirectEventFilter redirectEventFilter = new RedirectEventFilter();
    XMLEventReader filteredReader = inputFactory.createFilteredReader(eventReader, redirectEventFilter);

    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
    ReportingValidationEventHandler validationEventHandler = new ReportingValidationEventHandler();
    unmarshaller.setEventHandler(validationEventHandler);

    unmarshaller.setListener(new RedirectUnmarshallerListener(redirectEventFilter));
    unmarshaller.setSchema(slSchema);

    Object object;
    try {
        log.trace("Before unmarshal().");
        object = unmarshaller.unmarshal(filteredReader);
        log.trace("After unmarshal().");
    } catch (UnmarshalException e) {
        if (log.isDebugEnabled()) {
            log.debug("Failed to unmarshal security layer message.", e);
        } else {
            log.info("Failed to unmarshal security layer message."
                    + (e.getMessage() != null ? " " + e.getMessage() : ""));
        }

        if (validationEventHandler.getErrorEvent() != null) {
            ValidationEvent errorEvent = validationEventHandler.getErrorEvent();
            if (e.getLinkedException() == null) {
                e.setLinkedException(errorEvent.getLinkedException());
            }
        }
        throw e;
    }

    return object;

}

From source file:com.aionengine.gameserver.dataholders.loadingutils.XmlMerger.java

/**
 * Extract an attribute value from a <code>StartElement </code> event.
 *
 * @param element        Event object.//w  w w  .j  a  v  a  2  s  .  c o  m
 * @param name           Attribute QName
 * @param def            Default value.
 * @param onErrorMessage On error message.
 * @return attribute value
 * @throws XMLStreamException if attribute is missing and there is no default value set.
 */
private String getAttributeValue(StartElement element, QName name, String def, String onErrorMessage)
        throws XMLStreamException {
    Attribute attribute = element.getAttributeByName(name);

    if (attribute == null) {
        if (def == null)
            throw new XMLStreamException(onErrorMessage, element.getLocation());

        return def;
    }

    return attribute.getValue();
}

From source file:com.aionemu.gameserver.dataholders.loadingutils.XmlMerger.java

/**
 * Extract an attribute value from a/* www  . java 2s .c  o m*/
 * <code>StartElement </code> event.
 *
 * @param element        Event object.
 * @param name           Attribute QName
 * @param def            Default value.
 * @param onErrorMessage On error message.
 * @return attribute value
 * @throws XMLStreamException if attribute is missing and there is no
 *                            default value set.
 */
private String getAttributeValue(StartElement element, QName name, String def, String onErrorMessage)
        throws XMLStreamException {
    Attribute attribute = element.getAttributeByName(name);

    if (attribute == null) {
        if (def == null) {
            throw new XMLStreamException(onErrorMessage, element.getLocation());
        }

        return def;
    }

    return attribute.getValue();
}

From source file:com.streamsets.pipeline.lib.xml.StreamingXmlParser.java

@SuppressWarnings("unchecked")
Field parse(XMLEventReader reader, StartElement startE) throws XMLStreamException, ObjectLengthException {
    Map<String, Field> map = this.useFieldAttributesInsteadOfFields ? new LinkedHashMap<>() : toField(startE);
    Map<String, Field> startEMap = map;
    Map<String, Object> contents = new LinkedHashMap<>();
    boolean maybeText = true;
    while (hasNext(reader) && !peek(reader).isEndElement()) {
        XMLEvent next = read(reader);
        if (next.isCharacters()) {
            // If this set of characters is all whitespace, ignore.
            if (next.asCharacters().isWhiteSpace()) {
                continue;
            } else if (peek(reader).isEndElement() && maybeText) {
                contents.put(VALUE_KEY, Field.create(((Characters) next).getData()));
            } else if (peek(reader).isStartElement()) {
                StartElement subStartE = (StartElement) read(reader);
                Field subField = parse(reader, subStartE);
                addContent(contents, getName(subStartE), subField);
                if (hasNext(reader) && peek(reader).isCharacters()) {
                    read(reader);// w  ww .j a  v  a 2  s .c  om
                }
            } else if (maybeText) {
                throw new XMLStreamException(Utils
                        .format("Unexpected XMLEvent '{}', it should be START_ELEMENT or END_ELEMENT", next),
                        next.getLocation());
            }
        } else if (next.isStartElement()) {
            String name = getName((StartElement) next);
            Field field = parse(reader, (StartElement) next);
            addContent(contents, name, field);
        } else {
            throw new XMLStreamException(
                    Utils.format("Unexpected XMLEvent '{}', it should be START_ELEMENT or CHARACTERS", next),
                    next.getLocation());
        }
        maybeText = false;
    }
    if (hasNext(reader)) {
        EndElement endE = (EndElement) read(reader);
        if (!endE.getName().equals(startE.getName())) {
            throw new XMLStreamException(Utils.format("Unexpected EndElement '{}', it should be '{}'",
                    endE.getName().getLocalPart(), startE.getName().getLocalPart()), endE.getLocation());
        }
        for (Map.Entry<String, Object> entry : contents.entrySet()) {
            if (entry.getValue() instanceof Field) {
                startEMap.put(entry.getKey(), (Field) entry.getValue());
            } else {
                startEMap.put(entry.getKey(), Field.create((List<Field>) entry.getValue()));
            }
        }
    }
    final Field field = Field.create(startEMap);

    if (this.useFieldAttributesInsteadOfFields) {
        Iterator attrs = startE.getAttributes();
        while (attrs.hasNext()) {
            Attribute attr = (Attribute) attrs.next();
            field.setAttribute(getName(XMLATTR_ATTRIBUTE_PREFIX, attr), attr.getValue());
        }
        Iterator nss = startE.getNamespaces();
        while (nss.hasNext()) {
            Namespace ns = (Namespace) nss.next();
            field.setAttribute(getName(null, ns), ns.getNamespaceURI());
        }
    }

    lastParsedFieldXpathPrefix = getXpathPrefix();
    return field;
}

From source file:de.codesourcery.eve.skills.util.XMLMapper.java

public <T> Collection<T> read(Class<T> clasz, IFieldConverters converters, InputStream instream)
        throws XMLStreamException, IOException, IllegalArgumentException, InstantiationException,
        IllegalAccessException, InvocationTargetException, SecurityException, NoSuchMethodException {

    final Collection<T> result = new ArrayList<T>();

    try {/* w  w w  .j a  v  a  2s.  c  om*/

        final BeanDescription desc = createBeanDescription(clasz);

        /* 
         * Create inverse mapping attribute name -> field. 
         */
        final Map<String, Field> inverseMapping = new HashMap<String, Field>();

        if (!this.propertyNameMappings.isEmpty()) {

            // key = property name  / value = attribute name
            for (Map.Entry<String, String> propToAttribute : this.propertyNameMappings.entrySet()) {
                inverseMapping.put(propToAttribute.getValue(), desc.getFieldByName(propToAttribute.getKey()));
            }

        } else { // create default mappings
            for (Field f : desc.getFields()) {
                inverseMapping.put(f.getName(), f);
            }
        }

        final int fieldCount = desc.getFields().size();

        final XMLInputFactory factory = XMLInputFactory.newInstance();
        final XMLStreamReader parser = factory.createXMLStreamReader(instream);

        boolean inRow = false;

        final Constructor<T> constructor = clasz.getConstructor(new Class<?>[0]);

        for (int event = parser.next(); event != XMLStreamConstants.END_DOCUMENT; event = parser.next()) {
            switch (event) {
            case XMLStreamConstants.START_ELEMENT:
                if ("row".equals(parser.getLocalName())) { // parse row
                    if (inRow) {
                        throw new XMLStreamException("Found nested <row> tag ?", parser.getLocation());
                    }
                    inRow = true;

                    final T bean = constructor.newInstance(new Object[0]);
                    for (int i = 0; i < fieldCount; i++) {
                        final String attrName = parser.getAttributeLocalName(i);
                        final String attrValue = parser.getAttributeValue(i);
                        final Field field = inverseMapping.get(attrName);

                        if (!NIL.equals(attrValue)) {
                            final Object fieldValue = converters.getConverter(field)
                                    .toObject(fromAttributeValue(attrValue), field.getType());
                            field.set(bean, fieldValue);
                        } else {
                            field.set(bean, null);
                        }

                    }
                    result.add(bean);
                }
                break;

            case XMLStreamConstants.END_ELEMENT:
                if ("row".equals(parser.getLocalName())) { // parse row
                    if (!inRow) {
                        throw new XMLStreamException("Found </row> tag without start tag at ",
                                parser.getLocation());
                    }
                    inRow = false;
                }
                break;

            }
        }
    } finally {
        instream.close();
    }

    return result;
}