1 package org.apache.turbine.services;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 import java.util.ArrayList;
24 import java.util.Iterator;
25 import java.util.LinkedHashMap;
26 import java.util.LinkedHashSet;
27 import java.util.Map;
28 import java.util.Set;
29 import java.util.concurrent.ConcurrentHashMap;
30 import java.util.concurrent.locks.ReentrantLock;
31
32 import org.apache.commons.configuration2.Configuration;
33 import org.apache.commons.lang3.StringUtils;
34 import org.apache.logging.log4j.LogManager;
35 import org.apache.logging.log4j.Logger;
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58 public abstract class BaseServiceBroker implements ServiceBroker
59 {
60
61
62
63 private final Map<String, Class<?>> mapping = new LinkedHashMap<String, Class<?>>();
64
65
66
67
68 private final ConcurrentHashMap<String, Service> services = new ConcurrentHashMap<String, Service>();
69
70
71
72
73 private final ReentrantLock serviceLock = new ReentrantLock();
74
75
76
77
78
79
80 private Configuration configuration;
81
82
83
84
85
86 public static final String SERVICE_PREFIX = "services.";
87
88
89
90
91
92 public static final String CLASSNAME_SUFFIX = ".classname";
93
94
95
96
97
98
99
100
101
102
103
104
105 private final ConcurrentHashMap<String, Object> serviceObjects = new ConcurrentHashMap<String, Object>();
106
107
108 private static final Logger log = LogManager.getLogger(BaseServiceBroker.class);
109
110
111
112
113
114 private String applicationRoot;
115
116
117
118
119 private final ConcurrentHashMap<String, Service> serviceProviderInstanceMap = new ConcurrentHashMap<String, Service>();
120
121
122
123
124
125
126 protected BaseServiceBroker()
127 {
128
129 }
130
131
132
133
134
135
136
137
138
139 public void setConfiguration(Configuration configuration)
140 {
141 this.configuration = configuration;
142 }
143
144
145
146
147
148
149 public Configuration getConfiguration()
150 {
151 return configuration;
152 }
153
154
155
156
157
158 public void init() throws InitializationException
159 {
160
161
162
163
164
165
166
167
168
169
170 initMapping();
171
172
173
174 initServices(false);
175 }
176
177
178
179
180
181
182
183
184
185 public void setServiceObject(String name, Object value)
186 {
187 serviceObjects.put(name, value);
188 }
189
190
191
192
193
194
195
196 public Object getServiceObject(String name)
197 {
198 return serviceObjects.get(name);
199 }
200
201
202
203
204
205
206
207
208
209 private boolean checkForInterface(Class<?> checkIfc, Class<?>[] interfaces)
210 {
211 for (Class<?> ifc : interfaces)
212 {
213 if (ifc == checkIfc)
214 {
215 return true;
216 }
217
218 Class<?>[] subInterfaces = ifc.getInterfaces();
219 if (checkForInterface(checkIfc, subInterfaces))
220 {
221 return true;
222 }
223 }
224
225 return false;
226 }
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245 protected void initMapping() throws InitializationException
246 {
247
248
249 Map<String, String> earlyInitFlags = new LinkedHashMap<String, String>();
250
251
252
253
254
255
256 for (Iterator<String> keys = configuration.getKeys(); keys.hasNext();)
257 {
258 String key = keys.next();
259 String[] keyParts = StringUtils.split(key, ".");
260
261 if (keyParts.length == 3
262 && (keyParts[0] + ".").equals(SERVICE_PREFIX)
263 && ("." + keyParts[2]).equals(CLASSNAME_SUFFIX))
264 {
265 String serviceKey = keyParts[1];
266 log.info("Added Mapping for Service: {}", serviceKey);
267
268 if (!mapping.containsKey(serviceKey))
269 {
270 String className = configuration.getString(key);
271 try
272 {
273 Class<?> clazz = Class.forName(className);
274 mapping.put(serviceKey, clazz);
275
276
277 if (checkForInterface(TurbineServiceProvider.class, clazz.getInterfaces()))
278 {
279 log.info("Found a TurbineServiceProvider: {} - initializing it early", serviceKey);
280 earlyInitFlags.put(SERVICE_PREFIX + serviceKey + ".earlyInit", "true");
281 }
282 }
283
284 catch (ThreadDeath t)
285 {
286 throw t;
287 }
288 catch (OutOfMemoryError t)
289 {
290 throw t;
291 }
292 catch (ClassNotFoundException | NoClassDefFoundError e)
293 {
294 throw new InitializationException("Class " + className +
295 " is unavailable. Check your jars and classes.", e);
296 }
297 }
298 }
299 }
300
301 for (Map.Entry<String, String> entry : earlyInitFlags.entrySet())
302 {
303 configuration.setProperty(entry.getKey(), entry.getValue());
304 }
305 }
306
307
308
309
310
311
312
313
314 @Override
315 public boolean isRegistered(String serviceName)
316 {
317 return (services.get(serviceName) != null);
318 }
319
320
321
322
323
324
325 public Iterator<String> getServiceNames()
326 {
327 return mapping.keySet().iterator();
328 }
329
330
331
332
333
334
335
336
337 public Iterator<String> getServiceNames(String prefix)
338 {
339 Set<String> keys = new LinkedHashSet<String>(mapping.keySet());
340 for(Iterator<String> key = keys.iterator(); key.hasNext();)
341 {
342 if (!key.next().startsWith(prefix))
343 {
344 key.remove();
345 }
346 }
347
348 return keys.iterator();
349 }
350
351
352
353
354
355
356
357
358
359
360 @Override
361 public synchronized void initService(String name)
362 throws InitializationException
363 {
364
365
366
367 Service instance = getServiceInstance(name);
368
369 if (!instance.getInit())
370 {
371
372 instance.init();
373 }
374 }
375
376
377
378
379
380
381
382 public void initServices()
383 {
384 try
385 {
386 initServices(false);
387 }
388 catch (InstantiationException | InitializationException notThrown)
389 {
390 log.debug("Caught non fatal exception", notThrown);
391 }
392 }
393
394
395
396
397
398
399
400
401
402
403
404 public void initServices(boolean report)
405 throws InstantiationException, InitializationException
406 {
407 if (report)
408 {
409
410 for (Iterator<String> names = getServiceNames(); names.hasNext();)
411 {
412 doInitService(names.next());
413 }
414 }
415 else
416 {
417
418 for (Iterator<String> names = getServiceNames(); names.hasNext();)
419 {
420 try
421 {
422 doInitService(names.next());
423 }
424
425
426 catch (InstantiationException | InitializationException e)
427 {
428 log.error(e);
429 }
430 }
431 }
432 log.info("Finished initializing all services!");
433 }
434
435
436
437
438
439 private void doInitService(String name)
440 throws InstantiationException, InitializationException
441 {
442
443 if (getConfiguration(name).getBoolean("earlyInit", false))
444 {
445 log.info("Start Initializing service (early): {}", name);
446 initService(name);
447 log.info("Finish Initializing service (early): {}", name);
448 }
449 }
450
451
452
453
454
455
456
457
458
459 @Override
460 public synchronized void shutdownService(String name)
461 {
462 try
463 {
464 Service service = getServiceInstance(name);
465 if (service != null && service.getInit())
466 {
467 service.shutdown();
468
469 if (service.getInit() && service instanceof BaseService)
470 {
471
472
473 ((BaseService) service).setInit(false);
474 }
475 }
476 }
477 catch (InstantiationException e)
478 {
479
480 log.error("Shutdown of a nonexistent Service '"
481 + name + "' was requested", e);
482 }
483 }
484
485
486
487
488
489 @Override
490 public void shutdownServices()
491 {
492 log.info("Shutting down all services!");
493
494 String serviceName = null;
495
496
497
498
499
500
501
502
503 ArrayList<String> reverseServicesList = new ArrayList<String>();
504
505 for (Iterator<String> serviceNames = getServiceNames(); serviceNames.hasNext();)
506 {
507 serviceName = serviceNames.next();
508 reverseServicesList.add(0, serviceName);
509 }
510
511 for (Iterator<String> serviceNames = reverseServicesList.iterator(); serviceNames.hasNext();)
512 {
513 serviceName = serviceNames.next();
514 log.info("Shutting down service: {}", serviceName);
515 shutdownService(serviceName);
516 }
517 }
518
519
520
521
522
523
524
525
526
527 @Override
528 public Object getService(String name) throws InstantiationException
529 {
530 Service service;
531
532 if (this.isLocalService(name))
533 {
534 try
535 {
536 service = getServiceInstance(name);
537 if (!service.getInit())
538 {
539 synchronized (service.getClass())
540 {
541 if (!service.getInit())
542 {
543 log.info("Start Initializing service (late): {}", name);
544 service.init();
545 log.info("Finish Initializing service (late): {}", name);
546 }
547 }
548 }
549 if (!service.getInit())
550 {
551
552
553
554
555 throw new InitializationException(
556 "init() failed to initialize service " + name);
557 }
558 return service;
559 }
560 catch (InitializationException e)
561 {
562 throw new InstantiationException("Service " + name +
563 " failed to initialize", e);
564 }
565 }
566 else if (this.isNonLocalService(name))
567 {
568 return this.getNonLocalService(name);
569 }
570 else
571 {
572 throw new InstantiationException(
573 "ServiceBroker: unknown service " + name
574 + " requested");
575 }
576 }
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598 protected Service getServiceInstance(String name)
599 throws InstantiationException
600 {
601 Service service = services.get(name);
602
603 if (service == null)
604 {
605 serviceLock.lock();
606
607 try
608 {
609
610 service = services.get(name);
611
612 if (service == null)
613 {
614 if (!this.isLocalService(name))
615 {
616 throw new InstantiationException(
617 "ServiceBroker: unknown service " + name
618 + " requested");
619 }
620
621 try
622 {
623 Class<?> clazz = mapping.get(name);
624
625 try
626 {
627 service = (Service) clazz.newInstance();
628
629
630
631 if (service instanceof TurbineServiceProvider)
632 {
633 Service _service = this.serviceProviderInstanceMap.putIfAbsent(name,service);
634 if (_service != null)
635 {
636 service = _service;
637 }
638 }
639 }
640
641 catch (ClassCastException e)
642 {
643 throw new InstantiationException("Class " + clazz +
644 " doesn't implement the Service interface", e);
645 }
646 catch (ThreadDeath t)
647 {
648 throw t;
649 }
650 catch (OutOfMemoryError t)
651 {
652 throw t;
653 }
654 catch (Throwable t)
655 {
656 throw new InstantiationException("Failed to instantiate " + clazz, t);
657 }
658 }
659 catch (InstantiationException e)
660 {
661 throw new InstantiationException(
662 "Failed to instantiate service " + name, e);
663 }
664 service.setServiceBroker(this);
665 service.setName(name);
666 Service _service = services.putIfAbsent(name, service);
667 if (_service != null)
668 {
669 service = _service;
670 }
671 }
672 }
673 finally
674 {
675 serviceLock.unlock();
676 }
677 }
678
679 return service;
680 }
681
682
683
684
685
686
687
688 @Override
689 public Configuration getConfiguration(String name)
690 {
691 return configuration.subset(SERVICE_PREFIX + name);
692 }
693
694
695
696
697
698
699 public void setApplicationRoot(String applicationRoot)
700 {
701 this.applicationRoot = applicationRoot;
702 }
703
704
705
706
707
708
709
710 @Override
711 public String getApplicationRoot()
712 {
713 return applicationRoot;
714 }
715
716
717
718
719
720
721
722
723 protected boolean isLocalService(String name)
724 {
725 return this.mapping.containsKey(name);
726 }
727
728
729
730
731
732
733
734
735
736
737 protected boolean isNonLocalService(String name)
738 {
739 TurbineServiceProvider turbineServiceProvider = null;
740
741 for (Map.Entry<String, Service> entry : this.serviceProviderInstanceMap.entrySet())
742 {
743 turbineServiceProvider = (TurbineServiceProvider) this.getService(entry.getKey());
744
745 if (turbineServiceProvider.exists(name))
746 {
747 return true;
748 }
749 }
750
751 return false;
752 }
753
754
755
756
757
758
759
760
761 protected Object getNonLocalService(String name)
762 throws InstantiationException
763 {
764 TurbineServiceProvider turbineServiceProvider = null;
765
766 for (Map.Entry<String, Service> entry : this.serviceProviderInstanceMap.entrySet())
767 {
768 turbineServiceProvider = (TurbineServiceProvider) this.getService(entry.getKey());
769
770 if (turbineServiceProvider.exists(name))
771 {
772 return turbineServiceProvider.get(name);
773 }
774 }
775
776 throw new InstantiationException(
777 "ServiceBroker: unknown non-local service " + name
778 + " requested");
779 }
780 }