Example usage for javax.xml.stream XMLStreamConstants CHARACTERS

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

Introduction

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

Prototype

int CHARACTERS

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

Click Source Link

Document

Indicates an event is characters

Usage

From source file:com.microsoft.windowsazure.services.table.client.AtomPubParser.java

/**
 * Reserved for internal use. Parses the operation response as a collection of entities. Reads entity data from the
 * specified input stream using the specified class type and optionally projects each entity result with the
 * specified resolver into an {@link ODataPayload} containing a collection of {@link TableResult} objects. .
 * /*  w  w w  . ja  v a  2s  .  c  o m*/
 * @param inStream
 *            The <code>InputStream</code> to read the data to parse from.
 * @param clazzType
 *            The class type <code>T</code> implementing {@link TableEntity} for the entities returned. Set to
 *            <code>null</code> to ignore the returned entities and copy only response properties into the
 *            {@link TableResult} objects.
 * @param resolver
 *            An {@link EntityResolver} instance to project the entities into instances of type <code>R</code>. Set
 *            to <code>null</code> to return the entities as instances of the class type <code>T</code>.
 * @param opContext
 *            An {@link OperationContext} object used to track the execution of the operation.
 * @return
 *         An {@link ODataPayload} containing a collection of {@link TableResult} objects with the parsed operation
 *         response.
 * 
 * @throws XMLStreamException
 *             if an error occurs while accessing the stream.
 * @throws ParseException
 *             if an error occurs while parsing the stream.
 * @throws InstantiationException
 *             if an error occurs while constructing the result.
 * @throws IllegalAccessException
 *             if an error occurs in reflection while parsing the result.
 * @throws StorageException
 *             if a storage service error occurs.
 */
@SuppressWarnings("unchecked")
protected static <T extends TableEntity, R> ODataPayload<?> parseResponse(final InputStream inStream,
        final Class<T> clazzType, final EntityResolver<R> resolver, final OperationContext opContext)
        throws XMLStreamException, ParseException, InstantiationException, IllegalAccessException,
        StorageException {
    ODataPayload<T> corePayload = null;
    ODataPayload<R> resolvedPayload = null;
    ODataPayload<?> commonPayload = null;

    if (resolver != null) {
        resolvedPayload = new ODataPayload<R>();
        commonPayload = resolvedPayload;
    } else {
        corePayload = new ODataPayload<T>();
        commonPayload = corePayload;
    }

    final XMLStreamReader xmlr = Utility.createXMLStreamReaderFromStream(inStream);
    int eventType = xmlr.getEventType();
    xmlr.require(XMLStreamConstants.START_DOCUMENT, null, null);
    eventType = xmlr.next();

    xmlr.require(XMLStreamConstants.START_ELEMENT, null, ODataConstants.FEED);
    // skip feed chars
    eventType = xmlr.next();

    while (xmlr.hasNext()) {
        eventType = xmlr.next();

        if (eventType == XMLStreamConstants.CHARACTERS) {
            xmlr.getText();
            continue;
        }

        final String name = xmlr.getName().toString();

        if (eventType == XMLStreamConstants.START_ELEMENT) {
            if (name.equals(ODataConstants.BRACKETED_ATOM_NS + ODataConstants.ENTRY)) {
                final TableResult res = parseEntity(xmlr, clazzType, resolver, opContext);
                if (corePayload != null) {
                    corePayload.tableResults.add(res);
                }

                if (resolver != null) {
                    resolvedPayload.results.add((R) res.getResult());
                } else {
                    corePayload.results.add((T) res.getResult());
                }
            }
        } else if (eventType == XMLStreamConstants.END_ELEMENT
                && name.equals(ODataConstants.BRACKETED_ATOM_NS + ODataConstants.FEED)) {
            break;
        }
    }

    xmlr.require(XMLStreamConstants.END_ELEMENT, null, ODataConstants.FEED);
    return commonPayload;
}

From source file:com.marklogic.contentpump.AggregateXMLReader.java

