Example usage for javax.xml.stream XMLStreamConstants START_ELEMENT

List of usage examples for javax.xml.stream XMLStreamConstants START_ELEMENT

Introduction

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

Prototype

int START_ELEMENT

To view the source code for javax.xml.stream XMLStreamConstants START_ELEMENT.

Click Source Link

Document

Indicates an event is a start element

Usage

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/*from   ww w .  j a  v  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.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.pentaho.di.trans.steps.excelinput.staxpoi.StaxPoiSheet.java

public StaxPoiSheet(XSSFReader reader, String sheetName, String sheetID)
        throws InvalidFormatException, IOException, XMLStreamException {
    this.sheetName = sheetName;
    xssfReader = reader;//from  w  w w  .j  a  v  a 2  s  . co  m
    sheetId = sheetID;
    sst = reader.getSharedStringsTable();
    styles = reader.getStylesTable();
    sheetStream = reader.getSheet(sheetID);
    XMLInputFactory factory = XMLInputFactory.newInstance();
    sheetReader = factory.createXMLStreamReader(sheetStream);
    headerRow = new ArrayList<String>();
    while (sheetReader.hasNext()) {
        int event = sheetReader.next();
        if (event == XMLStreamConstants.START_ELEMENT && sheetReader.getLocalName().equals("dimension")) {
            String dim = sheetReader.getAttributeValue(null, "ref");
            // empty sheets have dimension with no range
            if (StringUtils.contains(dim, ':')) {
                dim = dim.split(":")[1];
                numRows = StaxUtil.extractRowNumber(dim);
                numCols = StaxUtil.extractColumnNumber(dim);
            }
        }
        if (event == XMLStreamConstants.START_ELEMENT && sheetReader.getLocalName().equals("row")) {
            currentRow = Integer.parseInt(sheetReader.getAttributeValue(null, "r"));
            firstRow = currentRow;

            // calculate the number of columns in the header row
            while (sheetReader.hasNext()) {
                event = sheetReader.next();
                if (event == XMLStreamConstants.END_ELEMENT && sheetReader.getLocalName().equals("row")) {
                    // if the row has ended, break the inner while loop
                    break;
                }
                if (event == XMLStreamConstants.START_ELEMENT && sheetReader.getLocalName().equals("c")) {
                    String attributeValue = sheetReader.getAttributeValue(null, "t");
                    if (attributeValue != null && attributeValue.equals("s")) {
                        // only if the type of the cell is string, we continue
                        while (sheetReader.hasNext()) {
                            event = sheetReader.next();
                            if (event == XMLStreamConstants.START_ELEMENT
                                    && sheetReader.getLocalName().equals("v")) {
                                int idx = Integer.parseInt(sheetReader.getElementText());
                                String content = new XSSFRichTextString(sst.getEntryAt(idx)).toString();
                                headerRow.add(content);
                                break;
                            }
                        }
                    } else {
                        break;
                    }
                }
            }
            // we have parsed the header row
            break;
        }
    }
}

From source file:org.pentaho.di.trans.steps.excelinput.staxpoi.StaxPoiSheet.java

@Override
public KCell[] getRow(int rownr) {
    // xlsx raw row numbers are 1-based index, KSheet is 0-based

    if (rownr < 0 || rownr >= numRows) {
        // KSheet requires out of bounds here
        throw new ArrayIndexOutOfBoundsException(rownr);
    }// w  w  w  . j a v a 2  s  .com
    if (rownr + 1 < firstRow) {
        // before first non-empty row
        return new KCell[0];
    }
    if (rownr > 0 && currentRow == rownr + 1) {
        return currentRowCells;
    }
    try {
        if (currentRow >= rownr + 1) {
            // allow random access per api despite performance hit
            resetSheetReader();
        }
        while (sheetReader.hasNext()) {
            int event = sheetReader.next();
            if (event == XMLStreamConstants.START_ELEMENT && sheetReader.getLocalName().equals("row")) {
                String rowIndicator = sheetReader.getAttributeValue(null, "r");
                currentRow = Integer.parseInt(rowIndicator);
                if (currentRow < rownr + 1) {
                    continue;
                }
                currentRowCells = parseRow();
                return currentRowCells;
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    numRows = currentRow;
    return new KCell[] {};
}

From source file:org.pentaho.di.trans.steps.excelinput.staxpoi.StaxPoiSheet.java

private KCell[] parseRow() throws XMLStreamException {
    KCell[] cells = new StaxPoiCell[numCols];
    for (int i = 0; i < numCols; i++) {
        // go to the "c" cell tag
        while (sheetReader.hasNext()) {
            int event = sheetReader.next();
            if (event == XMLStreamConstants.START_ELEMENT && sheetReader.getLocalName().equals("c")) {
                break;
            }//from   www . j a  v a  2 s . co  m
            if (event == XMLStreamConstants.END_ELEMENT && sheetReader.getLocalName().equals("row")) {
                // premature end of row, returning what we have
                return cells;
            }
        }
        String cellLocation = sheetReader.getAttributeValue(null, "r");
        int columnIndex = StaxUtil.extractColumnNumber(cellLocation) - 1;

        String cellType = sheetReader.getAttributeValue(null, "t");
        String cellStyle = sheetReader.getAttributeValue(null, "s");

        boolean isFormula = false;
        String content = null;
        // get value tag
        while (sheetReader.hasNext()) {
            int event = sheetReader.next();
            if (event == XMLStreamConstants.START_ELEMENT && sheetReader.getLocalName().equals("v")) {
                // read content as string
                if (cellType != null && cellType.equals("s")) {
                    int idx = Integer.parseInt(sheetReader.getElementText());
                    content = new XSSFRichTextString(sst.getEntryAt(idx)).toString();
                } else {
                    content = sheetReader.getElementText();
                }
            }
            if (event == XMLStreamConstants.START_ELEMENT && sheetReader.getLocalName().equals("f")) {
                isFormula = true;
            }
            if (event == XMLStreamConstants.END_ELEMENT && sheetReader.getLocalName().equals("c")) {
                break;
            }
        }
        if (content != null) {
            KCellType kcType = getCellType(cellType, cellStyle, isFormula);
            cells[columnIndex] = new StaxPoiCell(parseValue(kcType, content), kcType, currentRow);
        }
        // else let cell be null
    }
    return cells;
}

From source file:org.pentaho.di.trans.steps.webservices.WebService.java

private void compatibleProcessRows(InputStream anXml, Object[] rowData, RowMetaInterface rowMeta,
        boolean ignoreNamespacePrefix, String encoding) throws KettleException {

    // First we should get the complete string
    // The problem is that the string can contain XML or any other format such as HTML saying the service is no longer
    // available.
    // We're talking about a WEB service here.
    // As such, to keep the original parsing scheme, we first read the content.
    // Then we create an input stream from the content again.
    // It's elaborate, but that way we can report on the failure more correctly.
    ///*from ww  w.  ja va2  s.  co m*/
    String response = readStringFromInputStream(anXml, encoding);

    // Create a new reader to feed into the XML Input Factory below...
    //
    StringReader stringReader = new StringReader(response.toString());

    // TODO Very empirical : see if we can do something better here
    try {
        XMLInputFactory vFactory = XMLInputFactory.newInstance();
        XMLStreamReader vReader = vFactory.createXMLStreamReader(stringReader);

        Object[] outputRowData = RowDataUtil.allocateRowData(data.outputRowMeta.size());
        int outputIndex = 0;

        boolean processing = false;
        boolean oneValueRowProcessing = false;
        for (int event = vReader.next(); vReader.hasNext(); event = vReader.next()) {
            switch (event) {
            case XMLStreamConstants.START_ELEMENT:

                // Start new code
                // START_ELEMENT= 1
                //
                if (log.isRowLevel()) {
                    logRowlevel("START_ELEMENT / " + vReader.getAttributeCount() + " / "
                            + vReader.getNamespaceCount());
                }

                // If we start the xml element named like the return type,
                // we start a new row
                //
                if (log.isRowLevel()) {
                    logRowlevel("vReader.getLocalName = " + vReader.getLocalName());
                }
                if (Const.isEmpty(meta.getOutFieldArgumentName())) {
                    // getOutFieldArgumentName() == null
                    if (oneValueRowProcessing) {
                        WebServiceField field = meta.getFieldOutFromWsName(vReader.getLocalName(),
                                ignoreNamespacePrefix);
                        if (field != null) {
                            outputRowData[outputIndex++] = getValue(vReader.getElementText(), field);
                            putRow(data.outputRowMeta, outputRowData);
                            oneValueRowProcessing = false;
                        } else {
                            if (meta.getOutFieldContainerName().equals(vReader.getLocalName())) {
                                // meta.getOutFieldContainerName() = vReader.getLocalName()
                                if (log.isRowLevel()) {
                                    logRowlevel("OutFieldContainerName = " + meta.getOutFieldContainerName());
                                }
                                oneValueRowProcessing = true;
                            }
                        }
                    }
                } else {
                    // getOutFieldArgumentName() != null
                    if (log.isRowLevel()) {
                        logRowlevel("OutFieldArgumentName = " + meta.getOutFieldArgumentName());
                    }
                    if (meta.getOutFieldArgumentName().equals(vReader.getLocalName())) {
                        if (log.isRowLevel()) {
                            logRowlevel("vReader.getLocalName = " + vReader.getLocalName());
                        }
                        if (log.isRowLevel()) {
                            logRowlevel("OutFieldArgumentName = ");
                        }
                        if (processing) {
                            WebServiceField field = meta.getFieldOutFromWsName(vReader.getLocalName(),
                                    ignoreNamespacePrefix);
                            if (field != null) {
                                int index = data.outputRowMeta.indexOfValue(field.getName());
                                if (index >= 0) {
                                    outputRowData[index] = getValue(vReader.getElementText(), field);
                                }
                            }
                            processing = false;
                        } else {
                            WebServiceField field = meta.getFieldOutFromWsName(vReader.getLocalName(),
                                    ignoreNamespacePrefix);
                            if (meta.getFieldsOut().size() == 1 && field != null) {
                                // This can be either a simple return element, or a complex type...
                                //
                                try {
                                    if (meta.isPassingInputData()) {
                                        for (int i = 0; i < rowMeta.getValueMetaList().size(); i++) {
                                            ValueMetaInterface valueMeta = getInputRowMeta().getValueMeta(i);
                                            outputRowData[outputIndex++] = valueMeta.cloneValueData(rowData[i]);

                                        }
                                    }

                                    outputRowData[outputIndex++] = getValue(vReader.getElementText(), field);
                                    putRow(data.outputRowMeta, outputRowData);
                                } catch (WstxParsingException e) {
                                    throw new KettleStepException("Unable to get value for field ["
                                            + field.getName()
                                            + "].  Verify that this is not a complex data type by looking at the response XML.",
                                            e);
                                }
                            } else {
                                for (WebServiceField curField : meta.getFieldsOut()) {
                                    if (!Const.isEmpty(curField.getName())) {
                                        outputRowData[outputIndex++] = getValue(vReader.getElementText(),
                                                curField);
                                    }
                                }
                                processing = true;
                            }
                        }

                    } else {
                        if (log.isRowLevel()) {
                            logRowlevel("vReader.getLocalName = " + vReader.getLocalName());
                        }
                        if (log.isRowLevel()) {
                            logRowlevel("OutFieldArgumentName = " + meta.getOutFieldArgumentName());
                        }
                    }
                }
                break;

            case XMLStreamConstants.END_ELEMENT:
                // END_ELEMENT= 2
                if (log.isRowLevel()) {
                    logRowlevel("END_ELEMENT");
                }
                // If we end the xml element named as the return type, we
                // finish a row
                if ((meta.getOutFieldArgumentName() == null
                        && meta.getOperationName().equals(vReader.getLocalName()))) {
                    oneValueRowProcessing = false;
                } else if (meta.getOutFieldArgumentName() != null
                        && meta.getOutFieldArgumentName().equals(vReader.getLocalName())) {
                    putRow(data.outputRowMeta, outputRowData);
                    processing = false;
                }
                break;
            case XMLStreamConstants.PROCESSING_INSTRUCTION:
                // PROCESSING_INSTRUCTION= 3
                if (log.isRowLevel()) {
                    logRowlevel("PROCESSING_INSTRUCTION");
                }
                break;
            case XMLStreamConstants.CHARACTERS:
                // CHARACTERS= 4
                if (log.isRowLevel()) {
                    logRowlevel("CHARACTERS");
                }
                break;
            case XMLStreamConstants.COMMENT:
                // COMMENT= 5
                if (log.isRowLevel()) {
                    logRowlevel("COMMENT");
                }
                break;
            case XMLStreamConstants.SPACE:
                // PROCESSING_INSTRUCTION= 6
                if (log.isRowLevel()) {
                    logRowlevel("PROCESSING_INSTRUCTION");
                }
                break;
            case XMLStreamConstants.START_DOCUMENT:
                // START_DOCUMENT= 7
                if (log.isRowLevel()) {
                    logRowlevel("START_DOCUMENT");
                }
                if (log.isRowLevel()) {
                    logRowlevel(vReader.getText());
                }
                break;
            case XMLStreamConstants.END_DOCUMENT:
                // END_DOCUMENT= 8
                if (log.isRowLevel()) {
                    logRowlevel("END_DOCUMENT");
                }
                break;
            case XMLStreamConstants.ENTITY_REFERENCE:
                // ENTITY_REFERENCE= 9
                if (log.isRowLevel()) {
                    logRowlevel("ENTITY_REFERENCE");
                }
                break;
            case XMLStreamConstants.ATTRIBUTE:
                // ATTRIBUTE= 10
                if (log.isRowLevel()) {
                    logRowlevel("ATTRIBUTE");
                }
                break;
            case XMLStreamConstants.DTD:
                // DTD= 11
                if (log.isRowLevel()) {
                    logRowlevel("DTD");
                }
                break;
            case XMLStreamConstants.CDATA:
                // CDATA= 12
                if (log.isRowLevel()) {
                    logRowlevel("CDATA");
                }
                break;
            case XMLStreamConstants.NAMESPACE:
                // NAMESPACE= 13
                if (log.isRowLevel()) {
                    logRowlevel("NAMESPACE");
                }
                break;
            case XMLStreamConstants.NOTATION_DECLARATION:
                // NOTATION_DECLARATION= 14
                if (log.isRowLevel()) {
                    logRowlevel("NOTATION_DECLARATION");
                }
                break;
            case XMLStreamConstants.ENTITY_DECLARATION:
                // ENTITY_DECLARATION= 15
                if (log.isRowLevel()) {
                    logRowlevel("ENTITY_DECLARATION");
                }
                break;
            default:
                break;
            }
        }
    } catch (Exception e) {
        throw new KettleStepException(
                BaseMessages.getString(PKG, "WebServices.ERROR0010.OutputParsingError", response.toString()),
                e);
    }
}

