Package org.codehaus.stax2

Examples of org.codehaus.stax2.XMLStreamReader2


        throws IOException, XMLStreamException
    {
        final String INTERNAL_SUBSET = "<!--test-->";
       
        String DOC = "<?xml version='1.0'?><!DOCTYPE root ["+INTERNAL_SUBSET+"]> <root />";
        XMLStreamReader2 sr = createReader(DOC, encoding);
        assertTokenType(START_DOCUMENT, sr.getEventType());
        int t = sr.next();
        assertTokenType(DTD, t);
        if (!skip) {
            assertEquals("root", sr.getPrefixedName());
            assertEquals(INTERNAL_SUBSET, sr.getText());
        }
        assertTokenType(START_ELEMENT, sr.next());
        assertEquals("root", sr.getLocalName());
        assertTokenType(END_ELEMENT, sr.next());
        assertEquals("root", sr.getLocalName());
        assertTokenType(END_DOCUMENT, sr.next());
        sr.close();
    }
View Full Code Here


    private void _doTestInvalidDup(String encoding, boolean skip)
        throws IOException, XMLStreamException
    {
        String DOC = "<?xml version='1.0'?><!DOCTYPE root>  <!DOCTYPE root>";
        XMLStreamReader2 sr = createReader(DOC, encoding);
        assertTokenType(START_DOCUMENT, sr.getEventType());
        int t = sr.next();
        assertTokenType(DTD, t);
        if (!skip) {
            assertEquals("root", sr.getPrefixedName());
            sr.getText(); // just to force its parsing
        }
        // But second one should fail
        try {
            t = sr.next(); // to get second DTD
            fail("Should fail on invalid DOCTYPE declaration: instead got "+t);
        } catch (XMLStreamException e) {
            verifyException(e, "Duplicate DOCTYPE declaration");
        }
        sr.close();
    }
View Full Code Here

   
    public void _testNamespaces(boolean useBytes) throws Exception
    {
        // note: must specify encoding so parsers knows which decoder to use
        String DOC = "<root xmlns='abc' xmlns:a='b' xmlns:b='c'>\n</root>";
        XMLStreamReader2 sr = createReader(DOC, "UTF-8", useBytes);
        assertTokenType(START_DOCUMENT, sr.getEventType());
        assertTokenType(START_ELEMENT, sr.next());
        assertEquals("root", sr.getLocalName());
        assertEquals(3, sr.getNamespaceCount());
       
        /* Although Stax does not mandate that ordering of namespace
         * declarations is preserved, ideally we would want to have them
         * that way...
         */
        assertEquals("", sr.getNamespacePrefix(0));
        assertEquals("abc", sr.getNamespaceURI(0));
        assertEquals("a", sr.getNamespacePrefix(1));
        assertEquals("b", sr.getNamespaceURI(1));
        assertEquals("b", sr.getNamespacePrefix(2));
        assertEquals("c", sr.getNamespaceURI(2));

        // Aalto follows Woodstox, and by default reports token start loc for "getLocation()"
        Location loc = sr.getLocation();
        assertEquals(1, loc.getLineNumber());
        assertEquals(1, loc.getColumnNumber());
        assertEquals(0, loc.getCharacterOffset());

        // and end should differ a bit
        loc = sr.getLocationInfo().getEndLocation();
        assertEquals(1, loc.getLineNumber());
        assertEquals(43,  loc.getColumnNumber());
        assertEquals(42, loc.getCharacterOffset());
       
        assertTokenType(CHARACTERS, sr.next());
        assertEquals("\n", sr.getText());

        loc = sr.getLocation();
        assertEquals(1, loc.getLineNumber());
        assertEquals(43,  loc.getColumnNumber());
        assertEquals(42, loc.getCharacterOffset());
        loc = sr.getLocationInfo().getEndLocation();
        assertEquals(2, loc.getLineNumber());
        assertEquals(1,  loc.getColumnNumber());
        assertEquals(43, loc.getCharacterOffset());
       
        assertTokenType(END_ELEMENT, sr.next());
        assertEquals("root", sr.getLocalName());
        assertEquals(useBytes ? -1L : 43L, sr.getLocationInfo().getStartingCharOffset());
        assertEquals(useBytes ? 43L : -1L, sr.getLocationInfo().getStartingByteOffset());
        assertEquals(useBytes ? -1L : 50L, sr.getLocationInfo().getEndingCharOffset());
        assertEquals(useBytes ? 50L : -1L, sr.getLocationInfo().getEndingByteOffset());
       
        loc = sr.getLocation();
        assertEquals(1, loc.getColumnNumber());
        assertEquals(2, loc.getLineNumber());
        assertEquals(43, loc.getCharacterOffset());

        assertTokenType(END_DOCUMENT, sr.next());
        loc = sr.getLocation();
        assertEquals(2, loc.getLineNumber());
        assertEquals(8, loc.getColumnNumber());
        assertEquals(50, loc.getCharacterOffset());
        sr.close();
    }