private void processStartElement() throws XMLStreamException {
    String name = xmlSR.getLocalName();
    String namespace = xmlSR.getNamespaceURI();
    if (LOG.isTraceEnabled()) {
        LOG.trace("Start-tag: " + xmlSR.getName() + " at depth " + currDepth);
    }//from w  ww  .  j a va 2  s  .  c o m
    if (namespace == null) {
        String prefix = xmlSR.getPrefix();
        if ("".equals(prefix)) {
            prefix = DEFAULT_NS;
        }
        if (nameSpaces.get(prefix) != null) {
            namespace = nameSpaces.get(prefix).peek();
        }
    }

    String prefix = xmlSR.getPrefix();
    int attrCount = xmlSR.getAttributeCount();
    boolean isNewRootStart = false;
    currDepth++;
    Location loc = xmlSR.getLocation();
    if (recordName == null) {
        recordName = name;
        if (recordNamespace == null) {
            recordNamespace = namespace;
        }
        recordDepth = currDepth;
        isNewRootStart = true;
        newDoc = true;
        newUriId = true;
        if (useAutomaticId) {
            setKey(idGen.incrementAndGet(), loc.getLineNumber(), loc.getColumnNumber(), true);
        }
    } else {
        // record element name may not nest
        if (name.equals(recordName) && ((recordNamespace == null && namespace == null)
                || (recordNamespace != null && recordNamespace.equals(namespace)))) {
            recordDepth = currDepth;
            isNewRootStart = true;
            newDoc = true;
            newUriId = true;
            if (useAutomaticId) {
                setKey(idGen.incrementAndGet(), loc.getLineNumber(), loc.getColumnNumber(), true);
            }
        }
    }
    copyNameSpaceDecl();
    if (!newDoc) {
        return;
    }
    StringBuilder sb = new StringBuilder();
    sb.append("<");
    if (prefix != null && !prefix.equals("")) {
        sb.append(prefix + ":" + name);
    } else {
        sb.append(name);
    }
    // add namespaces declared into the new root element
    if (isNewRootStart) {
        Set<String> keys = nameSpaces.keySet();
        for (String k : keys) {
            String v = nameSpaces.get(k).peek();
            if (DEFAULT_NS == k) {
                sb.append(" xmlns=\"" + v + "\"");
            } else {
                sb.append(" xmlns:" + k + "=\"" + v + "\"");
            }
        }
    } else {
        // add new namespace declaration into current element
        int stop = xmlSR.getNamespaceCount();
        if (stop > 0) {
            String nsDeclPrefix, nsDeclUri;
            if (LOG.isTraceEnabled()) {
                LOG.trace("checking namespace declarations");
            }
            for (int i = 0; i < stop; i++) {
                nsDeclPrefix = xmlSR.getNamespacePrefix(i);
                nsDeclUri = xmlSR.getNamespaceURI(i);
                if (LOG.isTraceEnabled()) {
                    LOG.trace(nsDeclPrefix + ":" + nsDeclUri);
                }
                if (DEFAULT_NS == nsDeclPrefix) {
                    sb.append(" xmlns=\"" + nsDeclUri + "\"");
                } else {
                    sb.append(" xmlns:" + nsDeclPrefix + "=\"" + nsDeclUri + "\"");
                }
            }
        }
    }
    for (int i = 0; i < attrCount; i++) {
        String aPrefix = xmlSR.getAttributePrefix(i);
        String aName = xmlSR.getAttributeLocalName(i);
        String aValue = StringEscapeUtils.escapeXml(xmlSR.getAttributeValue(i));
        sb.append(" " + (null == aPrefix ? "" : (aPrefix + ":")) + aName + "=\"" + aValue + "\"");
        if (!useAutomaticId && newDoc && ("@" + aName).equals(idName) && currentId == null) {
            currentId = aValue;
            setKey(aValue, loc.getLineNumber(), loc.getColumnNumber(), true);
        }
    }
    sb.append(">");

    // allow for repeated idName elements: first one wins
    // NOTE: idName is namespace-insensitive
    if (!useAutomaticId && newDoc && name.equals(idName)) {
        int nextToken = xmlSR.next();
        if (nextToken != XMLStreamConstants.CHARACTERS) {
            throw new XMLStreamException(
                    "badly formed xml or " + idName + " is not a simple node: at" + xmlSR.getLocation());
        }
        do {
            String idStr = StringEscapeUtils.escapeXml(xmlSR.getText());
            if (currentId == null) {
                currentId = "";
            }
            currentId += idStr;
            sb.append(idStr);
        } while ((nextToken = xmlSR.next()) == XMLStreamConstants.CHARACTERS);
        if (newUriId) {
            setKey(currentId, loc.getLineNumber(), loc.getColumnNumber(), true);
            newUriId = false;
        } else if (LOG.isDebugEnabled()) {
            LOG.debug("Duplicate URI_ID match found: key = " + key);
        }
        if (LOG.isTraceEnabled()) {
            LOG.trace("URI_ID: " + currentId);
        }
        // advance to the END_ELEMENT
        if (nextToken != XMLStreamConstants.END_ELEMENT) {
            throw new XMLStreamException("badly formed xml: no END_TAG after id text" + xmlSR.getLocation());
        }
        sb.append("</");
        if (prefix != null && !prefix.equals("")) {
            sb.append(prefix + ":" + name);
        } else {
            sb.append(name);
        }
        sb.append(">");
        currDepth--;
    }
    write(sb.toString());
}

