项目:neoscada
文件:ProxyValueSource.java
public ProxyValueSource ( final BundleContext context,final String id,final ProxyHistoricalItem item,final int priority ) throws InvalidSyntaxException
{
this.item = item;
this.priority = priority;
this.listener = new SingleServiceListener<HistoricalItem> () {
@Override
public void serviceChange ( final ServiceReference<HistoricalItem> reference,final HistoricalItem service )
{
setService ( service );
}
};
this.tracker = new SingleServiceTracker<HistoricalItem> ( context,FilterUtil.createClassAndPidFilter ( HistoricalItem.class.getName (),id ),this.listener );
this.tracker.open ();
}
protected void setUp() throws Exception {
BundleContext bundleContext = new MockBundleContext() {
// service reference already registered
public ServiceReference[] getServiceReferences(String clazz,String filter) throws InvalidSyntaxException {
return new ServiceReference[] { new MockServiceReference(new String[] { Serializable.class.getName() }) };
}
};
appContext = new GenericApplicationContext();
appContext.getbeanfactory().addBeanPostProcessor(new BundleContextAwareProcessor(bundleContext));
appContext.setClassLoader(getClass().getClassLoader());
XmlBeanDeFinitionReader reader = new XmlBeanDeFinitionReader(appContext);
reader.loadBeanDeFinitions(new ClassPathResource("osgiDefaults.xml",getClass()));
appContext.refresh();
}
项目:neoscada
文件:Activator.java
@Override
public void start ( final BundleContext bundleContext ) throws Exception
{
Activator.context = bundleContext;
this.tracker = new SingleServiceTracker<Service> ( context,Service.class,new SingleServiceListener<Service> () {
@Override
public void serviceChange ( final ServiceReference<Service> reference,final Service service )
{
handleServiceChange ( service );
}
} );
this.tracker.open ();
}
protected void setUp() throws Exception {
services = new LinkedHashMap();
BundleContext ctx = new MockBundleContext() {
public ServiceReference[] getServiceReferences(String clazz,String filter) throws InvalidSyntaxException {
return new ServiceReference[0];
}
public Object getService(ServiceReference reference) {
Object service = services.get(reference);
return (service == null ? new Object() : service);
}
};
ClassLoader cl = getClass().getClassLoader();
proxyCreator =
new StaticServiceProxyCreator(new Class<?>[] { Cloneable.class },cl,ctx,ImportContextClassLoaderEnum.UNMANAGED,false,false);
}
项目:neoscada
文件:ServiceImpl.java
@Override
public void removedService ( final ServiceReference<HistoricalItem> reference,final HistoricalItem service )
{
final String itemId = (String)reference.getProperty ( Constants.SERVICE_PID );
synchronized ( this )
{
final HistoricalItem item = this.items.remove ( itemId );
if ( item != null )
{
this.context.ungetService ( reference );
this.iteminformations.remove ( item.getinformation () );
fireListChanged ( null,new HashSet<String> ( Arrays.asList ( itemId ) ),false );
}
}
}
protected void addOrReplaceBlock ( final ServiceReference<?> reference,final BlockConfiguration block )
{
logger.info ( String.format ( "Adding or replace block - ref: %s,block: %s",new Object[] { reference,block } ) );
final String oldBlock = this.blocks.put ( reference,block.getId () );
if ( oldBlock != null )
{
logger.info ( "Replacing exisiting block" );
this.device.removeBlock ( oldBlock );
}
final AbstractRequestBlock deviceBlock = makeBlock ( block );
try
{
this.device.addBlock ( block.getId (),deviceBlock );
}
catch ( final Exception e )
{
logger.warn ( "Failed to add block",e );
deviceBlock.dispose ();
}
}
/**
* Gather all Connectioninformation objects and set them as connections
*/
private void update ()
{
final Set<ConnectionDescriptor> infos = new HashSet<ConnectionDescriptor> ();
for ( final ServiceReference<?> ref : this.references )
{
final Connectioninformation ci = fromreference ( ref );
if ( ci != null )
{
final Object o = ref.getProperty ( Constants.SERVICE_PID );
final String id = o != null ? o.toString () : null;
final Object description = ref.getProperty ( Constants.SERVICE_DESCRIPTION );
final ConnectionDescriptor cd = new ConnectionDescriptor ( ci,id,description == null ? null : description.toString () );
infos.add ( cd );
}
}
setConnections ( infos );
}
public static void callListenersUnbind(Object serviceProxy,ServiceReference reference,OsgiServiceLifecycleListener[] listeners) {
if (!ObjectUtils.isEmpty(listeners)) {
boolean debug = log.isDebugEnabled();
// get a Dictionary implementing a Map
Dictionary properties =
(reference != null ? OsgiServiceReferenceUtils.getServicePropertiesSnapshot(reference) : null);
for (int i = 0; i < listeners.length; i++) {
if (debug)
log.debug("Calling unbind on " + listeners[i] + " w/ reference " + reference);
try {
listeners[i].unbind(serviceProxy,(Map) properties);
} catch (Exception ex) {
log.warn("Unbind method on listener " + listeners[i] + " threw exception ",ex);
}
if (debug)
log.debug("Called unbind on " + listeners[i] + " w/ reference " + reference);
}
}
}
@Override
public Configuration getConfiguration ()
{
final List<ConfigurationGroup> groups = new LinkedList<ConfigurationGroup> ();
Long lastRanking = null;
ConfigurationGroupImpl lastGroup = null;
for ( final Map.Entry<ServiceReference<AuthenticationService>,AuthenticationService> entry : this.tracker.getTracked ().entrySet () )
{
final Object o = entry.getKey ().getProperty ( Constants.SERVICE_RANKING );
final long ranking = o instanceof Number ? ( (Number)o ).longValue () : 0;
if ( lastRanking == null || lastRanking != ranking )
{
lastGroup = new ConfigurationGroupImpl ();
groups.add ( lastGroup );
lastRanking = ranking;
}
lastGroup.add ( entry.getValue () );
}
return new ConfigurationImpl ( groups );
}
项目:neoscada
文件:Activator.java
@Override
public void start ( final BundleContext context ) throws Exception
{
this.scheduler = Executors.newSingleThreadScheduledExecutor ( new NamedThreadFactory ( context.getBundle ().getSymbolicName () ) );
final String driver = DataSourceHelper.getDriver ( DS_PREFIX,DataSourceHelper.DEFAULT_PREFIX );
if ( driver == null )
{
logger.error ( "JDBC driver is not set" );
throw new IllegalStateException ( "JDBC driver name is not set" );
}
this.dataSourceFactoryTracker = new DataSourceFactoryTracker ( context,driver,new SingleServiceListener<DataSourceFactory> () {
@Override
public void serviceChange ( final ServiceReference<DataSourceFactory> reference,final DataSourceFactory service )
{
unregister ();
if ( service != null )
{
register ( service,context );
}
}
} );
this.dataSourceFactoryTracker.open ( true );
}
项目:neoscada
文件:EndpointExporter.java
@Override
protected void unexportService ( final ServiceReference<?> serviceReference )
{
final Endpoint e;
synchronized ( this )
{
e = this.endpoints.remove ( serviceReference );
}
if ( e != null )
{
if ( e.isPublished () )
{
try
{
e.stop ();
}
catch ( final Exception ex )
{
logger.warn ( "Failed to stop export",ex );
}
}
}
}
/**
* Determines through reflection the methods used for invoking the TestRunnerService.
*
* @throws Exception
*/
private void initializeServiceRunnerInvocationMethods() throws Exception {
// get JUnit test service reference
// this is a loose reference - update it if the JUnitTestActivator class is changed.
BundleContext ctx = getRuntimeBundleContext();
ServiceReference reference = ctx.getServiceReference(ACTIVATOR_REFERENCE);
Assert.notNull(reference,"no Osgi service reference found at " + ACTIVATOR_REFERENCE);
service = ctx.getService(reference);
Assert.notNull(service,"no service found for reference: " + reference);
serviceTrigger = service.getClass().getDeclaredMethod("executeTest",new Class[0]);
ReflectionUtils.makeAccessible(serviceTrigger);
Assert.notNull(serviceTrigger,"no executetest() method found on: " + service.getClass());
}
项目:neoscada
文件:AbstractExporter.java
public void init () throws InvalidSyntaxException
{
final String filter = String.format ( "(%s=%s)",JaxWsExporter.EXPORT_ENABLED,true );
synchronized ( this )
{
this.context.addServiceListener ( this,filter );
final ServiceReference<?>[] refs = this.context.getServiceReferences ( (String)null,filter );
if ( refs != null )
{
for ( final ServiceReference<?> ref : refs )
{
addService ( ref );
}
}
}
}
public void testInvocationWhenServiceNA() throws Throwable {
// service n/a
ServiceReference reference = new MockServiceReference() {
public Bundle getBundle() {
return null;
}
};
interceptor = new ServiceStaticInterceptor(new MockBundleContext(),reference);
Object target = new Object();
Method m = target.getClass().getDeclaredMethod("hashCode",null);
MethodInvocation invocation = new MockMethodInvocation(m);
try {
interceptor.invoke(invocation);
fail("should have thrown exception");
}
catch (ServiceUnavailableException ex) {
// expected
}
}
protected void setUp() throws Exception {
services = new LinkedHashMap();
context = new MockBundleContext() {
public ServiceReference[] getServiceReferences(String clazz,String filter) throws InvalidSyntaxException {
return new ServiceReference[0];
}
public Object getService(ServiceReference reference) {
Object service = services.get(reference);
return (service == null ? new Object() : service);
}
};
col = createCollection();
col.setrequiredAtStartup(false);
col.afterPropertiesSet();
}
/**
* Invoke method with signature <code>bla(ServiceReference ref)</code>.
*
* @param target
* @param method
* @param service
*/
private void invokeCustomServiceReferenceMethod(Object target,Method method,Object service) {
if (method != null) {
boolean trace = log.isTraceEnabled();
// get the service reference
// find the compatible types (accept null service)
if (trace)
log.trace("invoking listener custom method " + method);
ServiceReference ref =
(service != null ? ((ImportedOsgiServiceProxy) service).getServiceReference() : null);
try {
ReflectionUtils.invokeMethod(method,target,new Object[] { ref });
}
// make sure to log exceptions and continue with the
// rest of the listeners
catch (Exception ex) {
Exception cause = ReflectionUtils.getInvocationException(ex);
log.warn("custom method [" + method + "] threw exception when passing service ["
+ ObjectUtils.identityToString(service) + "]",cause);
}
}
}
private Advice determineTcclAdvice(ServiceReference reference) {
try {
switch (iccl) {
case CLIENT:
return clientTcclAdvice;
case SERVICE_PROVIDER:
return createServiceProviderTcclAdvice(reference);
case UNMANAGED:
// do nothing
return null;
default:
return null;
}
} finally {
if (log.isTraceEnabled()) {
log.trace(iccl + " Tccl used for invoking " + OsgiStringUtils.nullSafetoString(reference));
}
}
}
private PackageAdmin getPackageAdmin() {
return AccessController.doPrivileged(new PrivilegedAction<PackageAdmin>() {
public PackageAdmin run() {
ServiceReference ref = bundleContext.getServiceReference(PackageAdmin.class.getName());
if (ref == null)
throw new IllegalStateException(PackageAdmin.class.getName() + " service is required");
// don't do any proxying since PackageAdmin is normally a framework service
// we can assume for Now that it will always be available
return (PackageAdmin) bundleContext.getService(ref);
}
});
}
private void addReference ( final ServiceReference<?> ref )
{
logger.info ( "Adding service: {}",ref );
if ( this.references.add ( ref ) )
{
update ();
}
}
public void testServiceRefsWithSameRankAndDifId() throws Exception {
ServiceReference refA = createReference(new Long(1),new Integer(5));
ServiceReference refB = createReference(new Long(2),new Integer(5));
// same ranking,means id equality applies
assertTrue(comparator.compare(refA,refB) > 0);
}
public void testExtenderConfigAppCtxPublished() throws Exception {
ServiceReference[] refs =
bundleContext.getAllServiceReferences("org.springframework.context.ApplicationContext",null);
for (int i = 0; i < refs.length; i++) {
System.out.println(OsgiStringUtils.nullSafetoString(refs[i]));
}
assertNotNull(context);
}
项目:incubator-netbeans
文件:NetigsoServices.java
NetigsoServices(Netigso netigso,Framework f) {
this.netigso = netigso;
for (ServiceReference ref : f.getRegisteredServices()) {
MainLookup.register(ref,this);
}
f.getBundleContext().addServiceListener(this);
f.getBundleContext().addBundleListener(this);
}
/**
* Test method for
* {@link org.eclipse.gemini.blueprint.util.OsgiServiceReferenceUtils#getServiceId(org.osgi.framework.ServiceReference)}.
*/
public void testGetServiceId() {
long id = 12345;
Dictionary dict = new Hashtable();
dict.put(Constants.SERVICE_ID,id);
ServiceReference ref = new MockServiceReference(null,dict,null);
assertEquals(id,OsgiServiceReferenceUtils.getServiceId(ref));
}
private void checkedPublishedOsgiService(int expectedContexts) throws Exception {
ServiceReference[] refs = bundleContext.getServiceReferences(
ConfigurableOsgiBundleApplicationContext.class.getName(),null);
assertEquals("different number of published contexts encountered",expectedContexts,refs.length);
for (int i = 0; i < refs.length; i++) {
ServiceReference serviceReference = refs[i];
String[] interfaces = (String[]) serviceReference.getProperty(Constants.OBJECTCLASS);
assertEquals("not enough interfaces published",15,interfaces.length);
assertEquals(Version.emptyVersion,serviceReference.getProperty(Constants.BUNDLE_VERSION));
assertEquals(bundleContext.getBundle().getSymbolicName(),serviceReference.getProperty(Constants.BUNDLE_SYMBOLICNAME));
}
}
public void testNSBundlePublishedOkay() throws Exception {
ServiceReference ref = OsgiServiceReferenceUtils.getServiceReference(bundleContext,ApplicationContext.class.getName(),"(" + Constants.BUNDLE_SYMBOLICNAME + "=" + BND_SYM_NAME + ")");
assertNotNull(ref);
ApplicationContext ctx = (ApplicationContext) bundleContext.getService(ref);
assertNotNull(ctx);
assertNotNull(ctx.getBean("nsBean"));
assertNotNull(ctx.getBean("nsDate"));
}
public void testGetServiceRankingWithNonExistingRanking() {
Dictionary dict = new Hashtable() {
// forbid adding the service ranking
public synchronized Object put(Object key,Object value) {
if (!Constants.SERVICE_RANKING.equals(key))
return super.put(key,value);
return null;
}
};
ServiceReference ref = new MockServiceReference(null,null);
assertNull(ref.getProperty(Constants.SERVICE_RANKING));
assertEquals(0,OsgiServiceReferenceUtils.getServiceRanking(ref));
}
项目:neoscada
文件:ServiceImpl.java
private String getQueryId ( final ServiceReference<?> ref )
{
final Object p = ref.getProperty ( Constants.SERVICE_PID );
if ( p != null )
{
return p.toString ();
}
else
{
return null;
}
}
private void printServiceRefs(ServiceReference[] refs) {
for (ServiceReference ref : refs) {
String[] keys = ref.getPropertyKeys();
logger.info(ref);
for (String key : keys) {
if (Constants.OBJECTCLASS.equals(key)) {
logger.info("\t" + key + " = " + Arrays.toString((String[]) ref.getProperty(key)));
} else {
logger.info("\t" + key + " = " + ref.getProperty(key));
}
}
}
}
protected void setUp() throws Exception {
BundleContext bundleContext = new MockBundleContext() {
// service reference already registered
public ServiceReference[] getServiceReferences(String clazz,String filter) throws InvalidSyntaxException {
return new ServiceReference[] { new MockServiceReference(new String[] { Serializable.class.getName() }) };
}
};
appContext = new GenericApplicationContext();
appContext.getbeanfactory().addBeanPostProcessor(new BundleContextAwareProcessor(bundleContext));
appContext.setClassLoader(getClass().getClassLoader());
}
项目:incubator-netbeans
文件:NetigsoHasSAXParserTest.java
public void testSAXParserAvailable() throws Exception {
Framework f = IntegrationTest.findFramework();
BundleContext bc = f.getBundleContext();
ServiceReference sr = bc.getServiceReference(SAXParserFactory.class.getName());
assertNotNull("SAX Service found",sr);
Object srvc = bc.getService(sr);
assertTrue("Instance of the right type: " + srvc,srvc instanceof SAXParserFactory);
}
protected void setUp() throws Exception {
final Configuration cfg = createMock(Configuration.class);
expect(cfg.getProperties()).andReturn(new Hashtable<String,Object>());
replay(cfg);
BundleContext bundleContext = new MockBundleContext() {
// always return a ConfigurationAdmin
public Object getService(ServiceReference reference) {
return new MockConfigurationAdmin() {
public Configuration getConfiguration(String pid) throws IOException {
return cfg;
}
};
}
};
appContext = new GenericApplicationContext();
appContext.getbeanfactory().addBeanPostProcessor(new BundleContextAwareProcessor(bundleContext));
appContext.setClassLoader(getClass().getClassLoader());
XmlBeanDeFinitionReader reader = new XmlBeanDeFinitionReader(appContext);
reader.loadBeanDeFinitions(new ClassPathResource("managedServiceFactory.xml",getClass()));
appContext.refresh();
}
@Test
public void testLookupLdapProtocolCodecFactory()
{
ServiceReference<LdapProtocolCodecFactory> serviceReference = context.getServiceReference( LdapProtocolCodecFactory.class );
Object service = context.getService( serviceReference );
assertNotNull( service );
assertTrue( service instanceof LdapProtocolCodecFactory );
}
项目:directory-ldap-api
文件:LdapProtocolCodecActivator.java
@Override
public LdapApiService addingService( ServiceReference<LdapApiService> reference )
{
LdapApiService ldapApiService = bundleContext.getService( reference );
LdapProtocolCodecFactory factory = new LdapProtocolCodecFactory( ldapApiService );
registration = bundleContext.registerService( LdapProtocolCodecFactory.class.getName(),factory,null );
ldapApiService.registerProtocolCodecFactory( factory );
return ldapApiService;
}
/**
* Test method for
* {@link org.eclipse.gemini.blueprint.util.OsgiServiceReferenceUtils#getServiceRanking(org.osgi.framework.ServiceReference)}.
*/
public void testGetServiceRankingAvailable() {
int ranking = 12345;
Dictionary dict = new Hashtable();
dict.put(Constants.SERVICE_RANKING,ranking);
ServiceReference ref = new MockServiceReference(null,null);
assertEquals(ranking,OsgiServiceReferenceUtils.getServiceRanking(ref));
}
private ConfigurableApplicationContext getAppCtx(String symBundle) {
ServiceReference ref = OsgiServiceReferenceUtils.getServiceReference(bundleContext,"("
+ ConfigurableOsgiBundleApplicationContext.APPLICATION_CONTEXT_SERVICE_PROPERTY_NAME + "=" + symBundle
+ ")");
if (ref == null)
throw new IllegalArgumentException("cannot find appCtx for bundle " + symBundle);
return (ConfigurableApplicationContext) bundleContext.getService(ref);
}
protected void modifyBlock ( final ServiceReference<?> reference,final BlockConfiguration service )
{
logger.info ( "Modify block: {}",reference );
// will be a quick remove and add operation
addOrReplaceBlock ( reference,service );
}
protected ComponentFactory handleAddingService ( final ServiceReference<ComponentFactory> reference,final ComponentFactory service )
{
try
{
final ComponentHandle handle = this.componentHost.registerComponent ( service );
this.refMap.put ( reference,handle );
return service;
}
catch ( final Exception e )
{
return null;
}
}
public void testServiceAliveDuringUnregistration() throws Exception {
service = new polygon();
ServiceRegistration reg = bundleContext.registerService(Shape.class.getName(),service,null);
String filter = OsgiFilterUtils.unifyFilter(Shape.class,null);
ServiceListener listener = new ServiceListener() {
public void serviceChanged(ServiceEvent event) {
if (ServiceEvent.UNREGISTERING == event.getType()) {
ServiceReference ref = event.getServiceReference();
Object aliveService = bundleContext.getService(ref);
assertNotNull("services not available during unregistration",aliveService);
assertSame(service,aliveService);
}
}
};
try {
bundleContext.addServiceListener(listener,filter);
reg.unregister();
}
finally {
bundleContext.removeServiceListener(listener);
}
}
protected void warn(String message,Throwable t) {
ServiceReference<LogService> ref = bundleContext.getServiceReference(LogService.class);
if (ref != null) {
LogService svc = bundleContext.getService(ref);
svc.log(LogService.LOG_WARNING,message,t);
bundleContext.ungetService(ref);
}
}
protected void setUp() throws Exception {
ref = new MockServiceReference();
bundleContext = new MockBundleContext() {
public ServiceReference getServiceReference(String clazz) {
return ref;
}
public ServiceReference[] getServiceReferences(String clazz,String filter) throws InvalidSyntaxException {
return new ServiceReference[] { ref };
}
};
classLoader = getClass().getClassLoader();
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。