Example usage for javax.xml.stream XMLStreamReader getName

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

Introduction

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

Prototype

public QName getName();

Source Link

Document

Returns a QName for the current START_ELEMENT or END_ELEMENT event

Usage

From source file:org.geowebcache.georss.StaxGeoRSSReader.java

private Geometry geometry(final XMLStreamReader reader) throws XMLStreamException {
    reader.require(START_ELEMENT, GML.GML_NS_URI, null);
    QName name = reader.getName();
    Geometry geometry = gmlParser.parseGeometry(reader);
    reader.require(END_ELEMENT, name.getNamespaceURI(), name.getLocalPart());
    return geometry;
}

From source file:org.graphipedia.wikipedia.parser.SimpleStaxParser.java

/**
 * Parses the elements in the XML file.//from   w  ww.  ja v a 2 s  .c  om
 * @param reader The XML stream.
 * @throws XMLStreamException when something goes wrong while parsing the XML file.
 */
private void parseElements(XMLStreamReader reader) throws XMLStreamException {
    LinkedList<String> elementStack = new LinkedList<String>();
    StringBuilder textBuffer = new StringBuilder();
    List<String> attributeValues = new ArrayList<String>();

    while (reader.hasNext()) {
        switch (reader.next()) {
        case XMLEvent.START_ELEMENT:
            String startElement = reader.getName().getLocalPart();
            elementStack.push(startElement);
            attributeValues = new ArrayList<String>();
            if (isInterestingWithAttributes(startElement)) {
                int noAttributes = reader.getAttributeCount();
                for (int i = 0; i < noAttributes; i += 1)
                    attributeValues.add(reader.getAttributeValue(i));
            }
            textBuffer.setLength(0);
            break;
        case XMLEvent.END_ELEMENT:
            String element = elementStack.pop();
            if (isInterestingWithAttributes(element)) {
                if (!handleElement(element, textBuffer.toString().trim(), attributeValues))
                    return;
            } else if (isInteresting(element)) {
                if (!handleElement(element, textBuffer.toString().trim()))
                    return;
            }
            break;
        case XMLEvent.CHARACTERS:
            if (isInteresting(elementStack.peek())) {
                textBuffer.append(reader.getText());
            }
            break;
        }
    }
}

From source file:org.jasig.schedassist.impl.caldav.xml.ReportResponseHandlerImpl.java

/**
 * Extracts a {@link List} of {@link Calendar}s from the {@link InputStream}, if present.
 * //from ww w  .j  a v  a2 s .  co m
 * @param inputStream
 * @return a never null, but possibly empty {@link List} of {@link Calendar}s from the {@link InputStream}
 * @throws XmlParsingException in the event the stream could not be properly parsed
 */
public List<CalendarWithURI> extractCalendars(InputStream inputStream) {
    List<CalendarWithURI> results = new ArrayList<CalendarWithURI>();
    ByteArrayOutputStream capturedContent = null;
    XMLInputFactory factory = XMLInputFactory.newInstance();
    try {
        InputStream localReference = inputStream;
        if (log.isDebugEnabled()) {
            capturedContent = new ByteArrayOutputStream();
            localReference = new TeeInputStream(inputStream, capturedContent);
        }
        BufferedInputStream buffered = new BufferedInputStream(localReference);
        buffered.mark(1);
        int firstbyte = buffered.read();
        if (-1 == firstbyte) {
            // short circuit on empty stream
            return results;
        }
        buffered.reset();
        XMLStreamReader parser = factory.createXMLStreamReader(buffered);

        String currentUri = null;
        String currentEtag = null;
        for (int eventType = parser.next(); eventType != XMLStreamConstants.END_DOCUMENT; eventType = parser
                .next()) {
            switch (eventType) {
            case XMLStreamConstants.START_ELEMENT:
                QName name = parser.getName();
                if (isWebdavHrefElement(name)) {
                    currentUri = parser.getElementText();
                } else if (isWebdavEtagElement(name)) {
                    currentEtag = parser.getElementText();
                } else if (isCalendarDataElement(name)) {
                    Calendar cal = extractCalendar(parser.getElementText());
                    if (cal != null) {
                        CalendarWithURI withUri = new CalendarWithURI(cal, currentUri, currentEtag);
                        results.add(withUri);
                    } else if (log.isDebugEnabled()) {
                        log.debug("extractCalendar returned null for " + currentUri + ", skipping");
                    }
                }
                break;
            }
        }

        if (log.isDebugEnabled()) {
            log.debug("extracted " + results.size() + " calendar from " + capturedContent.toString());
        }

    } catch (XMLStreamException e) {
        if (capturedContent != null) {
            log.error("caught XMLStreamException in extractCalendars, captured content: "
                    + capturedContent.toString(), e);
        } else {
            log.error("caught XMLStreamException in extractCalendars, no captured content available", e);
        }
        throw new XmlParsingException("caught XMLStreamException in extractCalendars", e);
    } catch (IOException e) {
        log.error("caught IOException in extractCalendars", e);
        throw new XmlParsingException("caught IOException in extractCalendars", e);
    }

    return results;
}

