Package org.codehaus.stax2

Examples of org.codehaus.stax2.XMLEventReader2


        System.out.print("Entity-expanding: "+f.getProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES));
        System.out.println("Validating: "+f.getProperty(XMLInputFactory.IS_VALIDATING));
        System.out.println("Xml-id support: "+f.getProperty(XMLInputFactory2.XSP_SUPPORT_XMLID));

        int total = 0;
        XMLStreamReader2 sr;

        // Let's deal with gzipped files too?
        if (file.getName().endsWith(".gz")) {
            System.out.println("[gzipped input file!]");
            sr = (XMLStreamReader2) f.createXMLStreamReader
                (new InputStreamReader(new GZIPInputStream
                                       (new FileInputStream(file)), "UTF-8"));
        } else {
            sr = f.createXMLStreamReader(file);
            //sr = (XMLStreamReader2) f.createXMLStreamReader(new InputStreamReader(new FileInputStream(file), "IBM500"));
            //sr = (XMLStreamReader2) f.createXMLStreamReader(new StreamSource(file));
        }

        //sr.setProperty(WstxInputProperties.P_BASE_URL, "file:///tmp");

        System.err.println("Base URL: "+sr.getProperty(WstxInputProperties.P_BASE_URL));

        int type = sr.getEventType();

        System.out.println("START: version = '"+sr.getVersion()
                           +"', xml-encoding = '"+sr.getCharacterEncodingScheme()
                           +"', input encoding = '"+sr.getEncoding()+"'");

        //while (sr.hasNext()) {
        while (type != END_DOCUMENT) {
            type = sr.next();
            total += type; // so it won't be optimized out...

            @SuppressWarnings("unused")
      boolean hasName = sr.hasName();

            System.out.print("["+type+"]");

            // Uncomment for location info debugging:
      /*
            LocationInfo li = sr.getLocationInfo();
            System.out.println(" BEGIN: "+li.getStartLocation());
            //System.out.println(" CURR:  "+li.getCurrentLocation());
            System.out.println(" END:   "+li.getEndLocation());
      */

            if (sr.hasText()) {
                String text = null;

                // Choose normal or streaming
                if (true) {
                    text = sr.getText();
                    /*
                } else {
                    StringWriter swr = new StringWriter();
                    int gotLen = sr.getText(swr, false);
                    text = swr.toString();
                    if (gotLen != text.length()) {
                        throw new Error("Error: lengths didn't match: getText() returned "+gotLen+", but String has "+text.length()+" chars.");
                    }
                    */
                }

                if (text != null) { // Ref. impl. returns nulls sometimes
                    total += text.length(); // to prevent dead code elimination
                }
                if (type == CHARACTERS || type == CDATA || type == COMMENT) {
                    System.out.println(" Text("+text.length()+") = '"+text+"'.");
                    if (text.length() == 1) {
                        System.out.println(" [first char code: 0x"+Integer.toHexString(text.charAt(0))+"]");
                    }
                } else if (type == SPACE) {
                    System.out.print(" Ws = '"+text+"'.");
                    char c = (text.length() == 0) ? ' ': text.charAt(text.length()-1);
                    if (c != '\r' && c != '\n') {
                        System.out.println();
                    }
                } else if (type == DTD) {
                    DTDInfo info = sr.getDTDInfo();
                    System.out.println(" DTD (root "
                                       +getNullOrStr(info.getDTDRootName())
                                       +", sysid "+getNullOrStr(info.getDTDSystemId())
                                       +", pubid "+getNullOrStr(info.getDTDPublicId())
                                       +");");
                    List<?> entities = (List<?>) sr.getProperty("javax.xml.stream.entities");
                    List<?> notations = (List<?>) sr.getProperty("javax.xml.stream.notations");
                    int entCount = (entities == null) ? -1 : entities.size();
                    int notCount = (notations == null) ? -1 : notations.size();
                    System.out.print("  ("+entCount+" entities, "+notCount
                                       +" notations), sysid ");
                    if (notCount > 0) {
                        System.out.println();
                        for (int i = 0; i < notCount; ++i) {
                            NotationDeclaration2 nd = (NotationDeclaration2)notations.get(i);
                            System.out.println(" notation '"+nd.getName()+"', base: ["+nd.getBaseURI()+"]");
                        }
                    }
                    System.out.print(", declaration = <<");
                    System.out.print(text);
                    System.out.println(">>");
                } else if (type == ENTITY_REFERENCE) {
                    // entity ref
                    System.out.println(" Entity ref: &"+sr.getLocalName()+" -> '"+sr.getText()+"'.");
                    hasName = false; // to suppress further output
                } else { // PI?
                    ;
                }

                if (type == CHARACTERS) {
                    boolean isSpace = sr.isWhiteSpace();
                    int len = sr.getTextLength();

                    if (isSpace) {
                        text = sr.getText();
                        StringBuffer sb = new StringBuffer();
                        for (int i = 0; i < len; ++i) {
                            char c = text.charAt(i);
                            if (c == ' ') {
                                sb.append("\\s");
                            } else if (c == '\t') {
//if(true) throw new Error("TAB!");
                                sb.append("\\t");
                            } else if (c == '\r') {
                                sb.append("\\r");
                            } else if (c == '\n') {
                                sb.append("\\n");
                            } else {
                                sb.append("?");
                            }
                        }
                        text = sb.toString();
                        System.out.println("[SC:"+text+"]");
                    }
                }
            }

            if (type == PROCESSING_INSTRUCTION) {
                System.out.println(" PI target = '"+sr.getPITarget()+"'.");
                System.out.println(" PI data = '"+sr.getPIData()+"'.");
            } else if (type == START_ELEMENT) {
                String prefix = sr.getPrefix();
                System.out.print('<');
                if (prefix == null) {
                    System.out.print("{null-prefix}");
                } else if (prefix.length() == 0) {
                    System.out.print("{empty-prefix}");
                } else {
                    System.out.print(prefix);
                }
                System.out.print(sr.getLocalName());
                //System.out.println("[first char 0x"+Integer.toHexString(sr.getLocalName().charAt(0))+"]");
                System.out.print(" {ns '");
                System.out.print(sr.getNamespaceURI());
                System.out.print("'}> ");
                int count = sr.getAttributeCount();
                int nsCount = sr.getNamespaceCount();
                int idIx = sr.getAttributeInfo().getIdAttributeIndex();
                System.out.println(" ["+nsCount+" ns, "+count+" attrs, id: "
                                   +((idIx < 0) ? "none" : ("#"+idIx))+"]");
                // debugging:
                for (int i = 0; i < nsCount; ++i) {
                    System.out.println(" ns#"+i+": '"+sr.getNamespacePrefix(i)
                                     +"' -> '"+sr.getNamespaceURI(i)
                                     +"'");
                }
                for (int i = 0; i < count; ++i) {
                    String val = sr.getAttributeValue(i);
                    System.out.print(" attr#"+i+"("+sr.getAttributeType(i)+"): "+sr.getAttributePrefix(i)
                                     +":"+sr.getAttributeLocalName(i)
                                     +" ("+sr.getAttributeNamespace(i)
                                     +") -> '"+val
                                     +"' ["+(val.length())+"]");
                    System.out.println(sr.isAttributeSpecified(i) ?
                                       "[specified]" : "[Default]");
                }
                System.out.print(" [Loc -> "+sr.getLocation()+"]");
            } else if (type == END_ELEMENT) {
                System.out.print("</");
                String prefix = sr.getPrefix();
                if (prefix != null && prefix.length() > 0) {
                    System.out.print(prefix);
                    System.out.print(':');
                }
                System.out.print(sr.getLocalName());
                System.out.print(" {ns '");
                System.out.print(sr.getNamespaceURI());
                System.out.print("'}> ");
                int nsCount = sr.getNamespaceCount();
                System.out.print(" ["+nsCount+" ns unbound]");
                System.out.print(" [Loc -> "+sr.getLocation()+"]");
                System.out.println();
            } else if (type == START_DOCUMENT) { // only for multi-doc mode
                System.out.print("XML-DECL: version = '"+sr.getVersion()
                                 +"', xml-decl-encoding = '"+sr.getCharacterEncodingScheme()
                                 +"', app-encoding = '"+sr.getEncoding()
                                 +"', stand-alone set: "+sr.standaloneSet());
            }
        }
        return total;
    }