From source file:edu.utah.further.core.api.xml.XmlUtil.java

/**
 * Basic StAX element printout. For more sophisticated functionality, use
 * {@link XmlStreamPrinter}.//from  w  w  w  .  j  av a2s  .  com
 * 
 * @param reader
 *            reader
 * @return reader's next element textual representation
 */
public static String getEventSimpleString(final XMLStreamReader reader) {
    switch (reader.getEventType()) {
    case XMLStreamConstants.START_ELEMENT:
        return "START_ELEMENT:\t\"" + reader.getLocalName() + "\"";
    case XMLStreamConstants.END_ELEMENT:
        return "END_ELEMENT:\t\"" + reader.getLocalName() + "\"";
    case XMLStreamConstants.START_DOCUMENT:
        return "START_DOCUMENT";
    case XMLStreamConstants.END_DOCUMENT:
        return "END_DOCUMENT";
    case XMLStreamConstants.CHARACTERS:
        return "CHARACTERS:\t\"" + reader.getText() + "\"" + " blank? "
                + StringUtils.isWhitespace(reader.getText());
    case XMLStreamConstants.SPACE:
        return "SPACE:\t\"" + reader.getText() + "\"";
    default:
        return "EVENT:\t" + reader.getEventType();
    }
}

From source file:ca.uhn.fhir.parser.XmlParser.java

private <T> T doXmlLoop(XMLEventReader streamReader, ParserState<T> parserState) {
    ourLog.trace("Entering XML parsing loop with state: {}", parserState);

    try {//from ww w .j  ava2s .  c  om
        List<String> heldComments = new ArrayList<String>(1);

        while (streamReader.hasNext()) {
            XMLEvent nextEvent = streamReader.nextEvent();
            try {

                switch (nextEvent.getEventType()) {
                case XMLStreamConstants.START_ELEMENT: {
                    StartElement elem = nextEvent.asStartElement();

                    String namespaceURI = elem.getName().getNamespaceURI();

                    if ("extension".equals(elem.getName().getLocalPart())) {
                        Attribute urlAttr = elem.getAttributeByName(new QName("url"));
                        String url;
                        if (urlAttr == null || isBlank(urlAttr.getValue())) {
                            getErrorHandler().missingRequiredElement(new ParseLocation("extension"), "url");
                            url = null;
                        } else {
                            url = urlAttr.getValue();
                        }
                        parserState.enteringNewElementExtension(elem, url, false);
                    } else if ("modifierExtension".equals(elem.getName().getLocalPart())) {
                        Attribute urlAttr = elem.getAttributeByName(new QName("url"));
                        String url;
                        if (urlAttr == null || isBlank(urlAttr.getValue())) {
                            getErrorHandler().missingRequiredElement(new ParseLocation("modifierExtension"),
                                    "url");
                            url = null;
                        } else {
                            url = urlAttr.getValue();
                        }
                        parserState.enteringNewElementExtension(elem, url, true);
                    } else {
                        String elementName = elem.getName().getLocalPart();
                        parserState.enteringNewElement(namespaceURI, elementName);
                    }

                    if (!heldComments.isEmpty()) {
                        for (String next : heldComments) {
                            parserState.commentPre(next);
                        }
                        heldComments.clear();
                    }

                    @SuppressWarnings("unchecked")
                    Iterator<Attribute> attributes = elem.getAttributes();
                    for (Iterator<Attribute> iter = attributes; iter.hasNext();) {
                        Attribute next = iter.next();
                        parserState.attributeValue(next.getName().getLocalPart(), next.getValue());
                    }

                    break;
                }
                case XMLStreamConstants.END_DOCUMENT:
                case XMLStreamConstants.END_ELEMENT: {
                    if (!heldComments.isEmpty()) {
                        for (String next : heldComments) {
                            parserState.commentPost(next);
                        }
                        heldComments.clear();
                    }
                    parserState.endingElement();
                    //                  if (parserState.isComplete()) {
                    //                     return parserState.getObject();
                    //                  }
                    break;
                }
                case XMLStreamConstants.CHARACTERS: {
                    parserState.string(nextEvent.asCharacters().getData());
                    break;
                }
                case XMLStreamConstants.COMMENT: {
                    Comment comment = (Comment) nextEvent;
                    String commentText = comment.getText();
                    heldComments.add(commentText);
                    break;
                }
                }

                parserState.xmlEvent(nextEvent);

            } catch (DataFormatException e) {
                throw new DataFormatException("DataFormatException at [" + nextEvent.getLocation().toString()
                        + "]: " + e.getMessage(), e);
            }
        }
        return parserState.getObject();
    } catch (XMLStreamException e) {
        throw new DataFormatException(e);
    }
}

