KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > hivemind > test > services > TestServices


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

15 package hivemind.test.services;
16
17 import hivemind.test.FrameworkTestCase;
18 import hivemind.test.services.impl.ArrayServiceImpl;
19 import hivemind.test.services.impl.DemoServiceImpl;
20 import hivemind.test.services.impl.SimpleServiceImpl;
21 import hivemind.test.services.impl.ToStringImpl;
22 import hivemind.test.services.impl.TrackerFactory;
23
24 import java.lang.reflect.Constructor JavaDoc;
25 import java.util.ArrayList JavaDoc;
26 import java.util.Collections JavaDoc;
27 import java.util.List JavaDoc;
28
29 import org.apache.hivemind.ApplicationRuntimeException;
30 import org.apache.hivemind.InterceptorStack;
31 import org.apache.hivemind.Location;
32 import org.apache.hivemind.Registry;
33 import org.apache.hivemind.definition.ImplementationConstructionContext;
34 import org.apache.hivemind.definition.ImplementationConstructor;
35 import org.apache.hivemind.definition.InterceptorConstructor;
36 import org.apache.hivemind.definition.InterceptorDefinition;
37 import org.apache.hivemind.definition.ModuleDefinition;
38 import org.apache.hivemind.definition.ServicePointDefinition;
39 import org.apache.hivemind.definition.impl.ModuleDefinitionHelper;
40 import org.apache.hivemind.definition.impl.ModuleDefinitionImpl;
41 import org.apache.hivemind.definition.impl.OrderedInterceptorDefinitionImpl;
42 import org.apache.hivemind.definition.impl.InterceptorDefinitionImpl;
43 import org.apache.hivemind.internal.AbstractServiceImplementationConstructor;
44 import org.apache.hivemind.internal.AbstractServiceInterceptorConstructor;
45 import org.apache.hivemind.internal.Module;
46 import org.apache.hivemind.internal.ServiceModel;
47 import org.apache.hivemind.service.ClassFactory;
48 import org.apache.hivemind.service.MethodContribution;
49 import org.apache.hivemind.service.impl.LoggingInterceptorClassFactory;
50
51 /**
52  * Tests involving creating and using services.
53  *
54  * @author Howard Lewis Ship
55  */

