@Test public void testAttemptsToStopAllServicesOnCloseFailure() { Service s1 = mock(CacheProvider.class); Service s2 = mock(FooProvider.class); Service s3 = mock(CacheLoaderWriterProvider.class); ServiceLocator locator = new ServiceLocator(s1, s2, s3); try { locator.startAllServices(); } catch (Exception e) { fail(); } final RuntimeException thrown = new RuntimeException(); doThrow(thrown).when(s1).stop(); try { locator.stopAllServices(); fail(); } catch (Exception e) { assertThat(e, CoreMatchers.<Exception>sameInstance(thrown)); } verify(s1).stop(); verify(s2).stop(); verify(s3).stop(); }
private void generateMetadata(Archiver archiver) throws ArchiverException, MojoExecutionException { Log log = getLog(); File tmpServicesDir = new File(new File(tmpDirectory, "META-INF"), "services"); File buildServicesDir = new File(new File(buildOutputDirectory, "META-INF"), "services"); if (!tmpServicesDir.mkdirs()) { throw new MojoExecutionException( "Error while creating the directory: " + tmpServicesDir.getPath()); } log.debug("Initializing class scanner ..."); ClassScanner scanner = new ClassScanner(buildOutputDirectory); for (Artifact artifact : filterArtifacts( (Set<Artifact>) project.getArtifacts(), new ScopeArtifactFilter(Artifact.SCOPE_COMPILE))) { scanner.addToClasspath(artifact.getFile()); } List<ServiceLocator> serviceLocators = new ArrayList<ServiceLocator>(serviceClassNames.length); for (String serviceClassName : serviceClassNames) { // If the user provided its own service file, skip generation File file = new File(buildServicesDir, serviceClassName); if (file.exists()) { log.debug(file + " exists; don't scan for " + serviceClassName + " implementation"); } else { ServiceLocator sl = new ServiceLocator(serviceClassName); serviceLocators.add(sl); scanner.addVisitor(sl); } } try { scanner.scan(); } catch (ClassScannerException e) { throw new MojoExecutionException("Failed to scan classes for services", e); } for (ServiceLocator sl : serviceLocators) { File file = new File(tmpServicesDir, sl.getServiceClassName()); if (!sl.getImplementations().isEmpty()) { String destFileName = "META-INF/services/" + sl.getServiceClassName(); log.info("Generating " + destFileName); try { Writer out = new OutputStreamWriter(new FileOutputStream(file)); try { for (String impl : sl.getImplementations()) { log.debug(" " + impl); out.write(impl); out.write("\n"); } } finally { out.close(); } } catch (IOException e) { throw new MojoExecutionException("Unable to create temporary file " + file, e); } archiver.addFile(file, destFileName); } } }
@Override public IServiceLocator createServiceLocator( IServiceLocator parent, AbstractServiceFactory factory, IDisposable owner, IEclipseContext context) { ServiceLocator serviceLocator = new ServiceLocator(parent, factory, owner); serviceLocator.setContext(context); return serviceLocator; }
public static void main(String[] args) { Service service = ServiceLocator.getService("Service1"); service.execute(); service = ServiceLocator.getService("Service2"); service.execute(); service = ServiceLocator.getService("Service1"); service.execute(); service = ServiceLocator.getService("Service2"); service.execute(); }
@Override public IServiceLocator createServiceLocator( IServiceLocator parent, AbstractServiceFactory factory, IDisposable owner) { ServiceLocator serviceLocator = new ServiceLocator(parent, factory, owner); // System.err.println("parentLocator: " + parent); //$NON-NLS-1$ if (parent != null) { IEclipseContext ctx = parent.getService(IEclipseContext.class); if (ctx != null) { serviceLocator.setContext(ctx.createChild()); } } return serviceLocator; }
@Test public void testClassHierarchies() { ServiceLocator provider = new ServiceLocator(); final Service service = new ChildTestService(); provider.addService(service); assertThat(provider.getService(FooProvider.class), sameInstance(service)); final Service fancyCacheProvider = new FancyCacheProvider(); provider.addService(fancyCacheProvider); final Collection<CacheProvider> servicesOfType = provider.getServicesOfType(CacheProvider.class); assertThat(servicesOfType, is(not(empty()))); assertThat(servicesOfType.iterator().next(), sameInstance(fancyCacheProvider)); }
@Test public void testDoesNotUseTCCL() { Thread.currentThread() .setContextClassLoader( new ClassLoader() { @Override public Enumeration<URL> getResources(String name) throws IOException { throw new AssertionError(); } }); ServiceLocator serviceLocator = new ServiceLocator(); serviceLocator.getService(TestService.class); }
@Test public void testStopAllServicesOnlyStopsEachServiceOnce() throws Exception { Service s1 = mock(CacheProvider.class, withSettings().extraInterfaces(CacheLoaderWriterProvider.class)); ServiceLocator locator = new ServiceLocator(s1); try { locator.startAllServices(); } catch (Exception e) { fail(); } locator.stopAllServices(); verify(s1, times(1)).stop(); }
public void updateNotification() { if (!Preferences.isNotificationEnabled() || !playServicesAvailable) return; String title = null; String subtitle = null; long time = 0; if ((this.lastPublishedLocation != null) && Preferences.isNotificationLocationEnabled()) { time = this.lastPublishedLocationTime.getTime(); if ((this.lastPublishedLocation.getGeocoder() != null) && Preferences.isNotificationGeocoderEnabled()) { title = this.lastPublishedLocation.toString(); } else { title = this.lastPublishedLocation.toLatLonString(); } } else { title = this.context.getString(R.string.app_name); } subtitle = ServiceLocator.getStateAsString(this.context) + " | " + ServiceBroker.getStateAsString(this.context); notificationBuilder.setContentTitle(title); notificationBuilder .setSmallIcon(R.drawable.ic_notification) .setContentText(subtitle) .setPriority(android.support.v4.app.NotificationCompat.PRIORITY_MIN); if (time != 0) notificationBuilder.setWhen(this.lastPublishedLocationTime.getTime()); this.notification = notificationBuilder.build(); this.context.startForeground(Defaults.NOTIFCATION_ID, this.notification); }
@Test public void testAttemptsToStopStartedServicesOnInitFailure() { Service s1 = new ParentTestService(); FancyCacheProvider s2 = new FancyCacheProvider(); ServiceLocator locator = new ServiceLocator(s1, s2); try { locator.startAllServices(); fail(); } catch (Exception e) { // see org.ehcache.spi.ParentTestService.start() assertThat(e, instanceOf(RuntimeException.class)); assertThat(e.getMessage(), is("Implement me!")); } assertThat(s2.startStopCounter, is(0)); }
/** Uninstalls a feature and checks that feature is properly uninstalled. */ public void unInstallAndCheckFeature(String feature) throws Exception { System.err.println(executeCommand("features:uninstall " + feature)); FeaturesService featuresService = ServiceLocator.getOsgiService(FeaturesService.class); System.err.println(executeCommand("osgi:list -t 0")); Assert.assertFalse( "Expected " + feature + " feature to be installed.", featuresService.isInstalled(featuresService.getFeature(feature))); }
@Test public void testCanOverrideServiceDependencyWithoutOrderingProblem() throws Exception { final AtomicBoolean started = new AtomicBoolean(false); ServiceLocator serviceLocator = new ServiceLocator(new TestServiceConsumerService()); serviceLocator.addService( new TestService() { @Override public void start(ServiceProvider<Service> serviceProvider) { started.set(true); } @Override public void stop() { // no-op } }); serviceLocator.startAllServices(); assertThat(started.get(), is(true)); }
@Test public void testCreateTokenWithRefreshToken() throws Exception { when(ServiceLocator.getInstance().getTokenStore().get(anyString())) .thenReturn(new AuthenticationBuilder(claim).build()); when(ServiceLocator.getInstance().getIdmService().listRoles(anyString(), anyString())) .thenReturn(Arrays.asList("admin", "user")); HttpTester req = new HttpTester(); req.setMethod("POST"); req.setHeader("Content-Type", "application/x-www-form-urlencoded"); req.setContent(REFRESH_TOKEN); req.setURI(CONTEXT + TokenEndpoint.TOKEN_GRANT_ENDPOINT); req.setVersion("HTTP/1.0"); HttpTester resp = new HttpTester(); resp.parse(server.getResponses(req.generate())); assertEquals(201, resp.getStatus()); assertTrue(resp.getContent().contains("expires_in\":10")); assertTrue(resp.getContent().contains("Bearer")); }
public static <T, I extends T> void registerRemoteService( @Nonnull final String description, @Nonnull final String rmiServer, final int rmiPort, @Nonnull final Class<T> service) throws RemoteException, NotBoundException { LOG.info("Registering remote service: " + description); IServiceProvider<T> serviceProvider = new ServiceLocator.ServiceProviderForRemote<T, I>(rmiServer, rmiPort, service); ServiceLocator.registerServiceProvider(service, serviceProvider); }
/* package */ @SuppressWarnings({"unchecked"}) void register() { ServiceLocator locator = getServiceLocator(); ActiveDescriptor<?> myselfReified = locator.reifyDescriptor(this); DynamicConfigurationService dcs = locator.getService(DynamicConfigurationService.class); DynamicConfiguration dc = dcs.createDynamicConfiguration(); // habitat.add(this); HK2Loader loader = this.model.classLoaderHolder; Set<Type> ctrs = new HashSet<Type>(); ctrs.add(myselfReified.getImplementationClass()); if (ConfigBean.class.isAssignableFrom(this.getClass())) { ctrs.add(ConfigBean.class); } DomDescriptor<Dom> domDesc = new DomDescriptor<Dom>( this, ctrs, Singleton.class, getImplementation(), new HashSet<Annotation>()); domDesc.setLoader(loader); domDescriptor = dc.addActiveDescriptor(domDesc, false); String key = getKey(); for (String contract : model.contracts) { ActiveDescriptor<Dom> alias = new AliasDescriptor<Dom>(locator, domDescriptor, contract, key); dc.addActiveDescriptor(alias, false); } if (key != null) { ActiveDescriptor<Dom> alias = new AliasDescriptor<Dom>(locator, domDescriptor, model.targetTypeName, key); dc.addActiveDescriptor(alias, false); } dc.commit(); serviceHandle = getHabitat().getServiceHandle(domDescriptor); }
/** * Executes a shell command and returns output as a String. Commands have a default timeout of 10 * seconds. * * @param timeout The amount of time in millis to wait for the command to execute. * @param silent Specifies if the command should be displayed in the screen. * @param commands The command to execute. */ protected String executeCommands( final long timeout, final boolean silent, final String... commands) { String response = null; final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); final PrintStream printStream = new PrintStream(byteArrayOutputStream); final CommandProcessor commandProcessor = ServiceLocator.getOsgiService(CommandProcessor.class); final CommandSession commandSession = commandProcessor.createSession(System.in, printStream, printStream); commandSession.put("APPLICATION", System.getProperty("karaf.name", "root")); commandSession.put("USER", "karaf"); FutureTask<String> commandFuture = new FutureTask<String>( new Callable<String>() { public String call() throws Exception { for (String command : commands) { boolean keepRunning = true; if (!silent) { System.out.println(command); System.out.flush(); } while (!Thread.currentThread().isInterrupted() && keepRunning) { try { commandSession.execute(command); keepRunning = false; } catch (Exception e) { if (retryException(e)) { keepRunning = true; sleep(1000); } else { throw new CommandExecutionException(e); } } } } printStream.flush(); return byteArrayOutputStream.toString(); } }); try { executor.submit(commandFuture); response = commandFuture.get(timeout, TimeUnit.MILLISECONDS); } catch (ExecutionException e) { throw CommandExecutionException.launderThrowable(e.getCause()); } catch (Exception e) { throw CommandExecutionException.launderThrowable(e); } return response; }
public void removeExtension(IExtension extension, Object[] objects) { for (int i = 0; i < objects.length; i++) { Object object = objects[i]; if (object instanceof ServiceFactoryHandle) { ServiceFactoryHandle handle = (ServiceFactoryHandle) object; Set locatorSet = handle.serviceLocators.keySet(); ServiceLocator[] locators = (ServiceLocator[]) locatorSet.toArray(new ServiceLocator[locatorSet.size()]); Arrays.sort( locators, new Comparator() { public int compare(Object o1, Object o2) { ServiceLocator loc1 = (ServiceLocator) o1; ServiceLocator loc2 = (ServiceLocator) o2; int l1 = ((IWorkbenchLocationService) loc1.getService(IWorkbenchLocationService.class)) .getServiceLevel(); int l2 = ((IWorkbenchLocationService) loc2.getService(IWorkbenchLocationService.class)) .getServiceLevel(); return l1 < l2 ? -1 : (l1 > l2 ? 1 : 0); } }); for (int j = 0; j < locators.length; j++) { ServiceLocator serviceLocator = locators[j]; if (!serviceLocator.isDisposed()) { serviceLocator.unregisterServices(handle.serviceNames); } } handle.factory = null; for (int j = 0; j < handle.serviceNames.length; j++) { String serviceName = handle.serviceNames[j]; if (factories.get(serviceName) == handle) { factories.remove(serviceName); } } } } }
@SuppressWarnings("unchecked") private static void mockServiceLocator() { ServiceLocator.getInstance().setClientService(mock(ClientService.class)); ServiceLocator.getInstance().setIdmService(mock(IdMService.class)); ServiceLocator.getInstance().setAuthenticationService(mock(AuthenticationService.class)); ServiceLocator.getInstance().setTokenStore(mock(TokenStore.class)); ServiceLocator.getInstance().setCredentialAuth(mock(CredentialAuth.class)); ServiceLocator.getInstance().getTokenAuthCollection().add(mock(TokenAuth.class)); }
/** * Register the given service (consists of the interface type and the implementation) at the osgi * service registry and also at the service locator for singleton-style easy access. * * @param <T> type of the service interface * @param <I> implementation of the service * @param description only a descriptive string useful in the osgi console * @param context the bundle context, where the service is registered * @param service the service interface * @param impl the implementation */ public static <T, I extends T> void registerServiceWithTracker( @Nonnull final String description, @Nonnull final BundleContext context, @Nonnull final Class<T> service, @Nonnull final I impl) { LOG.info("Registering OSGi service: " + description); final Dictionary<String, String> properties = new Hashtable<String, String>(); properties.put("service.vendor", "DESY"); properties.put("service.description", description); context.registerService(service, impl, properties); ServiceLocator.registerServiceTracker( service, ServiceLocatorFactory.createServiceTracker(context, service)); }
@Test public void testServicesInstanciatedOnceAndStartedOnce() throws Exception { @ServiceDependencies(TestProvidedService.class) class Consumer1 implements Service { @Override public void start(ServiceProvider<Service> serviceProvider) {} @Override public void stop() {} } @ServiceDependencies(TestProvidedService.class) class Consumer2 implements Service { TestProvidedService testProvidedService; @Override public void start(ServiceProvider<Service> serviceProvider) { testProvidedService = serviceProvider.getService(TestProvidedService.class); } @Override public void stop() {} } Consumer1 consumer1 = spy(new Consumer1()); Consumer2 consumer2 = new Consumer2(); ServiceLocator serviceLocator = new ServiceLocator(); // add some services serviceLocator.addService(consumer1); serviceLocator.addService(consumer2); serviceLocator.addService( new TestService() { @Override public void start(ServiceProvider<Service> serviceProvider) {} @Override public void stop() { // no-op } }); // simulate what is done in ehcachemanager serviceLocator.loadDependenciesOf(TestServiceConsumerService.class); serviceLocator.startAllServices(); serviceLocator.stopAllServices(); verify(consumer1, times(1)).start(serviceLocator); verify(consumer1, times(1)).stop(); assertThat(consumer2.testProvidedService.ctors(), greaterThanOrEqualTo(1)); assertThat(consumer2.testProvidedService.stops(), equalTo(1)); assertThat(consumer2.testProvidedService.starts(), equalTo(1)); }
/** 读取数据库中的全局参数的配置,存到缓存中 */ private static void initSysParam() { try { String sql = "select * from T_SYS_PARAM"; JdbcTemplate jdbc = (JdbcTemplate) ServiceLocator.getBean("jdbcTemplate"); List list = jdbc.queryForList(sql); Map keyValue = new HashMap(); for (Iterator iter = list.iterator(); iter.hasNext(); ) { Map m = (Map) iter.next(); keyValue.put(m.get("CODE"), m.get("PAR_VALUE")); } setConfigMap(keyValue); } catch (Exception e) { logger.error("读取数据库中的全局参数的配置出错!"); e.printStackTrace(); } }
@Test public void testDeleteToken() throws Exception { when(ServiceLocator.getInstance().getTokenStore().delete("token_to_be_deleted")) .thenReturn(true); HttpTester req = new HttpTester(); req.setMethod("POST"); req.setHeader("Content-Type", "application/x-www-form-urlencoded"); req.setContent("token_to_be_deleted"); req.setURI(CONTEXT + TokenEndpoint.TOKEN_REVOKE_ENDPOINT); req.setVersion("HTTP/1.0"); HttpTester resp = new HttpTester(); resp.parse(server.getResponses(req.generate())); assertEquals(204, resp.getStatus()); }
@Test public void testCreateTokenWithPassword() throws Exception { when(ServiceLocator.getInstance() .getCredentialAuth() .authenticate(any(PasswordCredentials.class))) .thenReturn(claim); HttpTester req = new HttpTester(); req.setMethod("POST"); req.setHeader("Content-Type", "application/x-www-form-urlencoded"); req.setContent(DIRECT_AUTH); req.setURI(CONTEXT + TokenEndpoint.TOKEN_GRANT_ENDPOINT); req.setVersion("HTTP/1.0"); HttpTester resp = new HttpTester(); resp.parse(server.getResponses(req.generate())); assertEquals(201, resp.getStatus()); assertTrue(resp.getContent().contains("expires_in\":10")); assertTrue(resp.getContent().contains("Bearer")); }
/** * Register in service locator so that non-Spring objects can access me. This method is invoked * automatically by Spring. */ public void init() { ServiceLocator.setMediaFileService(this); }
@Test public void testCircularDeps() throws Exception { final class StartStopCounter { final AtomicInteger startCounter = new AtomicInteger(0); final AtomicReference<ServiceProvider<Service>> startServiceProvider = new AtomicReference<ServiceProvider<Service>>(); final AtomicInteger stopCounter = new AtomicInteger(0); public void countStart(ServiceProvider<Service> serviceProvider) { startCounter.incrementAndGet(); startServiceProvider.set(serviceProvider); } public void countStop() { stopCounter.incrementAndGet(); } } @ServiceDependencies(TestProvidedService.class) class Consumer1 implements Service { final StartStopCounter startStopCounter = new StartStopCounter(); @Override public void start(ServiceProvider<Service> serviceProvider) { assertThat(serviceProvider.getService(TestProvidedService.class), is(notNullValue())); startStopCounter.countStart(serviceProvider); } @Override public void stop() { startStopCounter.countStop(); } } @ServiceDependencies(Consumer1.class) class Consumer2 implements Service { final StartStopCounter startStopCounter = new StartStopCounter(); @Override public void start(ServiceProvider<Service> serviceProvider) { assertThat(serviceProvider.getService(Consumer1.class), is(notNullValue())); startStopCounter.countStart(serviceProvider); } @Override public void stop() { startStopCounter.countStop(); } } @ServiceDependencies(Consumer2.class) class MyTestProvidedService extends DefaultTestProvidedService { final StartStopCounter startStopCounter = new StartStopCounter(); @Override public void start(ServiceProvider<Service> serviceProvider) { assertThat(serviceProvider.getService(Consumer2.class), is(notNullValue())); startStopCounter.countStart(serviceProvider); super.start(serviceProvider); } @Override public void stop() { startStopCounter.countStop(); super.stop(); } } @ServiceDependencies(DependsOnMe.class) class DependsOnMe implements Service { final StartStopCounter startStopCounter = new StartStopCounter(); @Override public void start(ServiceProvider<Service> serviceProvider) { assertThat(serviceProvider.getService(DependsOnMe.class), sameInstance(this)); startStopCounter.countStart(serviceProvider); } @Override public void stop() { startStopCounter.countStop(); } } ServiceLocator serviceLocator = new ServiceLocator(); Consumer1 consumer1 = new Consumer1(); Consumer2 consumer2 = new Consumer2(); MyTestProvidedService myTestProvidedService = new MyTestProvidedService(); DependsOnMe dependsOnMe = new DependsOnMe(); // add some services serviceLocator.addService(consumer1); serviceLocator.addService(consumer2); serviceLocator.addService(myTestProvidedService); serviceLocator.addService(dependsOnMe); // simulate what is done in ehcachemanager serviceLocator.startAllServices(); serviceLocator.stopAllServices(); assertThat(consumer1.startStopCounter.startCounter.get(), is(1)); assertThat( consumer1.startStopCounter.startServiceProvider.get(), CoreMatchers.<ServiceProvider<Service>>is(serviceLocator)); assertThat(consumer2.startStopCounter.startCounter.get(), is(1)); assertThat( consumer2.startStopCounter.startServiceProvider.get(), CoreMatchers.<ServiceProvider<Service>>is(serviceLocator)); assertThat(myTestProvidedService.startStopCounter.startCounter.get(), is(1)); assertThat( myTestProvidedService.startStopCounter.startServiceProvider.get(), CoreMatchers.<ServiceProvider<Service>>is(serviceLocator)); assertThat(dependsOnMe.startStopCounter.startCounter.get(), is(1)); assertThat( dependsOnMe.startStopCounter.startServiceProvider.get(), CoreMatchers.<ServiceProvider<Service>>is(serviceLocator)); assertThat(consumer1.startStopCounter.stopCounter.get(), is(1)); assertThat(consumer2.startStopCounter.stopCounter.get(), is(1)); assertThat(myTestProvidedService.startStopCounter.stopCounter.get(), is(1)); assertThat(dependsOnMe.startStopCounter.stopCounter.get(), is(1)); }
@Test public void testRedefineDefaultServiceWhileDependingOnIt() throws Exception { ServiceLocator serviceLocator = new ServiceLocator(new YetAnotherCacheProvider()); serviceLocator.startAllServices(); }
@Test public void testCanOverrideDefaultServiceFromServiceLoader() { ServiceLocator locator = new ServiceLocator(new ExtendedTestService()); TestService testService = locator.getService(TestService.class); assertThat(testService, instanceOf(ExtendedTestService.class)); }
@Before public void setup() { mockServiceLocator(); when(ServiceLocator.getInstance().getTokenStore().tokenExpiration()) .thenReturn(TOKEN_TIMEOUT_SECS); }
@After public void teardown() { ServiceLocator.getInstance().getTokenAuthCollection().clear(); }