private void performAction(DependencyAction action, Map<MavenArtifact, ArtifactLoader> artifact2loader) throws BundleException { LOGGER.info("Perform " + action); EventAdmin eventAdmin = this.eventAdmin; if (eventAdmin != null) eventAdmin.postEvent(new DependencyActionEvent(action)); if (action instanceof InstallAction) { performInstall(action.artifact, artifact2loader.get(action.artifact)); } else if (action instanceof UpdateAction) { MavenArtifact target = ((UpdateAction) action).targetArtifact; performUpdate(action.artifact, target, artifact2loader.get(target)); } else if (action instanceof UninstallAction) { performUninstall(action.artifact); } else { throw new IllegalArgumentException("Unknown action: " + action); } }
@Override public void init() throws BundleException { super.init(); if (Boolean.getBoolean("osgi.framework.useSystemProperties")) { Properties prev = FrameworkProperties.getProperties(); try { Field f = FrameworkProperties.class.getDeclaredField("properties"); // NOI18N f.setAccessible(true); f.set(null, null); } catch (Exception ex) { throw new IllegalStateException(ex); } Properties newP = FrameworkProperties.getProperties(); for (Map.Entry en : prev.entrySet()) { if (en.getKey() instanceof String && en.getValue() instanceof String) { newP.setProperty((String)en.getKey(), (String)en.getValue()); } } assert System.getProperties() == FrameworkProperties.getProperties(); } }
@Override public Bundle installBundle(String url, InputStream in) throws BundleException { final String pref = "reference:"; if (url.startsWith(pref)) { // workaround for problems with space in path url = url.replaceAll("%20", " "); String filePart = url.substring(pref.length()); if (installArea != null && filePart.startsWith(installArea)) { String relPath = filePart.substring(installArea.length()); if (relPath.startsWith("/")) { // NOI18N relPath = relPath.substring(1); } url = pref + "file:" + relPath; NetbinoxFactory.LOG.log(Level.FINE, "Converted to relative {0}", url); } else { NetbinoxFactory.LOG.log(Level.FINE, "Kept absolute {0}", url); } } return delegate.installBundle(url, in); }
/** * Stops and un-installs the current bundle. */ public void stopAndUninstallBundles() { // --- Get a copy of loaded bundles ----- Vector<Bundle> bundlesToRemove = new Vector<>(this.getBundleVector()); for (Bundle bundle: bundlesToRemove) { try { // --- Remove, if active -------- if (bundle.getState()==Bundle.ACTIVE) { bundle.stop(); bundle.uninstall(); } // --- Remove from vector ------- this.getBundleVector().remove(bundle); if (this.debug) System.out.println("=> - " + bundle.getSymbolicName() + " stoped & uninstalled"); } catch (BundleException bEx) { bEx.printStackTrace(); } } }
/** * Test currently does not work as data source config is not deployed for unknown reason */ @Ignore @Test public void test() throws BundleException { resolveBundles(); Assert.assertEquals(0, taskService.getTasks().size()); Task task = new Task(); task.setId(1); task.setDescription("My task"); taskService.addTask(task); Collection<Task> tasks = taskService.getTasks(); Assert.assertEquals(1, tasks.size()); Task task1 = tasks.iterator().next(); Assert.assertEquals(1, task1.getId().intValue()); Assert.assertEquals("My task", task1.getDescription()); }
private void setStartLevel ( final String symbolicName, final int startLevel ) throws BundleException { final Bundle bundle = findBundle ( symbolicName ); if ( bundle == null ) { return; } final BundleStartLevel bundleStartLevel = bundle.adapt ( BundleStartLevel.class ); if ( bundleStartLevel == null ) { return; } bundleStartLevel.setStartLevel ( startLevel < 0 ? this.defaultStartLevel : startLevel ); bundle.start (); }
@Deprecated public void uninstallBundle(final String location) throws BundleException { Bundle bundle = Framework.getBundle(location); if (bundle != null) { BundleImpl b = (BundleImpl)bundle; File delDir = null; try { File soFile = b.getArchive().getArchiveFile(); if(soFile.canWrite()){ soFile.delete(); } delDir = b.getArchive().getCurrentRevision().getRevisionDir(); bundle.uninstall(); if(delDir !=null ){ Framework.deleteDirectory(delDir); } } catch (Exception e) { } } else { throw new BundleException("Could not uninstall bundle " + location + ", because could not find it"); } }
/** * create a new bundle object from InputStream. This is used when a new bundle is installed. * * @param location the bundle location. * @param stream the input stream. * @throws BundleException if something goes wrong. * @throws IOException */ BundleImpl(final File bundleDir, final String location, final InputStream stream, final File file, String unique_tag, boolean installForCurrentVersion, long dexPatchVersion) throws BundleException, IOException{ this.location = location; this.bundleDir = bundleDir; if(installForCurrentVersion) { Framework.notifyBundleListeners(BundleEvent.BEFORE_INSTALL, this); } if (stream != null) { this.archive = new BundleArchive(location,bundleDir, stream,unique_tag, dexPatchVersion); } else if (file != null) { this.archive = new BundleArchive(location,bundleDir, file,unique_tag, dexPatchVersion); } this.state = INSTALLED; if (installForCurrentVersion) { resolveBundle(); Framework.bundles.put(location, this); // notify the listeners Framework.notifyBundleListeners(BundleEvent.INSTALLED, this); } }
/** * uninstall the bundle. * * @throws BundleException if bundle is already uninstalled * @see org.osgi.framework.Bundle#uninstall() * @category Bundle */ public synchronized void uninstall() throws BundleException { if (state == UNINSTALLED) { throw new IllegalStateException("Bundle " + toString() + " is already uninstalled."); } if (state == ACTIVE) { try { stop(); } catch (Throwable t) { Framework.notifyFrameworkListeners(FrameworkEvent.ERROR, this, t); } } state = UNINSTALLED; classloader.cleanup(true); classloader = null; Framework.bundles.remove(getLocation()); Framework.notifyBundleListeners(BundleEvent.UNINSTALLED, this); }
private void startDependencyAsynch(final Bundle bundle) { System.out.println("starting dependency test bundle"); Runnable runnable = new Runnable() { public void run() { try { bundle.start(); System.out.println("started dependency test bundle"); } catch (BundleException ex) { System.err.println("can't start bundle " + ex); } } }; Thread thread = new Thread(runnable); thread.setDaemon(false); thread.setName("dependency test bundle"); thread.start(); }
/** * Starts a bundle and prints a nice logging message in case of failure. * * @param bundle to start * @throws BundleException */ private void startBundle(Bundle bundle) throws BundleException { boolean debug = logger.isDebugEnabled(); String info = "[" + OsgiStringUtils.nullSafeNameAndSymName(bundle) + "|" + bundle.getLocation() + "]"; if (!OsgiBundleUtils.isFragment(bundle)) { if (debug) logger.debug("Starting " + info); try { bundle.start(); } catch (BundleException ex) { logger.error("cannot start bundle " + info, ex); throw ex; } } else { // if (!OsgiBundleUtils.isBundleResolved(bundle)) { // logger.error("fragment not resolved: " + info); // throw new BundleException("Unable to resolve fragment: " + info); // } else if (debug) logger.debug(info + " is a fragment; start not invoked"); } }
@Deprecated private void checkExecutionEnviroment(String[] requireEnv, String[] execEnv) throws BundleException { if (requireEnv.length != 0) { Set hashSet = new HashSet(Arrays.asList(execEnv)); int i = 0; while (i < requireEnv.length) { if (!hashSet.contains(requireEnv[i])) { i++; } else { return; } } throw new BundleException("Platform does not provide EEs " + Arrays.asList(requireEnv)); } }
BundleImpl(File file) throws Exception { long currentTimeMillis = System.currentTimeMillis(); DataInputStream dataInputStream = new DataInputStream(new FileInputStream(new File(file, "meta"))); this.location = dataInputStream.readUTF(); this.currentStartlevel = dataInputStream.readInt(); this.persistently = dataInputStream.readBoolean(); dataInputStream.close(); this.bundleDir = file; this.state = BundleEvent.STARTED; try { this.archive = new BundleArchive(this.location, file); resolveBundle(false); Framework.bundles.put(this.location, this); Framework.notifyBundleListeners(BundleEvent.INSTALLED, this); if (Framework.DEBUG_BUNDLES && log.isInfoEnabled()) { log.info("Framework: Bundle " + toString() + " loaded. " + (System.currentTimeMillis() - currentTimeMillis) + " ms"); } } catch (Exception e) { throw new BundleException("Could not load bundle " + this.location, e.getCause()); } }
public synchronized void startBundle() throws BundleException { if (this.state == BundleEvent.INSTALLED) { throw new IllegalStateException("Cannot start uninstalled bundle " + toString()); } else if (this.state != BundleEvent.RESOLVED) { if (this.state == BundleEvent.STARTED) { resolveBundle(true); } this.state = BundleEvent.UPDATED; try { isValid = true; this.state = BundleEvent.RESOLVED; Framework.notifyBundleListeners(BundleEvent.STARTED, this); if (Framework.DEBUG_BUNDLES && log.isInfoEnabled()) { log.info("Framework: Bundle " + toString() + " started."); } } catch (Throwable th) { Framework.clearBundleTrace(this); this.state = BundleEvent.STOPPED; String msg = "Error starting bundle " + toString(); log.error(msg,th); } } }
public synchronized void stopBundle() throws BundleException { if (this.state == BundleEvent.INSTALLED) { throw new IllegalStateException("Cannot stop uninstalled bundle " + toString()); } else if (this.state == BundleEvent.RESOLVED) { this.state = BundleEvent.UNINSTALLED; try { if (Framework.DEBUG_BUNDLES && log.isInfoEnabled()) { log.info("Framework: Bundle " + toString() + " stopped."); } Framework.clearBundleTrace(this); this.state = BundleEvent.STOPPED; Framework.notifyBundleListeners(BundleEvent.STOPPED, this); isValid = false; } catch (Throwable th) { Framework.clearBundleTrace(this); this.state = BundleEvent.STOPPED; Framework.notifyBundleListeners(BundleEvent.STOPPED, this); isValid = false; } } }
@Override public synchronized void uninstall() throws BundleException { if (this.state == BundleEvent.INSTALLED) { throw new IllegalStateException("Bundle " + toString() + " is already uninstalled."); } if (this.state == BundleEvent.RESOLVED) { try { stopBundle(); } catch (Throwable th) { Framework.notifyFrameworkListeners(BundleEvent.STARTED, this, th); } } this.state = BundleEvent.INSTALLED; new File(this.bundleDir, "meta").delete(); this.classloader.cleanup(true); this.classloader = null; Framework.bundles.remove(this); Framework.notifyBundleListeners(BundleEvent.UNINSTALLED, this); isValid = false; }
/** * installs a bundle from file */ void installFromFile(File file) { try { Bundle bundle = context.installBundle(file.toURI().toString()); plugins.add(bundle); System.out.println ("Loading " + file.toURI()); bundles.put (bundle, file.toURI().toString()); } catch (BundleException e) { if (e.getType() == BundleException.DUPLICATE_BUNDLE_ERROR) { // duplicate bundle is a warning, not an error System.out.println("WARNING " + file.getName() + "; " + e.getMessage()); } else { System.out.println("Could not install bundle from file " + file.getName()); e.printStackTrace(); } } }
/** * update bundle whitout reboot app * Notice:this method is Experience!!,maybe not stabe,don't use is product better * * @param location bundle package name * @param mBundleFile bundle archive file * @throws BundleException if error occurred,will throw BundleException */ public void updateBundleForce(String location, File mBundleFile) throws BundleException { if (!mBundleFile.exists()) { throw new BundleException("file not found" + mBundleFile.getAbsolutePath()); } BundleImpl bundle = (BundleImpl) Framework.getBundle(location); if (bundle != null) { bundle.update(mBundleFile); bundle.refresh(); try { DelegateResources.newDelegateResources(RuntimeVariables.androidApplication, RuntimeVariables.delegateResources, bundle.getArchive().getArchiveFile().getAbsolutePath()); } catch (Exception e) { } return; } throw new BundleException("Could not update bundle " + location + ", because could not find it"); }
/** * uninstall specific bundle * * @param pkgName bundle package name you wanna uninstall * @throws BundleException */ public void uninstallBundle(String pkgName) throws BundleException { Bundle bundle = Framework.getBundle(pkgName); if (bundle != null) { BundleImpl bundleImpl = (BundleImpl) bundle; try { File archiveFile = bundleImpl.getArchive().getArchiveFile(); if (archiveFile.canWrite()) { archiveFile.delete(); } bundleImpl.getArchive().purge(); File revisionDir = bundleImpl.getArchive().getCurrentRevision() .getRevisionDir(); bundle.uninstall(); if (revisionDir != null) { Framework.deleteDirectory(revisionDir); return; } return; } catch (Exception e) { log.error("uninstall bundle error: " + pkgName + e.getMessage()); return; } } throw new BundleException("Could not uninstall bundle " + pkgName + ", because could not find it"); }
/** * http://njbartlett.name/2011/07/03/embedding-osgi.html * * http://felix.apache.org/documentation/subprojects/apache-felix-framework/apache-felix-framework-launching-and-embedding.html * * @return OSGi Framework System Bundle (#0) */ public Bundle start() throws BundleException { framework.init(loggingFrameworkListener); BundleContext frameworkBundleContext = framework.getBundleContext(); frameworkBundleContext.addFrameworkListener(loggingFrameworkListener); frameworkBundleContext.addBundleListener(new LoggingBundleListener()); frameworkBundleContext.addServiceListener(new LoggingServiceListener()); framework.start(); LOG.info("OSGi Framework init() & start() OK"); // http://felix.apache.org/documentation/subprojects/apache-felix-file-install.html // assuming that org.apache.felix.fileinstall-*.jar is in bootBundlesDirectory System.setProperty("felix.fileinstall.dir", hotBundlesDirectory.getAbsolutePath()); System.setProperty("felix.fileinstall.debug", "1"); System.setProperty("felix.fileinstall.noInitialDelay", "true"); return framework; }
@Test public void requireThatLogServiceCanNotBeStartedTwice() throws BundleException { OsgiFramework osgi = TestDriver.newOsgiFramework(); osgi.start(); BundleContext ctx = osgi.bundleContext(); OsgiLogService service = new OsgiLogService(); service.start(ctx); try { service.start(ctx); fail(); } catch (IllegalStateException e) { } osgi.stop(); }
@Test public void requireThatBundlesCanBeInstalled() throws BundleException { FelixFramework felix = TestDriver.newOsgiFramework(); felix.start(); Bundle bundle = felix.installBundle("cert-a.jar").get(0); assertNotNull(bundle); Iterator<Bundle> it = felix.bundles().iterator(); assertNotNull(it); assertTrue(it.hasNext()); assertEquals(FelixConstants.SYSTEM_BUNDLE_SYMBOLICNAME, it.next().getSymbolicName()); assertTrue(it.hasNext()); assertSame(bundle, it.next()); assertFalse(it.hasNext()); felix.stop(); }
@Test public void requireThatManifestContainsExportPackage() throws BundleException { FelixFramework felix = TestDriver.newOsgiFramework(); felix.start(); List<Bundle> bundles = felix.installBundle("jdisc_core.jar"); assertEquals(1, bundles.size()); Object obj = bundles.get(0).getHeaders().get("Export-Package"); assertTrue(obj instanceof String); String str = (String)obj; assertTrue(str.contains(ExportPackages.getSystemPackages())); assertTrue(str.contains("com.yahoo.jdisc")); assertTrue(str.contains("com.yahoo.jdisc.application")); assertTrue(str.contains("com.yahoo.jdisc.handler")); assertTrue(str.contains("com.yahoo.jdisc.service")); felix.stop(); }
@Test public void requireThatLogServiceIsRegistered() throws BundleException, InterruptedException { OsgiFramework osgi = TestDriver.newOsgiFramework(); osgi.start(); ServiceTracker<?,?> logs = newTracker(osgi, LogService.class); ServiceTracker<?,?> logReaders = newTracker(osgi, LogReaderService.class); assertEquals(1, logs.getTrackingCount()); assertEquals(1, logReaders.getTrackingCount()); OsgiLogService service = new OsgiLogService(); service.start(osgi.bundleContext()); assertEquals(2, logs.getTrackingCount()); assertEquals(2, logReaders.getTrackingCount()); osgi.stop(); }
@Override public void stop() throws BundleException { log.fine("Stopping felix."); BundleContext ctx = felix.getBundleContext(); if (ctx != null) { if (logListener != null) { logListener.uninstall(); } logHandler.uninstall(); logService.stop(); } felix.stop(); try { felix.waitForStop(0); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }
@Override protected void start() { try { framework.start(); } catch (BundleException ex) { LOG.log(Level.WARNING, "Cannot start Container" + framework, ex); } }
@Override protected void reload(Module m) throws IOException { try { Bundle b = findBundle(m.getCodeNameBase()); b.stop(); fakeOneModule(m, b); } catch (BundleException ex) { throw new IOException(ex); } }
/** * Installs the specified jar bundle and adds the Bundle instance to the local bundle vector {@link #getBundleVector()}. * @param bundleJarFilePath the bundle jar file path */ public void installBundle(String bundleJarFilePath) { Bundle bundle = null; try { BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()).getBundleContext(); bundle = bundleContext.installBundle(bundleJarFilePath); if (this.debug) System.out.println("=> + " + bundle.getSymbolicName() + " installed."); } catch (BundleException bEx) { bEx.printStackTrace(); } // --- Remind this bundle --------------- if (bundle!=null) this.getBundleVector().addElement(bundle); }
/** * Starts the specified bundle and return true if successful. * * @param bundle the bundle * @return true, if successful */ public boolean startBundle(Bundle bundle) { boolean bundleStarted = false; try { bundle.start(); bundleStarted = true; if (this.debug) System.out.println("=> ! " + bundle.getSymbolicName() + " started"); } catch (BundleException bEx) { bEx.printStackTrace(); } return bundleStarted; }
/** * Update plugin.xml according to the model * * @param resource */ private void updateProjectPluginConfiguration(IResource resource) { if (resource instanceof IFile && resource.getFileExtension().equals("melange")) { IFile file = (IFile) resource; IProject project = file.getProject(); // try { if (file.exists()) { //Load .melange file URI uri = URI.createPlatformResourceURI(file.getFullPath().toString(), true); ResourceSet rs = new ResourceSetImpl(); Resource res = rs.getResource(uri, true); ModelTypingSpace root = (ModelTypingSpace)res.getContents().get(0); String packageName = root.getName(); //Browse declared Languages for (fr.inria.diverse.melange.metamodel.melange.Element element : root.getElements()) { if(element instanceof Language){ Language language = (Language) element; // update entry in plugin.xml setPluginLanguageNameAndFilePath(project, file, packageName+"."+language.getName()); } } //Use default model loader updateModelLoaderClass(project, null); ManifestChanger manifestChanger = new ManifestChanger(project); try { manifestChanger.addPluginDependency(org.eclipse.gemoc.executionframework.extensions.sirius.Activator.PLUGIN_ID); manifestChanger.commit(); } catch (BundleException | IOException | CoreException e) { e.printStackTrace(); } } } }
private void updateManifestFile(IProject project){ // complement manifest ManifestChanger changer = new ManifestChanger(project); try { changer.addPluginDependency(org.eclipse.gemoc.xdsmlframework.api.Activator.PLUGIN_ID, "0.1.0", true, true); changer.addPluginDependency("org.eclipse.emf.ecore.xmi", "2.8.0", true, true); changer.addPluginDependency("org.eclipse.gemoc.xdsmlframework.api"); changer.addPluginDependency("org.eclipse.gemoc.execution.sequential.javaxdsml.api"); changer.addPluginDependency("org.eclipse.gemoc.executionframework.engine"); changer.commit(); } catch (BundleException | IOException | CoreException e) { Activator.error("Failed to update manifest "+e.getMessage(), e); } }
public static void updateManifest(final IProject project){ ManifestChanger changer = new ManifestChanger(project); try { changer.addPluginDependency("org.eclipse.gemoc.executionframework.extensions.sirius"); changer.addPluginDependency("org.eclipse.gemoc.execution.sequential.javaengine.ui"); changer.commit(); } catch (BundleException | IOException | CoreException e) { Activator.getMessagingSystem().error(e.getMessage(), Activator.PLUGIN_ID, e); } }
@Test public void test() throws BundleException { resolveBundles(); Assert.assertEquals(0, taskService.getTasks().size()); Task task = new Task(); task.setId(1); task.setDescription("My task"); taskService.addTask(task); Collection<Task> tasks = taskService.getTasks(); Assert.assertEquals(1, tasks.size()); Task task1 = tasks.iterator().next(); Assert.assertEquals(1, task1.getId().intValue()); Assert.assertEquals("My task", task1.getDescription()); }
/** * Helps to diagnose bundles that are not resolved as it will throw a detailed exception * * @throws BundleException */ public void resolveBundles() throws BundleException { Bundle[] bundles = bundleContext.getBundles(); for (Bundle bundle : bundles) { if (bundle.getState() == Bundle.INSTALLED) { System.out.println("Found non resolved bundle " + bundle.getBundleId() + ":" + bundle.getSymbolicName() + ":" + bundle.getVersion()); bundle.start(); } } }
/** * Create, find and delete car using resource local transactions * @param emf * @throws BundleException */ protected void carLifecycleRL(EntityManager em) throws BundleException { em.getTransaction().begin(); Car car = createBlueCar(); em.persist(car); em.getTransaction().commit(); Car car2 = em.find(Car.class, BLUE_PLATE); assertBlueCar(car2); em.getTransaction().begin(); em.remove(car2); em.getTransaction().commit(); em.close(); }
/** * Create, find and delete truck using resource local transactions * @param emf * @throws BundleException */ protected void truckLifecycleRL(EntityManager em) throws BundleException { em.getTransaction().begin(); Truck truck = createBlueTruck(); em.persist(truck); em.getTransaction().commit(); Truck truck2 = em.find(Truck.class, BLUE_PLATE); assertBlueTruck(truck2); em.getTransaction().begin(); em.remove(truck2); em.getTransaction().commit(); em.close(); }
@Deprecated public void installBundle(final String location, final InputStream input) throws BundleException { if (TextUtils.isEmpty(location)){ Log.e("Atlas","empty location"); } if (Framework.getBundle(location) == null) { checkingThread(false); BundleInstallerFetcher.obtainInstaller().installSync(new String[]{location}, new InputStream[]{input}); } }