Example usage for javax.xml.stream XMLStreamReader getTextStart

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

Introduction

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

Prototype

public int getTextStart();

Source Link

Document

Returns the offset into the text character array where the first character (of this text event) is stored.

Usage

From source file:Main.java

/**
 * @param xmlReader/*from w  ww  .  j ava 2  s .c  o  m*/
 */
public static void printLiterally(final PrintStream os, final XMLStreamReader xmlReader) {
    final int start = xmlReader.getTextStart();
    final int length = xmlReader.getTextLength();
    os.print(new String(xmlReader.getTextCharacters(), start, length));
}

From source file:Main.java

public static String parse(XMLStreamReader reader) {
    StringBuffer result = new StringBuffer();
    if (reader != null) {
        try {//from   w  w  w. j a va 2s.  co m
            while (reader.hasNext()) {
                switch (reader.getEventType()) {

                case XMLStreamConstants.START_ELEMENT:
                    result.append("<");
                    printName(reader, result);
                    printNamespaces(reader, result);
                    printAttributes(reader, result);
                    result.append(">");
                    break;

                case XMLStreamConstants.END_ELEMENT:
                    result.append("</");
                    printName(reader, result);
                    result.append(">");
                    break;

                case XMLStreamConstants.SPACE:

                case XMLStreamConstants.CHARACTERS:
                    int start = reader.getTextStart();
                    int length = reader.getTextLength();
                    result.append(new String(reader.getTextCharacters(), start, length));
                    break;

                case XMLStreamConstants.PROCESSING_INSTRUCTION:
                    result.append("<?");
                    if (reader.hasText())
                        result.append(reader.getText());
                    result.append("?>");
                    break;

                case XMLStreamConstants.CDATA:
                    result.append("<![CDATA[");
                    start = reader.getTextStart();
                    length = reader.getTextLength();
                    result.append(new String(reader.getTextCharacters(), start, length));
                    result.append("]]>");
                    break;

                case XMLStreamConstants.COMMENT:
                    result.append("<!--");
                    if (reader.hasText())
                        result.append(reader.getText());
                    result.append("-->");
                    break;

                case XMLStreamConstants.ENTITY_REFERENCE:
                    result.append(reader.getLocalName()).append("=");
                    if (reader.hasText())
                        result.append("[").append(reader.getText()).append("]");
                    break;

                case XMLStreamConstants.START_DOCUMENT:
                    result.append("<?xml");
                    result.append(" version='").append(reader.getVersion()).append("'");
                    result.append(" encoding='").append(reader.getCharacterEncodingScheme()).append("'");
                    if (reader.isStandalone())
                        result.append(" standalone='yes'");
                    else
                        result.append(" standalone='no'");
                    result.append("?>");
                    break;
                }
                reader.next();
            } // end while
        } catch (XMLStreamException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                reader.close();
            } catch (XMLStreamException e) {
            }
        }
    }
    return result.toString();
}

From source file:com.amalto.core.load.context.BufferStateContextWriter.java

public void writeCharacters(XMLStreamReader reader) throws XMLStreamException {
    char[] characters = reader.getTextCharacters();
    int textStart = reader.getTextStart();
    char[] textCharacters = ArrayUtils.subarray(characters, textStart, textStart + reader.getTextLength());
    processedElements.add(new ProcessedCharacters(textCharacters));
}

From source file:com.amalto.core.load.context.StateContextSAXWriter.java

public void writeCharacters(XMLStreamReader reader) throws Exception {
    char[] characters = reader.getTextCharacters();
    int textStart = reader.getTextStart();
    char[] chars = ArrayUtils.subarray(characters, textStart, textStart + reader.getTextLength());
    if (escapeCharacters) {
        chars = StringEscapeUtils.escapeXml(new String(chars)).toCharArray();
    }/*ww w.ja  v a  2  s  .c  o  m*/
    contentHandler.characters(chars, 0, chars.length);
}

From source file:edu.utah.further.core.xml.stax.XmlStreamElementPrinter.java

