Пример #1
1
  @SuppressWarnings("unchecked")
  public void init() {
    Map config = new HashMap();
    List list = new ArrayList();

    File pluginDir = Main.pref.getPluginsDirectory();
    pluginDirName = pluginDir.getAbsolutePath() + "/";

    list.add(this);
    // config.put(AutoProcessor.AUTO_START_PROP + ".1",
    //		"file:" + pluginDirName + "/bundle/de.vogella.felix.firstbundle_1.0.0.201010271606.jar");
    config.put(BundleCache.CACHE_ROOTDIR_PROP, pluginDirName);
    config.put(Constants.FRAMEWORK_STORAGE_CLEAN, "onFirstInit");
    config.put(FelixConstants.LOG_LEVEL_PROP, "4");
    config.put(FelixConstants.SYSTEMBUNDLE_ACTIVATORS_PROP, list);

    // Now create an instance of the framework with
    // our configurations properties
    felix = new Felix(config);

    // now start Felix instance
    try {
      felix.start();
    } catch (BundleException e) {
      System.err.println("Could not generate framework: " + e);
      e.printStackTrace();
    }
  }
Пример #2
0
  /*
   * (non-Javadoc)
   *
   * @see org.araqne.bundle.BundleManager#uninstallBundle(long)
   */
  @Override
  public boolean uninstallBundle(long bundleId) {
    Bundle bundle = context.getBundle(bundleId);
    if (bundle == null) {
      logger.warn(String.format("bundle %d not found.", bundleId));
      return false;
    }

    try {
      String downloadRoot = getDownloadRoot();

      String prefix = getPrefix();

      File bundleLocation = new File(bundle.getLocation().replace(prefix, ""));

      // prevents destruction out of the download directory.
      // delete cached bundle in download directory for redownloading
      if (bundle.getLocation().startsWith(prefix + downloadRoot)) {
        File bundleDirectory = new File(bundleLocation.getParent());
        bundleLocation.delete();
        deleteDirectory(bundleDirectory);
      }
      bundle.uninstall();
      return true;
    } catch (BundleException e) {
      logger.error(e.getMessage());
      return false;
    }
  }
Пример #3
0
  public String translateToMessage(BundleException e) {
    switch (e.getType()) {
      case BundleException.ACTIVATOR_ERROR:
        Throwable t = e.getCause();
        StackTraceElement[] stackTrace = t.getStackTrace();
        if (stackTrace == null || stackTrace.length == 0)
          return "activator error " + t.getMessage();
        StackTraceElement top = stackTrace[0];
        return "activator error "
            + t.getMessage()
            + " from: "
            + top.getClassName()
            + ":"
            + top.getMethodName()
            + "#"
            + top.getLineNumber();

      case BundleException.DUPLICATE_BUNDLE_ERROR:
      case BundleException.RESOLVE_ERROR:
      case BundleException.INVALID_OPERATION:
      case BundleException.MANIFEST_ERROR:
      case BundleException.NATIVECODE_ERROR:
      case BundleException.STATECHANGE_ERROR:
      case BundleException.UNSUPPORTED_OPERATION:
      case BundleException.UNSPECIFIED:
      default:
        return e.getMessage();
    }
  }