From source file:org.pentaho.di.trans.steps.xmlinputstream.XMLInputStream.java

private Object[] processEvent() throws KettleException {

    Object[] outputRowData = RowDataUtil.allocateRowData(data.outputRowMeta.size());
    XMLEvent e = null;// ww w. j a  v  a  2 s  .  c o m
    try {
        e = data.xmlEventReader.nextEvent();
    } catch (XMLStreamException ex) {
        throw new KettleException(ex);
    }

    int eventType = e.getEventType();
    if (data.pos_xml_data_type_numeric != -1) {
        outputRowData[data.pos_xml_data_type_numeric] = new Long(eventType);
    }
    if (data.pos_xml_data_type_description != -1) {
        if (eventType == 0 || eventType > eventDescription.length) {
            // unknown eventType
            outputRowData[data.pos_xml_data_type_description] = eventDescription[0] + "(" + eventType + ")";
        } else {
            outputRowData[data.pos_xml_data_type_description] = eventDescription[eventType];
        }
    }
    if (data.pos_xml_location_line != -1) {
        outputRowData[data.pos_xml_location_line] = new Long(e.getLocation().getLineNumber());
    }
    if (data.pos_xml_location_column != -1) {
        outputRowData[data.pos_xml_location_column] = new Long(e.getLocation().getColumnNumber());
    }

    switch (eventType) {

    case XMLStreamConstants.START_ELEMENT:
        data.elementLevel++;
        if (data.elementLevel > PARENT_ID_ALLOCATE_SIZE - 1) {
            throw new KettleException(BaseMessages.getString(PKG, "XMLInputStream.Log.TooManyNestedElements",
                    PARENT_ID_ALLOCATE_SIZE));
        }
        if (data.elementParentID[data.elementLevel] == null) {
            data.elementParentID[data.elementLevel] = data.elementID;
        }
        data.elementID++;
        data.elementLevelID[data.elementLevel] = data.elementID;

        String xml_data_name;
        if (meta.isEnableNamespaces()) {
            String prefix = e.asStartElement().getName().getPrefix();
            if (Utils.isEmpty(prefix)) {
                xml_data_name = e.asStartElement().getName().getLocalPart();
            } else { // add namespace prefix:
                xml_data_name = prefix + ":" + e.asStartElement().getName().getLocalPart();
            }
        } else {
            xml_data_name = e.asStartElement().getName().getLocalPart();
        }
        if (data.pos_xml_data_name >= 0) {
            outputRowData[data.pos_xml_data_name] = xml_data_name;
        }
        // store the name
        data.elementName[data.elementLevel] = xml_data_name;
        // store simple path
        data.elementPath[data.elementLevel] = data.elementPath[data.elementLevel - 1] + "/" + xml_data_name;

        // write Namespaces out
        if (meta.isEnableNamespaces()) {
            outputRowData = parseNamespaces(outputRowData, e);
        }

        // write Attributes out
        outputRowData = parseAttributes(outputRowData, e);

        break;

    case XMLStreamConstants.END_ELEMENT:
        parseEndElement(outputRowData, e.asEndElement());
        putRowOut(outputRowData);
        data.elementParentID[data.elementLevel + 1] = null;
        data.elementLevel--;
        outputRowData = null; // continue
        break;

    case XMLStreamConstants.SPACE:
        outputRowData = null; // ignore & continue
        break;

    case XMLStreamConstants.CHARACTERS:
    case XMLStreamConstants.CDATA:
        if (data.pos_xml_data_name >= 0) {
            outputRowData[data.pos_xml_data_name] = data.elementName[data.elementLevel];
        }
        String xml_data_value = e.asCharacters().getData();
        if (data.pos_xml_data_value >= 0) {
            if (meta.isEnableTrim()) {
                // optional trim is also eliminating white spaces, tab, cr, lf
                xml_data_value = Const.trim(xml_data_value);
            }
            outputRowData[data.pos_xml_data_value] = xml_data_value;
        }

        if (data.pos_xml_data_value < 0 || Utils.isEmpty((String) outputRowData[data.pos_xml_data_value])) {
            outputRowData = null; // ignore & continue
        }
        break;

    case XMLStreamConstants.PROCESSING_INSTRUCTION:
        outputRowData = null; // ignore & continue
        // TODO test if possible
        break;

    case XMLStreamConstants.COMMENT:
        outputRowData = null; // ignore & continue
        // TODO test if possible
        break;

    case XMLStreamConstants.ENTITY_REFERENCE:
        // should be resolved by default
        outputRowData = null; // ignore & continue
        break;

    case XMLStreamConstants.START_DOCUMENT:
        // just get this information out
        break;

    case XMLStreamConstants.END_DOCUMENT:
        // just get this information out
        break;

    default:
        logBasic("Event:" + eventType);
        outputRowData = null; // ignore & continue
    }

    return outputRowData;
}