@Override
public void visitCdata(final XMLStreamReader xmlReader) {
    os.print("<![CDATA[");
    final int start = xmlReader.getTextStart();
    final int length = xmlReader.getTextLength();
    os.print(new String(xmlReader.getTextCharacters(), start, length));
    os.print("]]>");
}

From source file:hudson.model.ExternalRun.java

/**
 * Instead of performing a build, accept the log and the return code from a
 * remote machine.//from w  w w .ja  v  a  2 s.c  om
 *
 * <p> The format of the XML is:
 *
 * <pre><xmp>
 * <run>
 *  <log>...console output...</log>
 *  <result>exit code</result>
 * </run>
 * </xmp></pre>
 */
@SuppressWarnings({ "Since15" })
public void acceptRemoteSubmission(final Reader in) throws IOException {
    final long[] duration = new long[1];
    run(new Runner() {
        private String elementText(XMLStreamReader r) throws XMLStreamException {
            StringBuilder buf = new StringBuilder();
            while (true) {
                int type = r.next();
                if (type == CHARACTERS || type == CDATA) {
                    buf.append(r.getTextCharacters(), r.getTextStart(), r.getTextLength());
                } else {
                    return buf.toString();
                }
            }
        }

        public Result run(BuildListener listener) throws Exception {
            PrintStream logger = null;
            try {
                logger = new PrintStream(new DecodingStream(listener.getLogger()));

                XMLInputFactory xif = XMLInputFactory.newInstance();
                XMLStreamReader p = xif.createXMLStreamReader(in);

                p.nextTag(); // get to the <run>
                p.nextTag(); // get to the <log>

                charset = p.getAttributeValue(null, "content-encoding");
                while (p.next() != END_ELEMENT) {
                    int type = p.getEventType();
                    if (type == CHARACTERS || type == CDATA) {
                        logger.print(p.getText());
                    }
                }
                p.nextTag(); // get to <result>

                Result r = Integer.parseInt(elementText(p)) == 0 ? Result.SUCCESS : Result.FAILURE;

                p.nextTag(); // get to <duration> (optional)
                if (p.getEventType() == START_ELEMENT && p.getLocalName().equals("duration")) {
                    duration[0] = Long.parseLong(elementText(p));
                }

                return r;
            } finally {
                IOUtils.closeQuietly(logger);
            }
        }

        public void post(BuildListener listener) {
            // do nothing
        }

        public void cleanUp(BuildListener listener) {
            // do nothing
        }
    });

    if (duration[0] != 0) {
        super.duration = duration[0];
        // save the updated duration
        save();
    }
}

From source file:XmlReaderToWriter.java

