OsgiClassPrefixer { public Optional<String> getPrefix(Class<?> type) { Optional<Bundle> bundle = (bundleRetriever != null) ? bundleRetriever.apply(type) : Osgis.getBundleOf(type); if (bundle.isPresent()) { return Optional.of(bundle.get().getSymbolicName() + DELIMITER); } return Optional.absent(); } OsgiClassPrefixer(); @VisibleForTesting protected  OsgiClassPrefixer(@Nullable Function<Class<?>, Optional<Bundle>> bundleRetriever); Optional<String> getPrefix(Class<?> type); Optional<String> stripMatchingPrefix(Bundle bundle, String type); boolean hasPrefix(String type); static final String DELIMITER; }
@Test public void testGetPrefixFromNonBundle() throws Exception { OsgiClassPrefixer prefixer = new OsgiClassPrefixer(); assertAbsent(prefixer.getPrefix(String.class)); }
@Test public void testGetPrefixWithBundle() throws Exception { final Class<?> classInBundle = String.class; final Bundle bundle = Mockito.mock(Bundle.class); Mockito.when(bundle.getSymbolicName()).thenReturn("my.symbolic.name"); Mockito.when(bundle.getVersion()).thenReturn(Version.valueOf("1.2.3")); Function<Class<?>, Optional<Bundle>> bundleRetriever = new Function<Class<?>, Optional<Bundle>>() { @Override public Optional<Bundle> apply(Class<?> input) { return (classInBundle.equals(input)) ? Optional.of(bundle) : Optional.<Bundle>absent(); } }; OsgiClassPrefixer prefixer = new OsgiClassPrefixer(bundleRetriever); assertAbsent(prefixer.getPrefix(Number.class)); assertPresent(prefixer.getPrefix(String.class), "my.symbolic.name:"); }
@Test public void testGetPrefixWithWhitelistedBundle() throws Exception { final Bundle bundle = Mockito.mock(Bundle.class); Mockito.when(bundle.getSymbolicName()).thenReturn("org.apache.brooklyn.my-bundle"); Mockito.when(bundle.getVersion()).thenReturn(Version.valueOf(BrooklynVersion.getOsgiVersion())); Function<Class<?>, Optional<Bundle>> bundleRetriever = new Function<Class<?>, Optional<Bundle>>() { @Override public Optional<Bundle> apply(Class<?> input) { return Optional.of(bundle); } }; OsgiClassPrefixer prefixer = new OsgiClassPrefixer(bundleRetriever); assertPresent(prefixer.getPrefix(String.class), "org.apache.brooklyn.my-bundle:"); }