KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > naming > resources > AbstractDirContextTest


1 /*
2  * Copyright 2004,2004 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package org.apache.naming.resources;
17
18 import java.io.ByteArrayInputStream JavaDoc;
19 import java.util.HashMap JavaDoc;
20 import java.util.Iterator JavaDoc;
21 import java.util.Map JavaDoc;
22 import java.util.NoSuchElementException JavaDoc;
23
24 import javax.naming.Binding JavaDoc;
25 import javax.naming.CompositeName JavaDoc;
26 import javax.naming.Context JavaDoc;
27 import javax.naming.Name JavaDoc;
28 import javax.naming.NameClassPair JavaDoc;
29 import javax.naming.NamingEnumeration JavaDoc;
30 import javax.naming.NamingException JavaDoc;
31 import javax.naming.NameParser JavaDoc;
32 import javax.naming.OperationNotSupportedException JavaDoc;
33 import javax.naming.directory.DirContext JavaDoc;
34 import javax.naming.directory.Attribute JavaDoc;
35 import javax.naming.directory.Attributes JavaDoc;
36 import javax.naming.directory.BasicAttribute JavaDoc;
37 import javax.naming.directory.ModificationItem JavaDoc;
38
39 import junit.framework.TestCase;
40
41 /**
42  * Abstract base class for DirContext tests.
43  *
44  * In addition to overriding makeInitialContext() and
45  * setting switches, test classes derived from this class should:
46  *
47  * -- override isSchemaSupported() to return false if schema are not supported
48  * -- override isAttributeModificationSupported() to return false if attribute
49  * modification is not supported
50  * -- if attribute modification operations are supported, override
51  * modifyAttributeName(), modifyAttributeValue(), etc. to designate names
52  * and values appropriate for firstBoundObject() (from AbstractContextTest).
53  *
54  * @version $Revision: 125387 $ $Date: 2003/11/30 05:36:07 $
55  */