Пример #4
0
  @SuppressWarnings("deprecation")
  public void testAllResolved() {
    assertNotNull("Expected a Bundle Context", context);
    StringBuilder sb = new StringBuilder();

    for (Bundle b : context.getBundles()) {
      if (b.getState() == Bundle.INSTALLED
          && b.getHeaders().get(aQute.bnd.osgi.Constants.FRAGMENT_HOST) == null) {
        try {
          b.start();
        } catch (BundleException e) {
          sb.append(b.getBundleId())
              .append(" ")
              .append(b.getSymbolicName())
              .append(";")
              .append(b.getVersion())
              .append("\n");
          sb.append("    ").append(e.getMessage()).append("\n\n");
          System.err.println(e.getMessage());
        }
      }
    }
    Matcher matcher = IP_P.matcher(sb);
    String out =
        matcher.replaceAll(
            "\n\n         " + aQute.bnd.osgi.Constants.IMPORT_PACKAGE + ": $1;version=[$2,$3)\n");
    assertTrue("Unresolved bundles\n" + out, sb.length() == 0);
  }
 public void run() {
   try {
     m_bundle.start();
   } catch (BundleException e) {
     // TODO: log this
     e.printStackTrace();
   }
 }
	private void assertInstallFail(String name, Region region) {
		try {
			Bundle b = bundleInstaller.installBundle(name, region);
			b.uninstall();
			fail("Expected a bundle exception on duplicate bundle install: " + region);
		} catch (BundleException e) {
			// expected
			assertEquals("Wrong exception type.", BundleException.DUPLICATE_BUNDLE_ERROR, e.getType());
		}
	}
 public synchronized void cleanup() {
   while ((!m_installed.isEmpty())) {
     try {
       Long id = m_installed.pop();
       Bundle bundle = m_framework.getBundleContext().getBundle(id);
       bundle.uninstall();
       LOG.debug("Uninstalled bundle " + id);
     } catch (BundleException e) {
       e.printStackTrace();
     }
   }
 }
Пример #8
0
  @MsgbusMethod
  public void stopBundle(Request req, Response resp) {
    int bundleId = req.getInteger("bundle_id");
    Bundle bundle = bc.getBundle(bundleId);
    if (bundle == null) throw new IllegalArgumentException("bundle not found: " + bundleId);

    try {
      bundle.stop();
    } catch (BundleException e) {
      throw new IllegalStateException(e.getMessage());
    }
  }
  public IResponse handlePut(
      String[] queryPath, Properties params, Properties uploads, InputStream content) {
    IResponse response;

    if (queryPath.length == 0) {
      response =
          new DefaultResponse(
              IResponse.HTTP_BADREQUEST, IResponse.MIME_PLAINTEXT, "Invalid request");
    } else {
      try {
        Bundle bundle = findBundle(queryPath[0]);
        try {
          if (queryPath.length == 1 && content != null) {
            // Update from supplied content
            bundle.update(content);
            response = listBundles();
          } else if (queryPath.length == 2 && "update".equals(queryPath[1])) {
            // Update from persistent location
            bundle.update();
            response = listBundles();
          } else if (queryPath.length == 2 && "start".equals(queryPath[1])) {
            bundle.start();
            response = listBundles();
          } else if (queryPath.length == 2 && "stop".equals(queryPath[1])) {
            bundle.stop();
            response = listBundles();
          } else {
            response =
                new DefaultResponse(
                    IResponse.HTTP_BADREQUEST, IResponse.MIME_PLAINTEXT, "Invalid request");
          }
        } catch (BundleException e) {
          response = DefaultResponse.createInternalError(e);
          response =
              new DefaultResponse(
                  IResponse.HTTP_INTERNALERROR, IResponse.MIME_PLAINTEXT, e.getMessage());
        }
      } catch (NumberFormatException e) {
        response =
            new DefaultResponse(
                IResponse.HTTP_BADREQUEST, IResponse.MIME_PLAINTEXT, e.getMessage());
      } catch (IllegalArgumentException e) {
        response =
            new DefaultResponse(
                IResponse.HTTP_NOTFOUND,
                IResponse.MIME_PLAINTEXT,
                "No such bundle " + queryPath[0]);
      }
    }

    return response;
  }
  @Test
  public void testInstallModule() throws Exception {

    // Try to start the bundle and verify the expected ResolutionException
    XBundle bundleA = (XBundle) installBundle(getBundleA());
    try {
      bundleA.start();
      Assert.fail("BundleException expected");
    } catch (BundleException ex) {
      ResolutionException cause = (ResolutionException) ex.getCause();
      Collection<Requirement> reqs = cause.getUnresolvedRequirements();
      Assert.assertEquals(1, reqs.size());
      Requirement req = reqs.iterator().next();
      String namespace = req.getNamespace();
      Assert.assertEquals(PackageNamespace.PACKAGE_NAMESPACE, namespace);
    }

    Module moduleB = loadModule(getModuleB());
    XBundleRevision brevB = installResource(moduleB);
    try {
      XBundle bundleB = brevB.getBundle();
      Assert.assertEquals(bundleA.getBundleId() + 1, bundleB.getBundleId());

      bundleA.start();
      assertLoadClass(bundleA, ModuleServiceX.class.getName(), bundleB);

      // verify wiring for A
      XBundleRevision brevA = bundleA.getBundleRevision();
      Assert.assertSame(bundleA, brevA.getBundle());
      BundleWiring wiringA = brevA.getWiring();
      List<BundleWire> requiredA = wiringA.getRequiredWires(null);
      Assert.assertEquals(1, requiredA.size());
      BundleWire wireA = requiredA.get(0);
      Assert.assertSame(brevA, wireA.getRequirer());
      Assert.assertSame(bundleB, wireA.getProvider().getBundle());
      List<BundleWire> providedA = wiringA.getProvidedWires(null);
      Assert.assertEquals(0, providedA.size());

      // verify wiring for B
      Assert.assertSame(bundleB, brevB.getBundle());
      BundleWiring wiringB = brevB.getWiring();
      List<BundleWire> requiredB = wiringB.getRequiredWires(null);
      Assert.assertEquals(0, requiredB.size());
      List<BundleWire> providedB = wiringB.getProvidedWires(null);
      Assert.assertEquals(1, providedB.size());
      BundleWire wireB = providedB.get(0);
      Assert.assertSame(brevA, wireB.getRequirer());
      Assert.assertSame(bundleB, wireB.getProvider().getBundle());
    } finally {
      removeModule(moduleB);
    }
  }