View Full Code Here


        conn.connect();
        // note, should check 'if (conn.getResponseCode() != 200) ...'
       
        // Ok, let's read it then... (note: StaxMate could simplify a lot!)
        InputStream in = conn.getInputStream();
        XMLStreamReader2 sr = (XMLStreamReader2) _xmlInputFactory.createXMLStreamReader(in);
        sr.nextTag(); // to "files"
        byte[] buffer = new byte[4000];
       
        while (sr.nextTag() != XMLStreamConstants.END_ELEMENT) { // one more 'file'
            String filename = sr.getAttributeValue("", "name");
            String csumType = sr.getAttributeValue("", "checksumType");
            File outputFile = new File(toDir, filename);
            FileOutputStream out = new FileOutputStream(outputFile);
            files.add(outputFile);
            MessageDigest md = MessageDigest.getInstance(csumType);
           
            int count;
            // Read binary contents of the file, calc checksum and write
            while ((count = sr.readElementAsBinary(buffer, 0, buffer.length)) != -1) {
                md.update(buffer, 0, count);
                out.write(buffer, 0, count);
            }
            out.close();
            // Then verify checksum
            sr.nextTag()
            byte[] expectedCsum = sr.getAttributeAsBinary(sr.getAttributeIndex("", "value"));
            byte[] actualCsum = md.digest();
            if (!Arrays.equals(expectedCsum, actualCsum)) {
                throw new IllegalArgumentException("File '"+filename+"' corrupt: content checksum does not match expected");
            }
            sr.nextTag(); // to match closing "checksum"
        }
        return files;
    }
