Example usage for javax.xml.stream XMLStreamReader next

List of usage examples for javax.xml.stream XMLStreamReader next

Introduction

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

Prototype

public int next() throws XMLStreamException;

Source Link

Document

Get next parsing event - a processor may return all contiguous character data in a single chunk, or it may split it into several chunks.

Usage

From source file:org.opentestsystem.delivery.AccValidator.handlers.ValidationHandler.java

public void validateXmlAccs(String filePath, String xsdPath) throws ValidationException {
    try {//from  ww w. j a v  a  2  s .com
        InputStream xmlInput = new FileInputStream(new File(filePath));
        InputStream xsdInput = new FileInputStream(new File(xsdPath));

        String text = null;
        XMLInputFactory factory = XMLInputFactory.newInstance();
        factory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
        XMLStreamReader reader = factory.createXMLStreamReader(xmlInput);

        boolean firstSelect = true;
        MasterResourceAccommodation masterResource = null;
        List<MasterResourceAccommodation> resourceFamiltyMasterResourceAccommodations = null;
        AccommodationText accommodationText = null;
        List<AccommodationText> accommodationTexts = null;
        AccommodationOption accommodationOption = null;
        List<AccommodationOption> accommodationOptions = null;
        AccFamilySubject familySubject = null;
        List<AccFamilySubject> familySubjects = null;
        ResourceFamily resourceFamily = null;
        List<String> grades = null;

        while (reader.hasNext()) {
            int Event = reader.next();
            switch (Event) {
            case XMLStreamConstants.START_ELEMENT: {
                switch (reader.getLocalName()) {
                case "MasterResourceFamily":
                    _masterResourceAccommodations = new ArrayList<MasterResourceAccommodation>();

                    break;
                case "SingleSelectResource":
                    masterResource = new MasterResourceAccommodation();
                    accommodationTexts = new ArrayList<AccommodationText>();
                    accommodationOptions = new ArrayList<AccommodationOption>();
                    break;

                case "MultiSelectResource":
                    masterResource = new MasterResourceAccommodation();
                    accommodationTexts = new ArrayList<AccommodationText>();
                    accommodationOptions = new ArrayList<AccommodationOption>();
                    break;
                case "EditResource":
                    masterResource = new MasterResourceAccommodation();
                    accommodationTexts = new ArrayList<AccommodationText>();
                    accommodationOptions = new ArrayList<AccommodationOption>();
                    break;
                case "ResourceFamily":
                    masterResource = new MasterResourceAccommodation();
                    familySubjects = new ArrayList<AccFamilySubject>();
                    resourceFamily = new ResourceFamily();
                    accommodationTexts = new ArrayList<AccommodationText>();
                    accommodationText = new AccommodationText();
                    resourceFamiltyMasterResourceAccommodations = new ArrayList<MasterResourceAccommodation>();
                    grades = new ArrayList<String>();
                    break;
                case "Subject":
                    familySubject = new AccFamilySubject();
                    break;
                case "Selection":
                    if (firstSelect) {
                        masterResource.setHeader(accommodationTexts);
                        accommodationOption = new AccommodationOption();
                        accommodationTexts = new ArrayList<AccommodationText>();
                    } else {
                        accommodationOption = new AccommodationOption();
                    }
                    firstSelect = false;
                    break;

                case "Text":
                    accommodationText = new AccommodationText();

                    break;
                default:
                    break;
                }
                break;
            }
            case XMLStreamConstants.CHARACTERS: {
                String nodeValue = getContents(reader.getText());
                if (nodeValue.length() > 0) {
                    text = nodeValue;
                }
                break;
            }
            case XMLStreamConstants.END_ELEMENT: {
                switch (reader.getLocalName()) {
                case "Code":
                    if (accommodationOption == null) {
                        if (familySubject == null) {
                            masterResource.setCode(text);
                        } else {
                            familySubject.setCode(text);
                        }
                    } else {
                        accommodationOption.setCode(text);
                    }
                    text = null;
                    break;
                case "Order":
                    if (accommodationOption == null) {
                        masterResource.setOrder(Integer.valueOf(text));
                    } else {
                        accommodationOption.setOrder(Integer.valueOf(text));
                    }
                    text = null;
                    break;
                case "MutuallyExclusive":
                    accommodationOption.setMutuallyExclusive(true);
                    text = null;
                    break;
                case "DefaultSelection":
                    masterResource.setDefaultSelection(text);
                    text = null;
                    break;
                case "Disabled":
                    masterResource.setDisabled(true);
                    text = null;
                    break;
                case "Language":
                    accommodationText.setLanguage(text);
                    text = null;
                    break;
                case "Label":
                    accommodationText.setLabel(text);
                    text = null;
                    break;
                case "Description":
                    accommodationText.setDescription(text);
                    text = null;
                    break;
                case "Message":
                    accommodationText.setMessage(text);
                    text = null;
                    break;
                case "Text":
                    accommodationTexts.add(accommodationText);
                    text = null;
                    break;
                case "Selection":
                    accommodationOption.setText(accommodationTexts);
                    accommodationOptions.add(accommodationOption);
                    accommodationOption = new AccommodationOption();
                    accommodationTexts = new ArrayList<AccommodationText>();
                    text = null;
                    break;
                case "SingleSelectResource":
                    masterResource.setResourceType("SingleSelectResource");
                    if (accommodationTexts.size() > 0) {
                        masterResource.setHeader(accommodationTexts);
                    }
                    masterResource.setOptions(accommodationOptions);
                    if (resourceFamily == null) {
                        _masterResourceAccommodations.add(masterResource);
                    } else {
                        resourceFamiltyMasterResourceAccommodations.add(masterResource);
                    }
                    masterResource = null;
                    accommodationOption = null;
                    accommodationOption = null;
                    firstSelect = true;
                    text = null;
                    break;
                case "MultiSelectResource":
                    masterResource.setResourceType("MultiSelectResource");
                    if (accommodationTexts.size() > 0) {
                        masterResource.setHeader(accommodationTexts);
                    }
                    masterResource.setOptions(accommodationOptions);
                    if (resourceFamily == null) {
                        _masterResourceAccommodations.add(masterResource);
                    } else {
                        resourceFamiltyMasterResourceAccommodations.add(masterResource);
                    }
                    masterResource = null;
                    accommodationOption = null;
                    accommodationOption = null;
                    firstSelect = true;
                    text = null;
                    break;
                case "EditResource":
                    masterResource.setResourceType("EditResource");
                    if (accommodationTexts.size() > 0) {
                        masterResource.setHeader(accommodationTexts);
                    }
                    masterResource.setOptions(accommodationOptions);
                    if (resourceFamily == null) {
                        _masterResourceAccommodations.add(masterResource);
                    } else {
                        resourceFamiltyMasterResourceAccommodations.add(masterResource);
                    }
                    masterResource = null;
                    accommodationOption = null;
                    accommodationOption = null;
                    firstSelect = true;
                    text = null;
                    break;
                case "ResourceFamily":
                    resourceFamily.setSubject(familySubjects);
                    resourceFamily.setGrade(grades);
                    resourceFamily.setMasterResourceAccommodation(resourceFamiltyMasterResourceAccommodations);
                    _resourceFamilies.add(resourceFamily);
                    familySubjects = null;
                    grades = null;
                    resourceFamily = null;
                    resourceFamiltyMasterResourceAccommodations = null;
                    text = null;
                    break;
                case "Name":
                    familySubject.setName(text);
                    text = null;
                    break;
                case "Subject":
                    familySubjects.add(familySubject);
                    familySubject = null;
                    text = null;
                    break;
                case "Grade":
                    grades.add(text);
                    text = null;
                    break;
                }
                break;
            }
            }
        }

        validateRules(_masterResourceAccommodations, _resourceFamilies);
        // validation against xsd
        xmlInput = new FileInputStream(new File(filePath));
        xsdInput = new FileInputStream(new File(xsdPath));
        validateAgainstXSD(xmlInput, xsdInput);

    } catch (IOException e) {
        throw new ValidationException("failed",
                "The xml could not be parsed into objects. The error message is:" + e.getMessage());
    } catch (XMLStreamException e) {
        throw new ValidationException("failed",
                "The xml could not be parsed into objects. The error message is:" + e.getMessage());
    }
}