From source file:com.microsoft.windowsazure.services.table.client.AtomPubParser.java

/**
 * Reserved for internal use. Reads the properties of an entity from the stream into a map of property names to
 * typed values. Reads the entity data as an AtomPub Entry Resource from the specified {@link XMLStreamReader} into
 * a map of <code>String</code> property names to {@link EntityProperty} data typed values.
 * /*ww  w  .  j av  a  2  s.co  m*/
 * @param xmlr
 *            The <code>XMLStreamReader</code> to read the data from.
 * @param opContext
 *            An {@link OperationContext} object used to track the execution of the operation.
 * 
 * @return
 *         A <code>java.util.HashMap</code> containing a map of <code>String</code> property names to
 *         {@link EntityProperty} data typed values found in the entity data.
 * @throws XMLStreamException
 *             if an error occurs accessing the stream.
 * @throws ParseException
 *             if an error occurs converting the input to a particular data type.
 */
protected static HashMap<String, EntityProperty> readProperties(final XMLStreamReader xmlr,
        final OperationContext opContext) throws XMLStreamException, ParseException {
    int eventType = xmlr.getEventType();
    xmlr.require(XMLStreamConstants.START_ELEMENT, null, ODataConstants.PROPERTIES);
    final HashMap<String, EntityProperty> properties = new HashMap<String, EntityProperty>();

    while (xmlr.hasNext()) {
        eventType = xmlr.next();
        if (eventType == XMLStreamConstants.CHARACTERS) {
            xmlr.getText();
            continue;
        }

        if (eventType == XMLStreamConstants.START_ELEMENT
                && xmlr.getNamespaceURI().equals(ODataConstants.DATA_SERVICES_NS)) {
            final String key = xmlr.getLocalName();
            String val = Constants.EMPTY_STRING;
            String edmType = null;

            if (xmlr.getAttributeCount() > 0) {
                edmType = xmlr.getAttributeValue(ODataConstants.DATA_SERVICES_METADATA_NS, ODataConstants.TYPE);
            }

            // move to chars
            eventType = xmlr.next();

            if (eventType == XMLStreamConstants.CHARACTERS) {
                val = xmlr.getText();

                // end element
                eventType = xmlr.next();
            }

            xmlr.require(XMLStreamConstants.END_ELEMENT, null, key);

            final EntityProperty newProp = new EntityProperty(val, EdmType.parse(edmType));
            properties.put(key, newProp);
        } else if (eventType == XMLStreamConstants.END_ELEMENT && xmlr.getName().toString()
                .equals(ODataConstants.BRACKETED_DATA_SERVICES_METADATA_NS + ODataConstants.PROPERTIES)) {
            // End read properties
            break;
        }
    }

    xmlr.require(XMLStreamConstants.END_ELEMENT, null, ODataConstants.PROPERTIES);
    return properties;
}