View Full Code Here

    protected int test3(byte[] bdata, char[] cdata, File file)
        throws Exception
    {
        XMLInputFactory2 f = (XMLInputFactory2) mInputFactory;
        XMLStreamReader2 sr;

        if (bdata != null) {
            //sr = (XMLStreamReader2) f.createXMLStreamReader(new ByteArrayInputStream(bdata));
            sr = (XMLStreamReader2) f.createXMLStreamReader(new org.codehaus.stax2.io.Stax2ByteArraySource(bdata, 0, bdata.length));
        } else {
            sr = (XMLStreamReader2) f.createXMLStreamReader(new CharArrayReader(cdata));
        }
        //sr = (XMLStreamReader2) f.createXMLStreamReader(file);

        int result = 0;

        while (sr.hasNext()) {
            int type = sr.next();
            if (type == CHARACTERS) { // let's prevent skipping
                result += sr.getTextLength();
            }
            result += type; // so it won't be optimized out...
        }
  sr.close();
        return result;
    }
View Full Code Here

        String text = childIt.getText(); // has to be a text event
        if (childIt.getNext() == null) {
            return text;
        }

        XMLStreamReader2 sr = childIt._getStreamReader();
        int size = text.length() + sr.getTextLength()+ 20;
        StringBuffer sb = new StringBuffer(Math.max(size, 100));
        sb.append(text);
        do {
            // Let's assume char array access is more efficient...
            sb.append(sr.getTextCharacters(), sr.getTextStart(),
                      sr.getTextLength());
        } while (childIt.getNext() != null);

        return sb.toString();
    }
View Full Code Here

            ? SMFilterFactory.getTextOnlyFilter()
            : SMFilterFactory.getNonIgnorableTextFilter();
        SMInputCursor childIt = descendantCursor(f);

        // Any text in there?
        XMLStreamReader2 sr = childIt._getStreamReader();
        while (childIt.getNext() != null) {
            /* 'true' indicates that we are not to lose the text contained
             * (can call getText() multiple times, idempotency). While this
             * may not be as efficient as allowing content to be discarded,
             * let's play it safe. Another method could be added for
             * the alternative (fast but dangerous) behaviour as needed.
             */
            sr.getText(w, true);
        }
    }
View Full Code Here

        }
        String text = childIt.getText(); // has to be a text event
        if (childIt.getNext() == null) {
            return text;
        }
        XMLStreamReader2 sr = childIt._getStreamReader();
        int size = text.length() + sr.getTextLength()+ 20;
        StringBuffer sb = new StringBuffer(Math.max(size, 100));
        sb.append(text);
        do {
            // Let's assume char array access is more efficient...
            sb.append(sr.getTextCharacters(), sr.getTextStart(),
                      sr.getTextLength());
        } while (childIt.getNext() != null);

        return sb.toString();
    }
View Full Code Here

        throws XMLStreamException
    {
        if (mElemInfoFactory != null) {
            return mElemInfoFactory.constructElementInfo(this, parent, prevSibling);
        }
        XMLStreamReader2 sr = mStreamReader;
        return new DefaultElementInfo(parent, prevSibling,
                                      sr.getPrefix(), sr.getNamespaceURI(), sr.getLocalName(),
                                      mNodeCount-1, mElemCount-1, getDepth());
    }