From source file:org.reusables.dbunit.autocomplete.AutoCompletionRules.java

private void parse(final URL rulesFileUrl) {
    InputStream input = null;/*from w  w w .  j a  v  a2s.  co  m*/
    XMLStreamReader parser = null;

    try {
        final XMLInputFactory factory = XMLInputFactory.newInstance();

        input = rulesFileUrl.openStream();
        parser = factory.createXMLStreamReader(input);

        for (int event = parser.next(); event != XMLStreamConstants.END_DOCUMENT; event = parser.next()) {
            if (event == XMLStreamConstants.START_ELEMENT && ELEM_RULES.equals(parser.getLocalName())) {
                parseRules(parser);
            } else if (event == XMLStreamConstants.START_ELEMENT && ELEM_TABLE.equals(parser.getLocalName())) {
                parseTable(parser);
            }
        }
    } catch (final XMLStreamException e) {
        throw new DbUnitAutoCompletionException("Error parsing xml stream.", e);
    } catch (final IOException e) {
        throw new DbUnitAutoCompletionException("Error reading stream.", e);
    } finally {
        IOUtils.closeQuietly(input);
        closeParser(parser);
    }
}

From source file:org.reusables.dbunit.autocomplete.AutoCompletionRules.java

private void parseTable(final XMLStreamReader parser) throws XMLStreamException {
    final String name = getName(parser);
    final Map<String, AutoCompletionColumn> columns = addTable(name);
    AutoCompletionColumn currentColumn = null;

    for (int event = parser.next(); event != XMLStreamConstants.END_DOCUMENT; event = parser.next()) {
        if (event == XMLStreamConstants.START_ELEMENT) {
            currentColumn = parseColumn(parser);
            columns.put(currentColumn.getName().toLowerCase(), currentColumn);
        } else if (event == XMLStreamConstants.CHARACTERS || event == XMLStreamConstants.CDATA) {
            parseColumnValue(parser, currentColumn);
        } else if (event == XMLStreamConstants.END_ELEMENT) {
            currentColumn = null;//from  w ww .  j a va  2 s  .  c om
            if (ELEM_TABLE.equals(parser.getLocalName())) {
                return;
            }
        }
    }
}