From source file:org.maodian.flyingcat.xmpp.state.SASLCommandTest.java

@Test
public void testPlainMechanismSuccess() throws Exception {
    String inXML = "<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='PLAIN'>AGp1bGlldAByMG0zMG15cjBtMzA=</auth>";

    Writer writer = new StringWriter();
    XMLStreamReader xmlsr1 = newXMLStreamReader(new StringReader(inXML));
    XMLStreamWriter xmlsw = newXMLStreamWriter(writer);
    // skipt start document
    xmlsr1.nextTag();//from w  ww . j  av a  2  s .  c  o m
    State state = cmd.execute(xmlsr1, xmlsw);

    Reader reader = new StringReader(writer.toString());
    XMLStreamReader xmlsr = XMLInputFactoryHolder.getXMLInputFactory().createXMLStreamReader(reader);

    xmlsr.next();
    QName qname = new QName(XmppNamespace.SASL, "success");
    assertEquals(qname, xmlsr.getName());
    assertTrue(state instanceof AuthenticatedStreamState);
}

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 {//  www . j av 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. jav a  2s  .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;
}

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);
                    }/* ww w. j a  v  a2  s  .co  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 <E, X> String importSingle(Subject subject, Map<String, Configuration> importConfigs,
        XMLStreamReader rdr) throws Exception {
    String synchronizerClassName = rdr.getAttributeValue(null, SynchronizationConstants.ID_ATTRIBUTE);

    @SuppressWarnings("unchecked")
    Synchronizer<E, X> synchronizer = instantiate(synchronizerClassName, Synchronizer.class,
            "The synchronizer denoted in the export file ('%s') does not implement the importer interface. This should not happen.");

    synchronizer.initialize(subject, entityManager);

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

    ExportedEntityMatcher<E, X> matcher = null; //this will be initialized once the importer is configured

    boolean configured = false;
    Configuration importConfiguration = importConfigs.get(synchronizerClassName);

    //the passed in configuration has precedence over the default one inlined in 
    //the config file.
    if (importConfiguration != null) {
        importer.configure(importConfiguration);
        matcher = importer.getExportedEntityMatcher();
        configured = true;/* ww w .j a  v a2s  .c  om*/
    }

    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);
                    matcher = importer.getExportedEntityMatcher();
                    configured = true;
                }

                //now do the import

                rdr.nextTag();
                X exportedEntity = importer.unmarshallExportedEntity(new ExportReader(rdr));
                E entity = matcher == null ? null : matcher.findMatch(exportedEntity);
                importer.update(entity, exportedEntity);
            }
            break;
        case XMLStreamConstants.END_ELEMENT:
            if (SynchronizationConstants.ENTITIES_EXPORT_ELEMENT.equals(rdr.getName().getLocalPart())) {
                bailout = true;
            }
        }

        if (bailout) {
            break;
        }
    }

    //we might have had no data and because we configure the importer lazily, it might
    //be left unconfigured by the above loop.
    if (!configured) {
        importer.configure(importConfiguration);
    }

    return importer.finishImport();
}

From source file:org.rhq.plugins.hadoop.HadoopServerConfigurationDelegate.java

public static void parseAndAssignProps(File configFile, Map<String, PropertySimple> props)
        throws XMLStreamException, IOException {
    FileInputStream in = new FileInputStream(configFile);
    XMLStreamReader rdr = XML_INPUT_FACTORY.createXMLStreamReader(in);
    try {/*from   w w w.j  a  va 2s. co m*/
        boolean inProperty = false;
        String propertyName = null;
        String propertyValue = null;

        while (rdr.hasNext()) {
            int event = rdr.next();

            String tag = null;

            switch (event) {
            case XMLStreamReader.START_ELEMENT:
                tag = rdr.getName().getLocalPart();
                if (PROPERTY_TAG_NAME.equals(tag)) {
                    inProperty = true;
                } else if (inProperty && NAME_TAG_NAME.equals(tag)) {
                    propertyName = rdr.getElementText();
                } else if (inProperty && VALUE_TAG_NAME.equals(tag)) {
                    propertyValue = rdr.getElementText();
                }
                break;
            case XMLStreamReader.END_ELEMENT:
                tag = rdr.getName().getLocalPart();
                if (PROPERTY_TAG_NAME.equals(tag)) {
                    inProperty = false;

                    PropertySimple prop = props.get(propertyName);
                    if (prop != null) {
                        prop.setValue(propertyValue);
                    }

                    propertyName = null;
                    propertyValue = null;
                }
                break;
            }
        }
    } finally {
        rdr.close();
        in.close();
    }
}

From source file:org.rhq.plugins.hadoop.HadoopServerConfigurationDelegate.java