public static void write(XMLStreamReader xmlr, XMLStreamWriter writer) throws XMLStreamException {
    switch (xmlr.getEventType()) {
    case XMLEvent.START_ELEMENT:
        final String localName = xmlr.getLocalName();
        final String namespaceURI = xmlr.getNamespaceURI();
        if (namespaceURI != null && namespaceURI.length() > 0) {
            final String prefix = xmlr.getPrefix();
            if (prefix != null)
                writer.writeStartElement(prefix, localName, namespaceURI);
            else/* w w  w. j a  v a  2  s  .co m*/
                writer.writeStartElement(namespaceURI, localName);
        } else {
            writer.writeStartElement(localName);
        }

        for (int i = 0, len = xmlr.getNamespaceCount(); i < len; i++) {
            writer.writeNamespace(xmlr.getNamespacePrefix(i), xmlr.getNamespaceURI(i));
        }

        for (int i = 0, len = xmlr.getAttributeCount(); i < len; i++) {
            String attUri = xmlr.getAttributeNamespace(i);
            if (attUri != null)
                writer.writeAttribute(attUri, xmlr.getAttributeLocalName(i), xmlr.getAttributeValue(i));
            else
                writer.writeAttribute(xmlr.getAttributeLocalName(i), xmlr.getAttributeValue(i));
        }
        break;
    case XMLEvent.END_ELEMENT:
        writer.writeEndElement();
        break;
    case XMLEvent.SPACE:
    case XMLEvent.CHARACTERS:
        writer.writeCharacters(xmlr.getTextCharacters(), xmlr.getTextStart(), xmlr.getTextLength());
        break;
    case XMLEvent.PROCESSING_INSTRUCTION:
        writer.writeProcessingInstruction(xmlr.getPITarget(), xmlr.getPIData());
        break;
    case XMLEvent.CDATA:
        writer.writeCData(xmlr.getText());
        break;

    case XMLEvent.COMMENT:
        writer.writeComment(xmlr.getText());
        break;
    case XMLEvent.ENTITY_REFERENCE:
        writer.writeEntityRef(xmlr.getLocalName());
        break;
    case XMLEvent.START_DOCUMENT:
        String encoding = xmlr.getCharacterEncodingScheme();
        String version = xmlr.getVersion();

        if (encoding != null && version != null)
            writer.writeStartDocument(encoding, version);
        else if (version != null)
            writer.writeStartDocument(xmlr.getVersion());
        break;
    case XMLEvent.END_DOCUMENT:
        writer.writeEndDocument();
        break;
    case XMLEvent.DTD:
        writer.writeDTD(xmlr.getText());
        break;
    }
}

From source file:XmlStreamUtils.java

public static String printEvent(XMLStreamReader xmlr) {
    StringBuffer b = new StringBuffer();
    b.append("EVENT:[" + xmlr.getLocation().getLineNumber() + "][" + xmlr.getLocation().getColumnNumber()
            + "] ");
    b.append(getName(xmlr.getEventType()));
    b.append(" [");
    switch (xmlr.getEventType()) {
    case XMLStreamReader.START_ELEMENT:
        b.append("<");
        printName(xmlr, b);/*  w  ww.  j a  va 2  s  .com*/
        for (int i = 0; i < xmlr.getNamespaceCount(); i++) {
            b.append(" ");
            String n = xmlr.getNamespacePrefix(i);
            if ("xmlns".equals(n)) {
                b.append("xmlns=\"" + xmlr.getNamespaceURI(i) + "\"");
            } else {
                b.append("xmlns:" + n);
                b.append("=\"");
                b.append(xmlr.getNamespaceURI(i));
                b.append("\"");
            }
        }

        for (int i = 0; i < xmlr.getAttributeCount(); i++) {
            b.append(" ");
            printName(xmlr.getAttributePrefix(i), xmlr.getAttributeNamespace(i), xmlr.getAttributeLocalName(i),
                    b);
            b.append("=\"");
            b.append(xmlr.getAttributeValue(i));
            b.append("\"");
        }

        b.append(">");
        break;
    case XMLStreamReader.END_ELEMENT:
        b.append("</");
        printName(xmlr, b);
        for (int i = 0; i < xmlr.getNamespaceCount(); i++) {
            b.append(" ");
            String n = xmlr.getNamespacePrefix(i);
            if ("xmlns".equals(n)) {
                b.append("xmlns=\"" + xmlr.getNamespaceURI(i) + "\"");
            } else {
                b.append("xmlns:" + n);
                b.append("=\"");
                b.append(xmlr.getNamespaceURI(i));
                b.append("\"");
            }
        }
        b.append(">");
        break;
    case XMLStreamReader.SPACE:
    case XMLStreamReader.CHARACTERS:
        // b.append(xmlr.getText());
        int start = xmlr.getTextStart();
        int length = xmlr.getTextLength();
        b.append(new String(xmlr.getTextCharacters(), start, length));
        break;
    case XMLStreamReader.PROCESSING_INSTRUCTION:
        String target = xmlr.getPITarget();
        if (target == null)
            target = "";
        String data = xmlr.getPIData();
        if (data == null)
            data = "";
        b.append("<?");
        b.append(target + " " + data);
        b.append("?>");
        break;
    case XMLStreamReader.CDATA:
        b.append("<![CDATA[");
        if (xmlr.hasText())
            b.append(xmlr.getText());
        b.append("]]&gt;");
        break;

    case XMLStreamReader.COMMENT:
        b.append("<!--");
        if (xmlr.hasText())
            b.append(xmlr.getText());
        b.append("-->");
        break;
    case XMLStreamReader.ENTITY_REFERENCE:
        b.append(xmlr.getLocalName() + "=");
        if (xmlr.hasText())
            b.append("[" + xmlr.getText() + "]");
        break;
    case XMLStreamReader.START_DOCUMENT:
        b.append("<?xml");
        b.append(" version='" + xmlr.getVersion() + "'");
        b.append(" encoding='" + xmlr.getCharacterEncodingScheme() + "'");
        if (xmlr.isStandalone())
            b.append(" standalone='yes'");
        else
            b.append(" standalone='no'");
        b.append("?>");
        break;

    }
    b.append("]");
    return b.toString();
}