From source file:org.rhq.enterprise.server.sync.SynchronizationManagerBean.java

private void validateExport(Subject subject, InputStream exportFile, Map<String, Configuration> importConfigs)
        throws ValidationException, XMLStreamException {
    XMLStreamReader rdr = XMLInputFactory.newInstance().createXMLStreamReader(exportFile);

    try {/* w  w w .  ja v a 2 s.c o  m*/
        Set<ConsistencyValidatorFailureReport> failures = new HashSet<ConsistencyValidatorFailureReport>();
        Set<ConsistencyValidator> consistencyValidators = new HashSet<ConsistencyValidator>();

        while (rdr.hasNext()) {
            switch (rdr.next()) {
            case XMLStreamConstants.START_ELEMENT:
                String tagName = rdr.getName().getLocalPart();
                if (SynchronizationConstants.VALIDATOR_ELEMENT.equals(tagName)) {
                    ConsistencyValidator validator = null;
                    String validatorClass = rdr.getAttributeValue(null,
                            SynchronizationConstants.CLASS_ATTRIBUTE);
                    if (!isConsistencyValidatorClass(validatorClass)) {
                        LOG.info("The export file contains an unknown consistency validator: " + validatorClass
                                + ". Ignoring.");
                        continue;
                    }

                    try {
                        validator = validateSingle(rdr, subject);
                    } catch (Exception e) {
                        failures.add(new ConsistencyValidatorFailureReport(validatorClass,
                                printExceptionToString(e)));
                    }
                    if (validator != null) {
                        consistencyValidators.add(validator);
                    }
                } else if (SynchronizationConstants.ENTITIES_EXPORT_ELEMENT.equals(tagName)) {
                    String synchronizerClass = rdr.getAttributeValue(null,
                            SynchronizationConstants.ID_ATTRIBUTE);
                    try {
                        failures.addAll(validateEntities(rdr, subject, consistencyValidators, importConfigs));
                    } catch (Exception e) {
                        throw new ValidationException(
                                "Validation failed unexpectedly while processing the entities exported by the synchronizer '"
                                        + synchronizerClass + "'.",
                                e);
                    }
                }
            }
        }

        if (!failures.isEmpty()) {
            throw new ValidationException(failures);
        }
    } finally {
        rdr.close();
    }
}