From source file:org.openvpms.tools.data.loader.DataLoader.java

/**
 * Loads data from a stream./*w  ww.  j  a va 2  s.c  o m*/
 *
 * @param reader the stream reader
 * @param path   a path representing the stream source, for logging purposes
 * @throws XMLStreamException for any stream error
 */
public void load(XMLStreamReader reader, String path) throws XMLStreamException {

    Stack<LoadState> stack = new Stack<LoadState>();
    for (int event = reader.next(); event != XMLStreamConstants.END_DOCUMENT; event = reader.next()) {
        LoadState current;
        switch (event) {
        case XMLStreamConstants.START_DOCUMENT:
            break;
        case XMLStreamConstants.START_ELEMENT:
            String elementName = reader.getLocalName();
            if ("data".equals(elementName)) {
                startData(reader, stack, path);
            } else if (!"archetype".equals(elementName)) {
                throw new ArchetypeDataLoaderException(ErrorInStartElement);
            }
            break;
        case XMLStreamConstants.END_ELEMENT:
            if (!stack.isEmpty()) {
                current = stack.pop();
                load(current);
            }

            if (verbose) {
                log.info("[END PROCESSING element=" + reader.getLocalName() + "]");
            }
            break;

        default:
            break;
        }
    }
}

From source file:org.orbisgis.core.layerModel.mapcatalog.RemoteMapCatalog.java

