View Javadoc
1   /*
2    * Copyright (C) 2007-2012 Argeo GmbH
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *         http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.argeo.slc.osgi;
17  
18  import java.util.ArrayList;
19  import java.util.HashMap;
20  import java.util.Hashtable;
21  import java.util.List;
22  import java.util.Map;
23  import java.util.Properties;
24  
25  import org.apache.commons.logging.Log;
26  import org.apache.commons.logging.LogFactory;
27  import org.osgi.framework.Bundle;
28  import org.osgi.framework.BundleContext;
29  import org.osgi.framework.Constants;
30  import org.springframework.context.ApplicationContext;
31  import org.springframework.context.ApplicationEvent;
32  import org.springframework.context.ApplicationListener;
33  import org.springframework.context.event.ContextRefreshedEvent;
34  import org.springframework.core.Ordered;
35  
36  /** Publishes beans of the application context as OSGi services. */
37  @SuppressWarnings(value = { "unchecked", "rawtypes" })
38  public class MultipleServiceExporterPostProcessor implements
39  		ApplicationListener, Ordered {
40  	private final static Log log = LogFactory
41  			.getLog(MultipleServiceExporterPostProcessor.class);
42  
43  	private List<Class> interfaces = new ArrayList<Class>();
44  
45  	private int order = Ordered.LOWEST_PRECEDENCE;
46  
47  	private BundleContext bundleContext = null;
48  
49  	// private Class osgiServiceFactoryClass = OsgiServiceFactoryBean.class;
50  	// private Boolean useServiceProviderContextClassLoader = false;
51  
52  	public void onApplicationEvent(ApplicationEvent event) {
53  		Map<String, Object> beans = new HashMap<String, Object>();
54  		if (event instanceof ContextRefreshedEvent) {
55  			if (bundleContext != null) {
56  				for (Class clss : interfaces) {
57  					ApplicationContext ac = ((ContextRefreshedEvent) event)
58  							.getApplicationContext();
59  					beans.putAll(ac.getBeansOfType(clss, false, false));
60  				}
61  
62  				int count = 0;
63  				for (String beanName : beans.keySet()) {
64  					Object bean = beans.get(beanName);
65  					List<String> classes = new ArrayList<String>();
66  					for (Class clss : interfaces) {
67  						if (clss.isAssignableFrom(bean.getClass())) {
68  							classes.add(clss.getName());
69  						}
70  					}
71  					Properties props = new Properties();
72  					Bundle bundle = bundleContext.getBundle();
73  					props.put(Constants.BUNDLE_SYMBOLICNAME,
74  							bundle.getSymbolicName());
75  					props.put(Constants.BUNDLE_VERSION, bundle.getVersion());
76  					// retrocompatibility with pre-1.0:
77  					props.put("org.eclipse.gemini.blueprint.bean.name", beanName);
78  					bundleContext.registerService(
79  							classes.toArray(new String[classes.size()]), bean,
80  							new Hashtable(props));
81  					count++;
82  				}
83  				if (log.isTraceEnabled())
84  					log.trace("Published " + count + " " + interfaces
85  							+ " as OSGi services from bundle "
86  							+ bundleContext.getBundle().getSymbolicName() + " "
87  							+ bundleContext.getBundle().getVersion());
88  				// note: the services will be automatically unregistered when
89  				// the bundle will be stopped
90  			}
91  		}
92  	}
93  
94  	// public void postProcessBeanFactory(
95  	// ConfigurableListableBeanFactory beanFactory) throws BeansException {
96  	// if (!(beanFactory instanceof BeanDefinitionRegistry)) {
97  	// throw new SlcException("Can only work on "
98  	// + BeanDefinitionRegistry.class);
99  	// }
100 	//
101 	// long begin = System.currentTimeMillis();
102 	//
103 	// // Merge all beans implementing these interfaces
104 	// Set<String> beanNames = new HashSet<String>();
105 	// for (Class clss : interfaces) {
106 	// String[] strs = beanFactory.getBeanNamesForType(clss, true, false);
107 	// beanNames.addAll(Arrays.asList(strs));
108 	// }
109 	//
110 	// // Register service factory beans for them
111 	// for (String beanName : beanNames) {
112 	// MutablePropertyValues mpv = new MutablePropertyValues();
113 	// mpv.addPropertyValue("interfaces", interfaces.toArray());
114 	// mpv.addPropertyValue("targetBeanName", beanName);
115 	// if (useServiceProviderContextClassLoader)
116 	// mpv.addPropertyValue("contextClassLoader",
117 	// ExportContextClassLoader.SERVICE_PROVIDER);
118 	// RootBeanDefinition bd = new RootBeanDefinition(
119 	// osgiServiceFactoryClass, mpv);
120 	//
121 	// String exporterBeanName = "osgiService." + beanName;
122 	// if (log.isTraceEnabled())
123 	// log.debug("Registering OSGi service exporter "
124 	// + exporterBeanName);
125 	// ((BeanDefinitionRegistry) beanFactory).registerBeanDefinition(
126 	// exporterBeanName, bd);
127 	// }
128 	//
129 	// long end = System.currentTimeMillis();
130 	// if (log.isTraceEnabled())
131 	// log.debug("Multiple services exported in " + (end - begin)
132 	// + " ms in bundle.");
133 	//
134 	// }
135 
136 	public void setInterfaces(List<Class> interfaces) {
137 		this.interfaces = interfaces;
138 	}
139 
140 	// public void setOsgiServiceFactoryClass(Class osgiServiceFactoryClass) {
141 	// this.osgiServiceFactoryClass = osgiServiceFactoryClass;
142 	// }
143 
144 	public int getOrder() {
145 		return order;
146 	}
147 
148 	public void setOrder(int order) {
149 		this.order = order;
150 	}
151 
152 	// public void setUseServiceProviderContextClassLoader(
153 	// Boolean useServiceProviderContextClassLoader) {
154 	// this.useServiceProviderContextClassLoader =
155 	// useServiceProviderContextClassLoader;
156 	// }
157 
158 	public void setBundleContext(BundleContext bundleContext) {
159 		this.bundleContext = bundleContext;
160 	}
161 }