From source file:com.clustercontrol.agent.winevent.WinEventMonitor.java

/**
 * XMLStAX???EventLogRecord????//w w w . java2 s.  c o  m
 * @param eventXmlStream
 * @return EventLogRecord?
 */
private ArrayList<EventLogRecord> parseEventXML(InputStream eventXmlStream) {
    ArrayList<EventLogRecord> eventlogs = new ArrayList<EventLogRecord>();

    try {
        XMLInputFactory xmlif = XMLInputFactory.newInstance();
        /**
         * OpenJDK7/OracleJDK7??"]"?2?????????????????????????????
         * ?XML?????????OpenJDK7/OracleJDK7???????/??????????
         * URL???????????????
         * 
         * URL
         * http://docs.oracle.com/javase/jp/6/api/javax/xml/stream/XMLStreamReader.html#next()
         */
        String xmlCoalescingKey = "javax.xml.stream.isCoalescing";// TODO JRE???????????????????
        if (m_log.isDebugEnabled()) {
            m_log.debug(xmlCoalescingKey + " = true");
        }
        xmlif.setProperty(xmlCoalescingKey, true);
        XMLStreamReader xmlr = xmlif.createXMLStreamReader(eventXmlStream);

        while (xmlr.hasNext()) {
            switch (xmlr.getEventType()) {
            case XMLStreamConstants.START_ELEMENT:
                m_log.trace("EventType : XMLStreamConstants.START_ELEMENT");

                String localName = xmlr.getLocalName();
                m_log.trace("local name : " + localName);

                if ("Event".equals(localName)) {
                    EventLogRecord eventlog = new EventLogRecord();
                    eventlogs.add(eventlog);
                    m_log.debug("create new EventLogRecord");
                } else {
                    String attrLocalName = null;
                    String attrValue = null;

                    if (xmlr.getAttributeCount() != 0) {
                        attrLocalName = xmlr.getAttributeLocalName(0);
                        attrValue = xmlr.getAttributeValue(0);
                        m_log.trace("attribute local name : " + attrLocalName);
                        m_log.trace("attribute local value : " + attrValue);
                    }

                    if ("Provider".equals(localName)) {
                        if ("Name".equals(attrLocalName)) {
                            m_log.trace("target value : " + attrValue);

                            EventLogRecord eventlog = eventlogs.get(eventlogs.size() - 1);
                            eventlog.setProviderName(attrValue);
                            m_log.debug("set ProviderName : " + eventlog.getProviderName());
                        }
                    }
                    // Get-WinEvent/wevtutil.exe
                    else if ("TimeCreated".equals(localName) && "SystemTime".equals(attrLocalName)) {
                        m_log.trace("target value : " + attrValue);

                        // "yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSS'Z'"???S????????????
                        String formatedDateString = attrValue.replaceAll("\\..*Z", "");
                        m_log.trace("formatted target value : " + formatedDateString);
                        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
                        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

                        EventLogRecord eventlog = eventlogs.get(eventlogs.size() - 1);
                        ;
                        try {
                            eventlog.setTimeCreated(sdf.parse(formatedDateString));
                        } catch (ParseException e) {
                            // do nothing
                            m_log.error("set TimeCreated Error", e);
                        }
                        m_log.debug("set TimeCreated : " + eventlog.getTimeCreated());
                    }
                    // Get-EventLog
                    if ("TimeGenerated".equals(localName) && "SystemTime".equals(attrLocalName)) {
                        m_log.trace("target value : " + attrValue);
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss'Z'");
                        sdf.setTimeZone(HinemosTime.getTimeZone());

                        EventLogRecord eventlog = eventlogs.get(eventlogs.size() - 1);
                        ;
                        try {
                            eventlog.setTimeCreated(sdf.parse(attrValue));
                        } catch (ParseException e) {
                            // do nothing
                            m_log.error("set TimeCreated Error", e);
                        }
                        m_log.debug("set TimeCreated : " + eventlog.getTimeCreated());
                    } else {
                        targetProperty = localName;
                        m_log.trace("target property : " + targetProperty);
                    }
                }

                break;
            case XMLStreamConstants.SPACE:
            case XMLStreamConstants.CHARACTERS:
                m_log.trace("EventType : XMLStreamConstants.CHARACTERS, length=" + xmlr.getTextLength());
                if (targetProperty != null) {
                    try {
                        EventLogRecord eventlog = eventlogs.get(eventlogs.size() - 1);
                        ;
                        if ("EventID".equals(targetProperty)) {
                            eventlog.setId(Integer.parseInt(new String(xmlr.getTextCharacters(),
                                    xmlr.getTextStart(), xmlr.getTextLength())));
                            m_log.debug("set EventID : " + eventlog.getId());
                        }
                        // Get-WinEvent/wevtutil.exe
                        else if ("Level".equals(targetProperty)) {
                            if (eventlog.getLevel() == WinEventConstant.UNDEFINED) {
                                eventlog.setLevel(Integer.parseInt(new String(xmlr.getTextCharacters(),
                                        xmlr.getTextStart(), xmlr.getTextLength())));
                                m_log.debug("set Level : " + eventlog.getLevel());
                            }
                        } else if ("Task".equals(targetProperty)) {
                            if (eventlog.getTask() == WinEventConstant.UNDEFINED) {
                                eventlog.setTask(Integer.parseInt(new String(xmlr.getTextCharacters(),
                                        xmlr.getTextStart(), xmlr.getTextLength())));
                                m_log.debug("set Task : " + eventlog.getTask());
                            }
                        } else if ("Keywords".equals(targetProperty)) {
                            // TODO ????????0x8080000000000000
                            //eventlog.setKeywords(Long.decode(new String(xmlr.getTextCharacters(), xmlr.getTextStart(), xmlr.getTextLength())));
                            //m_log.debug("set Keywords : " + eventlog.getKeywords());
                        } else if ("EventRecordId".equals(targetProperty)) {
                            eventlog.setRecordId(Long.parseLong(new String(xmlr.getTextCharacters(),
                                    xmlr.getTextStart(), xmlr.getTextLength())));
                            m_log.debug("set RecordId : " + eventlog.getRecordId());
                        } else if ("Channel".equals(targetProperty)) {
                            eventlog.setLogName(new String(xmlr.getTextCharacters(), xmlr.getTextStart(),
                                    xmlr.getTextLength()));
                            m_log.debug("set LogName : " + eventlog.getLogName());
                        } else if ("Computer".equals(targetProperty)) {
                            eventlog.setMachineName(new String(xmlr.getTextCharacters(), xmlr.getTextStart(),
                                    xmlr.getTextLength()));
                            m_log.debug("set MachineName : " + eventlog.getMachineName());
                        } else if ("Message".equals(targetProperty)) {
                            String message = new String(xmlr.getTextCharacters(), xmlr.getTextStart(),
                                    xmlr.getTextLength());
                            message = message.replaceAll(tmpReturnCode, "\r\n");
                            message = message.replaceAll(tmpLtCode, "<");
                            message = message.replaceAll(tmpGtCode, ">");
                            eventlog.setMessage(message);
                            m_log.debug("set Message : " + eventlog.getMessage());
                        } else if ("Data".equals(targetProperty)) {
                            String data = new String(xmlr.getTextCharacters(), xmlr.getTextStart(),
                                    xmlr.getTextLength());
                            eventlog.getData().add(data);
                            m_log.debug("set Data : " + data);
                        } else {
                            m_log.debug("unknown target property : " + targetProperty);
                        }
                    } catch (NumberFormatException e) {
                        m_log.debug("number parse error", e);
                    }
                }
                targetProperty = null;
                break;
            default: // 
                break;
            }
            xmlr.next();
        }
        xmlr.close();
    } catch (XMLStreamException e) {
        m_log.warn("parseEvent() xmlstream error", e);
    }

    return eventlogs;

}