From source file:org.rhq.enterprise.server.sync.SynchronizationManagerBean.java

private <E, X> Set<ConsistencyValidatorFailureReport> validateEntities(XMLStreamReader rdr, Subject subject,
        Set<ConsistencyValidator> consistencyValidators, Map<String, Configuration> importConfigurations)
        throws Exception {
    String synchronizerClass = rdr.getAttributeValue(null, SynchronizationConstants.ID_ATTRIBUTE);
    HashSet<ConsistencyValidatorFailureReport> ret = new HashSet<ConsistencyValidatorFailureReport>();

    @SuppressWarnings("unchecked")
    Synchronizer<E, X> synchronizer = instantiate(synchronizerClass, Synchronizer.class,
            "The id attribute of entities doesn't correspond to a class implementing the Synchronizer interface.");

    synchronizer.initialize(subject, entityManager);

    Importer<E, X> importer = synchronizer.getImporter();

    Set<ConsistencyValidator> requriedConsistencyValidators = synchronizer.getRequiredValidators();

    //check that all the required consistency validators were run
    for (ConsistencyValidator v : requriedConsistencyValidators) {
        if (!consistencyValidators.contains(v)) {
            ret.add(new ConsistencyValidatorFailureReport(v.getClass().getName(),
                    "The validator '" + v.getClass().getName() + "' is required by the synchronizer '"
                            + synchronizerClass + "' but was not found in the export file."));
        }// w  w w. j  av  a  2 s.  c  o m
    }

    //don't bother checking if there are inconsistencies in the export file
    if (!ret.isEmpty()) {
        return ret;
    }

    boolean configured = false;
    Configuration importConfiguration = importConfigurations.get(synchronizerClass);

    Set<EntityValidator<X>> validators = null;

    //the passed in configuration has precedence over the default one inlined in 
    //the config file.
    if (importConfiguration != null) {
        importer.configure(importConfiguration);
        validators = importer.getEntityValidators();
        for (EntityValidator<X> v : validators) {
            v.initialize(subject, entityManager);
        }
        configured = true;
    }

    while (rdr.hasNext()) {
        boolean bailout = false;
        switch (rdr.next()) {
        case XMLStreamConstants.START_ELEMENT:
            if (SynchronizationConstants.DEFAULT_CONFIGURATION_ELEMENT.equals(rdr.getName().getLocalPart())) {
                if (!configured) {
                    importConfiguration = getDefaultConfiguration(rdr);
                }
            } else if (SynchronizationConstants.DATA_ELEMENT.equals(rdr.getName().getLocalPart())) {

                //first check if the configure method has been called
                if (!configured) {
                    importer.configure(importConfiguration);
                    validators = importer.getEntityValidators();
                    for (EntityValidator<X> v : validators) {
                        v.initialize(subject, entityManager);
                    }
                    configured = true;
                }

                //now do the validation

                rdr.nextTag();
                X exportedEntity = importer.unmarshallExportedEntity(new ExportReader(rdr));

                for (EntityValidator<X> validator : validators) {
                    try {
                        validator.validateExportedEntity(exportedEntity);
                    } catch (Exception e) {
                        ValidationException v = new ValidationException(
                                "Failed to validate entity [" + exportedEntity + "]", e);
                        ret.add(new ConsistencyValidatorFailureReport(validator.getClass().getName(),
                                printExceptionToString(v)));
                    }
                }
            }
            break;
        case XMLStreamConstants.END_ELEMENT:
            if (SynchronizationConstants.ENTITIES_EXPORT_ELEMENT.equals(rdr.getName().getLocalPart())) {
                bailout = true;
            }
        }

        if (bailout) {
            break;
        }
    }

    return ret;
}