/**
 * Read the parser and feed the provided list with workspaces
 * @param workspaces Writable, empty list of workspaces
 * @param parser Opened parser/*from ww  w  . ja  v a2 s .  co  m*/
 * @throws XMLStreamException 
 */
public void parseXML(List<Workspace> workspaces, XMLStreamReader parser) throws XMLStreamException {
    List<String> hierarchy = new ArrayList<String>();
    // Hold workspace name
    StringBuilder characters = new StringBuilder();
    // Starting with a valid event, iterating while the parser
    // does not reach the end document XML tag
    for (int event = parser.next(); event != XMLStreamConstants.END_DOCUMENT; event = parser.next()) {
        // For each XML elements
        switch (event) {
        case XMLStreamConstants.START_ELEMENT:
            hierarchy.add(parser.getLocalName());
            break;
        case XMLStreamConstants.END_ELEMENT:
            if (RemoteCommons.endsWith(hierarchy, "workspaces", "workspace", "name")) {
                workspaces.add(new Workspace(cParams, characters.toString().trim()));
            }
            hierarchy.remove(hierarchy.size() - 1);
            characters = new StringBuilder(); // Clear the string buffer
            break;
        case XMLStreamConstants.CHARACTERS:
            characters.append(StringEscapeUtils.unescapeHtml(parser.getText()));
            break;
        }
    }
}

From source file:org.orbisgis.core.layerModel.mapcatalog.Workspace.java

private int parsePublishResponse(XMLStreamReader parser) throws XMLStreamException {
    List<String> hierarchy = new ArrayList<String>();
    for (int event = parser.next(); event != XMLStreamConstants.END_DOCUMENT; event = parser.next()) {
        // For each XML elements
        switch (event) {
        case XMLStreamConstants.START_ELEMENT:
            hierarchy.add(parser.getLocalName());
            // Parse attributes
            if (RemoteCommons.endsWith(hierarchy, "context")) {
                for (int attributeId = 0; attributeId < parser.getAttributeCount(); attributeId++) {
                    String attributeName = parser.getAttributeLocalName(attributeId);
                    if (attributeName.equals("id")) {
                        return Integer.parseInt(parser.getAttributeValue(attributeId));
                    }/*from   w w  w.j a v  a 2s.  co m*/
                }
            }
            break;
        case XMLStreamConstants.END_ELEMENT:
            hierarchy.remove(hierarchy.size() - 1);
            break;
        }
    }
    throw new XMLStreamException("Bad response on publishing a map context");
}

From source file:org.orbisgis.core.layerModel.mapcatalog.Workspace.java

/**
 * Read the parser and feed the provided list with workspaces
 * @param mapContextList Writable, empty list of RemoteMapContext
 * @param parser Opened parser//w ww.  jav a2  s  .  c  o  m
 * @throws XMLStreamException 
 */
