KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > enhydra > xml > xmlc > html > ApiTests


1 /*
2  * Enhydra Java Application Server Project
3  *
4  * The contents of this file are subject to the Enhydra Public License
5  * Version 1.1 (the "License"); you may not use this file except in
6  * compliance with the License. You may obtain a copy of the License on
7  * the Enhydra web site ( http://www.enhydra.org/ ).
8  *
9  * Software distributed under the License is distributed on an "AS IS"
10  * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
11  * the License for the specific terms governing rights and limitations
12  * under the License.
13  *
14  * The Initial Developer of the Enhydra Application Server is Lutris
15  * Technologies, Inc. The Enhydra Application Server and portions created
16  * by Lutris Technologies, Inc. are Copyright Lutris Technologies, Inc.
17  * All Rights Reserved.
18  *
19  * Contributor(s):
20  *
21  * $Id: ApiTests.java,v 1.2 2005/01/26 08:29:25 jkjome Exp $
22  */

23
24 package org.enhydra.xml.xmlc.html;
25 import java.io.FileOutputStream JavaDoc;
26 import java.io.IOException JavaDoc;
27 import java.io.PrintWriter JavaDoc;
28 import java.lang.reflect.Constructor JavaDoc;
29 import java.lang.reflect.Method JavaDoc;
30
31 import junit.framework.Test;
32
33 import org.enhydra.xml.dom.DOMInfo;
34 import org.enhydra.xml.dom.DOMStats;
35 import org.enhydra.xml.driver.TestException;
36 import org.enhydra.xml.xmlc.XMLCUtil;
37 import org.enhydra.xml.xmlc.XMLObject;
38 import org.enhydra.xml.xmlc.dom.xerces.XercesHTMLDomFactory;
39 import org.enhydra.xml.xmlc.driver.ExecXmlc;
40 import org.enhydra.xml.xmlc.driver.TestDOMSource;
41 import org.w3c.dom.Document JavaDoc;
42 import org.w3c.dom.Element JavaDoc;
43 import org.w3c.dom.Node JavaDoc;
44 import org.w3c.dom.NodeList JavaDoc;
45 import org.w3c.dom.html.HTMLAnchorElement;
46 import org.w3c.dom.html.HTMLBodyElement;
47 import org.w3c.dom.html.HTMLCollection;
48 import org.w3c.dom.html.HTMLDocument;
49 import org.w3c.dom.html.HTMLElement;
50 import org.w3c.dom.html.HTMLFormElement;
51 import org.w3c.dom.html.HTMLHeadElement;
52 import org.w3c.dom.html.HTMLHtmlElement;
53 import org.w3c.dom.html.HTMLLIElement;
54 import org.w3c.dom.html.HTMLTableElement;
55 import org.w3c.dom.html.HTMLTableRowElement;
56 import org.w3c.dom.html.HTMLTitleElement;
57 import org.w3c.dom.html.HTMLUListElement;
58
59 /**
60  * Tests of various things at the API level. Interfaces or reflection is used
61  * to access to compiled objects as we want this test to work with documents
62  * compiled in different ways.
63  */