From source file:org.deegree.services.csw.exporthandling.GetCapabilitiesHelper.java

private void writeTemplateElement(XMLStreamWriter writer, XMLStreamReader inStream,
        Map<String, String> varToValue) throws XMLStreamException {

    if (inStream.getEventType() != XMLStreamConstants.START_ELEMENT) {
        throw new XMLStreamException("Input stream does not point to a START_ELEMENT event.");
    }//from  w  w w .  j  av  a  2 s .  c  om
    int openElements = 0;
    boolean firstRun = true;
    while (firstRun || openElements > 0) {
        firstRun = false;
        int eventType = inStream.getEventType();

        switch (eventType) {
        case CDATA: {
            writer.writeCData(inStream.getText());
            break;
        }
        case CHARACTERS: {
            String s = new String(inStream.getTextCharacters(), inStream.getTextStart(),
                    inStream.getTextLength());
            // TODO optimize
            for (String param : varToValue.keySet()) {
                String value = varToValue.get(param);
                s = s.replace(param, value);
            }
            writer.writeCharacters(s);

            break;
        }
        case END_ELEMENT: {
            writer.writeEndElement();
            openElements--;
            break;
        }
        case START_ELEMENT: {
            if (inStream.getNamespaceURI() == "" || inStream.getPrefix() == DEFAULT_NS_PREFIX
                    || inStream.getPrefix() == null) {
                writer.writeStartElement(inStream.getLocalName());
            } else {
                if (writer.getNamespaceContext().getPrefix(inStream.getPrefix()) == "") {
                    // TODO handle special cases for prefix binding, see
                    // http://download.oracle.com/docs/cd/E17409_01/javase/6/docs/api/javax/xml/namespace/NamespaceContext.html#getNamespaceURI(java.lang.String)
                    writer.setPrefix(inStream.getPrefix(), inStream.getNamespaceURI());
                }
                writer.writeStartElement(inStream.getPrefix(), inStream.getLocalName(),
                        inStream.getNamespaceURI());
            }
            // copy all namespace bindings
            for (int i = 0; i < inStream.getNamespaceCount(); i++) {
                String nsPrefix = inStream.getNamespacePrefix(i);
                String nsURI = inStream.getNamespaceURI(i);
                writer.writeNamespace(nsPrefix, nsURI);
            }

            // copy all attributes
            for (int i = 0; i < inStream.getAttributeCount(); i++) {
                String localName = inStream.getAttributeLocalName(i);
                String nsPrefix = inStream.getAttributePrefix(i);
                String value = inStream.getAttributeValue(i);
                String nsURI = inStream.getAttributeNamespace(i);
                if (nsURI == null) {
                    writer.writeAttribute(localName, value);
                } else {
                    writer.writeAttribute(nsPrefix, nsURI, localName, value);
                }
            }

            openElements++;
            break;
        }
        default: {
            break;
        }
        }
        if (openElements > 0) {
            inStream.next();
        }
    }
}