From source file:act.installer.pubchem.PubchemParser.java

/**
 * Incrementally parses a stream of XML events from a PubChem file, extracting the next available PC-Compound entry
 * as a Chemical object./*from   w w  w . j  a v  a 2 s.  co m*/
 * @param eventReader The xml event reader we are parsing the XML from
 * @return The constructed chemical
 * @throws XMLStreamException
 * @throws XPathExpressionException
 */
public Chemical extractNextChemicalFromXMLStream(XMLEventReader eventReader)
        throws XMLStreamException, JaxenException {
    Document bufferDoc = null;
    Element currentElement = null;
    StringBuilder textBuffer = null;
    /* With help from
     * http://stackoverflow.com/questions/7998733/loading-local-chunks-in-dom-while-parsing-a-large-xml-file-in-sax-java
     */
    while (eventReader.hasNext()) {
        XMLEvent event = eventReader.nextEvent();

        switch (event.getEventType()) {
        case XMLStreamConstants.START_ELEMENT:
            String eventName = event.asStartElement().getName().getLocalPart();
            if (COMPOUND_DOC_TAG.equals(eventName)) {
                // Create a new document if we've found the start of a compound object.
                bufferDoc = documentBuilder.newDocument();
                currentElement = bufferDoc.createElement(eventName);
                bufferDoc.appendChild(currentElement);
            } else if (currentElement != null) { // Wait until we've found a compound entry to start slurping up data.
                // Create a new child element and push down the current pointer when we find a new node.
                Element newElement = bufferDoc.createElement(eventName);
                currentElement.appendChild(newElement);
                currentElement = newElement;
            } // If we aren't in a PC-Compound tree, we just let the elements pass by.
            break;

        case XMLStreamConstants.CHARACTERS:
            if (currentElement == null) { // Ignore this event if we're not in a PC-Compound tree.
                continue;
            }

            Characters chars = event.asCharacters();
            // Ignore only whitespace strings, which just inflate the size of the DOM.  Text coalescing makes this safe.
            if (chars.isWhiteSpace()) {
                continue;
            }

            // Rely on the XMLEventStream to coalesce consecutive text events.
            Text textNode = bufferDoc.createTextNode(chars.getData());
            currentElement.appendChild(textNode);
            break;

        case XMLStreamConstants.END_ELEMENT:
            if (currentElement == null) { // Ignore this event if we're not in a PC-Compound tree.
                continue;
            }

            eventName = event.asEndElement().getName().getLocalPart();
            Node parentNode = currentElement.getParentNode();
            if (parentNode instanceof Element) {
                currentElement = (Element) parentNode;
            } else if (parentNode instanceof Document && eventName.equals(COMPOUND_DOC_TAG)) {
                // We're back at the top of the node stack!  Convert the buffered document into a Chemical.
                PubchemEntry entry = extractPCCompoundFeatures(bufferDoc);
                if (entry != null) {
                    return entry.asChemical();
                } else {
                    // Skip this entry if we can't process it correctly by resetting the world and continuing on.
                    bufferDoc = null;
                    currentElement = null;
                }
            } else {
                // This should not happen, but is here as a sanity check.
                throw new RuntimeException(String.format("Parent of XML element %s is of type %d, not Element",
                        currentElement.getTagName(), parentNode.getNodeType()));
            }
            break;

        // TODO: do we care about attributes or other XML structures?
        }
    }

    // Return null when we run out of chemicals, just like readLine().
    return null;
}

From source file:com.marklogic.contentpump.AggregateXMLReader.java

