use of org.osgi.service.packageadmin.PackageAdmin in project tdi-studio-se by Talend.
the class ComponentsFactory method loadComponentsFromFolder.
private void loadComponentsFromFolder(String pathSource, AbstractComponentsProvider provider) {
boolean isCustom = false;
if ("org.talend.designer.components.model.UserComponentsProvider".equals(provider.getId()) || "org.talend.designer.components.exchange.ExchangeComponentsProvider".equals(provider.getId())) {
isCustom = true;
}
File source;
try {
source = provider.getInstallationFolder();
} catch (IOException e1) {
ExceptionHandler.process(e1);
return;
}
File[] childDirectories;
FileFilter fileFilter = new FileFilter() {
@Override
public boolean accept(final File file) {
return file.isDirectory() && file.getName().charAt(0) != '.' && !file.getName().equals(IComponentsFactory.EXTERNAL_COMPONENTS_INNER_FOLDER);
}
};
if (source == null) {
//$NON-NLS-1$
ExceptionHandler.process(new Exception(Messages.getString("ComponentsFactory.componentNotFound") + pathSource));
return;
}
childDirectories = source.listFiles(fileFilter);
IBrandingService service = (IBrandingService) GlobalServiceRegister.getDefault().getService(IBrandingService.class);
// String[] availableComponents = service.getBrandingConfiguration().getAvailableComponents();
FileFilter skeletonFilter = new FileFilter() {
@Override
public boolean accept(final File file) {
String fileName = file.getName();
return file.isFile() && fileName.charAt(0) != '.' && (fileName.endsWith(SKELETON_SUFFIX) || fileName.endsWith(INCLUDEFILEINJET_SUFFIX));
}
};
// Changed by Marvin Wang on Feb.22 for bug TDI-19166, caz the test ConnectionManagerTest maybe get the null
// context.
BundleContext context = null;
if (Platform.getProduct() != null) {
final Bundle definingBundle = Platform.getProduct().getDefiningBundle();
if (definingBundle != null) {
context = definingBundle.getBundleContext();
}
}
if (context == null) {
context = CodeGeneratorActivator.getDefault().getBundle().getBundleContext();
}
ServiceReference sref = context.getServiceReference(PackageAdmin.class.getName());
PackageAdmin admin = (PackageAdmin) context.getService(sref);
String bundleName;
if (!isCustom) {
bundleName = admin.getBundle(provider.getClass()).getSymbolicName();
} else {
bundleName = IComponentsFactory.COMPONENTS_LOCATION;
}
if (childDirectories != null) {
if (monitor != null) {
this.subMonitor = SubMonitor.convert(monitor, Messages.getString("ComponentsFactory.load.components"), //$NON-NLS-1$
childDirectories.length);
}
if (skeletonList != null) {
// to optimize the size of the array
skeletonList.ensureCapacity(childDirectories.length);
for (File currentFolder : childDirectories) {
// get the skeleton files first, then XML config files later.
File[] skeletonFiles = currentFolder.listFiles(skeletonFilter);
if (skeletonFiles != null) {
for (File file : skeletonFiles) {
// path
skeletonList.add(file.getAbsolutePath());
}
}
try {
File xmlMainFile = new File(currentFolder, ComponentFilesNaming.getInstance().getMainXMLFileName(currentFolder.getName(), getCodeLanguageSuffix()));
if (!xmlMainFile.exists()) {
// if not a component folder, ignore it.
continue;
}
String currentXmlSha1 = null;
try {
currentXmlSha1 = SHA1Util.calculateFromTextStream(new FileInputStream(xmlMainFile));
} catch (FileNotFoundException e) {
// nothing since exceptions are directly in the check bellow
}
// Need to check if this component is already in the cache or not.
// if yes, then we compare the sha1... and if different we reload the component
// if component is not in the cache, of course just load it!
ComponentsCache cache = ComponentManager.getComponentCache();
boolean foundComponentIsSame = false;
ComponentInfo existingComponentInfoInCache = null;
if (cache.getComponentEntryMap().containsKey(currentFolder.getName())) {
EList<ComponentInfo> infos = cache.getComponentEntryMap().get(currentFolder.getName());
for (ComponentInfo info : infos) {
if (StringUtils.equals(bundleName, info.getSourceBundleName())) {
existingComponentInfoInCache = info;
if (StringUtils.equals(info.getSha1(), currentXmlSha1)) {
foundComponentIsSame = true;
}
// found component, no matter changed or not
break;
}
}
}
if (foundComponentIsSame) {
// it should go here mainly for commandline or if use like ctrl+shift+f3
if (componentsCache.containsKey(xmlMainFile.getAbsolutePath())) {
IComponent componentFromThisProvider = null;
for (IComponent component : componentsCache.get(xmlMainFile.getAbsolutePath()).values()) {
if (component instanceof EmfComponent) {
if (bundleName.equals(((EmfComponent) component).getSourceBundleName())) {
componentFromThisProvider = component;
break;
}
}
}
if (componentFromThisProvider != null) {
// In headless mode, we assume the components won't change and we will use a cache
componentList.add(componentFromThisProvider);
if (isCustom) {
customComponentList.add(componentFromThisProvider);
}
continue;
}
}
}
if (!foundComponentIsSame) {
ComponentFileChecker.checkComponentFolder(currentFolder, getCodeLanguageSuffix());
}
String pathName = xmlMainFile.getAbsolutePath();
String applicationPath = ComponentBundleToPath.getPathFromBundle(bundleName);
// pathName = C:\myapp\plugins\myplugin\components\mycomponent\mycomponent.xml
pathName = (new Path(pathName)).toPortableString();
// pathName = C:/myapp/plugins/myplugin/components/mycomponent/mycomponent.xml
//$NON-NLS-1$
pathName = pathName.replace(applicationPath, "");
// pathName = /components/mycomponent/mycomponent.xml
// if not already in memory, just load the component from cache.
// if the component is already existing in cache and if it's the same, it won't reload all (cf
// flag: foundComponentIsSame)
EmfComponent currentComp = new EmfComponent(pathName, bundleName, xmlMainFile.getParentFile().getName(), pathSource, cache, foundComponentIsSame, provider);
if (!foundComponentIsSame) {
// force to call some functions to update the cache. (to improve)
currentComp.isVisibleInComponentDefinition();
currentComp.isTechnical();
currentComp.getOriginalFamilyName();
currentComp.getTranslatedFamilyName();
currentComp.getPluginExtension();
currentComp.getVersion();
currentComp.getModulesNeeded(null);
currentComp.getPluginDependencies();
// end of force cache update.
EList<ComponentInfo> componentsInfo = cache.getComponentEntryMap().get(currentFolder.getName());
for (ComponentInfo cInfo : componentsInfo) {
if (cInfo.getSourceBundleName().equals(bundleName)) {
cInfo.setSha1(currentXmlSha1);
break;
}
}
// this will force to save the cache later.
ComponentManager.setModified(true);
}
boolean hiddenComponent = false;
Collection<IComponentFactoryFilter> filters = ComponentsFactoryProviderManager.getInstance().getProviders();
for (IComponentFactoryFilter filter : filters) {
if (!filter.isAvailable(currentComp.getName())) {
hiddenComponent = true;
break;
}
}
// just don't load it
if (hiddenComponent && !(currentComp.getOriginalFamilyName().contains("Technical") || currentComp.isTechnical())) {
continue;
}
componentToProviderMap.put(currentComp, provider);
// hide it
if (hiddenComponent && (currentComp.getOriginalFamilyName().contains("Technical") || currentComp.isTechnical())) {
currentComp.setVisible(false);
currentComp.setTechnical(true);
}
if (provider.getId().contains("Camel")) {
currentComp.setPaletteType(ComponentCategory.CATEGORY_4_CAMEL.getName());
} else {
currentComp.setPaletteType(currentComp.getType());
}
if (componentList.contains(currentComp)) {
//$NON-NLS-1$ //$NON-NLS-2$
log.warn("Component " + currentComp.getName() + " already exists. Cannot load user version.");
} else {
// currentComp.setResourceBundle(getComponentResourceBundle(currentComp, source.toString(),
// null,
// provider));
currentComp.setProvider(provider);
componentList.add(currentComp);
if (isCustom) {
customComponentList.add(currentComp);
}
if (pathSource != null) {
Path userComponent = new Path(pathSource);
Path templatePath = new Path(IComponentsFactory.COMPONENTS_INNER_FOLDER + File.separatorChar + IComponentsFactory.EXTERNAL_COMPONENTS_INNER_FOLDER + File.separatorChar + ComponentUtilities.getExtFolder(OLD_COMPONENTS_USER_INNER_FOLDER));
if (userComponent.equals(templatePath)) {
userComponentList.add(currentComp);
}
}
}
// componentsCache only used bellow in case of headless (commandline) or if use like
// ctrl+shift+f3
String componentName = xmlMainFile.getAbsolutePath();
if (!componentsCache.containsKey(componentName)) {
componentsCache.put(componentName, new HashMap<String, IComponent>());
}
componentsCache.get(xmlMainFile.getAbsolutePath()).put(currentComp.getPaletteType(), currentComp);
} catch (MissingMainXMLComponentFileException e) {
//$NON-NLS-1$ //$NON-NLS-2$
log.trace(currentFolder.getName() + " is not a " + getCodeLanguageSuffix() + " component", e);
} catch (BusinessException e) {
BusinessException ex = new BusinessException(//$NON-NLS-1$ //$NON-NLS-2$
"Cannot load component \"" + currentFolder.getName() + "\": " + e.getMessage(), e);
ExceptionHandler.process(ex, Level.ERROR);
}
if (this.subMonitor != null) {
this.subMonitor.worked(1);
}
if (this.monitor != null && this.monitor.isCanceled()) {
return;
}
}
// to optimize the size of the array
skeletonList.trimToSize();
}
}
}
use of org.osgi.service.packageadmin.PackageAdmin in project aries by apache.
the class BundleStateMBeanHandlerTest method testOpenAndClose.
@Test
public void testOpenAndClose() throws Exception {
BundleContext context = mock(BundleContext.class);
when(context.getProperty(Constants.FRAMEWORK_UUID)).thenReturn("some-uuid");
Logger logger = mock(Logger.class);
Bundle mockSystemBundle = mock(Bundle.class);
when(mockSystemBundle.getSymbolicName()).thenReturn("the.sytem.bundle");
when(context.getBundle(0)).thenReturn(mockSystemBundle);
ServiceReference packageAdminRef = mock(ServiceReference.class);
PackageAdmin packageAdmin = mock(PackageAdmin.class);
when(context.getServiceReference(PackageAdmin.class.getName())).thenReturn(packageAdminRef);
when(context.getService(packageAdminRef)).thenReturn(packageAdmin);
ServiceReference startLevelRef = mock(ServiceReference.class);
StartLevel startLevel = mock(StartLevel.class);
when(context.getServiceReference(StartLevel.class.getName())).thenReturn(startLevelRef);
when(context.getService(startLevelRef)).thenReturn(startLevel);
JMXAgent agent = mock(JMXAgent.class);
JMXAgentContext agentContext = new JMXAgentContext(context, agent, logger);
BundleStateMBeanHandler handler = new BundleStateMBeanHandler(agentContext, new StateConfig());
handler.open();
assertNotNull(handler.getMbean());
handler.close();
verify(context).ungetService(packageAdminRef);
verify(context).ungetService(startLevelRef);
}
use of org.osgi.service.packageadmin.PackageAdmin in project aries by apache.
the class BundleStateTest method createBundle.
private void createBundle(StateConfig stateConfig, final List<Notification> received, final List<AttributeChangeNotification> attributeChanges) throws Exception {
BundleContext context = mock(BundleContext.class);
when(context.getBundles()).thenReturn(new Bundle[] {});
PackageAdmin admin = mock(PackageAdmin.class);
StartLevel startLevel = mock(StartLevel.class);
Logger logger = mock(Logger.class);
BundleState bundleState = new BundleState(context, admin, startLevel, stateConfig, logger);
Bundle b1 = mock(Bundle.class);
when(b1.getBundleId()).thenReturn(new Long(9));
when(b1.getSymbolicName()).thenReturn("bundle");
when(b1.getLocation()).thenReturn("file:/location");
BundleEvent installedEvent = mock(BundleEvent.class);
when(installedEvent.getBundle()).thenReturn(b1);
when(installedEvent.getType()).thenReturn(BundleEvent.INSTALLED);
BundleEvent resolvedEvent = mock(BundleEvent.class);
when(resolvedEvent.getBundle()).thenReturn(b1);
when(resolvedEvent.getType()).thenReturn(BundleEvent.RESOLVED);
MBeanServer server = mock(MBeanServer.class);
//setup for notification
ObjectName objectName = new ObjectName(OBJECTNAME);
bundleState.preRegister(server, objectName);
bundleState.postRegister(true);
//add NotificationListener to receive the events
bundleState.addNotificationListener(new NotificationListener() {
public void handleNotification(Notification notification, Object handback) {
if (notification instanceof AttributeChangeNotification) {
attributeChanges.add((AttributeChangeNotification) notification);
} else {
received.add(notification);
}
}
}, null, null);
// capture the BundleListener registered with BundleContext to issue BundleEvents
ArgumentCaptor<BundleListener> argument = ArgumentCaptor.forClass(BundleListener.class);
verify(context).addBundleListener(argument.capture());
//send events
BundleListener listener = argument.getValue();
listener.bundleChanged(installedEvent);
listener.bundleChanged(resolvedEvent);
//shutdown dispatcher via unregister callback
bundleState.postDeregister();
//check the BundleListener is cleaned up
verify(context).removeBundleListener(listener);
ExecutorService dispatcher = bundleState.getEventDispatcher();
assertTrue(dispatcher.isShutdown());
dispatcher.awaitTermination(2, TimeUnit.SECONDS);
assertTrue(dispatcher.isTerminated());
}
use of org.osgi.service.packageadmin.PackageAdmin in project aries by apache.
the class BundleStateTest method testLifeCycleOfNotificationSupport.
@Test
public void testLifeCycleOfNotificationSupport() throws Exception {
BundleContext context = mock(BundleContext.class);
PackageAdmin admin = mock(PackageAdmin.class);
StartLevel startLevel = mock(StartLevel.class);
Logger logger = mock(Logger.class);
BundleState bundleState = new BundleState(context, admin, startLevel, new StateConfig(), logger);
MBeanServer server1 = mock(MBeanServer.class);
MBeanServer server2 = mock(MBeanServer.class);
ObjectName objectName = new ObjectName(OBJECTNAME);
bundleState.preRegister(server1, objectName);
bundleState.postRegister(true);
// capture the BundleListener registered with BundleContext
ArgumentCaptor<BundleListener> argument = ArgumentCaptor.forClass(BundleListener.class);
verify(context).addBundleListener(argument.capture());
assertEquals(1, argument.getAllValues().size());
BundleListener listener = argument.getValue();
assertNotNull(listener);
ExecutorService dispatcher = bundleState.getEventDispatcher();
//do registration with another server
bundleState.preRegister(server2, objectName);
bundleState.postRegister(true);
// check no more actions on BundleContext
argument = ArgumentCaptor.forClass(BundleListener.class);
verify(context, atMost(1)).addBundleListener(argument.capture());
assertEquals(1, argument.getAllValues().size());
//do one unregister
bundleState.postDeregister();
//verify bundleListener not invoked
verify(context, never()).removeBundleListener(listener);
assertFalse(dispatcher.isShutdown());
//do second unregister and check cleanup
bundleState.postDeregister();
verify(context).removeBundleListener(listener);
assertTrue(dispatcher.isShutdown());
dispatcher.awaitTermination(2, TimeUnit.SECONDS);
assertTrue(dispatcher.isTerminated());
}
use of org.osgi.service.packageadmin.PackageAdmin in project aries by apache.
the class BundleContextInfoProvider method getRelationships.
@Override
public List<RelationshipInfo> getRelationships() {
ArrayList<RelationshipInfo> r = new ArrayList<RelationshipInfo>();
Bundle[] bundles = ctx.getBundles();
PackageAdmin pa = (PackageAdmin) ctx.getService(ctx.getServiceReference(PackageAdmin.class.getName().toString()));
if (bundles != null && bundles.length != 0) {
for (Bundle b : bundles) {
String bkey = getKeyForBundle(b);
ComponentInfo ci = getComponentForId(bkey);
//add all the packages..
//we only add exports, as imports are implied in the reverse
ExportedPackage[] eps = pa.getExportedPackages(b);
if (eps != null && eps.length != 0) {
for (ExportedPackage ep : eps) {
RelationshipInfoImpl ri = new RelationshipInfoImpl();
ri.setProvidedBy(ci);
ri.setType("Package");
ri.setName(ep.getName());
ri.setRelationshipAspects(new ArrayList<RelationshipAspect>());
ri.setConsumedBy(new ArrayList<ComponentInfo>());
//TODO: add versioning aspect.
Bundle[] imps = ep.getImportingBundles();
if (imps != null && imps.length != 0) {
for (Bundle imp : imps) {
ri.getConsumedBy().add(getComponentForId(getKeyForBundle(imp)));
}
}
r.add(ri);
}
}
//add all the services..
//we only add registered services, as ones in use are handled in the reverse
ServiceReference[] srs = b.getRegisteredServices();
if (srs != null && srs.length != 0) {
for (ServiceReference sr : srs) {
RelationshipInfoImpl ri = getRIforSR(sr);
ri.setProvidedBy(ci);
r.add(ri);
}
}
}
}
return r;
}
Aggregations