Пример #11
0
 public static Bundle installAndStartBundle(
     BundleContext context, String location, ClassLoader classLoader, String bundleFileName) {
   Bundle bundle = OsgiUtils.installBundle(context, location, bundleFileName, classLoader);
   if (bundle == null) return null;
   try {
     bundle.start();
   } catch (BundleException e2) {
     e2.printStackTrace();
   }
   // System.out.println(bundle.getSymbolicName() + ": "
   // + getBundleState(bundle.getState()));
   return bundle;
 }
 public BundleDescription create_bundle_5(StateObjectFactory sof) {
   java.util.Dictionary dictionary_5 = new java.util.Properties();
   BundleDescription bundle = null;
   dictionary_5.put("Bundle-ManifestVersion", "2");
   dictionary_5.put("Bundle-SymbolicName", "DOM B");
   dictionary_5.put("Export-Package", "org.w3c.dom; version=2.2.0");
   try {
     bundle = sof.createBundleDescription(dictionary_5, "bundle_5", 5);
   } catch (BundleException be) {
     fail(be.getMessage());
   }
   return bundle;
 } // end of method
 public BundleDescription create_bundle_3(StateObjectFactory sof) {
   java.util.Dictionary dictionary_3 = new java.util.Properties();
   BundleDescription bundle = null;
   dictionary_3.put("Bundle-ManifestVersion", "2");
   dictionary_3.put("Bundle-SymbolicName", "SAX");
   dictionary_3.put("Export-Package", "org.xml.sax; version=1.3.0");
   try {
     bundle = sof.createBundleDescription(dictionary_3, "bundle_3", 3);
   } catch (BundleException be) {
     fail(be.getMessage());
   }
   return bundle;
 } // end of method
 public synchronized long install(InputStream stream) {
   try {
     Bundle b = m_framework.getBundleContext().installBundle("local", stream);
     m_installed.push(b.getBundleId());
     LOG.debug("Installed bundle " + b.getSymbolicName() + " as Bundle ID " + b.getBundleId());
     setBundleStartLevel(b.getBundleId(), Constants.START_LEVEL_TEST_BUNDLE);
     // stream.close();
     b.start();
     return b.getBundleId();
   } catch (BundleException e) {
     e.printStackTrace();
   }
   return -1;
 }