64 public class ApiTests extends HtmlTestCaseBase {
65     /** Object for creating instances of FrameTreeHTML. */
66     private TestDOMSource fFrameTreeSource;
67
68     /** Object for creating instances of ShelfHTML. */
69     private TestDOMSource fShelfSource;
70
71     /** Object for creating instances of GetElementByIdHTML. */
72     private TestDOMSource fGetElementByIdSource;
73
74     /** Factory method to create suite of these tests */
75     public static Test suite() {
76         return createSuite(ApiTests.class, null);
77     }
78     
79     /** Constructor */
80     public ApiTests(Method JavaDoc method) {
81         super(method);
82         fFrameTreeSource = new TestDOMSource(this, getParams(),
83                                              getInputFile("FrameTree.html"),
84                                              "FrameTreeHTMLImpl",
85                                              FrameTreeHTML.class);
86         fShelfSource = new TestDOMSource(this, getParams(),
87                                          getInputFile("Shelf.html"),
88                                          "ShelfHTMLImpl",
89                                          ShelfHTML.class);
90         fGetElementByIdSource = new TestDOMSource(this, getParams(),
91                                                   getInputFile("GetElementById.html"),
92                                                   "GetElementByIdHTMLImpl",
93                                                   GetElementByIdHTML.class);
94     }
95
96     /**
97      * Verify various attributes of a compiled HTML document object.
98      */

99     private void verifyHtmlDoc(XMLObject htmlObj) {
100         if (!(htmlObj instanceof HTMLObject)) {
101             throw new TestException("Document not an instance of HTMLObject: "
102                                     + htmlObj.getClass());
103         }
104         if (!(htmlObj instanceof HTMLDocument)) {
105             throw new TestException("Document not an instance of HTMLDocument: "
106                                     + htmlObj.getClass());
107         }
108         Object JavaDoc docObj = htmlObj.getDocument();
109         if (!(docObj instanceof HTMLDocument)) {
110             throw new TestException("Document contained in XMLObject is not instance of HTMLDocument: "
111                                     + docObj.getClass());
112         }
113     }
114
115     /**
116      * Get and instance of the FrameTreeHTML object.
117      */

118     private FrameTreeHTML createFrameTreeDoc() {
119         FrameTreeHTML htmlObj = (FrameTreeHTML)fFrameTreeSource.create();
120         verifyHtmlDoc(htmlObj);
121         return htmlObj;
122     }
123
124     /*
125      * Find an element by class attribute name. Makes the incorrect
126      * assumption that there is only one class name per element.
127      */

128     private Element JavaDoc getByClassAttrName(Node JavaDoc node,
129                                        String JavaDoc className) {
130         if (node instanceof HTMLElement) {
131             String JavaDoc elemClassName = ((HTMLElement)node).getClassName();
132             if ((elemClassName != null)
133                 && elemClassName.equalsIgnoreCase(className)) {
134                 return (HTMLElement)node;
135             }
136         }
137         NodeList JavaDoc children = node.getChildNodes();
138         for (int i=0; i<children.getLength();i++) {
139             Element JavaDoc ret = getByClassAttrName(children.item(i), className);
140             if (ret != null) {
141                 return ret;
142             }
143         }
144         return null;
145     }
146     
147     /*
148      * Find an element by class attribute name. Generates error if not found.
149      */

150     private Element JavaDoc getFirstByClassAttrName(Node JavaDoc node,
151                                             String JavaDoc className) {
152         Element JavaDoc elem = getByClassAttrName(node, className);
153         if (elem == null) {
154             throw new TestException("Could't find class \"" + className
155                                     + "\" starting at: " + node.toString());
156         }
157         return elem;
158     }
159
160     /* Delete an element of the table */
161     private void deleteElement(HTMLTableElement table,
162                                String JavaDoc className) {
163         Element JavaDoc elem = getFirstByClassAttrName(table, className);
164         table.removeChild(elem);
165     }
166
167     /*
168      * Test 1: deleting of children. Taken from code that (I thought) caused
169      * grief in the past. In fact, there it was a bug in the XMLC
170      * application, but this test will be left in.
171      */

172     public void test1() {
173         FrameTreeHTML htmlObj = createFrameTreeDoc();
174
175         // Use reflection here, as we want to make sure the
176
// constants are in the generated file.
177
HTMLTableElement table = htmlObj.getElementTable();
178
179         // deleteElement(table, htmlObj.CLASS_customerExpanded);
180
deleteElement(table, getStringField(htmlObj, "CLASS_customerExpanded"));
181         deleteElement(table, getStringField(htmlObj, "CLASS_projectNoSite"));
182         deleteElement(table, getStringField(htmlObj, "CLASS_projectWithSite"));
183         deleteElement(table, getStringField(htmlObj, "CLASS_selectedProjectNoSite"));
184         deleteElement(table, getStringField(htmlObj, "CLASS_selectedProjectWithSite"));
185         deleteElement(table, getStringField(htmlObj, "CLASS_newProject"));
186         deleteElement(table, getStringField(htmlObj, "CLASS_customerWithProject"));
187         deleteElement(table, getStringField(htmlObj, "CLASS_customerNoProject"));
188         dumpVerifyDom(htmlObj, DOC_DOM_DUMP_EXT);
189     }
190
191     /** Clone a document via the copy constructor */
192     private HTMLObject copyConstruct(HTMLObject srcDoc) {
193         Class JavaDoc srcClass = srcDoc.getClass();
194         try {
195             Constructor JavaDoc constr = srcClass.getConstructor(new Class JavaDoc[]{srcClass});
196             return (HTMLObject)constr.newInstance(new Object JavaDoc[]{srcDoc});
197         } catch (Throwable JavaDoc except) {
198             throw new TestException("call of copy constructe failed on "
199                                     + srcClass, except);
200         }
201     }
202
203     /**
204      * Test 2: copy constructor of generate object.
205      */

206     public void test2() {
207         FrameTreeHTML htmlObj = createFrameTreeDoc();
208
209         // Set fields values in the original document
210
htmlObj.getElementIMG1().setSrc("image1.gif");
211         htmlObj.getElementIMG2().setSrc("image2.gif");
212
213         // Clone object and set other field values.
214
FrameTreeHTML html2Obj = (FrameTreeHTML)copyConstruct(htmlObj);
215         html2Obj.getElementIMG2().setSrc("image2-clone.gif");
216         html2Obj.getElementIMG3().setSrc("image3-clone.gif");
217
218         // Modify the original document
219
htmlObj.getElementIMG3().setSrc("image3.gif");
220
221         // Write em out and verify
222
String JavaDoc name1 = "1.doc.dom";
223         dumpVerifyDom(htmlObj, getResultFile(name1),
224                       getExpectedFile(name1));
225         String JavaDoc name2 = "2.doc.dom";
226         dumpVerifyDom(htmlObj, getResultFile(name2),
227                       getExpectedFile(name2));
228     }
229
230     /*
231      * Test 3: setting title
232      */

233     public void test3() {
234         FrameTreeHTML htmlObj = createFrameTreeDoc();
235         htmlObj.setTitle("This is a new title");
236         dumpVerifyDom(htmlObj, DOC_DOM_DUMP_EXT);
237     }
238
239     /* Create a new HTML document. */
240     private HTMLDocument createHTMLDocument() {
241         // Use the right method, depending on the DOM.
242
if (getParams().getDom().equals(ExecXmlc.LAZY_DOM)) {
243             return HTMLDocumentFactory.createDocument();
244         } else {
245             return (HTMLDocument)new XercesHTMLDomFactory().createDocument(null, null, null);
246         }
247     }
248
249     /** Append a test special character to the list. */
250     private void appendChar(HTMLUListElement list,
251                             String JavaDoc entityName,
252                             char entityChar) {
253         Document JavaDoc doc = list.getOwnerDocument();
254         HTMLLIElement li = (HTMLLIElement)doc.createElement("li");
255         list.appendChild(li);
256
257         String JavaDoc txt = entityName + " `" + entityChar + "'";
258         li.appendChild(doc.createTextNode(txt));
259     }
260
261     /*
262      * Test 4: special characters.
263      */

264     public void test4() {
265         HTMLDocument doc = createHTMLDocument();
266
267         HTMLHtmlElement htmlElem = (HTMLHtmlElement)doc.getDocumentElement();
268
269         HTMLHeadElement headElem = (HTMLHeadElement)doc.createElement("head");
270         htmlElem.appendChild(headElem);
271
272         HTMLTitleElement title = (HTMLTitleElement)doc.createElement("title");
273         headElem.appendChild(title);
274         title.appendChild(doc.createTextNode("Test of inserting special characeters into DOM"));
275
276         HTMLBodyElement body = (HTMLBodyElement)doc.createElement("body");
277         htmlElem.appendChild(body);
278
279         HTMLUListElement list = (HTMLUListElement)doc.createElement("ul");
280         body.appendChild(list);
281                 
282         appendChar(list, "nbsp", '\u00a0');
283         appendChar(list, "gt", '\u003e');
284         appendChar(list, "pound", '\u00a3');
285
286         dumpVerifyDom(doc, DOC_DOM_DUMP_EXT);
287     }
288
289     /*
290      * Test 5: bug where createElement didn't work right when called on XMLC
291      * document object.
292      */

293     public void test5() {
294         FrameTreeHTML htmlObj = createFrameTreeDoc();
295
296         // This created a class cast exception in the reported bug.
297
HTMLAnchorElement anchor = (HTMLAnchorElement)htmlObj.createElement("A");
298     }
299
300     /*
301      * Do most of the work of getElementByIdTest().
302      */

303     private void doGetElementByIdTest(String JavaDoc id,
304                                       boolean modifyAttr,
305                                       boolean addChild,
306                                       PrintWriter JavaDoc out) {
307         FrameTreeHTML htmlObj = createFrameTreeDoc();
308
309         HTMLElement element = (HTMLElement)htmlObj.getElementById(id);
310                 
311         DOMInfo.printTree("Element returned for id=\"" + id + "\"",
312                           element, out);
313         out.println();
314         if ((modifyAttr || addChild) && (element != null)) {
315             if (modifyAttr) {
316                 element.setClassName("modified");
317             }
318             if (addChild) {
319                 element.appendChild(htmlObj.createComment("this was modified"));
320             }
321             DOMInfo.printTree("Element after modification",
322                               element, out);
323             out.println();
324         }
325         DOMInfo.printTree("Tree after getElementById(\"" + id + "\")",
326                           htmlObj, out);
327     }
328
329     /*
330      * Method used to implements tests of getElementById().
331      */

332     private void getElementByIdTest(String JavaDoc id,
333                                     boolean modifyAttr,
334                                     boolean addChild) {
335         try {
336             PrintWriter JavaDoc out = new PrintWriter JavaDoc(new FileOutputStream JavaDoc(getResultFile(DOC_DOM_DUMP_EXT)));
337             try {
338                 doGetElementByIdTest(id, modifyAttr, addChild, out);
339             } finally {
340                 out.close();
341             }
342         } catch (IOException JavaDoc except) {
343             throw new TestException(except);
344         }
345                 
346         getDiffer().diff(getExpectedFile(DOC_DOM_DUMP_EXT),
347                          getResultFile(DOC_DOM_DUMP_EXT));
348     }
349
350     /*
351      * Do work of getElementsByNameTest()
352      */

353     private void doGetElementsByNameTest(String JavaDoc name,
354                                          PrintWriter JavaDoc out) {
355         FrameTreeHTML htmlObj = createFrameTreeDoc();
356
357         NodeList JavaDoc elements = htmlObj.getElementsByName(name);
358         out.println("Number of elements for name=\"" + name + "\": "
359                     + elements.getLength());
360         out.println();
361         for (int i = 0 ; i < elements.getLength(); i++) {
362             DOMInfo.printTree("Element " + i, elements.item(i),
363                               out);
364             out.println();
365         }
366         DOMInfo.printTree("Tree after getElementsByName(\"" + name + "\")", htmlObj,
367                           out);
368     }
369
370     /*
371      * Method used to implements tests of getElementsByName()
372      */

373     private void getElementsByNameTest(String JavaDoc name) {
374         try {
375             PrintWriter JavaDoc out = new PrintWriter JavaDoc(new FileOutputStream JavaDoc(getResultFile(DOC_DOM_DUMP_EXT)));
376             try {
377                 doGetElementsByNameTest(name, out);
378             } finally {
379                 out.close();
380             }
381         } catch (IOException JavaDoc except) {
382             throw new TestException(except);
383         }
384         getDiffer().diff(getExpectedFile(DOC_DOM_DUMP_EXT),
385                          getResultFile(DOC_DOM_DUMP_EXT));
386     }
387
388     /*
389      * Tests 6-11: test element lookup functions. Function print both thes
390      * Elements found and the trees after search, so that expansion of lazydom
391      * can be detected.
392      */

393     public void test6() {
394         getElementByIdTest("table", false, false);
395     }
396     public void test7() {
397         getElementByIdTest("IMG2", false, false);
398     }
399     public void test8() {
400         getElementByIdTest("table", true, true);
401     }
402     public void test9() {
403         getElementByIdTest("IMG2", true, true);
404     }
405     public void test10() {
406         getElementsByNameTest("CustomerA");
407     }
408     public void test11() {
409         getElementsByNameTest("CustomerB");
410     }
411
412     /*
413      * Test 12: HTMLTableElement operations
414      */

415     public void test12() {
416         try {
417             PrintWriter JavaDoc out = new PrintWriter JavaDoc(new FileOutputStream JavaDoc(getResultFile(DOC_DOM_DUMP_EXT)));
418             try {
419                 FrameTreeHTML htmlObj = createFrameTreeDoc();
420                 HTMLTableElement table = htmlObj.getElementTable();
421                 HTMLCollection rows = table.getRows();
422                 out.println("Number of rows for table: " + rows.getLength());
423                 for (int rowIdx = 0; rowIdx < rows.getLength(); rowIdx++) {
424                     HTMLTableRowElement row = (HTMLTableRowElement)rows.item(rowIdx);
425                     out.println();
426                     DOMInfo.printTree("row " + rowIdx, rows.item(rowIdx),
427                                       out);
428                 }
429                 out.println();
430                 DOMInfo.printTree("Table after getRows", table, out);
431             } finally {
432                 out.close();
433             }
434         } catch (IOException JavaDoc except) {
435             throw new TestException(except);
436         }
437         getDiffer().diff(getExpectedFile(DOC_DOM_DUMP_EXT),
438                          getResultFile(DOC_DOM_DUMP_EXT));
439     }
440
441     /*
442      * Test 13: setText methods.
443      */

444     public void test13() {
445         ShelfHTML htmlObj = (ShelfHTML)fShelfSource.create();
446         verifyHtmlDoc(htmlObj);
447
448         // See if setting to null is detected:
449
Throwable JavaDoc gotExcept = null;
450         try {
451             htmlObj.setTextSampleCatText(null);
452         } catch (IllegalArgumentException JavaDoc except) {
453             gotExcept = except;
454         }
455         if (!(gotExcept instanceof IllegalArgumentException JavaDoc)) {
456             throw new TestException("didn't get expected IllegalArgumentException");
457         }
458
459         htmlObj.setTextSampleCatText("@@@@ This value updated by a setText method @@@@");
460         dumpVerifyDom(htmlObj, DOC_DOM_DUMP_EXT);
461     }
462
463     /**
464      * Test 14: Problem that occured with OpenXML and Xerces where Node
465      * implemented NodeList so save creating an object when getChildNodes is
466      * called. However, caused problems with HTMLFormElement and
467      * HTMLSelectElement, since they have getLength() methods that override
468      * NodeList.getLength().
469      */

470     public void test14() {
471         // Construct an element with at part of a form
472
HTMLDocument doc = createHTMLDocument();
473         Element JavaDoc body = doc.getBody();
474         HTMLFormElement form = (HTMLFormElement)doc.createElement("FORM");
475         body.appendChild(form);
476
477         // Add 3 text children and 3 element children
478
for (int i = 0; i < 3; i++) {
479             form.appendChild(doc.createTextNode("form text child #" + i));
480             Element JavaDoc input = doc.createElement("INPUT");
481             form.appendChild(input);
482             input.appendChild(doc.createTextNode("input #" + i + " text child"));
483         }
484
485         dumpVerifyDom(doc, DOC_DOM_DUMP_EXT);
486         if (form.getLength() != 3) {
487             throw new TestException("form.getLength() != 3");
488         }
489         if (form.getChildNodes().getLength() != 6) {
490             throw new TestException("form.getChildNodes().getLength() != 6");
491         }
492     }
493
494     /*
495      * Test 15: reproduce bug with calling XMLCUtil.getFirstText() to set a
496      * text node followed by calling HTMLDocument.getElementById(). This
497      * caused the LazyDOM to hang.
498      */

499     public void test15() {
500         try {
501             PrintWriter JavaDoc out = new PrintWriter JavaDoc(new FileOutputStream JavaDoc(getResultFile(DOC_DOM_DUMP_EXT)));
502             try {
503                 GetElementByIdHTML htmlObj = (GetElementByIdHTML)fGetElementByIdSource.create();
504
505                 XMLCUtil.getFirstText(htmlObj.getElementTime()).setData("the time is now");
506                 Element JavaDoc testElem = htmlObj.getElementById("test");
507
508                 DOMInfo.printTree("test element", testElem, out);
509                 DOMInfo.printTree("tree", htmlObj, out);
510                 DOMStats.printStats(null, htmlObj,
511                                     DOMStats.SIMPLE_CLASS_NAMES, out);
512             } finally {
513                 out.close();
514             }
515         } catch (IOException JavaDoc except) {
516             throw new TestException(except);
517         }
518         getDiffer().diff(getExpectedFile(DOC_DOM_DUMP_EXT),
519                          getResultFile(DOC_DOM_DUMP_EXT));
520     }
521 }
522
Popular Tags