56 public abstract class AbstractDirContextTest extends TestCase {
57     public AbstractDirContextTest(String JavaDoc name) {
58         super(name);
59     }
60     //-------------------------- Contexts to use in tests ----------------------------------------------------
61

62     /** Initial Context used in tests */
63     protected Context JavaDoc initialContext;
64     
65     /** Immediate subcontext of initialContext */
66     protected Context JavaDoc firstContext;
67     
68     /** Immediate subcontext of firstContext */
69     protected Context JavaDoc secondContext;
70     
71     /** HashMap of Object Bindings for verification */
72     protected HashMap JavaDoc binding;
73     
74   //----------------- Switches to turn off tests for unsupported operations ----------------------
75

76     /**
77      * Does this context support getNameInNamespace()?
78      * Defaults to true -- override if not supported
79      */

80     protected boolean isGetNameInNamespaceSupported() {
81         return true;
82     }
83     
84     /**
85      * Can bindings be added to this context?
86      * Defaults to true -- override if not supported
87      */

88     protected boolean isWritable() {
89         return true;
90     }
91     
92     /**
93      * Create an initial context to be used in tests
94      */

95     protected abstract Context JavaDoc makeInitialContext();
96     
97     //-------------------- Override these methods to set up test namespace ------------------------
98

99     /** firstContext name -- relative to InitialContext */
100     protected String JavaDoc firstContextName() {
101         return "firstDir";
102     }
103     
104     /** secondContext name -- relative to first context */
105     protected String JavaDoc secondContextName() {
106         return "secondDir";
107     }
108     
109     /** First name to bind */
110     protected String JavaDoc firstBoundName() {
111         return "test1";
112     }
113     
114     /** First bound object */
115     protected Object JavaDoc firstBoundObject() {
116         return new Resource(new ByteArrayInputStream JavaDoc(bytes));
117     }
118     
119     /** Second name to bind */
120     protected String JavaDoc secondBoundName() {
121         return "test2";
122     }
123     
124     /** Second bound object */
125     protected Object JavaDoc secondBoundObject() {
126         return new Resource(new ByteArrayInputStream JavaDoc(bytes));
127     }
128     
129 //---------------------------------- Setup / teardown operations -----------------------------
130

131     /**
132      * Add bindings
133      */

134     protected void addBindings() throws Exception JavaDoc {
135         secondContext.bind(firstBoundName(), firstBoundObject());
136         secondContext.bind(secondBoundName(), secondBoundObject());
137         binding.put(firstBoundName(), firstBoundObject());
138         binding.put(secondBoundName(), secondBoundObject());
139     }
140     
141     /**
142      * Remove bindings
143      */

144     protected void removeBindings() throws Exception JavaDoc {
145         secondContext.unbind(firstBoundName());
146         secondContext.unbind(secondBoundName());
147         binding.clear();
148     }
149     
150     protected void setUp() throws Exception JavaDoc {
151         super.setUp();
152         binding = new HashMap JavaDoc();
153         initialContext = makeInitialContext();
154         if (isWritable()) {
155             firstContext = initialContext.createSubcontext(firstContextName());
156             secondContext = firstContext.createSubcontext(secondContextName());
157             addBindings();
158         }
159         nameParser = initialContext.getNameParser("");
160     }
161     
162     protected void tearDown() throws Exception JavaDoc {
163         if (isWritable()) {
164             removeBindings();
165             firstContext.destroySubcontext(secondContextName());
166             initialContext.destroySubcontext(firstContextName());
167         }
168         initialContext = null;
169     }
170     
171     //---------------------- Test data for DirContext tests ---------------------------------------
172

173     /** A few bytes to write to temp files created */
174     protected byte[] bytes = {'a', 'b', 'c'};
175     
176     /**
177      * Expected attributes associated with firstBoundObject()
178      */

179     protected Attributes JavaDoc expectedAttributes() {
180         return null;
181     }
182     
183     /** Name parser from initialContext */
184     protected NameParser JavaDoc nameParser = null;
185     
186     //-------------- Switches to turn off tests if features are not supported ---------------------
187

188     /**
189      * Does this DirContext support shema -- i.e. implement getSchema(), getSchemaClassDefinition()?
190      * Override to return false if schema methods are not supported.
191      */

192     protected boolean isSchemaSupported() {
193         return true;
194     }
195     
196     /**
197      * Does this DirContext support attribute modification?
198      * Override to return false if attributes cannot be modified.
199      */

200     protected boolean isAttributeModificationSupported() {
201         return true;
202     }
203     
204     //---------------- Attribute names and values for modification tests --------------------------
205
/**
206      * Name of the attribute associated with firstBoundObject() to replace.
207      * Override to return the name of an attribute of firstBoundObject() whose value can be replaced
208      * if this is supported
209      */

210     protected String JavaDoc replaceAttributeName() {
211         return null;
212     }
213     
214     /**
215      * Replacement value for replaceAttributeName.
216      * Override to return the replacement value if this is supported.
217      */

218     protected Object JavaDoc replaceAttributeValue() {
219         return null;
220     }
221     
222     /**
223      * Name of attribute of firstBoundObject() object to add.
224      * Override to return the name of a new attribute to add to the attributes of firstBoundObject()
225      * if this is supported.
226      */

227     protected String JavaDoc addAttributeName() {
228         return null;
229     }
230     
231     /**
232      * Value for addAttributeName.
233      * Override to return the value for the new attribute if this is supported.
234      */

235     protected Object JavaDoc addAttributeValue() {
236         return null;
237     }
238     
239     /**
240      * Name of attribute of firstBoundObject() to remove.
241      * Override to return the name of an attribute to remove from the attributes of firstBoundObject()
242      * if this is supported.
243      */

244     protected String JavaDoc removeAttributeName() {
245         return null;
246     }
247     
248     // -------------------------------- Verification methods -----------------------------------------------
249

250     /**
251      * Verify that object returned by lookup operation is "same" as bound object.
252      * Override this method if the object returned by looking up the name of a bound
253      * object is not equal to the originally bound object.
254      */

255     protected void verifyLookup(Object JavaDoc boundObject, Object JavaDoc returnedObject) {
256         assertEquals(boundObject, returnedObject);
257     }
258     
259     /**
260      * Verify that the listed bound names match expectation and
261      * that the class names of bound objects are not empty
262      */

263     protected void verifyList(Map JavaDoc expected, Map JavaDoc returned) {
264         assertEquals(expected.keySet(), returned.keySet());
265         Iterator JavaDoc iterator = returned.values().iterator();
266         while (iterator.hasNext()) {
267             assertTrue(((String JavaDoc) iterator.next()).length() > 0);
268         }
269     }
270     
271     /**
272      * Verify that the listed bound names match expectation
273      */

274     protected void verifyListBindings(Map JavaDoc expected, Map JavaDoc returned) {
275         assertEquals(expected.keySet(), returned.keySet());
276     }
277     
278     /**
279      * Verify that the Attributes associated with <name> in <context> include an Attribute with
280      * attribute ID = <attributeName> and this Attribute contains the value <attributeValue>
281      */

282     protected void verifyAttribute(DirContext JavaDoc context, String JavaDoc name, String JavaDoc attributeName,
283             Object JavaDoc attributeValue) throws Exception JavaDoc {
284         String JavaDoc attrIds[] = new String JavaDoc[1];
285         attrIds[0] = attributeName;
286         Attributes JavaDoc attrs = context.getAttributes(name, attrIds);
287         assertTrue(attrs.get(attributeName).contains(attributeValue));
288     }
289     
290     /**
291      * Verify that the Attributes associated with <name> in <context> do not include an Attribute with
292      * attribute ID = <attributeName>
293      */

294     protected void verifyAttributeMissing(DirContext JavaDoc context, String JavaDoc name, String JavaDoc attributeName) throws Exception JavaDoc {
295         String JavaDoc attrIds[] = new String JavaDoc[1];
296         attrIds[0] = attributeName;
297         Attributes JavaDoc attrs = context.getAttributes(name, attrIds);
298         assertEquals(0, attrs.size());
299     }
300     
301     //--------------------------- Default implementations for basic tests --------------------------
302

303     public void testInitialContext() throws NamingException JavaDoc {
304         verifyLookup(firstBoundObject(),
305                 initialContext.lookup(firstContextName() + "/"
306                         + secondContextName() +"/" + firstBoundName()));
307         verifyLookup(secondBoundObject(),
308                 initialContext.lookup(new CompositeName JavaDoc
309                         (firstContextName() + "/" + secondContextName() + "/" + secondBoundName())));
310         verifyLookup(secondContext.lookup(firstBoundName()),
311                 ((Context JavaDoc) secondContext.lookup("")).lookup(firstBoundName()));
312     }
313
314     public void testLookup() throws NamingException JavaDoc {
315         verifyLookup(firstBoundObject(), secondContext.lookup(firstBoundName()));
316         verifyLookup(firstBoundObject(),
317                 firstContext.lookup(secondContextName() + "/" +firstBoundName()));
318         try {
319             secondContext.lookup("foo");
320             fail("expecting NamingException");
321         } catch (NamingException JavaDoc e) {
322             // expected
323
}
324         verifyLookup(firstBoundObject(),
325                 secondContext.lookup(new CompositeName JavaDoc(firstBoundName())));
326         verifyLookup(firstBoundObject(),
327                 firstContext.lookup(new CompositeName JavaDoc(secondContextName() + "/" + firstBoundName())));
328         verifyLookup(secondBoundObject(),
329                 ((Context JavaDoc) initialContext.lookup(firstContextName())).lookup(secondContextName() + "/" + secondBoundName()));
330     }
331     
332     public void testComposeName() throws NamingException JavaDoc {
333         assertEquals("org/research/user/jane",
334                 secondContext.composeName("user/jane", "org/research"));
335         assertEquals("research/user/jane",
336                 secondContext.composeName("user/jane", "research"));
337         assertEquals(new CompositeName JavaDoc("org/research/user/jane"),
338                 secondContext.composeName(new CompositeName JavaDoc("user/jane"),
339                         new CompositeName JavaDoc("org/research")));
340         assertEquals(new CompositeName JavaDoc("research/user/jane"),
341                 secondContext.composeName(new CompositeName JavaDoc("user/jane"),
342                         new CompositeName JavaDoc("research")));
343     }
344
345     public void testList() throws NamingException JavaDoc {
346         NamingEnumeration JavaDoc enumeration;
347         Map JavaDoc expected;
348         Map JavaDoc result;
349
350         expected = new HashMap JavaDoc();
351         for (Iterator JavaDoc i = binding.entrySet().iterator(); i.hasNext();) {
352             Map.Entry JavaDoc entry = (Map.Entry JavaDoc) i.next();
353             expected.put(entry.getKey(), entry.getValue().getClass().getName());
354         }
355         enumeration = secondContext.list("");
356         result = new HashMap JavaDoc();
357         while (enumeration.hasMore()) {
358             NameClassPair JavaDoc pair = (NameClassPair JavaDoc) enumeration.next();
359             result.put(pair.getName(), pair.getClassName());
360         }
361         verifyList(expected, result);
362
363         try {
364             enumeration.next();
365             fail("Expecting NoSuchElementException");
366         } catch (NoSuchElementException JavaDoc e) {
367             // expected
368
}
369         try {
370             enumeration.nextElement();
371             fail("Expecting NoSuchElementException");
372         } catch (NoSuchElementException JavaDoc e) {
373             // expected
374
}
375     }
376
377     public void testListBindings() throws NamingException JavaDoc {
378         NamingEnumeration JavaDoc enumeration;
379         Map JavaDoc result;
380         enumeration = secondContext.listBindings("");
381         result = new HashMap JavaDoc();
382         while (enumeration.hasMore()) {
383             Binding JavaDoc pair = (Binding JavaDoc) enumeration.next();
384             result.put(pair.getName(), pair.getObject());
385         }
386         verifyListBindings(binding, result);
387
388         try {
389             enumeration.next();
390             fail("Expecting NoSuchElementException");
391         } catch (NoSuchElementException JavaDoc e) {
392             // expected
393
}
394         try {
395             enumeration.nextElement();
396             fail("Expecting NoSuchElementException");
397         } catch (NoSuchElementException JavaDoc e) {
398             // expected
399
}
400     }
401     
402     /**
403      * Default implementation just tests to make sure non-null names are returned
404      * or correct exception is thrown.
405      */

406     public void testGetNameInNamespace() throws Exception JavaDoc {
407         if (isGetNameInNamespaceSupported()) {
408             String JavaDoc name = initialContext.getNameInNamespace();
409             if (name == null) {
410                 fail("Null NameInNamespace for initial context");
411             }
412         } else {
413             try {
414                 String JavaDoc name = firstContext.getNameInNamespace();
415                 fail("Expecting OperationNotSupportedException");
416             } catch(OperationNotSupportedException JavaDoc ex) {
417                 // expected
418
}
419         }
420     }
421     
422     /**
423      * Test rebind -- swap bound objects and verify
424      */

425     public void testRebind() throws Exception JavaDoc {
426         secondContext.rebind(firstBoundName(), secondBoundObject());
427         secondContext.rebind(secondBoundName(), firstBoundObject());
428         binding.put(firstBoundName(), secondBoundObject());
429         binding.put(secondBoundName(), firstBoundObject());
430         NamingEnumeration JavaDoc enumeration;
431         Map JavaDoc result;
432         enumeration = secondContext.listBindings("");
433         result = new HashMap JavaDoc();
434         while (enumeration.hasMore()) {
435             Binding JavaDoc pair = (Binding JavaDoc) enumeration.next();
436             result.put(pair.getName(), pair.getObject());
437         }
438         verifyListBindings(binding, result);
439     }
440     
441     /**
442      * Verify that getAttributes returns a valid NamingEnumeration of Attributes.
443      * If expectedAttributes() has been overriden to return a non-null set of attributes,
444      * this set is tested for equality with the Attributes returned by getAttributes.
445      */

446    public void testAttributes() throws Exception JavaDoc {
447       DirContext JavaDoc context = (DirContext JavaDoc) initialContext.lookup(firstContextName()+ "/" + secondContextName());
448       Attributes JavaDoc attrs = (Attributes JavaDoc) context.getAttributes(firstBoundName());
449       NamingEnumeration JavaDoc enumeration = attrs.getAll();
450       while (enumeration.hasMoreElements()) {
451           assertTrue(enumeration.nextElement() instanceof Attribute JavaDoc);
452       }
453       Attributes JavaDoc expected = expectedAttributes();
454       if (expected != null) {
455           assertEquals(expected, attrs);
456       }
457    }
458    
459    /**
460     * Verify that getSchema and getSchemaClassDefinition return non-null DirContexts.
461     * This test will only be run if isSchemaSupported returns true.
462     * @throws Exception
463     */

464    public void testGetSchema() throws Exception JavaDoc {
465        if (!isSchemaSupported()) {
466            try {
467                ((DirContext JavaDoc) initialContext.lookup("")).getSchema("");
468                fail("Expecting OperationNotSupportedException");
469            } catch (OperationNotSupportedException JavaDoc ex) {
470                // expected
471
}
472            return;
473        }
474        DirContext JavaDoc context = (DirContext JavaDoc) initialContext.lookup("");
475        DirContext JavaDoc schemaContext = context.getSchema("");
476        assertNotNull(schemaContext);
477        Name JavaDoc name = nameParser.parse(firstContext.getNameInNamespace());
478        schemaContext = context.getSchema(name);
479        assertNotNull(schemaContext);
480        schemaContext = context.getSchema(firstBoundName());
481        assertNotNull(schemaContext);
482        schemaContext = context.getSchemaClassDefinition(name);
483        assertNotNull(schemaContext);
484        schemaContext = context.getSchemaClassDefinition(firstBoundName());
485        assertNotNull(schemaContext);
486    }
487    
488    /**
489     * Tests attribute modification operations on attributes -- add, update, delete.
490     * If no attribute modifications are supported, override isAttributeModificationSupported() to return
491     * false and this test will be skipped. If one or more of add, update, delete are not supported,
492     * just leave the associated *attributeName() method returning null and the associated operation
493     * will not be tested.
494     */

495    public void testAttributeModification() throws Exception JavaDoc {
496        if (!isAttributeModificationSupported()) {
497            return;
498        }
499        ModificationItem JavaDoc[] modifications = new ModificationItem JavaDoc[1];
500        DirContext JavaDoc context = (DirContext JavaDoc) initialContext.lookup(firstContextName() + "/"
501                + secondContextName() +"/" + firstBoundName());
502       
503       if(addAttributeName() != null) {
504           Attribute JavaDoc addModification = new BasicAttribute JavaDoc(addAttributeName(), addAttributeValue());
505           modifications[0] = new ModificationItem JavaDoc(DirContext.ADD_ATTRIBUTE, addModification);
506           context.modifyAttributes("", modifications);
507           verifyAttribute(context, "", addAttributeName(), addAttributeValue());
508       }
509       
510       if(replaceAttributeName() != null) {
511           Attribute JavaDoc replaceModification = new BasicAttribute JavaDoc(replaceAttributeName(), replaceAttributeValue());
512           modifications[0] = new ModificationItem JavaDoc(DirContext.REPLACE_ATTRIBUTE, replaceModification);
513           context.modifyAttributes("", modifications);
514           verifyAttribute(context, "", replaceAttributeName(), replaceAttributeValue());
515       }
516       
517       if(removeAttributeName() != null) {
518           Attribute JavaDoc removeModification = new BasicAttribute JavaDoc(removeAttributeName());
519           modifications[0] = new ModificationItem JavaDoc(DirContext.REMOVE_ATTRIBUTE, removeModification);
520           context.modifyAttributes("", modifications);
521           verifyAttributeMissing(context, "", removeAttributeName());
522       }
523    }
524   
525 }
526
Popular Tags