1 package org.apache.onami.lifecycle.jsr250;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import com.google.inject.AbstractModule;
23 import com.google.inject.CreationException;
24 import com.google.inject.Provides;
25 import org.apache.onami.lifecycle.core.DisposingStager;
26 import org.apache.onami.lifecycle.core.StageHandler;
27 import org.junit.Test;
28
29 import javax.annotation.PreDestroy;
30 import java.util.concurrent.ExecutorService;
31 import java.util.concurrent.Executors;
32
33 import static com.google.inject.Guice.createInjector;
34 import static org.junit.Assert.*;
35
36 public final class PreDestroyModuleTestCase
37 {
38
39 @Test
40 public void disposeUsingModuleOnInjectorFailure()
41 {
42 PreDestroyModule preDestroyModule = new PreDestroyModule();
43 try
44 {
45 createInjector( preDestroyModule, new AbstractModule()
46 {
47
48 @Override
49 protected void configure()
50 {
51 bind( ThrowingExceptionConstructor.class ).asEagerSingleton();
52 }
53
54 } );
55 fail( "Expected exception was not thrown" );
56 }
57 catch( CreationException e )
58 {
59 Throwable cause = e.getCause();
60 assertTrue( cause instanceof IllegalArgumentException );
61 assertEquals( "Expected exception", cause.getMessage() );
62 }
63 finally
64 {
65 preDestroyModule.getStager().stage( new StageHandler()
66 {
67
68 @Override
69 public <I> void onSuccess( I injectee )
70 {
71 assertTrue( injectee instanceof DisposableObject );
72 assertTrue( ( (DisposableObject) injectee ).disposed );
73 }
74
75 @Override
76 public <I, E extends Throwable> void onError( I injectee, E error )
77 {
78 fail( error.toString() );
79 }
80
81 } );
82 }
83 }
84
85 @Test
86 public void disposeUsingModuleWithProvidesMethodOnInjectorFailure()
87 {
88 PreDestroyModule preDestroyModule = new PreDestroyModule();
89 try
90 {
91 createInjector( preDestroyModule, new AbstractModule()
92 {
93
94 @Override
95 protected void configure()
96 {
97 bind( ThrowingExceptionConstructor2.class ).asEagerSingleton();
98 }
99
100 @Provides
101 public ExecutorService provideExecutorService( DisposingStager<PreDestroy> stager )
102 {
103 return stager.register( Executors.newCachedThreadPool() );
104 }
105
106 } );
107 fail( "Expected exception was not thrown" );
108 }
109 catch( CreationException e )
110 {
111 Throwable cause = e.getCause();
112 assertTrue( cause instanceof IllegalArgumentException );
113 assertEquals( "Expected exception", cause.getMessage() );
114 }
115 finally
116 {
117 preDestroyModule.getStager().stage( new StageHandler()
118 {
119
120 @Override
121 public <I> void onSuccess( I injectee )
122 {
123 assertTrue( injectee instanceof ExecutorService );
124 assertTrue( ( (ExecutorService) injectee ).isShutdown() );
125 }
126
127 @Override
128 public <I, E extends Throwable> void onError( I injectee, E error )
129 {
130 fail( error.toString() );
131 }
132
133 } );
134 }
135 }
136
137 }