001    /*
002     * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons-sandbox//xmlio/src/test/org/apache/commons/xmlio/in/SimpleImportTest.java,v 1.1 2004/10/08 11:56:20 ozeigermann Exp $
003     * $Revision: 155476 $
004     * $Date: 2005-02-26 13:31:24 +0000 (Sat, 26 Feb 2005) $
005     *
006     * ====================================================================
007     *
008     * Copyright 2004 The Apache Software Foundation 
009     *
010     * Licensed under the Apache License, Version 2.0 (the "License");
011     * you may not use this file except in compliance with the License.
012     * You may obtain a copy of the License at
013     *
014     *     http://www.apache.org/licenses/LICENSE-2.0
015     *
016     * Unless required by applicable law or agreed to in writing, software
017     * distributed under the License is distributed on an "AS IS" BASIS,
018     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
019     * See the License for the specific language governing permissions and
020     * limitations under the License.
021     *
022     */
023    
024    package org.apache.commons.xmlio.in;
025    
026    
027    import java.io.*;
028    import java.util.*;
029    
030    import junit.framework.*;
031    
032    import org.apache.commons.xmlio.in.ConversionHelpers;
033    import org.apache.commons.xmlio.in.DefaultSimpleImportHandler;
034    import org.apache.commons.xmlio.in.Item;
035    import org.apache.commons.xmlio.in.SimpleImportHandler;
036    import org.apache.commons.xmlio.in.SimpleImporter;
037    import org.apache.commons.xmlio.in.SimplePath;
038    import org.apache.commons.xmlio.out.*;
039    import org.xml.sax.helpers.AttributesImpl;
040    import org.xml.sax.InputSource;
041    
042    /**
043     * Try out importer a little bit. 
044     *
045     */
046    public class SimpleImportTest extends TestCase {
047    
048        public static Test suite() {
049            TestSuite suite = new TestSuite(SimpleImportTest.class);
050            return suite;
051        }
052    
053        public SimpleImportTest(String testName) {
054            super(testName);
055        }
056    
057        public static void main(java.lang.String[] args) {
058            junit.textui.TestRunner.run(suite());
059        }
060    
061        public void testMain() {
062            System.out.println("MAIN TEST");
063            String testString =
064                "<?xml version='1.0' encoding='ISO-8859-1'?><response state='ok'><mixed>Olli <b>ist</b> toll&lt;</mixed><text>Text&lt;<![CDATA[<huhu>Dies ist aller CDATA</huhu>]]></text></response>\n";
065            System.out.println("TEST STRING:");
066            System.out.println(testString);
067            System.out.println("");
068            SimpleImporter dumpImporter = new SimpleImporter();
069            DumpTester dumpTester = new DumpTester();
070            try {
071                InputStream in = new ByteArrayInputStream(testString.getBytes("ISO-8859-1"));
072                dumpImporter.addSimpleImportHandler(dumpTester);
073                dumpImporter.setIncludeLeadingCDataIntoStartElementCallback(true);
074                dumpImporter.setFullDebugMode(true);
075                dumpImporter.setUseQName(false);
076                dumpImporter.parse(new InputSource(in));
077    
078                String fullDebug = dumpImporter.getParsedStreamForDebug();
079                System.out.println("FULL DEBUG START");
080                System.out.println(fullDebug);
081                System.out.println("FULL DEBUG END");
082    
083                assertEquals(testString, fullDebug);
084    
085                System.out.println(dumpImporter.getFoundMixedPCData() ? "MIXED" : "NOT MIXED");
086    
087                // checks for maximum chunk go here as well (no two text() callbacks may follow each other)
088                String expectedDump =
089                    "DOCUMENT START\n/response:\n<response state=\"ok\">\n/response/mixed:\n<mixed>\nOlli\n/response/mixed/b:\n<b>\nist\n/response/mixed/b:\n</b>\n/response/mixed/text():\ntoll&lt;\n/response/mixed:\n</mixed>\n/response/text:\n<text>\n<![CDATA[Text<<huhu>Dies ist aller CDATA</huhu>]]>\n/response/text:\n</text>\n/response:\n</response>\nDOCUMENT END\n";
090                String actualDump = dumpTester.logBuffer.toString();
091    
092                System.out.println("COLLECTED DUMP START");
093                System.out.println(actualDump);
094                System.out.println("COLLECTED DUMP END");
095    
096                if (!actualDump.equals(expectedDump)) {
097                    fail("\nWrong output:\n'" + actualDump + "'\nShould be:\n'" + expectedDump + "'\n");
098                }
099            } catch (Exception e) {
100                e.printStackTrace();
101                fail("Error: " + e);
102            }
103        }
104    
105        public void testDetail() {
106            System.out.println("DETAIL TEST");
107    
108            String testString =
109                "<?xml version='1.0' encoding='ISO-8859-1'?><response state='ok' boolean='true' int='-100' long='4676767676' ns:olli='cool'><mixed>Olli <b>ist</b> toll&lt;</mixed><text>Text&lt;<![CDATA[<huhu>Dies ist aller CDATA</huhu>]]></text></response>\n";
110            System.out.println("TEST STRING:");
111            System.out.println(testString);
112            System.out.println("");
113            try {
114                InputStream in = new ByteArrayInputStream(testString.getBytes("ISO-8859-1"));
115                SimpleImporter dumpImporter = new SimpleImporter();
116                DetailTester detailTester = new DetailTester();
117                dumpImporter.addSimpleImportHandler(detailTester);
118                dumpImporter.setIncludeLeadingCDataIntoStartElementCallback(true);
119                dumpImporter.parse(new InputSource(in));
120            } catch (Exception e) {
121                e.printStackTrace();
122                fail("Error: " + e);
123            }
124        }
125    
126        public void testPathList() {
127            System.out.println("PATH LIST TEST");
128            String testString =
129                "<?xml version='1.0' encoding='ISO-8859-1'?>"
130                    + "<root xmlns:olli=\"http://www.zeigermann.de\" xmlns:daniel=\"http://www.floreysoft.de\"><sub>"
131                    + "<olli:element>\n"
132                    + "<daniel:element>Huhu</daniel:element>\n"
133                    + "</olli:element>"
134                    + "</sub></root>";
135            System.out.println("TEST STRING:");
136            System.out.println(testString);
137            System.out.println("");
138    
139            try {
140                InputStream in = new ByteArrayInputStream(testString.getBytes("ISO-8859-1"));
141                SimpleImporter testImporter = new SimpleImporter();
142                PathListTester tester = new PathListTester();
143                testImporter.addSimpleImportHandler(tester);
144                testImporter.setBuildComplexPath(true);
145                testImporter.setUseQName(false);
146                testImporter.setIncludeLeadingCDataIntoStartElementCallback(false);
147                testImporter.parse(new InputSource(in));
148            } catch (Exception e) {
149                e.printStackTrace();
150                fail("Error: " + e);
151            }
152        }
153    
154        private final static class PathListTester extends DefaultSimpleImportHandler {
155    
156            public void startElement(SimplePath path, String name, AttributesImpl attributes, String leadingCDdata) {
157    
158                boolean matchesRoot = path.matches(new Item("root")) && path.matches(Item.ITEM_ANY);
159                boolean matchesOlli =
160                    path.matches(new Item("element")) && path.matches(new Item("element", "http://www.zeigermann.de"));
161                boolean matchesDaniel =
162                    path.matches(
163                        new Item[] {
164                            new Item("root"),
165                            Item.ITEM_ANY,
166                            Item.ITEM_ANY,
167                            new Item("element", "http://www.floreysoft.de")},
168                        false);
169                boolean matchesSub = path.matches(new Item("sub"));
170    
171                boolean matchesFromStart = path.matchesFromRoot(new Item[] { new Item("root")});
172    
173                if (matchesFromStart && !matchesRoot && !matchesOlli && !matchesDaniel && !matchesSub) {
174                    fail("Item matching does not work");
175                }
176            }
177    
178            public void cData(SimplePath path, String cdata) {
179                if ("Huhu".equals(cdata)) {
180                    if (!path
181                        .matches(
182                            new Item[] {
183                                new Item("root"),
184                                new Item("sub"),
185                                new Item("element"),
186                                new Item("element", "http://www.floreysoft.de")})) {
187                        fail("CDATA is in wrong path");
188                    }
189                }
190            }
191    
192        }
193    
194        private final static class DumpTester implements SimpleImportHandler {
195    
196            public StringBuffer logBuffer = new StringBuffer();
197            public boolean previousCallbackWasCDATA = true;
198    
199            public void startDocument() {
200                previousCallbackWasCDATA = false;
201                log("DOCUMENT START");
202            }
203    
204            public void endDocument() {
205                previousCallbackWasCDATA = false;
206                log("DOCUMENT END");
207            }
208    
209            public void cData(SimplePath path, String cdata) {
210                if (previousCallbackWasCDATA)
211                    fail("No two cData callbacks may follow each other, as this violates the maximum chunk guarantee given in API spec");
212                previousCallbackWasCDATA = true;
213    
214                log(path.toString() + "/text():");
215                String encodedText = XMLEncode.xmlEncodeText(cdata);
216                log(encodedText);
217            }
218    
219            public void startElement(SimplePath path, String name, AttributesImpl attributes, String leadingCDdata) {
220                previousCallbackWasCDATA = false;
221                log(path.toString() + ":");
222                String startTag = XMLWriter.createStartTag(name, attributes);
223                log(startTag);
224                if (leadingCDdata != null) {
225                    String encodedText = XMLEncode.xmlEncodeText(leadingCDdata);
226                    log(encodedText);
227                }
228            }
229    
230            public void endElement(SimplePath path, String name) {
231                previousCallbackWasCDATA = false;
232                log(path.toString() + ":");
233                log("</" + name + ">");
234            }
235    
236            private void log(String text) {
237                logBuffer.append(text).append('\n');
238            }
239        }
240    
241        private final class DetailTester extends DefaultSimpleImportHandler {
242    
243            public void startElement(SimplePath path, String name, AttributesImpl attributes, String leadingCDdata) {
244    
245                // checking path
246    
247                if (!path.matchsAny(new String[] { "response", "mixed", "text", "b" })) {
248                    fail("matchesAny(String[]) does not work");
249                }
250    
251                List list = new ArrayList();
252                list.add(new SimplePath("response"));
253                list.add(new SimplePath("mixed"));
254                list.add(new SimplePath("text"));
255                list.add(new SimplePath("b"));
256                if (!path.matchsAny(list)) {
257                    fail("matchesAny(Collection) does not work");
258                }
259    
260                if (!path
261                    .matchsAny(new String[] { "/response", "/response/mixed", "/response/text", "/response/mixed/b" })) {
262                    fail("absolute paths do not seem to work");
263                }
264    
265                if (!path.matchsAny(new String[] { "response", "response/mixed", "response/text", "mixed/b" })) {
266                    fail("relative paths do not seem to work");
267                }
268    
269                // checking attribute
270                if (path.matches("/response")) {
271                    String state = ConversionHelpers.getString(attributes.getValue("state"), "error");
272                    boolean b = ConversionHelpers.getBoolean(attributes.getValue("boolean"), false);
273                    int i = ConversionHelpers.getInt(attributes.getValue("int"), 4711);
274                    long l = ConversionHelpers.getLong(attributes.getValue("long"), 1L);
275                    assertEquals(state, "ok");
276                    assertEquals(b, true);
277                    assertEquals(i, -100);
278                    assertEquals(l, 4676767676L);
279    
280                    // this is actually not there
281                    String notThere = ConversionHelpers.getString(attributes.getValue("notThere"), "is not there");
282                    assertEquals(notThere, "is not there");
283    
284                    assertEquals(attributes.getLength(), 5);
285                    assertEquals(attributes.getValue(0), "ok");
286                    assertEquals(attributes.getType("ns:olli"), "CDATA");
287                    // these should be enough...
288                }
289            }
290        }
291    
292    }