private static void updateFile(File configFile, Map<String, PropertySimple> allProps)
        throws IOException, InterruptedException, XMLStreamException {
    InputStream in = null;/*from   w  w w  . ja  va  2s. co m*/
    XMLStreamReader rdr = null;

    OutputStream out = null;
    XMLStreamWriter outWrt = null;

    try {
        Set<String> processedPropertyNames = new HashSet<String>();

        in = new BufferedInputStream(new FileInputStream(configFile));
        rdr = XML_INPUT_FACTORY.createXMLStreamReader(in);

        File tmpFile = File.createTempFile("hadoop-plugin", null);
        out = new FileOutputStream(tmpFile);
        outWrt = XML_OUTPUT_FACTORY.createXMLStreamWriter(out);

        ByteArrayOutputStream stash = new ByteArrayOutputStream();
        XMLStreamWriter stashWrt = XML_OUTPUT_FACTORY.createXMLStreamWriter(stash);
        boolean outputActive = true;

        outWrt.writeStartDocument();

        while (rdr.hasNext()) {
            int event = rdr.next();

            XMLStreamWriter wrt = outputActive ? outWrt : stashWrt;

            switch (event) {
            case XMLStreamConstants.ATTRIBUTE:
                break;
            case XMLStreamConstants.CDATA:
                wrt.writeCData(rdr.getText());
                break;
            case XMLStreamConstants.CHARACTERS:
                wrt.writeCharacters(rdr.getText());
                break;
            case XMLStreamConstants.COMMENT:
                wrt.writeComment(rdr.getText());
                break;
            case XMLStreamConstants.DTD:
                wrt.writeDTD(rdr.getText());
                break;
            case XMLStreamConstants.END_DOCUMENT:
                wrt.writeEndDocument();
                break;
            case XMLStreamConstants.END_ELEMENT:
                if (PROPERTY_TAG_NAME.equals(rdr.getName().getLocalPart())) {
                    String encoding = rdr.getEncoding();
                    if (encoding == null) {
                        encoding = "UTF-8";
                    }

                    String propertyTagSoFar = Charset.forName(encoding)
                            .decode(ByteBuffer.wrap(stash.toByteArray())).toString();
                    DetectedPropertyNameAndUpdatedTag propAndTag = updateProperty(propertyTagSoFar, allProps);

                    //yes, we're intentionally circumventing the xml stream writer, because we already have the XML data we want to write.
                    outWrt.flush();
                    out.write(propAndTag.updatedTag.getBytes("UTF-8"));

                    processedPropertyNames.add(propAndTag.propertyName);

                    //reset stuff
                    stash.reset();
                    wrt = outWrt;
                    outputActive = true;
                } else if (CONFIGURATION_TAG_NAME.equals(rdr.getName().getLocalPart())) {
                    //now add the new props
                    for (String prop : processedPropertyNames) {
                        allProps.remove(prop);
                    }

                    for (Map.Entry<String, PropertySimple> e : allProps.entrySet()) {
                        outWrt.writeStartElement(PROPERTY_TAG_NAME);

                        outWrt.writeStartElement(NAME_TAG_NAME);
                        outWrt.writeCharacters(e.getKey());
                        outWrt.writeEndElement();

                        outWrt.writeStartElement(VALUE_TAG_NAME);
                        outWrt.writeCharacters(e.getValue().getStringValue());
                        outWrt.writeEndElement();

                        outWrt.writeEndElement();
                    }
                }
                wrt.writeEndElement();
                break;
            case XMLStreamConstants.ENTITY_DECLARATION:
                //XXX could not find what to do with this
                break;
            case XMLStreamConstants.ENTITY_REFERENCE:
                wrt.writeEntityRef(rdr.getText());
                break;
            case XMLStreamConstants.NAMESPACE:
                for (int i = 0; i < rdr.getNamespaceCount(); ++i) {
                    wrt.writeNamespace(rdr.getNamespacePrefix(i), rdr.getNamespaceURI(i));
                }
                break;
            case XMLStreamConstants.NOTATION_DECLARATION:
                //XXX could not find what to do with this
                break;
            case XMLStreamConstants.PROCESSING_INSTRUCTION:
                wrt.writeProcessingInstruction(rdr.getPITarget(), rdr.getPIData());
                break;
            case XMLStreamConstants.SPACE:
                wrt.writeCharacters(rdr.getText());
                break;
            case XMLStreamConstants.START_DOCUMENT:
                //this seems to be never called for some strange reason
                //wrt.writeStartDocument();
                break;
            case XMLStreamConstants.START_ELEMENT:
                wrt.writeStartElement(rdr.getName().getPrefix(), rdr.getName().getLocalPart(),
                        rdr.getName().getNamespaceURI());

                for (int i = 0; i < rdr.getAttributeCount(); ++i) {
                    wrt.writeAttribute(rdr.getAttributePrefix(i), rdr.getAttributeNamespace(i),
                            rdr.getAttributeLocalName(i), rdr.getAttributeValue(i));
                }

                if (PROPERTY_TAG_NAME.equals(rdr.getName().getLocalPart())) {
                    wrt.writeCharacters("");
                    outputActive = false;
                }
                break;
            }
        }

        outWrt.flush();
        out.flush();
        out.close();

        in.close();

        //now copy the temp file in the place of the original one
        FileUtil.copyFile(tmpFile, configFile);
    } finally {
        rdr.close();

        outWrt.flush();
        outWrt.close();

        try {
            in.close();
        } finally {
            out.flush();
            out.close();
        }
    }
}