public void parseXML(List<RemoteMapContext> mapContextList, XMLStreamReader parser)
        throws XMLStreamException, UnsupportedEncodingException {
    List<String> hierarchy = new ArrayList<String>();
    RemoteMapContext curMapContext = null;
    Locale curLocale = null;
    StringBuilder characters = new StringBuilder();
    for (int event = parser.next(); event != XMLStreamConstants.END_DOCUMENT; event = parser.next()) {
        // For each XML elements
        switch (event) {
        case XMLStreamConstants.START_ELEMENT:
            hierarchy.add(parser.getLocalName());
            if (RemoteCommons.endsWith(hierarchy, "contexts", "context")) {
                curMapContext = new RemoteOwsMapContext(cParams);
                curMapContext.setWorkspaceName(workspaceName);
            }
            // Parse attributes
            for (int attributeId = 0; attributeId < parser.getAttributeCount(); attributeId++) {
                String attributeName = parser.getAttributeLocalName(attributeId);
                if (attributeName.equals("id")) {
                    curMapContext.setId(Integer.parseInt(parser.getAttributeValue(attributeId)));
                } else if (attributeName.equals("date")) {
                    String attributeValue = parser.getAttributeValue(attributeId);
                    try {
                        curMapContext.setDate(parseDate(attributeValue));
                    } catch (ParseException ex) {
                        LOGGER.warn(I18N.tr("Cannot parse the provided date {0}", attributeValue), ex);
                    }
                } else if (attributeName.equals("lang")) {
                    curLocale = LocalizedText.forLanguageTag(parser.getAttributeValue(attributeId));
                }
            }
            break;
        case XMLStreamConstants.END_ELEMENT:
            if (RemoteCommons.endsWith(hierarchy, "contexts", "context")) {
                mapContextList.add(curMapContext);
                curMapContext = null;
            } else if (RemoteCommons.endsWith(hierarchy, "contexts", "context", "title")) {
                Locale descLocale = Locale.getDefault();
                if (curLocale != null) {
                    descLocale = curLocale;
                }
                curMapContext.getDescription().addTitle(descLocale,
                        StringEscapeUtils.unescapeHtml(characters.toString().trim()));
            } else if (RemoteCommons.endsWith(hierarchy, "contexts", "context", "abstract")) {
                Locale descLocale = Locale.getDefault();
                if (curLocale != null) {
                    descLocale = curLocale;
                }
                curMapContext.getDescription().addAbstract(descLocale,
                        StringEscapeUtils.unescapeHtml(characters.toString().trim()));
            }
            characters = new StringBuilder();
            curLocale = null;
            hierarchy.remove(hierarchy.size() - 1);
            break;
        case XMLStreamConstants.CHARACTERS:
            characters.append(StringEscapeUtils.unescapeHtml(parser.getText()));
            break;
        }
    }
}

From source file:org.orbisgis.coremap.layerModel.mapcatalog.RemoteMapCatalog.java

/**
 * Read the parser and feed the provided list with workspaces
 * @param workspaces Writable, empty list of workspaces
 * @param parser Opened parser/*from  ww w . ja  va 2s  . c om*/
 * @throws XMLStreamException 
 */
public void parseXML(List<Workspace> workspaces, XMLStreamReader parser) throws XMLStreamException {
    List<String> hierarchy = new ArrayList<String>();
    // Hold workspace name
    StringBuilder characters = new StringBuilder();
    // Starting with a valid event, iterating while the parser
    // does not reach the end document XML tag
    for (int event = parser.next(); event != XMLStreamConstants.END_DOCUMENT; event = parser.next()) {
        // For each XML elements
        switch (event) {
        case XMLStreamConstants.START_ELEMENT:
            hierarchy.add(parser.getLocalName());
            break;
        case XMLStreamConstants.END_ELEMENT:
            if (RemoteCommons.endsWith(hierarchy, "workspaces", "workspace", "name")) {
                workspaces.add(new Workspace(cParams, characters.toString().trim()));
            }
            hierarchy.remove(hierarchy.size() - 1);
            characters = new StringBuilder(); // Clear the string buffer
            break;
        case XMLStreamConstants.CHARACTERS:
            characters.append(StringEscapeUtils.unescapeHtml4(parser.getText()));
            break;
        }
    }
}

From source file:org.orbisgis.coremap.layerModel.mapcatalog.Workspace.java