Пример #15
0
 protected Bundle install(String location) {
   try {
     return getBundleContext().installBundle(location, null);
   } catch (BundleException ex) {
     if (ex.getNestedException() != null) {
       println(ex.getNestedException().toString());
     } else {
       println(ex.toString());
     }
   } catch (Exception ex) {
     println(ex.toString());
   }
   return null;
 }
  @Before
  public void setUp() {
    try {
      _bundle.start();
    } catch (BundleException e) {
      e.printStackTrace();
    }

    _anonymousUserLocalService =
        ServiceTrackerUtil.getService(AnonymousUserLocalService.class, _bundle.getBundleContext());
    _ruleInstanceLocalService =
        ServiceTrackerUtil.getService(RuleInstanceLocalService.class, _bundle.getBundleContext());
    _rulesRegistry = ServiceTrackerUtil.getService(RulesRegistry.class, _bundle.getBundleContext());
  }
 private void ensureEventAdminStarted() {
   if (Activator.getDefault().getEventAdmin() == null) {
     Bundle[] bundles = Activator.getDefault().getBundle().getBundleContext().getBundles();
     for (Bundle bundle : bundles) {
       if (!"org.eclipse.equinox.event".equals(bundle.getSymbolicName())) continue;
       try {
         bundle.start(Bundle.START_TRANSIENT);
       } catch (BundleException e) {
         e.printStackTrace();
       }
       break;
     }
   }
 }
Пример #18
0
  public void start(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String bundleID = request.getParameter("bundleId");
    try {
      try {
        OSGIUtil.getInstance().getBundleContext().getBundle(new Long(bundleID)).start();
      } catch (NumberFormatException e) {
        OSGIUtil.getInstance().getBundleContext().getBundle(bundleID).start();
      }
    } catch (BundleException e) {
      Logger.error(OSGIAJAX.class, e.getMessage(), e);
      throw new ServletException(e.getMessage() + " Unable to start bundle", e);
    }
  }
Пример #19
0
  @Test
  public void testExtensionFragmentFramework() throws Exception {

    try {
      installBundle(getFragmentG4());
      fail("BundleException expected");
    } catch (BundleException ex) {
      Throwable cause = ex.getCause();
      assertNotNull("BundleException cause not null", cause);
      assertEquals(
          "UnsupportedOperationException expected",
          UnsupportedOperationException.class,
          cause.getClass());
    }
  }
 public BundleDescription create_bundle_2(StateObjectFactory sof) {
   java.util.Dictionary dictionary_2 = new java.util.Properties();
   BundleDescription bundle = null;
   dictionary_2.put("Bundle-ManifestVersion", "2");
   dictionary_2.put("Bundle-SymbolicName", "Client B");
   dictionary_2.put(
       "Import-Package",
       "org.xml.sax; version=\"[1.3.0, 1.3.0]\", org.w3c.dom; version=\"[2.2.0, 2.2.0]\", javax.xml.parsers; version=\"[1.1.0, 1.1.0]\"");
   try {
     bundle = sof.createBundleDescription(dictionary_2, "bundle_2", 2);
   } catch (BundleException be) {
     fail(be.getMessage());
   }
   return bundle;
 } // end of method