@Override
public boolean nextKeyValue() throws IOException, InterruptedException {
    if (xmlSR == null) {
        hasNext = false;/*from   w ww .j  a v a2  s. c  om*/
        return false;
    }

    try {
        while (xmlSR.hasNext()) {
            int eventType;
            //getCharacterOffset() returns int; 
            //int will overflows if file is larger than 2GB
            if (!overflow && xmlSR.getLocation().getCharacterOffset() < -1) {
                overflow = true;
                LOG.info("In progress...");
            }
            //do not update pos if offset overflows
            if (!overflow) {
                pos = xmlSR.getLocation().getCharacterOffset();
            }
            eventType = xmlSR.next();
            switch (eventType) {
            case XMLStreamConstants.START_ELEMENT:
                if (startOfRecord) {
                    // this is the start of the root, only copy
                    // namespaces
                    copyNameSpaceDecl();
                    startOfRecord = false;
                    continue;
                }
                processStartElement();
                break;
            case XMLStreamConstants.CHARACTERS:
                write(StringEscapeUtils.escapeXml(xmlSR.getText()));
                break;
            case XMLStreamConstants.CDATA:
                write("<![CDATA[");
                write(xmlSR.getText());
                write("]]>");
                break;
            case XMLStreamConstants.SPACE:
                write(xmlSR.getText());
                break;
            case XMLStreamConstants.ENTITY_REFERENCE:
                write("&");
                write(xmlSR.getLocalName());
                write(";");
                break;
            case XMLStreamConstants.DTD:
                write("<!DOCTYPE");
                write(xmlSR.getText());
                write(">");
                break;
            case XMLStreamConstants.PROCESSING_INSTRUCTION:
                write("<?");
                write(xmlSR.getPIData());
                write("?>");
                break;
            case XMLStreamConstants.COMMENT:
                write("<!--");
                write(xmlSR.getText());
                write("-->");
                break;
            case XMLStreamConstants.END_ELEMENT:
                keepGoing = processEndElement();
                if (!keepGoing) {
                    keepGoing = true;
                    return true;
                }
                break;
            case XMLStreamConstants.START_DOCUMENT:
                throw new XMLStreamException("unexpected start of document within record!\n" + "recordName = "
                        + recordName + ", recordNamespace = " + recordNamespace + " at " + xmlSR.getLocation());
            case XMLStreamConstants.END_DOCUMENT:
                if (currentId != null) {
                    throw new XMLStreamException(
                            "end of document before end of current record!\n" + "recordName = " + recordName
                                    + ", recordNamespace = " + recordNamespace + " at " + xmlSR.getLocation());
                } else {
                    if (compressed) {
                        //this doc is done, refer to the zip for next doc
                        hasNext = false;
                        return false;
                    } else {
                        //get next file from FileIterator
                        if (iterator != null && iterator.hasNext()) {
                            close();
                            initStreamReader(iterator.next());
                            continue;
                        } else {
                            hasNext = false;
                            return false;
                        }
                    }
                }
            default:
                throw new XMLStreamException("UNIMPLEMENTED: " + eventType);
            }
        }
    } catch (XMLStreamException e) {
        LOG.error("Parsing error", e);
        throw new IOException("Parsing error", e);
    }

    return false;
}

From source file:de.uzk.hki.da.cb.CreatePremisAction.java

/**
 * Accepts a premis.xml file and creates a new xml file for each jhove section  
 * //  w  w w  . j a v  a2 s  .c  o m
 * @author Thomas Kleinke
 * Extract jhove data.
 *
 * @param premisFilePath the premis file path
 * @param outputFolder the output folder
 * @throws XMLStreamException the xML stream exception
 */