/**
 * Read the parser and feed the provided list with workspaces
 * @param mapContextList Writable, empty list of RemoteMapContext
 * @param parser Opened parser/* w w w .  j a  v  a2s . c o  m*/
 * @throws XMLStreamException 
 */
public void parseXML(List<RemoteMapContext> mapContextList, XMLStreamReader parser)
        throws XMLStreamException, UnsupportedEncodingException {
    List<String> hierarchy = new ArrayList<String>();
    RemoteMapContext curMapContext = null;
    Locale curLocale = null;
    StringBuilder characters = new StringBuilder();
    for (int event = parser.next(); event != XMLStreamConstants.END_DOCUMENT; event = parser.next()) {
        // For each XML elements
        switch (event) {
        case XMLStreamConstants.START_ELEMENT:
            hierarchy.add(parser.getLocalName());
            if (RemoteCommons.endsWith(hierarchy, "contexts", "context")) {
                curMapContext = new RemoteOwsMapContext(cParams);
                curMapContext.setWorkspaceName(workspaceName);
            }
            // Parse attributes
            for (int attributeId = 0; attributeId < parser.getAttributeCount(); attributeId++) {
                String attributeName = parser.getAttributeLocalName(attributeId);
                if (attributeName.equals("id")) {
                    curMapContext.setId(Integer.parseInt(parser.getAttributeValue(attributeId)));
                } else if (attributeName.equals("date")) {
                    String attributeValue = parser.getAttributeValue(attributeId);
                    try {
                        curMapContext.setDate(parseDate(attributeValue));
                    } catch (ParseException ex) {
                        LOGGER.warn(I18N.tr("Cannot parse the provided date {0}", attributeValue), ex);
                    }
                } else if (attributeName.equals("lang")) {
                    curLocale = LocalizedText.forLanguageTag(parser.getAttributeValue(attributeId));
                }
            }
            break;
        case XMLStreamConstants.END_ELEMENT:
            if (RemoteCommons.endsWith(hierarchy, "contexts", "context")) {
                mapContextList.add(curMapContext);
                curMapContext = null;
            } else if (RemoteCommons.endsWith(hierarchy, "contexts", "context", "title")) {
                Locale descLocale = Locale.getDefault();
                if (curLocale != null) {
                    descLocale = curLocale;
                }
                curMapContext.getDescription().addTitle(descLocale,
                        StringEscapeUtils.unescapeHtml4(characters.toString().trim()));
            } else if (RemoteCommons.endsWith(hierarchy, "contexts", "context", "abstract")) {
                Locale descLocale = Locale.getDefault();
                if (curLocale != null) {
                    descLocale = curLocale;
                }
                curMapContext.getDescription().addAbstract(descLocale,
                        StringEscapeUtils.unescapeHtml4(characters.toString().trim()));
            }
            characters = new StringBuilder();
            curLocale = null;
            hierarchy.remove(hierarchy.size() - 1);
            break;
        case XMLStreamConstants.CHARACTERS:
            characters.append(StringEscapeUtils.unescapeHtml4(parser.getText()));
            break;
        }
    }
}

From source file:org.osaf.cosmo.model.text.XhtmlCollectionFormat.java

public CollectionItem parse(String source, EntityFactory entityFactory) throws ParseException {
    CollectionItem collection = entityFactory.createCollection();

    try {// w  w  w  .j  av  a  2  s  . c o m
        if (source == null)
            throw new ParseException("Source has no XML data", -1);
        StringReader sr = new StringReader(source);
        XMLStreamReader reader = createXmlReader(sr);

        boolean inCollection = false;
        while (reader.hasNext()) {
            reader.next();
            if (!reader.isStartElement())
                continue;

            if (hasClass(reader, "collection")) {
                if (log.isDebugEnabled())
                    log.debug("found collection element");
                inCollection = true;
                continue;
            }

            if (inCollection && hasClass(reader, "name")) {
                if (log.isDebugEnabled())
                    log.debug("found name element");

                String name = reader.getElementText();
                if (StringUtils.isBlank(name))
                    throw new ParseException("Empty name not allowed",
                            reader.getLocation().getCharacterOffset());
                collection.setDisplayName(name);

                continue;
            }

            if (inCollection && hasClass(reader, "uuid")) {
                if (log.isDebugEnabled())
                    log.debug("found uuid element");

                String uuid = reader.getElementText();
                if (StringUtils.isBlank(uuid))
                    throw new ParseException("Empty uuid not allowed",
                            reader.getLocation().getCharacterOffset());
                collection.setUid(uuid);

                continue;
            }
        }

        reader.close();
    } catch (XMLStreamException e) {
        handleXmlException("Error reading XML", e);
    }

    return collection;
}

