Example usage for javax.xml.stream XMLStreamReader getAttributeValue

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

Introduction

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

Prototype

public String getAttributeValue(String namespaceURI, String localName);

Source Link

Document

Returns the normalized attribute value of the attribute with the namespace and localName If the namespaceURI is null the namespace is not checked for equality

Usage

From source file:org.pentaho.platform.dataaccess.datasource.api.AnalysisService.java

private String getSchemaName(String encoding, InputStream inputStream) throws XMLStreamException, IOException {
    String domainId = null;/*from   ww w  .j a  va 2  s  .  c  o m*/
    XMLStreamReader reader = null;
    try {
        XMLInputFactory factory = XMLInputFactory.newInstance();
        factory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
        if (StringUtils.isEmpty(encoding)) {
            reader = factory.createXMLStreamReader(inputStream);
        } else {
            reader = factory.createXMLStreamReader(inputStream, encoding);
        }

        while (reader.next() != XMLStreamReader.END_DOCUMENT) {
            if (reader.getEventType() == XMLStreamReader.START_ELEMENT
                    && reader.getLocalName().equalsIgnoreCase("Schema")) {
                domainId = reader.getAttributeValue("", "name");
                return domainId;
            }
        }
    } finally {
        if (reader != null) {
            reader.close();
        }
        inputStream.reset();
    }

    return domainId;
}

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

private AutoCompletionColumn parseColumn(final XMLStreamReader parser) {
    final ColumnType type = ColumnType.valueOf(parser.getLocalName().toUpperCase());
    final AutoCompletionColumn column = new AutoCompletionColumn(type, getName(parser));
    column.setMin(parseNumber(parser, ATTR_MIN));
    column.setMax(parseNumber(parser, ATTR_MAX));
    column.setOptional(parseBoolean(parser, ATTR_OPTIONAL));
    column.setReference(parser.getAttributeValue(null, ATTR_REFERENCE));
    return column;
}

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

private String getName(final XMLStreamReader parser) {
    final String name = parser.getAttributeValue(null, ATTR_NAME);

    if (name == null || name.length() == 0) {
        throw new IllegalArgumentException("Missing 'name' attribute.");
    }/*from  ww  w  .  j  a va2s  .  c  o  m*/

    return name;
}

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

private String parseString(final XMLStreamReader parser, final String attributeName,
        final String defaultValue) {
    final String value = parser.getAttributeValue(null, attributeName);
    return value != null ? value : defaultValue;
}

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

private Integer parseNumber(final XMLStreamReader parser, final String attributeName) {
    final String value = parser.getAttributeValue(null, attributeName);

    if (value != null) {
        return Integer.parseInt(value);
    }/*from   w  w w .  ja v  a2  s .c  o m*/

    return null;
}

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

private boolean parseBoolean(final XMLStreamReader parser, final String attributeName) {
    final String value = parser.getAttributeValue(null, attributeName);

    if (value != null) {
        return Boolean.parseBoolean(value);
    }//from  ww w  .j  av a2s. co  m

    return false;
}

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 .  j av a  2  s  . co 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  a  va2 s .  c om*/
    }

    //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;
}

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

private ImportReport importExportFile(Subject subject, InputStream exportFile,
        Map<String, Configuration> importerConfigs) throws ImportException, XMLStreamException {
    XMLStreamReader rdr = XMLInputFactory.newInstance().createXMLStreamReader(exportFile);

    ImportReport report = new ImportReport();

    while (rdr.hasNext()) {
        switch (rdr.next()) {
        case XMLStreamReader.START_ELEMENT:
            String tagName = rdr.getName().getLocalPart();
            if (SynchronizationConstants.ENTITIES_EXPORT_ELEMENT.equals(tagName)) {
                try {
                    String synchronizer = rdr.getAttributeValue(null, SynchronizationConstants.ID_ATTRIBUTE);
                    String notes = importSingle(subject, importerConfigs, rdr);
                    if (notes != null) {
                        report.getImporterNotes().put(synchronizer, notes);
                    }/*from  w ww .j  a v  a2  s .  c o m*/
                } catch (Exception e) {
                    //fail fast on the import errors... This runs in a single transaction
                    //so all imports done so far will get rolled-back.
                    //(Even if we change our minds later and run a transaction per importer
                    //we should fail fast to prevent further damage due to possible
                    //constraint violations in the db, etc.)
                    throw new ImportException("Import failed.", e);
                }
            }
            break;
        }
    }

    return report;
}

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

private ConsistencyValidator validateSingle(XMLStreamReader rdr, Subject subject) throws InstantiationException,
        IllegalAccessException, ClassNotFoundException, XMLStreamException, InconsistentStateException {
    String validatorClassName = rdr.getAttributeValue(null, SynchronizationConstants.CLASS_ATTRIBUTE);
    ConsistencyValidator validator = instantiate(validatorClassName, ConsistencyValidator.class,
            "The validator class denoted in the export file ('%s') does not implement the ConsistencyValidator interface. This should not happen.");

    //init the validator
    validator.initialize(subject, entityManager);

    //perform the validation
    validator.initializeExportedStateValidation(new ExportReader(rdr));
    validator.validateExportedState();/*w w  w  .  j  a va 2 s. c  om*/

    return validator;
}