/
OmeroContext.java
400 lines (350 loc) · 14.5 KB
/
OmeroContext.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
/*
* $Id$
*
* Copyright 2006 University of Dundee. All rights reserved.
* Use is subject to license terms supplied in LICENSE.txt
*/
package ome.system;
// Java imports
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import ome.api.ServiceInterface;
import ome.conditions.ApiUsageException;
import ome.util.messages.InternalMessage;
import ome.util.messages.MessageException;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConstructorArgumentValues;
import org.springframework.beans.factory.config.TypedStringValue;
import org.springframework.beans.factory.config.ConstructorArgumentValues.ValueHolder;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.access.ContextSingletonBeanFactoryLocator;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.StaticApplicationContext;
/**
* Provides static access for the creation of singleton and non-singleton
* application contexts. Also provides context names as constant fields which
* can be used for the lookup of particular contexts, through either
* {@link #getInstance(String)} or
* {@link ome.system.ServiceFactory#ServiceFactory(String)}.
*
* By passing a {@link java.util.Properties} instance into the
* {@link #getClientContext(Properties)} method, a non-static version is
* created. Currently this is only supported for the client context.
*
* @author <br>
* Josh Moore <a
* href="mailto:josh.moore@gmx.de"> josh.moore@gmx.de</a>
* @since OME3.0
*/
public class OmeroContext extends ClassPathXmlApplicationContext {
/**
* identifier for an OmeroContext configured in
* classpath*:beanRefContext.xml for use by remote (via JNDI/RMI) clients.
*/
public final static String CLIENT_CONTEXT = "ome.client";
/**
* identifier for an OmeroContext configured in
* classpath*:beanRefContext.xml for use by server-side processes. All
* objects obtained from the context are in a state for immediate use.
*/
public final static String MANAGED_CONTEXT = "ome.server";
private static OmeroContext _client;
private static OmeroContext _managed;;
/**
* Multicaster used by this instance. Unlike other Spring application
* contexts, this context assumes that a "global multicaster" is configured
* and so does not pass messages to the parent context, but assumes that
* the multicaster will do this. In order to implement this logic, it is
* necessary to lookup the entity by name, since all getters and fields
* are private in the superclasses.
*/
private ApplicationEventMulticaster multicaster;
// ~ Constructors
// =========================================================================
public OmeroContext(String configLocation) throws BeansException {
super(configLocation);
}
public OmeroContext(String[] configLocations) throws BeansException {
super(configLocations);
}
public OmeroContext(String[] configLocations, boolean refresh)
throws BeansException {
super(configLocations, refresh);
}
public OmeroContext(String[] configLocations, ApplicationContext parent)
throws BeansException {
super(configLocations, parent);
}
public OmeroContext(String[] configLocations, boolean refresh,
ApplicationContext parent) throws BeansException {
super(configLocations, refresh, parent);
}
// ~ Creation
// =========================================================================
private final static Object mutex = new Object();
/**
* create (if necessary) and return the single default client OmeroContext.
* Any two calls to this method will return the same (==) context instance.
*
* @see #CLIENT_CONTEXT
*/
public static OmeroContext getClientContext() {
synchronized (mutex) {
if (_client == null) {
_client = getInstance(CLIENT_CONTEXT);
}
return _client;
}
}
/**
* initialize a new client OmeroContext (named {@link #CLIENT_CONTEXT}),
* using the {@link #getContext(Properties, String)} method.
*
* @see #getContext(Properties, String)
* @see #CLIENT_CONTEXT
* @see ServiceFactory#ServiceFactory(Login)
* @see ServiceFactory#ServiceFactory(Server)
* @see ServiceFactory#ServiceFactory(Properties)
*/
public static OmeroContext getClientContext(Properties props) {
return getContext(props, CLIENT_CONTEXT);
}
/**
* initialize a new client OmeroContext using the {@link Properties}
* provided as values for property (e.g. ${name}) replacement in Spring. Two
* calls to this method with the same argument will return different ( =! )
* contexts.
*
* @param props
* Non-null properties for replacement.
* @param context
* Non-null name of context to find in beanRefContext.xml
*
* @see ServiceFactory#ServiceFactory(Login)
* @see ServiceFactory#ServiceFactory(Server)
* @see ServiceFactory#ServiceFactory(Properties)
*/
public static OmeroContext getContext(Properties props, String context) {
if (props == null || context == null) {
throw new ApiUsageException("Arguments may not be null.");
}
Properties copy = new Properties(props);
ConstructorArgumentValues ctorArg = new ConstructorArgumentValues();
ctorArg.addGenericArgumentValue(copy);
BeanDefinition definition = new RootBeanDefinition(Properties.class,
ctorArg, null);
StaticApplicationContext staticContext = new StaticApplicationContext();
staticContext.registerBeanDefinition("properties", definition);
staticContext.refresh();
OmeroContext ctx = new Locator().lookup(context, staticContext);
return ctx;
}
/**
* create (if necessary) and return the single default managed OmeroContext.
* Any two calls to this method will return the same (==) context instance.
* Managed means that the services are fully wrapped by interceptors, and
* are essentially the services made available remotely.
*
* @see #INTERNAL_CONTEXT
*/
public static OmeroContext getManagedServerContext() {
synchronized (mutex) {
if (_managed == null) {
_managed = getInstance(MANAGED_CONTEXT);
}
return _managed;
}
}
/**
* create (if necessary) and return the single default OmeroContext named by
* the beanFactoryName parameter. Any two calls to this method with the same
* parameter will return the same (==) context instance.
*
* @see #getClientContext()
* @see #getInternalServerContext()
* @see #getManagedServerContext()
*/
public static OmeroContext getInstance(String beanFactoryName) {
OmeroContext ctx = (OmeroContext) ContextSingletonBeanFactoryLocator
.getInstance().useBeanFactory(beanFactoryName).getFactory();
try {
ctx.getBeanFactory();
} catch (IllegalStateException ise) {
// Here we catch IllegalStateException because it implies that
// the bean factory isn't created yet. However, if that goes
// wrong, we need to rollback.
try {
ctx.refresh();
} catch (RuntimeException re) {
if (ctx != null) {
try {
ctx.close();
} catch (Exception e) {
// OK ignoring to rethrow the original exception
}
}
throw re;
}
}
return ctx;
}
// ~ Utilities
// =========================================================================
/**
* Uses the methods of this context's {@link BeanFactory} to autowire any
* Object based on the given beanName.
*
* @see org.springframework.beans.factory.config.AutowireCapableBeanFactory#applyBeanPropertyValues(java.lang.Object,
* java.lang.String)
*/
public void applyBeanPropertyValues(Object target, String beanName) {
this.getAutowireCapableBeanFactory().applyBeanPropertyValues(target,
beanName);
}
/**
* Uses the methods of this context's {@link BeanFactory} to autowire any
* Object based on the service class. This is used by
* {@link SelfConfigurableService} instances to acquire dependencies.
*
* @see SelfConfigurableService
* @see org.springframework.beans.factory.config.AutowireCapableBeanFactory#applyBeanPropertyValues(java.lang.Object,
* java.lang.String)
*/
public void applyBeanPropertyValues(Object target,
Class<? extends ServiceInterface> beanInterface) {
// TODO: it would be better to have this as <? extends
// SelfConfigurableService>
// but there are issues because of the ApplicationContextAware. Perhaps
// we can combine them later.
applyBeanPropertyValues(target, "internal-" + beanInterface.getName());
}
/**
* refreshes all the nested OmeroContexts within this instance. This is
* useful when using a static context, and {@link Properties} which were
* pulled from {@link System#getProperties()} have been changed.
*
* If this is a server-side instance ({@link OmeroContext#MANAGED_CONTEXT}
* or {@link OmeroContext#INTERNAL_CONTEXT}), this may take a significant
* amount of time.
*
* @see org.springframework.context.ConfigurableApplicationContext#refresh()
*/
public void refreshAll() {
ApplicationContext ac = this;
List<ConfigurableApplicationContext> list = new LinkedList<ConfigurableApplicationContext>();
while (ac instanceof ConfigurableApplicationContext) {
list.add((ConfigurableApplicationContext) ac);
ac = ac.getParent();
}
for (int i = list.size() - 1; i >= 0; i--) {
list.get(i).refresh();
}
}
/**
* Calls {@link #refreshAll() if {@link #isRunning()} throws an
* {@link IllegalStateException}.
*/
public void refreshAllIfNecessary() {
try {
isRunning();
} catch (IllegalStateException ise) {
refreshAll();
}
}
/**
* closes all the nested OmeroContexts within this instance.
*
* If this is a server-side instance ({@link OmeroContext#MANAGED_CONTEXT}
* or {@link OmeroContext#INTERNAL_CONTEXT}), this may take a significant
* amount of time.
*
* @see org.springframework.context.ConfigurableApplicationContext#close()
*/
public void closeAll() {
ApplicationContext ac = this;
List<ConfigurableApplicationContext> list = new LinkedList<ConfigurableApplicationContext>();
while (ac instanceof ConfigurableApplicationContext) {
list.add((ConfigurableApplicationContext) ac);
ac = ac.getParent();
}
for (int i = 0; i < list.size(); i++) {
list.get(i).close();
}
}
public String getProperty(String propertyName) {
PreferenceContext pc = (PreferenceContext) getBean("preferenceContext");
return pc.getProperty(propertyName);
}
@Override
public void publishEvent(ApplicationEvent event) {
multicaster.multicastEvent(event);
}
/**
* Convenience method around
* {@link #publishEvent(org.springframework.context.ApplicationEvent)} which
* catches all {@link MessageException} and unwraps the contained
* {@link Throwable} instance and rethrows.
*
* @param msg
* @throws Throwable
*/
public void publishMessage(InternalMessage msg) throws Throwable {
try {
publishEvent(msg);
} catch (MessageException me) {
throw me.getException();
}
}
@Override
protected void onRefresh() throws BeansException {
super.onRefresh();
multicaster = (ApplicationEventMulticaster) getBean("applicationEventMulticaster");
}
// ~ Non-singleton locator
// =========================================================================
/**
* provides access to the protected methods of
* {@link org.springframework.context.access.ContextSingletonBeanFactoryLocator}
* which cannot be used externally.
*/
protected static class Locator extends ContextSingletonBeanFactoryLocator {
// copied from ContextSingletonBeanFactoryLocator
private static final String BEANS_REFS_XML_NAME = "classpath*:beanRefContext.xml";
public Locator() {
super(null);
}
/**
* uses
* {@link ContextSingletonBeanFactoryLocator#createDefinition(java.lang.String, java.lang.String)}
* and
* {@link ContextSingletonBeanFactoryLocator#initializeDefinition(org.springframework.beans.factory.BeanFactory)}
* to create a new context from a given definition.
*/
public OmeroContext lookup(String selector, ApplicationContext parent) {
ConfigurableApplicationContext beanRefContext = (ConfigurableApplicationContext) createDefinition(
BEANS_REFS_XML_NAME, "manual");
initializeDefinition(beanRefContext);
BeanDefinition definition = beanRefContext.getBeanFactory()
.getBeanDefinition(selector);
ValueHolder holder = definition.getConstructorArgumentValues()
.getGenericArgumentValue(List.class);
List<TypedStringValue> files = (List<TypedStringValue>) holder
.getValue();
List<String> fileStrings = new ArrayList<String>(files.size());
for (TypedStringValue tsv : files) {
fileStrings.add(tsv.getValue());
}
OmeroContext c = new OmeroContext(fileStrings
.toArray(new String[0]), true, parent);
return c;
}
}
}