View Full Code Here

        System.out.print("Entity-expanding: "+f.getProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES));
        System.out.println(", validating: "+f.getProperty(XMLInputFactory.IS_VALIDATING));
        //System.out.println(", name interning: "+f.getProperty(XMLInputFactory2.P_INTERN_NAMES));
        int total = 0;

        XMLStreamReader2 sr;

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

        /*
        {
            byte[] data = readData(file);
            sr = f.createXMLStreamReader(new Stax2ByteArraySource(data, 0, data.length));
            System.out.println("File '"+file+"', read "+data.length+" bytes in.");
        }
        */

        sr = (XMLStreamReader2) f.createXMLStreamReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
        //sr = f.createXMLStreamReader(new FileInputStream(file));

        System.out.println("SR; name interning: "+sr.getProperty(XMLInputFactory2.P_INTERN_NAMES));
        System.out.println("SR; URI interning: "+sr.getProperty(XMLInputFactory2.P_INTERN_NS_URIS));

        int type = sr.getEventType();

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


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

            //boolean hasName = sr.hasName();

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

            if (sr.hasText()) {
                String text = sr.getText();
                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))+"]");
                    }

                    LocationInfo li = sr.getLocationInfo();
                    System.out.println(" [Loc, start: "+li.getStartLocation()+", end: "+li.getEndLocation()+"]");

                } 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) {
                    System.out.println(" DTD;");
                    List<Object> entities = (List<Object>) sr.getProperty("javax.xml.stream.entities");
                    List<Object> notations = (List<Object>) 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 ");
                    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 == 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 && prefix.length() > 0) {
                    System.out.print(prefix);
                    System.out.print(':');
                }
                System.out.print(sr.getLocalName());
                //System.out.println("[first char 0x"+Integer.toHexString(sr.getLocalName().charAt(0))+"]");

                System.out.print(" [QNameNS: "+sr.getName().getNamespaceURI()+"]");

                System.out.print(" {ns '");
                System.out.print(sr.getNamespaceURI());
                System.out.print("'}> ");
                int count = sr.getAttributeCount();
                int nsCount = sr.getNamespaceCount();
                System.out.println(" ["+nsCount+" ns, "+count+" attrs]");
                // 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.getAttributePrefix(i)
                                     +":"+sr.getAttributeLocalName(i)
                                     +" ("+sr.getAttributeNamespace(i)
                                     +") -> '"+val
                                     +"' ["+(val.length())+"]");
                    System.out.println(sr.isAttributeSpecified(i) ?
                                       "[specified]" : "[Default]");
                }
            } 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.println(" ["+nsCount+" ns unbound]");
            } 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

  @Override
  @NotNull
  public T deserialize( @NotNull InputStream in, @Nullable Lookup context ) throws IOException {
    try {
      XMLStreamReader2 reader = StaxSupport.getSmInputFactory().createStax2Reader( in );
      reader.nextTag();
      T deserialized = deserialize( reader, context != null ? context : Lookups.emtyLookup() );

      if ( !reader.isEndElement() ) {
        throw new IllegalStateException( "Not consumed everything in <" + getClass().getName() + ">" );
      }

      if ( reader.next() != XMLStreamReader2.END_DOCUMENT ) {
        throw new IllegalStateException( "Not consumed everything in <" + getClass().getName() + ">" );
      }

      return deserialized;
    } catch ( XMLStreamException e ) {
View Full Code Here

  @Override
  @NotNull
  public T deserialize( @NotNull InputStream in, @Nullable Lookup context ) throws IOException {
    try {
      XMLStreamReader2 reader = StaxSupport.getSmInputFactory().createStax2Reader( in );
      Version version = Version.parse( getProcessingInstructionData( reader, PI_TARGET_FORMAT ) );
      if ( !getFormatVersionRange().contains( version ) ) {
        throw new VersionMismatchException( getFormatVersion(), version );
      }

      reader.nextTag();
      T deserialized = deserialize( reader, context != null ? context : Lookups.emtyLookup() );

      if ( !reader.isEndElement() ) {
        throw new IllegalStateException( "Not consumed everything in <" + getClass().getName() + ">" );
      }

      if ( reader.next() != XMLStreamReader2.END_DOCUMENT ) {
        throw new IllegalStateException( "Not consumed everything in <" + getClass().getName() + ">" );
      }

      return deserialized;
    } catch ( XMLStreamException e ) {
View Full Code Here

        // to require the stax2 API no matter what.
        XMLStreamReader effectiveReader = reader;
        if (effectiveReader instanceof DepthXMLStreamReader) {
            effectiveReader = ((DepthXMLStreamReader)reader).getReader();
        }
        final XMLStreamReader2 reader2 = (XMLStreamReader2)effectiveReader;
        XMLValidationSchema vs = getValidator(serviceInfo);
        reader2.setValidationProblemHandler(new ValidationProblemHandler() {

            public void reportProblem(XMLValidationProblem problem) throws XMLValidationException {
                throw new Fault(new Message("READ_VALIDATION_ERROR", LOG, problem.getMessage()),
                                Fault.FAULT_CODE_CLIENT);
            }
        });
        reader2.validateAgainst(vs);
    }
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.XMLStreamReader2

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.