public void extractJhoveData(String premisFilePath, String outputFolder) throws XMLStreamException {

    outputFolder += "/premis_output/";

    FileInputStream inputStream = null;

    try {
        inputStream = new FileInputStream(premisFilePath);
    } catch (FileNotFoundException e) {
        throw new RuntimeException("Couldn't find file " + premisFilePath, e);
    }

    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    XMLStreamReader streamReader = inputFactory.createXMLStreamReader(inputStream);

    boolean textElement = false;
    boolean jhoveSection = false;
    boolean objectIdentifierValue = false;
    int tab = 0;
    String fileId = "";

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

        switch (event) {

        case XMLStreamConstants.START_ELEMENT:

            if (streamReader.getLocalName().equals("jhove")) {
                jhoveSection = true;
                String outputFilePath = outputFolder + fileId.replace('/', '_').replace('.', '_') + ".xml";
                if (!new File(outputFolder).exists())
                    new File(outputFolder).mkdirs();
                writer = startNewDocument(outputFilePath);
            }

            if (streamReader.getLocalName().equals("objectIdentifierValue"))
                objectIdentifierValue = true;

            if (jhoveSection) {
                writer.writeDTD("\n");
                indent(tab);
                tab++;

                String prefix = streamReader.getPrefix();

                if (prefix != null && !prefix.equals("")) {
                    writer.setPrefix(prefix, streamReader.getNamespaceURI());
                    writer.writeStartElement(streamReader.getNamespaceURI(), streamReader.getLocalName());
                } else
                    writer.writeStartElement(streamReader.getLocalName());

                for (int i = 0; i < streamReader.getNamespaceCount(); i++)
                    writer.writeNamespace(streamReader.getNamespacePrefix(i), streamReader.getNamespaceURI(i));

                for (int i = 0; i < streamReader.getAttributeCount(); i++) {
                    QName qname = streamReader.getAttributeName(i);
                    String attributeName = qname.getLocalPart();
                    String attributePrefix = qname.getPrefix();
                    if (attributePrefix != null && !attributePrefix.equals(""))
                        attributeName = attributePrefix + ":" + attributeName;

                    writer.writeAttribute(attributeName, streamReader.getAttributeValue(i));
                }
            }

            break;

        case XMLStreamConstants.CHARACTERS:
            if (objectIdentifierValue) {
                fileId = streamReader.getText();
                objectIdentifierValue = false;
            }

            if (jhoveSection && !streamReader.isWhiteSpace()) {
                writer.writeCharacters(streamReader.getText());
                textElement = true;
            }
            break;

        case XMLStreamConstants.END_ELEMENT:
            if (jhoveSection) {
                tab--;

                if (!textElement) {
                    writer.writeDTD("\n");
                    indent(tab);
                }

                writer.writeEndElement();
                textElement = false;

                if (streamReader.getLocalName().equals("jhove")) {
                    jhoveSection = false;
                    finalizeDocument();
                }
            }
            break;

        case XMLStreamConstants.END_DOCUMENT:
            streamReader.close();
            try {
                inputStream.close();
            } catch (IOException e) {
                throw new RuntimeException("Failed to close input stream", e);
            }
            break;

        default:
            break;
        }
    }
}

From source file:com.liferay.portal.util.LocalizationImpl.java

private void _copyNonExempt(XMLStreamReader xmlStreamReader, XMLStreamWriter xmlStreamWriter,
        String exemptLanguageId, String defaultLanguageId, boolean cdata) throws XMLStreamException {

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

        if (event == XMLStreamConstants.START_ELEMENT) {
            String languageId = xmlStreamReader.getAttributeValue(null, _LANGUAGE_ID);

            if (Validator.isNull(languageId)) {
                languageId = defaultLanguageId;
            }//from   ww  w.jav  a2  s.c om

            if (!languageId.equals(exemptLanguageId)) {
                xmlStreamWriter.writeStartElement(xmlStreamReader.getLocalName());
                xmlStreamWriter.writeAttribute(_LANGUAGE_ID, languageId);

                while (xmlStreamReader.hasNext()) {
                    event = xmlStreamReader.next();

                    if ((event == XMLStreamConstants.CHARACTERS) || (event == XMLStreamConstants.CDATA)) {

                        String text = xmlStreamReader.getText();

                        if (cdata) {
                            xmlStreamWriter.writeCData(text);
                        } else {
                            xmlStreamWriter.writeCharacters(xmlStreamReader.getText());
                        }

                        break;
                    } else if (event == XMLStreamConstants.END_ELEMENT) {
                        break;
                    }
                }

                xmlStreamWriter.writeEndElement();
            }
        } else if (event == XMLStreamConstants.END_DOCUMENT) {
            break;
        }
    }
}

From source file:com.sun.socialsite.pojos.PropDefinition.java