Пример #21
0
  /**
   * Installs a bundle specified by its jar name into the given bundle context.
   *
   * @param bundleContext The bundle context where to install the bundle
   * @param jarName the file name of a jar located in the classpath known by the given <code>
   *     ClassLoader</code>
   * @param classLoader Used to find the jar using <code>getResourceAsStream</code>
   * @return
   */
  public static final Bundle installBundle(
      BundleContext bundleContext, String location, String jarName, ClassLoader classLoader) {

    if (bundleContext == null || classLoader == null) return null;
    try {
      InputStream in = classLoader.getResourceAsStream(jarName);

      Bundle bundle = bundleContext.installBundle(location, in);
      in.close();
      return bundle;
    } catch (BundleException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return null;
  }
 private void managePlugin(String toDo, String pluginName) {
   try {
     if (toDo.equals(START)) {
       JarvisPluginMenager.getJarvisPluginMenger().start(pluginName);
       consoleUtil.printToConsole(info(ACTIVATED));
     } else if (toDo.equals(STOP)) {
       JarvisPluginMenager.getJarvisPluginMenger().stop(pluginName);
       consoleUtil.printToConsole(info(DEACTIVATED));
     } else if (toDo.equals(UNINSTALL)) {
       JarvisPluginMenager.getJarvisPluginMenger().uninstall(pluginName);
       consoleUtil.printToConsole(info(UNINSTALLED));
     } else {
       consoleUtil.printToConsole(badCommandInfo("plugin managment", "pluginmanager"));
     }
   } catch (BundleException e) {
     // e.printStackTrace();
     consoleUtil.printToConsole("[JARVIS]>> Error: " + e.getMessage());
   }
 }
Пример #23
0
 @Override
 public boolean install(
     Configuration oteConfiguration, OTEStatusCallback<ConfigurationStatus> statusCallback) {
   boolean pass = true;
   for (ConfigurationItem bundleDescription : oteConfiguration.getItems()) {
     String bundleName = bundleDescription.getSymbolicName();
     try {
       boolean exists = false;
       for (Bundle bundle : runningBundles) {
         if (bundle.getSymbolicName().equals(bundleName)) {
           exists = true;
           break;
         }
       }
       if (!exists) {
         Bundle bundle = Platform.getBundle(bundleDescription.getSymbolicName());
         if (bundle == null) {
           Bundle installedBundle;
           File bundleData = acquireSystemLibraryStream(bundleDescription);
           installedBundle =
               context.installBundle("reference:" + bundleData.toURI().toURL().toExternalForm());
           bundleNameToMd5Map.put(bundleName, bundleDescription.getMd5Digest());
           installedBundles.add(installedBundle);
         }
       }
       statusCallback.log("installed " + bundleName);
     } catch (BundleException ex) {
       if (ex.getType() == BundleException.DUPLICATE_BUNDLE_ERROR) {
         statusCallback.log(String.format("Duplicate bundle [%s].", bundleName));
       } else {
         statusCallback.error(String.format("Unable to load [%s].", bundleName), ex);
         pass = false;
       }
     } catch (Throwable th) {
       statusCallback.error(String.format("Unable to load [%s].", bundleName), th);
       pass = false;
     } finally {
       statusCallback.incrememtUnitsWorked(1);
     }
   }
   return pass;
 }
  @Override
  public void onActivityResult(int requestCode, int resultCode, Intent data) {
    Log.d(
        TAG,
        "onActivityResult. requestCode: "
            + requestCode
            + " resultCode: "
            + resultCode
            + " data: "
            + data);
    Uri uri = data.getData();
    if (null == uri) {
      return;
    }

    String path = uri.toString();
    if (!TextUtils.isEmpty(path)) {
      try {
        if (path.startsWith("file:///")) {
          path = path.substring("file://".length());
        }
        Log.d(TAG, "path: " + path);

        FelixWrapper.getInstance(this)
            .getFramework()
            .getBundleContext()
            .installBundle(path, new FileInputStream(new File(path)));
        updateUI();
      } catch (BundleException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    super.onActivityResult(requestCode, resultCode, data);
  }
	public void testInvalidRegionName() {
		Collection<String> invalidNames = new ArrayList<String>();
		invalidNames.addAll(Arrays.asList(":", "bad:Name", ":bad::name:", ":badname", "badname:"));
		invalidNames.addAll(Arrays.asList("=", "bad=Name", "=bad==name=", "=badname", "badname="));
		invalidNames.addAll(Arrays.asList("\n", "bad\nName", "\nbad\n\nname\n", "\nbadname", "badname\n"));
		invalidNames.addAll(Arrays.asList("*", "bad*Name", "*bad**name*", "*badname", "badname*"));
		invalidNames.addAll(Arrays.asList("?", "bad?Name", "?bad??name?", "?badname", "badname?"));
		invalidNames.addAll(Arrays.asList(",", "bad,Name", ",bad,,name,", ",badname", "badname,"));
		invalidNames.addAll(Arrays.asList("\"", "bad\"Name", "\"bad\"\"name\"", "\"badname", "badname\""));
		invalidNames.addAll(Arrays.asList("\\", "bad\\Name", "\\bad\\\\name\\", "\\badname", "badname\\"));

		for (String invalidName : invalidNames) {
			try {
				digraph.createRegion(invalidName);
				fail("Expected failure to create region.");
			} catch (IllegalArgumentException e) {
				// expected
			} catch (BundleException e) {
				fail("Unexpected bundle exception: " + e.getMessage());
			}
		}

	}
Пример #26
0
  public int translateToError(BundleException e) {
    switch (e.getType()) {
      case BundleException.ACTIVATOR_ERROR:
        return LauncherConstants.ACTIVATOR_ERROR;

      case BundleException.DUPLICATE_BUNDLE_ERROR:
        return LauncherConstants.DUPLICATE_BUNDLE;

      case BundleException.RESOLVE_ERROR:
        return LauncherConstants.RESOLVE_ERROR;

      case BundleException.INVALID_OPERATION:
      case BundleException.MANIFEST_ERROR:
      case BundleException.NATIVECODE_ERROR:
      case BundleException.STATECHANGE_ERROR:
      case BundleException.UNSUPPORTED_OPERATION:
      case BundleException.UNSPECIFIED:
      default:
        return LauncherConstants.ERROR;
    }
  }
Пример #27
0
    private Bundle startBundle(URI bundleURI) {
      NavigableMap<URI, Bundle> expect, update;
      Bundle bundle = null;
      do {
        expect = get();
        if (expect.containsKey(bundleURI)) break;

        BundleContext ctx = m_framework.getBundleContext();
        bundle = ctx.getBundle(bundleURI.toASCIIString());
        if (bundle != null) {
          try {
            bundle.update();
          } catch (BundleException e) {
            String msg = e.getMessage();
            throw loggedModularException(e, "Unable to update bundle %s. %s", bundleURI, msg);
          } catch (Throwable t) {
            throw loggedModularException(t, "Unable to update bundle %s", bundleURI);
          }
        } else {
          try {
            bundle = ctx.installBundle(bundleURI.toASCIIString());
          } catch (BundleException e) {
            String msg = e.getMessage();
            throw loggedModularException(e, "Unable to install bundle %s. %s", bundleURI, msg);
          } catch (Throwable t) {
            throw loggedModularException(t, "Unable to instal bundle %s", bundleURI);
          }
        }
        try {
          bundle.start();
        } catch (BundleException e) {
          String msg = e.getMessage();
          throw loggedModularException(e, "Unable to start bundle %s. %s", bundleURI, msg);
        } catch (Throwable t) {
          throw loggedModularException(t, "Unable to start bundle %s", bundleURI);
        }

        update =
            ImmutableSortedMap.<URI, Bundle>naturalOrder()
                .putAll(expect)
                .put(bundleURI, bundle)
                .build();
      } while (!compareAndSet(expect, update));

      return get().get(bundleURI);
    }
Пример #28
0
  /**
   * Installs the bundle corresponding to the model.
   *
   * @param model Model of the bundle to be installed.
   */
  private void installBundle(IPluginModelBase model) {
    try {
      final IResource candidateManifest = model.getUnderlyingResource();
      final IProject project = candidateManifest.getProject();

      URL url = null;
      try {
        url = project.getLocationURI().toURL();
      } catch (MalformedURLException e) {
        // See https://bugs.eclipse.org/bugs/show_bug.cgi?id=354360
        try {
          URI uri = project.getLocationURI();
          IFileStore store = EFS.getStore(uri);
          File file = store.toLocalFile(0, null);
          if (file != null) {
            url = file.toURI().toURL();
          }
        } catch (CoreException ex) {
          // Logging both exceptions just to be sure
          AcceleoCommonPlugin.log(e, false);
          AcceleoCommonPlugin.log(ex, false);
        }
      }

      if (url != null) {
        final String candidateLocationReference =
            REFERENCE_URI_PREFIX
                + URLDecoder.decode(
                    url.toExternalForm(), System.getProperty("file.encoding")); // $NON-NLS-1$

        Bundle bundle = getBundle(candidateLocationReference);

        /*
         * Install the bundle if needed. Note that we'll check bundle dependencies in two phases as
         * even if there cannot be cyclic dependencies through the "require-bundle" header, there
         * could be through the "import package" header.
         */
        if (bundle == null) {
          checkRequireBundleDependencies(model);
          bundle = installBundle(candidateLocationReference);
          setBundleClasspath(project, bundle);
          workspaceInstalledBundles.put(model, bundle);
          checkImportPackagesDependencies(model);
        }
        refreshPackages(
            new Bundle[] {
              bundle,
            });
      }
    } catch (BundleException e) {
      String bundleName = model.getBundleDescription().getName();
      if (!logOnceProjectLoad.contains(bundleName)) {
        logOnceProjectLoad.add(bundleName);
        AcceleoCommonPlugin.log(
            new Status(
                IStatus.WARNING,
                AcceleoCommonPlugin.PLUGIN_ID,
                AcceleoCommonMessages.getString(
                    "WorkspaceUtil.InstallationFailure", //$NON-NLS-1$
                    bundleName,
                    e.getMessage()),
                e));
      }
    } catch (MalformedURLException e) {
      AcceleoCommonPlugin.log(e, false);
    } catch (UnsupportedEncodingException e) {
      AcceleoCommonPlugin.log(e, false);
    }
  }
Пример #29
0
  @Override
  public View getContentView(HttpServletRequest request, PluginContext pluginContext) {
    if (pluginContext.getLocalPath().equals("/edit")) {
      Bundle bundle = getBundleById(request.getParameter("id"));

      BundleConfiguration bundleConfiguration = null;
      try {
        bundleConfiguration = new BundleConfiguration(bundle, configAdmin, metaTypeService);
      } catch (Exception e) {
        message = "Error: " + e.getMessage();
        return new RedirectView(pluginContext.getApplicationPath());
      }

      return new ConfigurationView(bundle, bundleConfiguration, metaTypeService, loader);

    } else if (pluginContext.getLocalPath().equals("/changebundle")) {
      String id = request.getParameter("id");
      Bundle bundle = getBundleById(id);
      try {
        BundleConfiguration bundleConfiguration =
            new BundleConfiguration(bundle, configAdmin, metaTypeService);
        Dictionary<String, String> bundleProperties = new Hashtable<String, String>();

        String[] keys = request.getParameterValues("keyList");
        if (keys != null) {
          for (String key : keys) {
            String value = request.getParameter(key + "Property");
            if (value != null && !value.isEmpty()) {
              bundleProperties.put(key, request.getParameter(key + "Property"));
            }
          }
        }
        String newkey = request.getParameter("newkey");
        if (!newkey.equals("")) {
          bundleProperties.put(newkey, request.getParameter("newkeyProperty"));
        }
        bundleConfiguration.setBundleProperties(bundleProperties);

        return new RedirectView(pluginContext.getApplicationPath() + "/edit?id=" + id);
      } catch (Exception e) {
        message = "Error: " + e.getMessage();
        return new RedirectView(pluginContext.getApplicationPath());
      }
    } else if (pluginContext.getLocalPath().equals("/install")) {
      installBundle(request, pluginContext);
      return new RedirectView(pluginContext.getApplicationPath());
    } else if (pluginContext.getLocalPath().equals("/uninstall")) {
      Bundle bundle = getBundleById(request.getParameter("id"));
      if (bundle != null) {
        try {
          message = "Info: " + bundle.getSymbolicName() + " uninstalled";
          bundle.uninstall();
        } catch (BundleException e) {
          message = "Error: " + e.getMessage();
        }
      }
      return new RedirectView(pluginContext.getApplicationPath());
    } else if (pluginContext.getLocalPath().equals("/update")) {
      Bundle bundle = getBundleById(request.getParameter("id"));
      if (bundle != null) {
        try {
          message = "Info: " + bundle.getSymbolicName() + " updated";
          bundle.update();
        } catch (BundleException e) {
          message = "Error: " + e.getMessage();
        }
      }
      return new RedirectView(pluginContext.getApplicationPath());
    } else if (pluginContext.getLocalPath().equals("/stop")) {
      Bundle bundle = getBundleById(request.getParameter("id"));
      if (bundle != null) {
        try {
          message = "Info: " + bundle.getSymbolicName() + " stoped";
          bundle.stop();
        } catch (BundleException e) {
          message = "Error: " + e.getMessage();
        }
      }
      return new RedirectView(pluginContext.getApplicationPath());
    } else if (pluginContext.getLocalPath().equals("/start")) {
      Bundle bundle = getBundleById(request.getParameter("id"));
      if (bundle != null) {
        try {
          message = "Info: " + bundle.getSymbolicName() + " started";
          bundle.start();
        } catch (BundleException e) {
          message = "Error: " + e.getMessage();
        }
      }
      return new RedirectView(pluginContext.getApplicationPath());
    } else {
      String temp = message;
      message = null;
      return new BundleListView(context, loader, temp);
    }
  }
	public void testBundleCollisionDisconnectedRegions() throws BundleException, InvalidSyntaxException {
		// get the system region
		Region systemRegion = digraph.getRegion(0);
		Collection<Bundle> bundles = new HashSet<Bundle>();
		// create 4 disconnected test regions and install each bundle into each region
		int numRegions = 4;
		String regionName = "IsolatedRegion_";
		for (int i = 0; i < numRegions; i++) {
			Region region = digraph.createRegion(regionName + i);
			// Import the system bundle from the systemRegion
			digraph.connect(region, digraph.createRegionFilterBuilder().allow(RegionFilter.VISIBLE_BUNDLE_NAMESPACE, "(id=0)").build(), systemRegion);
			// must import Boolean services into systemRegion to test
			digraph.connect(systemRegion, digraph.createRegionFilterBuilder().allow(RegionFilter.VISIBLE_SERVICE_NAMESPACE, "(objectClass=java.lang.Boolean)").build(), region);
			for (String location : ALL) {
				Bundle b = bundleInstaller.installBundle(location, region);
				bundles.add(b);
			}
		}

		assertEquals("Wrong number of bundles installed", numRegions * ALL.size(), bundles.size());
		assertTrue("Could not resolve bundles.", bundleInstaller.resolveBundles(bundles.toArray(new Bundle[bundles.size()])));

		// test install of duplicates
		for (int i = 0; i < numRegions; i++) {
			Region region = digraph.getRegion(regionName + i);
			for (String name : ALL) {
				String location = bundleInstaller.getBundleLocation(name);
				try {
					Bundle b = region.installBundle(getName() + "_expectToFail", new URL(location).openStream());
					b.uninstall();
					fail("Expected a bundle exception on duplicate bundle installation: " + name);
				} catch (BundleException e) {
					// expected
					assertEquals("Wrong exception type.", BundleException.DUPLICATE_BUNDLE_ERROR, e.getType());
				} catch (IOException e) {
					fail("Failed to open bunldle location: " + e.getMessage());
				}
			}
		}

		// test update to a duplicate
		for (int i = 0; i < numRegions; i++) {
			Region region = digraph.getRegion(regionName + i);

			Bundle regionPP1 = region.getBundle(PP1, new Version(1, 0, 0));

			String locationSP1 = bundleInstaller.getBundleLocation(SP1);
			try {
				regionPP1.update(new URL(locationSP1).openStream());
				fail("Expected a bundle exception on duplicate bundle update: " + region);
			} catch (BundleException e) {
				// expected
				assertEquals("Wrong exception type.", BundleException.DUPLICATE_BUNDLE_ERROR, e.getType());
			} catch (IOException e) {
				fail("Failed to open bunldle location: " + e.getMessage());
			}

			// now uninstall SP1 and try to update PP1 to SP1 again
			Bundle regionSP1 = region.getBundle(SP1, new Version(1, 0, 0));
			regionSP1.uninstall();

			try {
				regionPP1.update(new URL(locationSP1).openStream());
			} catch (IOException e) {
				fail("Failed to open bunldle location: " + e.getMessage());
			}
		}
	}