From source file:org.osaf.cosmo.model.text.XhtmlPreferenceFormat.java

public Preference parse(String source, EntityFactory entityFactory) throws ParseException {
    Preference pref = entityFactory.createPreference();

    try {/*from  w  ww.  j  a  v a2  s .co m*/
        if (source == null)
            throw new ParseException("Source has no XML data", -1);
        StringReader sr = new StringReader(source);
        XMLStreamReader reader = createXmlReader(sr);

        boolean inPreference = false;
        while (reader.hasNext()) {
            reader.next();
            if (!reader.isStartElement())
                continue;

            if (hasClass(reader, "preference")) {
                if (log.isDebugEnabled())
                    log.debug("found preference element");
                inPreference = true;
                continue;
            }

            if (inPreference && hasClass(reader, "key")) {
                if (log.isDebugEnabled())
                    log.debug("found key element");

                String key = reader.getElementText();
                if (StringUtils.isBlank(key))
                    handleParseException("Key element must not be empty", reader);
                pref.setKey(key);

                continue;
            }

            if (inPreference && hasClass(reader, "value")) {
                if (log.isDebugEnabled())
                    log.debug("found value element");

                String value = reader.getElementText();
                if (StringUtils.isBlank(value))
                    value = "";
                pref.setValue(value);

                continue;
            }
        }

        reader.close();
    } catch (XMLStreamException e) {
        handleXmlException("Error reading XML", e);
    }

    return pref;
}

From source file:org.osaf.cosmo.model.text.XhtmlSubscriptionFormat.java

public CollectionSubscription parse(String source, EntityFactory entityFactory) throws ParseException {
    CollectionSubscription sub = entityFactory.createCollectionSubscription();

    try {/*from   www .  j  a  va 2s  . c  o  m*/
        if (source == null)
            throw new ParseException("Source has no XML data", -1);
        StringReader sr = new StringReader(source);
        XMLStreamReader reader = createXmlReader(sr);

        boolean inLocalSub = false;
        boolean inCollection = false;
        boolean inTicket = false;
        while (reader.hasNext()) {
            reader.next();
            if (!reader.isStartElement())
                continue;

            if (hasClass(reader, "local-subscription")) {
                if (log.isDebugEnabled())
                    log.debug("found local-subscription element");
                inLocalSub = true;
                continue;
            }

            if (inLocalSub && hasClass(reader, "name")) {
                if (log.isDebugEnabled())
                    log.debug("found name element");

                String name = reader.getElementText();
                if (StringUtils.isBlank(name))
                    handleParseException("Name element must not be empty", reader);
                sub.setDisplayName(name);

                continue;
            }

            if (inLocalSub && hasClass(reader, "collection")) {
                if (log.isDebugEnabled())
                    log.debug("found collection element");
                inCollection = true;
                inTicket = false;
                continue;
            }

            if (inCollection && hasClass(reader, "uuid")) {
                if (log.isDebugEnabled())
                    log.debug("found uuid element");

                String uuid = reader.getElementText();
                if (StringUtils.isBlank(uuid))
                    handleParseException("Uuid element must not be empty", reader);
                sub.setCollectionUid(uuid);

                continue;
            }

            if (inLocalSub && hasClass(reader, "ticket")) {
                if (log.isDebugEnabled())
                    log.debug("found ticket element");
                inCollection = false;
                inTicket = true;
                continue;
            }

            if (inTicket && hasClass(reader, "key")) {
                if (log.isDebugEnabled())
                    log.debug("found key element");

                String key = reader.getElementText();
                if (StringUtils.isBlank(key))
                    handleParseException("Key element must not be empty", reader);
                sub.setTicketKey(key);

                continue;
            }
        }

        reader.close();
    } catch (XMLStreamException e) {
        handleXmlException("Error reading XML", e);
    }

    return sub;
}