View Full Code Here

    }

    public void testPropertiesStreamWriter() throws XMLStreamException
    {
        XMLOutputFactory f = getOutputFactory();
        XMLStreamWriter2 w = (XMLStreamWriter2) f.createXMLStreamWriter(new StringWriter());
       
        // First, verify property is indeed unsupported
        assertFalse(w.isPropertySupported(NO_SUCH_PROPERTY));
       
        // First: error for trying to access unknown, as per Stax 1.0 spec:
        try {
            w.getProperty(NO_SUCH_PROPERTY);
            fail("Expected exception");
        } catch (IllegalArgumentException e) {
            verifyException(e, NO_SUCH_PROPERTY);
        }

        // And although setter is specified by Stax2, it too fails on unrecognized:
        try {
            w.setProperty(NO_SUCH_PROPERTY, "foobar");
            fail("Expected exception");
        } catch (IllegalArgumentException e) {
            verifyException(e, NO_SUCH_PROPERTY);
        }
    }
View Full Code Here

            }
            */
            ;

        //XMLStreamWriter2 sw = (XMLStreamWriter2) f.createXMLStreamWriter(w);
        XMLStreamWriter2 sw = (XMLStreamWriter2) f.createXMLStreamWriter(new StreamResult(w));

        /*
        final String dtdStr =
            "<!ELEMENT root (elem, elem3)>\n"
            +"<!ATTLIST root attr CDATA #IMPLIED>\n"
            +"<!ATTLIST root another CDATA #IMPLIED>\n"
            +"<!ELEMENT elem ANY>\n"
            +"<!ELEMENT elem3 ANY>\n"
            ;
            */

        //XMLValidationSchemaFactory vd = XMLValidationSchemaFactory.newInstance(XMLValidationSchema.SCHEMA_ID_DTD);
        //XMLValidationSchema schema = vd.createSchema(new StringReader(dtdStr));
        //sw.validateAgainst(schema);

        sw.writeStartDocument();
        sw.writeComment("Comment!");
        sw.writeCharacters("\r");
        sw.writeStartElement("root");
        sw.writeAttribute("attr", "value");
        sw.writeAttribute("another", "this & that");
        //sw.writeAttribute("attr", "whatever"); // error!
        sw.writeStartElement(null, "elem");
        sw.writeCharacters("Sub-text");
        sw.writeEndElement();
        //sw.writeStartElement("elem3:foo"); // error, colon inside local name
        sw.writeStartElement("elem3");
        sw.writeEndElement();
        //sw.writeCharacters("Root text <> ]]>\n");
        sw.writeEndElement();
        //sw.writeEmptyElement("secondRoot"); // error!
        sw.writeCharacters("\n"); // white space in epilog
        sw.writeProcessingInstruction("target", "some data");
        sw.writeCharacters("\n"); // white space in epilog
        sw.writeEndDocument();

        sw.flush();
        sw.close();

        System.out.println("DOC = ["+w.toString()+"]");
        //System.out.println("sw = "+sw);
    }
View Full Code Here

    }

    private void writeFileContentsAsXML(OutputStream out)
        throws IOException, XMLStreamException
    {
        XMLStreamWriter2 sw = (XMLStreamWriter2) _xmlOutputFactory.createXMLStreamWriter(out);
        sw.writeStartDocument();
        sw.writeStartElement("files");
        byte[] buffer = new byte[4000];
        MessageDigest md;
        try {
            md = MessageDigest.getInstance(DIGEST_TYPE);
        } catch (Exception e) { // no such hash type?
            throw new IOException(e);
        }

        for (File f : _downloadableFiles.listFiles()) {
            sw.writeStartElement("file");
            sw.writeAttribute("name", f.getName());
            sw.writeAttribute("checksumType", DIGEST_TYPE);
            FileInputStream fis = new FileInputStream(f);
            int count;
            while ((count = fis.read(buffer)) != -1) {
                md.update(buffer, 0, count);
                sw.writeBinary(buffer, 0, count);
            }
            fis.close();
            sw.writeEndElement(); // file
            sw.writeStartElement("checksum");
            sw.writeBinaryAttribute("", "", "value", md.digest());
            sw.writeEndElement(); // checksum
        }
        sw.writeEndElement(); // files
        sw.writeEndDocument();
        sw.close();
    }
View Full Code Here

TOP

Related Classes of org.codehaus.stax2.XMLEventReader2

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.