protected void init(PropDefinition profileDef, InputStream input) throws SocialSiteException {
    try {//from   ww w . j a  v  a 2s .  c om
        XMLInputFactory factory = XMLInputFactory.newInstance();
        XMLStreamReader parser = factory.createXMLStreamReader(input);
        String ns = null; // TODO: namespace for ProfileDef

        // hold the current things we're working on
        Map<String, DisplaySectionDefinition> sdefs = new LinkedHashMap<String, DisplaySectionDefinition>();
        Stack<PropertyDefinitionHolder> propertyHolderStack = new Stack<PropertyDefinitionHolder>();
        List<AllowedValue> allowedValues = null;
        PropertyDefinition pdef = null;

        for (int event = parser.next(); event != XMLStreamConstants.END_DOCUMENT; event = parser.next()) {
            switch (event) {
            case XMLStreamConstants.START_ELEMENT:
                log.debug("START ELEMENT -- " + parser.getLocalName());

                if ("display-section".equals(parser.getLocalName())) {
                    propertyHolderStack.push(new DisplaySectionDefinition(parser.getAttributeValue(ns, "name"),
                            parser.getAttributeValue(ns, "namekey")));

                } else if ("property".equals(parser.getLocalName())) {
                    PropertyDefinitionHolder holder = propertyHolderStack.peek();
                    pdef = new PropertyDefinition(holder.getBasePath(), parser.getAttributeValue(ns, "name"),
                            parser.getAttributeValue(ns, "namekey"), parser.getAttributeValue(ns, "type"));

                } else if ("object".equals(parser.getLocalName())) {
                    PropertyDefinitionHolder holder = propertyHolderStack.peek();
                    propertyHolderStack.push(new PropertyObjectDefinition(holder.getBasePath(),
                            parser.getAttributeValue(ns, "name"), parser.getAttributeValue(ns, "namekey")));

                } else if ("collection".equals(parser.getLocalName())) {
                    PropertyDefinitionHolder holder = propertyHolderStack.peek();
                    propertyHolderStack.push(new PropertyObjectCollectionDefinition(holder.getBasePath(),
                            parser.getAttributeValue(ns, "name"), parser.getAttributeValue(ns, "namekey")));

                } else if ("allowed-values".equals(parser.getLocalName())) {
                    allowedValues = new ArrayList<AllowedValue>();

                } else if ("value".equals(parser.getLocalName())) {
                    AllowedValue allowedValue = new AllowedValue(parser.getAttributeValue(ns, "name"),
                            parser.getAttributeValue(ns, "namekey"));
                    allowedValues.add(allowedValue);

                } else if ("default-value".equals(parser.getLocalName())) {
                    pdef.setDefaultValue(parser.getText());
                }
                break;

            case XMLStreamConstants.END_ELEMENT:
                log.debug("END ELEMENT -- " + parser.getLocalName());

                if ("display-section".equals(parser.getLocalName())) {
                    DisplaySectionDefinition sdef = (DisplaySectionDefinition) propertyHolderStack.pop();
                    sdefs.put(sdef.getName(), sdef);

                } else if ("property".equals(parser.getLocalName())) {
                    PropertyDefinitionHolder holder = propertyHolderStack.peek();
                    holder.getPropertyDefinitions().add(pdef);
                    propertyDefs.put(pdef.getName(), pdef);
                    pdef = null;

                } else if ("object".equals(parser.getLocalName())) {
                    PropertyObjectDefinition odef = (PropertyObjectDefinition) propertyHolderStack.pop();
                    PropertyDefinitionHolder holder = propertyHolderStack.peek();
                    holder.getPropertyObjectDefinitions().add(odef);

                    // add to list of all property object defs
                    propertyObjectDefs.put(odef.getName(), odef);
                    odef = null;

                } else if ("collection".equals(parser.getLocalName())) {
                    PropertyObjectCollectionDefinition cdef = (PropertyObjectCollectionDefinition) propertyHolderStack
                            .pop();
                    PropertyDefinitionHolder holder = propertyHolderStack.peek();
                    holder.getPropertyObjectCollectionDefinitions().add(cdef);

                    // add to list of all property object defs
                    propertyObjectCollectionDefs.put(cdef.getName(), cdef);
                    cdef = null;

                } else if ("allowed-values".equals(parser.getLocalName())) {
                    pdef.setAllowedValues(allowedValues);
                    allowedValues = null;
                }
                break;

            case XMLStreamConstants.CHARACTERS:
                break;

            case XMLStreamConstants.CDATA:
                break;

            } // end switch
        } // end while

        parser.close();

        profileDef.sectionDefs = sdefs;

    } catch (Exception ex) {
        throw new SocialSiteException("ERROR parsing profile definitions", ex);
    }
}