KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > opensugar > cube > BundleContextImpl


1 /*
2  * JEFFREE: Java(TM) Embedded Framework FREE
3  * Copyright (C) 1999-2003 - Opensugar
4  *
5  * The contents of this file are subject to the Jeffree Public License,
6  * as defined by the file JEFFREE_LICENSE.TXT
7  *
8  * You may not use this file except in compliance with the License.
9  * You may obtain a copy of the License on the Objectweb web site
10  * (www.objectweb.org).
11  *
12  * Software distributed under the License is distributed on an "AS IS" basis,
13  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
14  * the specific terms governing rights and limitations under the License.
15  *
16  * The Original Code is JEFFREE, including the java package com.opensugar.cube,
17  * released January 1, 2003.
18  *
19  * The Initial Developer of the Original Code is Opensugar.
20  * The Original Code is Copyright Opensugar.
21  * All Rights Reserved.
22  *
23  * Initial developer(s): Pierre Scokaert (Opensugar)
24  * Contributor(s):
25  */

26
27 package com.opensugar.cube;
28
29 import com.opensugar.cube.ldap.LDAPFilter;
30 import com.opensugar.cube.serviceRegistry.ServiceRegistryException;
31
32 import org.osgi.framework.BundleContext;
33 import org.osgi.framework.Bundle;
34 import org.osgi.framework.BundleException;
35 import org.osgi.framework.ServiceListener;
36 import org.osgi.framework.InvalidSyntaxException;
37 import org.osgi.framework.BundleListener;
38 import org.osgi.framework.FrameworkListener;
39 import org.osgi.framework.ServiceRegistration;
40 import org.osgi.framework.ServiceReference;
41 import org.osgi.framework.ServiceEvent;
42 import org.osgi.framework.BundleEvent;
43 import org.osgi.framework.ServiceFactory;
44 import org.osgi.framework.ServicePermission;
45 import org.osgi.framework.FrameworkEvent;
46 import org.osgi.framework.Constants;
47 import org.osgi.framework.Filter;
48
49 import java.io.InputStream JavaDoc;
50 import java.io.File JavaDoc;
51 import java.io.FileOutputStream JavaDoc;
52 import java.io.IOException JavaDoc;
53 import java.util.Dictionary JavaDoc;
54 import java.util.Vector JavaDoc;
55 import java.util.Hashtable JavaDoc;
56 import java.net.URL JavaDoc;
57
58 public class BundleContextImpl implements BundleContext {
59
60    public String JavaDoc getProperty( String JavaDoc key ) {
61       Util.checkNullParameter( key, getClass().getName(), "getProperty", "key" );
62
63       String JavaDoc value = cube.getProperty( key );
64       if ( value != null ) {
65          return value;
66       }
67       else {
68          // if property is not a framework property
69
// and if bundle has PropertyPermission "read",
70
// then search the system properties for the property and return that
71
try {
72             cube.checkPropertyPermission( key, "read" );
73             return (String JavaDoc)System.getProperties().get( key );
74          }
75          catch ( SecurityException JavaDoc e ) {
76             return null;
77          }
78       }
79    }
80
81    public Bundle getBundle() {
82       checkBundleContextIsNotStopped();
83
84       return bundle;
85    }
86
87    public Bundle installBundle( String JavaDoc location ) throws BundleException, SecurityException JavaDoc {
88       Util.checkNullParameter( location, getClass().getName(), "installBundle", "location" );
89
90       return installBundle( location, null );
91    }
92
93    public Bundle installBundle( String JavaDoc location, InputStream JavaDoc in ) throws BundleException, SecurityException JavaDoc {
94       Util.checkNullParameter( location, getClass().getName(), "installBundle", "location" );
95
96       cube.checkAdminPermission();
97
98       return cube.installBundle( location, in );
99    }
100
101    public Bundle getBundle( long id ) {
102       return cube.getBundle( id );
103    }
104
105    public Bundle[] getBundles() {
106       return cube.getBundles();
107    }
108
109    public Filter createFilter( String JavaDoc filter ) throws InvalidSyntaxException {
110       if ( filter == null ) {
111          throw new NullPointerException JavaDoc( "Filter string is null" );
112       }
113       // return filter that uses case-sensitive keys
114
return new LDAPFilter( filter, false );
115    }
116
117    public void addServiceListener( ServiceListener listener, String JavaDoc filterString ) throws InvalidSyntaxException {
118       Util.checkNullParameter( listener, getClass().getName(), "addServiceListener", "listener" );
119       // filterString can be null
120

121       checkBundleContextIsNotStopped();
122
123       cube.addServiceListener( bundle, listener, filterString );
124    }
125
126    public void addServiceListener( ServiceListener listener ) {
127       Util.checkNullParameter( listener, getClass().getName(), "addServiceListener", "listener" );
128
129       checkBundleContextIsNotStopped();
130
131       cube.addServiceListener( bundle, listener );
132    }
133
134    public void removeServiceListener( ServiceListener listener ) {
135       Util.checkNullParameter( listener, getClass().getName(), "removeServiceListener", "listener" );
136
137       checkBundleContextIsNotStopped();
138
139       cube.removeServiceListener( bundle, listener );
140    }
141
142    public void addBundleListener( BundleListener listener ) {
143       Util.checkNullParameter( listener, getClass().getName(), "addBundleListener", "listener" );
144
145       checkBundleContextIsNotStopped();
146
147       cube.addBundleListener( bundle, listener );
148    }
149
150    public void removeBundleListener( BundleListener listener ) {
151       Util.checkNullParameter( listener, getClass().getName(), "removeBundleListener", "listener" );
152
153       checkBundleContextIsNotStopped();
154
155       cube.removeBundleListener( bundle, listener );
156    }
157
158    public void addFrameworkListener( FrameworkListener listener ) {
159       Util.checkNullParameter( listener, getClass().getName(), "addFrameworkListener", "listener" );
160
161       checkBundleContextIsNotStopped();
162
163       cube.addFrameworkListener( bundle, listener );
164    }
165
166    public void removeFrameworkListener( FrameworkListener listener ) {
167       Util.checkNullParameter( listener, getClass().getName(), "removeFrameworkListener", "listener" );
168
169       checkBundleContextIsNotStopped();
170
171       cube.removeFrameworkListener( bundle, listener );
172    }
173
174    public ServiceRegistration registerService( String JavaDoc[] classNames, Object JavaDoc service, Dictionary JavaDoc properties ) {
175       Util.checkNullArrayParameter( classNames, getClass().getName(), "registerService", "classNames" );
176       Util.checkNullParameter( service, getClass().getName(), "registerService", "service" );
177       // properties can be null
178

179       if ( properties == null ) {
180          properties = new Hashtable JavaDoc();
181       }
182       properties.put( Constants.SERVICE_ID, generateServiceId() );
183       properties.put( Constants.OBJECTCLASS, classNames );
184
185       if ( !( service instanceof ServiceFactory ) ) {
186          Class JavaDoc clazz;
187          for ( int i = 0; i < classNames.length; i++ ) {
188             try {
189                clazz = bundle.getClassLoader().loadClass( classNames[ i ] );
190                if ( !clazz.isInstance( service ) ) {
191                   throw new IllegalArgumentException JavaDoc( "Error while registering service: " + service.getClass().getName() + " is not an instance of " + clazz.getName() );
192                }
193             }
194             catch( ClassNotFoundException JavaDoc e ) {
195                getCube().log( getCube().LOG_ERROR, "classNotFound: " + getBundle().getLocation(), e );
196                throw new IllegalArgumentException JavaDoc( "Invalid class name: " + classNames[ i ] );
197             }
198          }
199       }
200
201       cube.checkServicePermissionForAll( classNames, ServicePermission.REGISTER );
202
203       // osgi_compliance
204
// framework lifecycle test does not like it when we do this check.
205
// but the spec says we should do it
206
//checkBundleContextIsNotStopped();
207

208       ServiceRegistration serviceRegistration = cube.getServiceRegistry().registerService( bundle, classNames, service, properties );
209       cube.fireServiceEvent( ServiceEvent.REGISTERED, serviceRegistration.getReference() );
210       return serviceRegistration;
211    }
212
213    public ServiceRegistration registerService( String JavaDoc className, Object JavaDoc service, Dictionary JavaDoc properties ) {
214       String JavaDoc[] classNames = { className };
215       return registerService( classNames, service, properties );
216    }
217 /*
218    public ServiceReference[] getServiceReferences( String className, String filterString ) throws InvalidSyntaxException {
219       // osgi_compliance
220       // The OSGi 2.0 spec does not say we should throw an IllegalStateException if
221       // the bundle context is stopped here.
222       // But the framework lifecycle compliance test fails, if we don't!!!
223       checkBundleContextIsNotStopped();
224
225       return getServiceReferences( className, filterString, true );
226    }
227 */

228 // private ServiceReference[] getServiceReferences( String className, String filterString, boolean checkBundleContextIsNotStopped ) throws InvalidSyntaxException {
229
public ServiceReference[] getServiceReferences( String JavaDoc className, String JavaDoc filterString ) throws InvalidSyntaxException {
230       // className can be null (in that case, return all registered services)
231
// filterString can be null
232

233       String JavaDoc[] classNames = { className };
234       try {
235          cube.checkServicePermissionForAll( classNames, ServicePermission.GET );
236       }
237       catch( SecurityException JavaDoc e ) {
238          return null;
239       }
240
241 // if ( checkBundleContextIsNotStopped ) {
242
checkBundleContextIsNotStopped();
243 // }
244

245       LDAPFilter filter = null;
246       if ( filterString != null ) {
247          // filter should use case-insensitive keys (service property names are case-insensitive)
248
filter = new LDAPFilter( filterString, false );
249       }
250       return cube.getServiceRegistry().getServiceReferences( className, filter );
251    }
252
253    public ServiceReference getServiceReference( String JavaDoc className ) {
254       // className can be null (in that case, return all registered services)
255

256       String JavaDoc[] classNames = { className };
257       try {
258 // ServiceReference[] serviceReferences = getServiceReferences( className, null, true );
259
ServiceReference[] serviceReferences = getServiceReferences( className, null );
260          if ( serviceReferences != null && serviceReferences.length > 0 ) {
261             // find services with largest ranking
262
int largestRanking = Integer.MIN_VALUE;
263             Object JavaDoc val;
264             int ranking;
265             for ( int i = 0; i < serviceReferences.length; i++ ) {
266                val = serviceReferences[ i ].getProperty( Constants.SERVICE_RANKING );
267                // val can be null, it can be an Integer, or it can be a String representing an integer
268
if ( val != null ) {
269                   ranking = Integer.valueOf( val.toString() ).intValue();
270                   if ( ranking > largestRanking ) {
271                      largestRanking = ranking;
272                   }
273                }
274             }
275             Vector JavaDoc largestRankingServices = new Vector JavaDoc();
276             if ( largestRanking == Integer.MIN_VALUE ) {
277                for ( int i = 0; i < serviceReferences.length; i++ ) {
278                   largestRankingServices.addElement( serviceReferences[ i ] );
279                }
280             }
281             else {
282                for ( int i = 0; i < serviceReferences.length; i++ ) {
283                   val = serviceReferences[ i ].getProperty( Constants.SERVICE_RANKING );
284                   // val can be null, it can be an Integer, or it can be a String representing an integer
285
if ( val != null && Integer.valueOf( val.toString() ).intValue() == largestRanking ) {
286                      largestRankingServices.addElement( serviceReferences[ i ] );
287                   }
288                }
289             }
290
291             // among the services that tie for highest ranking, return service with
292
// smallest id (i.e. service that was registered first)
293
ServiceReference largestRankingServiceWithSmallestId = null;
294             ServiceReference sr;
295             long smallestId = Long.MAX_VALUE;
296             long id;
297             for ( int i = 0; i < largestRankingServices.size(); i++ ) {
298                sr = (ServiceReference)largestRankingServices.elementAt( i );
299                id = ( (Long JavaDoc)serviceReferences[ i ].getProperty( Constants.SERVICE_ID ) ).longValue();
300                if ( id < smallestId ) {
301                   largestRankingServiceWithSmallestId = sr;
302                   smallestId = id;
303                }
304             }
305             return largestRankingServiceWithSmallestId;
306          }
307       }
308       catch( InvalidSyntaxException e ) {
309          // This cannot happen (the filter is null)
310
throw new UnreachableCodeException();
311       }
312       return null;
313    }
314
315    public Object JavaDoc getService( ServiceReference reference ) {
316       Util.checkNullParameter( reference, getClass().getName(), "getService", "reference" );
317
318       cube.checkServicePermissionForAtLeastOne( (String JavaDoc[])reference.getProperty( Constants.OBJECTCLASS ), ServicePermission.GET );
319
320       checkBundleContextIsNotStopped();
321
322       try {
323          Object JavaDoc service = cube.getServiceRegistry().getService( reference, bundle );
324          return service;
325       }
326       catch( IllegalStateException JavaDoc e ) {
327          // service has been unregistered
328
return null;
329       }
330       catch( ServiceRegistryException e ) {
331          // Either the service factory threw an exception while creating a new service instance,
332
// or it created a service instance that was not an instance of all the classes named when
333
// the service was registered, or some other error occured while creating a new service instance
334
cube.fireFrameworkErrorEvent( getBundle(), e );
335          return null;
336       }
337    }
338
339    public boolean ungetService( ServiceReference reference ) {
340       Util.checkNullParameter( reference, getClass().getName(), "ungetService", "reference" );
341
342       checkBundleContextIsNotStopped();
343
344       return cube.getServiceRegistry().ungetService( reference, bundle );
345    }
346
347    public File JavaDoc getDataFile( String JavaDoc fileName ) {
348       Util.checkNullParameter( fileName, getClass().getName(), "getDataFile", "fileName" );
349
350       checkBundleContextIsNotStopped();
351
352       File JavaDoc dataDirectory = cube.getBundleDataDirectory( bundle.getBundleId() );
353       cube.checkFilePermission( dataDirectory.getAbsolutePath() + File.separator + "-", "read,write,execute,delete" );
354       if ( fileName.length() == 0 ) {
355          return dataDirectory;
356       }
357       return new File JavaDoc( dataDirectory, fileName );
358    }
359
360 // *****************************************************************************
361

362    private static long lastAssignedServiceId = 0;
363
364    private AbstractCube cube;
365    private BundleImpl bundle;
366    private boolean stopped;
367
368    protected BundleContextImpl( AbstractCube cube, BundleImpl bundle ) {
369       this.cube = cube;
370       this.bundle = bundle;
371       stopped = false;
372    }
373
374    public AbstractCube getCube() {
375       return cube;
376    }
377
378    protected void setStopped() {
379       stopped = true;
380    }
381
382 // *****************************************************************************
383

384    private void checkBundleContextIsNotStopped() {
385       if ( stopped ) {
386          throw new IllegalStateException JavaDoc( "Bundle context has been stopped (bundle id: " + bundle.getBundleId() + ")" );
387       }
388    }
389
390    private static synchronized Long JavaDoc generateServiceId() {
391       long id = lastAssignedServiceId + 1;
392       lastAssignedServiceId = id;
393       return new Long JavaDoc( id );
394    }
395
396 }
Popular Tags