1 package com.sri.common;
2
3 import com.jcorporate.expresso.core.dbobj.Schema;
4 import com.sri.common.controller.ComponentServiceLocator;
5 import com.sri.common.controller.NoSuchServiceException;
6 import org.picocontainer.MutablePicoContainer;
7 import org.picocontainer.Parameter;
8 import org.picocontainer.PicoContainer;
9 import org.picocontainer.PicoIntrospectionException;
10 import org.picocontainer.PicoRegistrationException;
11 import org.picocontainer.defaults.DefaultComponentAdapterFactory;
12 import org.picocontainer.defaults.DefaultPicoContainer;
13
14 import java.util.Enumeration;
15 import java.util.Iterator;
16
17 /***
18 * Abstract Base class for Schemas that wish to serve as a component factory.
19 *
20 * @author Michael Rimov
21 * @version 1.0
22 */
23 abstract public class ComponentSchema extends Schema implements ComponentSPI, ComponentServiceLocator {
24
25 /***
26 * The application service locator.
27 */
28 private MutablePicoContainer applicationContainer;
29
30 /***
31 * Initialize the application container.
32 *
33 * @return PicoContainer
34 */
35 public PicoContainer initializeApplicationContainer() {
36 DefaultPicoContainer pico = new DefaultPicoContainer();
37 addAllSchemaElementsToContainer(pico);
38 return pico;
39 }
40
41 public void setApplicationContainer(MutablePicoContainer container) {
42 applicationContainer = container;
43 }
44
45
46 /***
47 * Retrieves the desired service defined by the key.
48 *
49 * @param serviceKey Object usually the service interface class, but may
50 * be other object.
51 * @return Object.
52 * @throws NoSuchServiceException if unable to locate the service.
53 * @throws IllegalArgumentException if service key is null.
54 */
55 public Object locate(Object serviceKey) throws NoSuchServiceException, IllegalArgumentException {
56 assert applicationContainer != null;
57
58 if (serviceKey == null) {
59 throw new IllegalArgumentException("Parameter 'serviceKey' must not be null");
60 }
61
62 if (applicationContainer == null) {
63 throw new IllegalStateException("Application Container has not been initialized");
64 }
65
66 Object result = applicationContainer.getComponentInstance(serviceKey);
67 if (result == null) {
68 throw new NoSuchServiceException("Unable to locate service: " + serviceKey.toString());
69 }
70
71 return result;
72 }
73
74 protected void addAllSchemaElementsToContainer(MutablePicoContainer pico) throws PicoIntrospectionException,
75 PicoRegistrationException {
76
77 for (Enumeration e = this.getMembers(); e.hasMoreElements();) {
78 Object oneObj = e.nextElement();
79
80
81
82 pico.registerComponent(new DefaultComponentAdapterFactory().createComponentAdapter(oneObj.getClass(),
83 oneObj.getClass(), new Parameter[]{}));
84 }
85
86
87
88 for (Iterator i = this.getControllerList().iterator(); i.hasNext();) {
89 pico.registerComponentInstance(i.next());
90 }
91
92 }
93
94 public MutablePicoContainer getApplicationContainer() {
95 return applicationContainer;
96 }
97 }