56 public class TestServices extends FrameworkTestCase
57 {
58
59     public void testSimple() throws Exception JavaDoc
60     {
61         Registry r = buildFrameworkRegistry(new SimpleModule());
62
63         assertNotNull(r);
64
65         SimpleService s =
66             (SimpleService) r.getService("hivemind.test.services.Simple", SimpleService.class);
67
68         assertNotNull(s);
69         assertEquals(11, s.add(4, 7));
70     }
71
72     /**
73      * Test that service instances are cached.
74      */

75     public void testCache() throws Exception JavaDoc
76     {
77         Registry r = buildFrameworkRegistry(new SimpleModule());
78
79         assertNotNull(r);
80
81         SimpleService s1 =
82             (SimpleService) r.getService("hivemind.test.services.Simple", SimpleService.class);
83         SimpleService s2 =
84             (SimpleService) r.getService("hivemind.test.services.Simple", SimpleService.class);
85
86         assertSame(s1, s2);
87     }
88
89     // Note: this works when run by Maven, but for some reason
90
// is failing inside Eclipse. It appears the be a Log4J
91
// configuration problem ... but I have no idea why.
92

93     public void testInterceptorSort() throws Exception JavaDoc
94     {
95         ModuleDefinition module = new SimpleModule();
96         ServicePointDefinition servicePoint = module.getServicePoint("Simple");
97         
98         InterceptorDefinition interceptor1 = new OrderedInterceptorDefinitionImpl(module, "Fred", newLocation(), new TrackerServiceInterceptorConstructor("Fred"), "Barney", null);
99         servicePoint.addInterceptor(interceptor1);
100         InterceptorDefinition interceptor2 = new OrderedInterceptorDefinitionImpl(module, "Barney", newLocation(), new TrackerServiceInterceptorConstructor("Barney"), null, null);
101         servicePoint.addInterceptor(interceptor2);
102         InterceptorDefinition interceptor3 = new OrderedInterceptorDefinitionImpl(module, "Wilma", newLocation(), new TrackerServiceInterceptorConstructor("Wilma"), null, "Barney");
103         servicePoint.addInterceptor(interceptor3);
104         
105         Registry r =
106             buildFrameworkRegistry(module);
107
108         SimpleService s =
109             (SimpleService) r.getService("hivemind.test.services.Simple", SimpleService.class);
110
111         TrackerFactory.reset();
112
113         assertEquals(11, s.add(4, 7));
114
115         assertListsEqual(
116             new String JavaDoc[] { "Wilma:add", "Barney:add", "Fred:add" },
117             TrackerFactory.getInvocations().toArray());
118
119     }
120     
121     class TrackerServiceInterceptorConstructor extends AbstractServiceInterceptorConstructor
122     {
123         String JavaDoc _name;
124         
125         public TrackerServiceInterceptorConstructor(String JavaDoc name)
126         {
127             super(null);
128             _name = name;
129         }
130
131         public void constructServiceInterceptor(InterceptorStack interceptorStack,
132                 Module contributingModule)
133         {
134             TrackerFactory factory = new TrackerFactory();
135             factory.setName(_name);
136             factory.createInterceptor(interceptorStack, contributingModule, null);
137         }
138
139         public Location getLocation()
140         {
141             return newLocation();
142         }
143
144     }
145     
146     public void testLogging() throws Exception JavaDoc
147     {
148         interceptLogging("hivemind.test.services.Demo");
149
150         Registry r = createRegistryWithInterceptedService("Demo", DemoService.class.getName(),
151                 DemoServiceImpl.class.getName(), Collections.EMPTY_LIST);
152
153         DemoService s =
154             (DemoService) r.getService("hivemind.test.services.Demo", DemoService.class);
155
156         s.add(5, 3);
157
158         assertLoggedMessages(
159             new String JavaDoc[] {
160                 "Creating SingletonProxy for service hivemind.test.services.Demo",
161                 "Constructing core service implementation for service hivemind.test.services.Demo",
162                 "Applying interceptor factory hivemind.LoggingInterceptor",
163                 "BEGIN add(5, 3)",
164                 "END add() [8]" });
165
166         s.noResult();
167
168         assertLoggedMessages(new String JavaDoc[] { "BEGIN noResult()", "END noResult()" });
169
170         try
171         {
172             s.alwaysFail();
173             unreachable();
174         }
175         catch (ApplicationRuntimeException ex)
176         {
177             assertExceptionSubstring(ex, "Failure in method alwaysFail.");
178         }
179
180         assertLoggedMessages(
181             new String JavaDoc[] {
182                 "BEGIN alwaysFail()",
183                 "EXCEPTION alwaysFail() -- org.apache.hivemind.ApplicationRuntimeException" });
184
185     }
186
187     /**
188      * Builds a registry that contains a single service that is intercepted by logging interceptor.
189      */

190     private Registry createRegistryWithInterceptedService(String JavaDoc serviceName, String JavaDoc serviceInterface, String JavaDoc implementationClass,
191             final List JavaDoc interceptedMethods)
192     {
193         ModuleDefinitionImpl module = createModuleDefinition("hivemind.test.services");
194         ModuleDefinitionHelper helper = new ModuleDefinitionHelper(module);
195         ServicePointDefinition sp = helper.addServicePoint(serviceName, serviceInterface);
196         helper.addSimpleServiceImplementation(sp, implementationClass, ServiceModel.SINGLETON);
197         
198         // Add logging interceptor
199
InterceptorConstructor constructor = new AbstractServiceInterceptorConstructor(module.getLocation()) {
200
201             public void constructServiceInterceptor(InterceptorStack interceptorStack, Module contributingModule)
202             {
203                 ClassFactory cf = (ClassFactory) contributingModule.getService(ClassFactory.class);
204                 // Create the interceptor with the LoggingInterceptorClassFactory which is quite uncomfortable
205
// in the moment
206
LoggingInterceptorClassFactory f = new LoggingInterceptorClassFactory(cf);
207                 Class JavaDoc interceptorClass = f.constructInterceptorClass(interceptorStack, Collections.EMPTY_LIST);
208                 Constructor JavaDoc c = interceptorClass.getConstructors()[0];
209                 Object JavaDoc interceptor;
210                 try
211                 {
212                     interceptor = c.newInstance(new Object JavaDoc[] { interceptorStack.getServiceLog(), interceptorStack.peek() });
213                 }
214                 catch (Exception JavaDoc e) {
215                     throw new ApplicationRuntimeException(e);
216                 }
217                 interceptorStack.push(interceptor);
218             }};
219         InterceptorDefinition interceptor = new InterceptorDefinitionImpl(module, "hivemind.LoggingInterceptor", module.getLocation(), constructor);
220         sp.addInterceptor(interceptor);
221         return buildFrameworkRegistry(module);
222     }
223     
224     /**
225      * Test the filters; where we include "no*" but exclude "always*".
226      */

227     public void testLoggingMethodFilters() throws Exception JavaDoc
228     {
229         interceptLogging("hivemind.test.services.Demo");
230
231         // configure intercepted methods: include "no*", exclude "always*"
232
List JavaDoc interceptedMethods = new ArrayList JavaDoc();
233         MethodContribution include = new MethodContribution();
234         include.setMethodPattern("no*");
235         include.setInclude(true);
236         MethodContribution exclude = new MethodContribution();
237         exclude.setMethodPattern("always*");
238         interceptedMethods.add(include);
239         interceptedMethods.add(exclude);
240         
241         Registry r = createRegistryWithInterceptedService("Demo", DemoService.class.getName(),
242                 DemoServiceImpl.class.getName(), interceptedMethods);
243
244         DemoService s =
245             (DemoService) r.getService("hivemind.test.services.Demo", DemoService.class);
246
247         s.add(5, 3);
248
249         assertLoggedMessages(
250             new String JavaDoc[] {
251                 "Creating SingletonProxy for service hivemind.test.services.Demo",
252                 "Constructing core service implementation for service hivemind.test.services.Demo",
253                 "Applying interceptor factory hivemind.LoggingInterceptor",
254                 "BEGIN add(5, 3)",
255                 "END add() [8]" });
256
257         s.noResult();
258
259         assertLoggedMessages(new String JavaDoc[] { "BEGIN noResult()", "END noResult()" });
260
261         try
262         {
263             s.alwaysFail();
264             unreachable();
265         }
266         catch (ApplicationRuntimeException ex)
267         {
268             assertExceptionSubstring(ex, "Failure in method alwaysFail.");
269         }
270
271         // Check that no logging took place.
272

273         assertLoggedMessages(new String JavaDoc[0]);
274     }
275
276     /**
277      * Checks for the detection of a recursive service; one that is dependant on
278      * itself.
279      */

280     public void testRecursiveService() throws Exception JavaDoc
281     {
282         Registry r = createRegistryWithRecursiveService();
283
284         try
285         {
286             r.getService("hivemind.test.services.Recursive", Object JavaDoc.class);
287             unreachable();
288         }
289         catch (Exception JavaDoc ex)
290         {
291             assertExceptionSubstring(
292                 ex,
293                 "A recursive call to construct service hivemind.test.services.Recursive has occured.");
294         }
295
296     }
297     
298     /**
299      * Builds a registry that contains a single service that references itself during construction
300      */

301     private Registry createRegistryWithRecursiveService()
302     {
303         ModuleDefinitionImpl module = createModuleDefinition("hivemind.test.services");
304         ModuleDefinitionHelper helper = new ModuleDefinitionHelper(module);
305         ServicePointDefinition sp = helper.addServicePoint("Recursive", SimpleService.class.getName());
306
307         ImplementationConstructor constructor = new AbstractServiceImplementationConstructor(module.getLocation())
308         {
309             public Object JavaDoc constructCoreServiceImplementation(ImplementationConstructionContext context)
310             {
311                 Object JavaDoc result = new SimpleServiceImpl();
312                 // Here is the recursion
313
context.getService("hivemind.test.services.Recursive", SimpleService.class);
314                 return result;
315             }
316         };
317
318         helper.addServiceImplementation(sp, constructor, ServiceModel.PRIMITIVE);
319         
320         return buildFrameworkRegistry(module);
321     }
322
323     /**
324      * Test that checks that interceptors don't override toString() if toString()
325      * is part of the service interface.
326      */

327     public void testToString() throws Exception JavaDoc
328     {
329         Registry r = createRegistryWithInterceptedService("ToString", ToString.class.getName(),
330                 ToStringImpl.class.getName(), Collections.EMPTY_LIST);
331
332         ToString ts = (ToString) r.getService("hivemind.test.services.ToString", ToString.class);
333
334         interceptLogging("hivemind.test.services.ToString");
335
336         assertEquals("ToStringImpl of toString()", ts.toString());
337
338         List JavaDoc events = getInterceptedLogEvents();
339         assertLoggedMessage("BEGIN toString()", events);
340         assertLoggedMessage("END toString() [ToStringImpl of toString()]", events);
341
342     }
343
344     public void testArrayResult() throws Exception JavaDoc
345     {
346         Registry r = createRegistryWithInterceptedService("ArrayResult", ArrayService.class.getName(),
347                 ArrayServiceImpl.class.getName(), Collections.EMPTY_LIST);
348
349         ArrayService s =
350             (ArrayService) r.getService("hivemind.test.services.ArrayResult", ArrayService.class);
351
352         interceptLogging("hivemind.test.services.ArrayResult");
353
354         String JavaDoc[] result = s.returnArrayType();
355
356         assertListsEqual(new String JavaDoc[] { "alpha", "beta" }, result);
357
358         assertLoggedMessage("END returnArrayType() [(java.lang.String[]){alpha, beta}]");
359     }
360
361
362 }
363
Popular Tags