@Test
 public void testUpdateExceptionStop() throws Exception {
   Archive<?> assembly1 =
       assembleArchive(
           "update-bundle-stop-exc1",
           "/bundles/update/update-bundle-stop-exc1",
           BundleStopExActivator.class);
   Archive<?> assembly2 =
       assembleArchive("update-bundle-stop-exc2", "/bundles/update/update-bundle-stop-exc2");
   Bundle bundle1 = installBundle(assembly1);
   try {
     bundle1.start();
     assertEquals(Version.parseVersion("1"), bundle1.getVersion());
     try {
       bundle1.update(toInputStream(assembly2));
       fail("Should have thrown a bundle exception.");
     } catch (BundleException be) {
       // good
     }
     assertEquals(
         "Because bundle.stop() throws an exception the update should not have been applied",
         Version.parseVersion("1"),
         bundle1.getVersion());
   } finally {
     bundle1.uninstall();
   }
 }
Example #2
0
 private static Resource getResource(Set<Resource> resources, String bsn, String versionString) {
   for (Resource resource : resources) {
     List<Capability> identities = resource.getCapabilities(IdentityNamespace.IDENTITY_NAMESPACE);
     if (identities != null && identities.size() == 1) {
       Capability idCap = identities.get(0);
       Object id = idCap.getAttributes().get(IdentityNamespace.IDENTITY_NAMESPACE);
       Object version = idCap.getAttributes().get(IdentityNamespace.CAPABILITY_VERSION_ATTRIBUTE);
       if (bsn.equals(id)) {
         if (versionString == null) {
           return resource;
         }
         Version requested = Version.parseVersion(versionString);
         Version current;
         if (version instanceof Version) {
           current = (Version) version;
         } else {
           current = Version.parseVersion((String) version);
         }
         if (requested.equals(current)) {
           return resource;
         }
       }
     }
   }
   return null;
 }
  @Test
  public void testUpdateImportedPackagesRemoved() throws Exception {
    Archive<?> assemblyx =
        assembleArchive("bundlex", "/bundles/update/update-bundlex", ObjectX.class);
    Archive<?> assembly1 =
        assembleArchive("bundle1", "/bundles/update/update-bundle1", ObjectA.class);
    Archive<?> assembly2 =
        assembleArchive("bundle2", "/bundles/update/update-bundle101", ObjectB.class);

    Bundle bundleA = installBundle(assembly1);
    Bundle bundleX = installBundle(assemblyx);
    try {
      BundleContext systemContext = getFramework().getBundleContext();
      int beforeCount = systemContext.getBundles().length;

      bundleA.start();
      bundleX.start();

      Class<?> cls = bundleX.loadClass(ObjectX.class.getName());
      cls.newInstance();

      assertBundleState(Bundle.ACTIVE, bundleA.getState());
      assertBundleState(Bundle.ACTIVE, bundleX.getState());
      assertEquals(Version.parseVersion("1.0.0"), bundleA.getVersion());
      assertEquals("update-bundle1", bundleA.getSymbolicName());
      assertLoadClass(bundleA, ObjectA.class.getName());
      assertLoadClassFail(bundleA, ObjectB.class.getName());
      assertLoadClass(bundleX, ObjectA.class.getName());

      bundleA.update(toInputStream(assembly2));
      assertBundleState(Bundle.ACTIVE, bundleA.getState());
      assertBundleState(Bundle.ACTIVE, bundleX.getState());
      assertEquals(Version.parseVersion("1.0.1"), bundleA.getVersion());
      // Assembly X depends on a package in the bundle, this should still be available
      assertLoadClass(bundleX, ObjectA.class.getName());

      getSystemContext().addFrameworkListener(this);
      getPackageAdmin().refreshPackages(new Bundle[] {bundleA});
      assertFrameworkEvent(FrameworkEvent.ERROR, bundleX, BundleException.class);
      assertFrameworkEvent(
          FrameworkEvent.PACKAGES_REFRESHED, getSystemContext().getBundle(0), null);

      assertBundleState(Bundle.ACTIVE, bundleA.getState());
      // Bundle X is installed because it cannot be resolved any more
      assertBundleState(Bundle.INSTALLED, bundleX.getState());
      assertEquals(Version.parseVersion("1.0.1"), bundleA.getVersion());
      // Nobody depends on the packages, so we can update them straight away
      assertLoadClass(bundleA, ObjectB.class.getName());
      assertLoadClassFail(bundleA, ObjectA.class.getName());

      int afterCount = systemContext.getBundles().length;
      assertEquals("Bundle count", beforeCount, afterCount);
    } finally {
      getSystemContext().removeFrameworkListener(this);
      bundleX.uninstall();
      bundleA.uninstall();
    }
  }
Example #4
0
  /**
   * Look at the argument URL for the workspace's version information. Return that version if found
   * and null otherwise.
   */
  private static Version readWorkspaceVersion(URL workspace) {
    File versionFile = getVersionFile(workspace, false);
    if (versionFile == null || !versionFile.exists()) {
      return null;
    }

    try {
      // Although the version file is not spec'ed to be a Java properties
      // file, it happens to follow the same format currently, so using
      // Properties to read it is convenient.
      Properties props = new Properties();
      FileInputStream is = new FileInputStream(versionFile);
      try {
        props.load(is);
      } finally {
        is.close();
      }

      String versionString = props.getProperty(WORKSPACE_CHECK_REFERENCE_BUNDLE_NAME);
      if (versionString != null) {
        return Version.parseVersion(versionString);
      }
      versionString = props.getProperty(WORKSPACE_CHECK_REFERENCE_BUNDLE_NAME_LEGACY);
      if (versionString != null) {
        return Version.parseVersion(versionString);
      }
      return null;
    } catch (IOException e) {
      IDEWorkbenchPlugin.log(
          "Could not read version file " + versionFile,
          new Status( //$NON-NLS-1$
              IStatus.ERROR,
              IDEWorkbenchPlugin.IDE_WORKBENCH,
              IStatus.ERROR,
              e.getMessage() == null ? "" : e.getMessage(), // $NON-NLS-1$
              e));
      return null;
    } catch (IllegalArgumentException e) {
      IDEWorkbenchPlugin.log(
          "Could not parse version in " + versionFile,
          new Status( //$NON-NLS-1$
              IStatus.ERROR,
              IDEWorkbenchPlugin.IDE_WORKBENCH,
              IStatus.ERROR,
              e.getMessage() == null ? "" : e.getMessage(), // $NON-NLS-1$
              e));
      return null;
    }
  }
  /**
   * Construct a {@link StandardDeploymentIdentity} with the given type, name, and version.
   *
   * @param type the type of the deployed artefact
   * @param symbolicName the symbolic name of the deployed artefact
   * @param version the version of the deployed artefact
   */
  public StandardDeploymentIdentity(String type, String symbolicName, String version) {
    this.type = type;
    this.symbolicName = symbolicName;

    // Normalise the version to ensure accurate comparisons.
    this.version = Version.parseVersion(version).toString();
  }
  private static Object convertValueIfNecessary(Object value, String type) throws Exception {
    if (type == null) {
      // No conversion needed
    } else if ("String".equals(type)) {
      // No conversion needed
    } else if ("Version".equals(type)) {
      value = Version.parseVersion(((String) value).trim());
    } else if ("Long".equals(type)) {
      value = Long.parseLong(((String) value).trim());
    } else if ("Double".equals(type)) {
      value = Double.parseDouble(((String) value).trim());
    } else if (type.startsWith("List<")) {
      String scalarType = type.substring("List<".length(), type.length() - 1);
      StringTokenizer values = new StringTokenizer((String) value, ",\\", true);

      ArrayList<Object> list = new ArrayList<Object>();
      String t = null;
      String v = null;
      while (t != null || values.hasMoreTokens()) {
        if (t == null) t = values.nextToken();
        if (t.equals("\\")) {
          if (values.hasMoreTokens()) {
            t = values.nextToken();
            if (t.equals("\\")) {
              v = v == null ? "\\" : v + "\\";
              t = null;
            } else if (t.equals(",")) {
              v = v == null ? "," : v + ",";
              t = null;
            } else {
              v = v == null ? "\\" : v + "\\";
            }
          } else {
            v = v == null ? "\\" : v + "\\";
            t = null;
          }
        } else if (t.equals(",")) {
          if (v == null) {
            list.add(convertValueIfNecessary("", scalarType));
          } else if (v.endsWith("\\")) {
            v += ",";
          } else {
            list.add(convertValueIfNecessary(v.trim(), scalarType));
            v = null;
          }
          t = null;
        } else {
          v = v == null ? t : v + t;
          t = null;
        }
      }
      if (v != null) {
        list.add(convertValueIfNecessary(v.trim(), scalarType));
      }
      value = list;
    } else {
      throw new Exception("Unknown or unsupported type: " + type);
    }
    return value;
  }
  private String getConfigInfoFromManifest(String configType, IPath portalDir) {
    File implJar = portalDir.append("/WEB-INF/lib/portal-impl.jar").toFile();

    String version = null;
    String serverInfo = null;

    if (implJar.exists()) {
      try (JarFile jar = new JarFile(implJar)) {
        Manifest manifest = jar.getManifest();

        Attributes attributes = manifest.getMainAttributes();

        version = attributes.getValue("Liferay-Portal-Version");
        serverInfo = attributes.getValue("Liferay-Portal-Server-Info");

        if (CoreUtil.compareVersions(Version.parseVersion(version), MANIFEST_VERSION_REQUIRED)
            < 0) {
          version = null;
          serverInfo = null;
        }
      } catch (IOException e) {
        LiferayServerCore.logError(e);
      }
    }

    if (configType.equals(CONFIG_TYPE_VERSION)) {
      return version;
    }

    if (configType.equals(CONFIG_TYPE_SERVER)) {
      return serverInfo;
    }

    return null;
  }
Example #8
0
  /**
   * Given a precise version create a version range suitable for an import package specification.
   * Currently an input version of M.N.U.Q will result in an output range "[M.N.U.Q, M+1)" following
   * the version usage recommended by OSGi (a package that is not backwards compatible must
   * increment the major number in its version number).
   *
   * @param version an OSGi compatibel version on string form.
   * @return a quoted version range starting with the given version (inclusive) ending with the next
   *     major version (exclusive). If the specified version is <code>null</code> or an empty string
   *     a <code>null</code> is returned.
   */
  private static String toImportRange(final String version) throws IllegalArgumentException {
    if (null == version || 0 == version.length()) {
      return null;
    }

    final Version vStart = Version.parseVersion(version);
    final Version vEnd = new Version(vStart.getMajor() + 1, 0, 0, null);
    return "\"[" + vStart.toString() + "," + vEnd.toString() + ")\"";
  }
  @Test
  public void testUpdate() throws Exception {
    Archive<?> assembly1 =
        assembleArchive("bundle1", "/bundles/update/update-bundle1", ObjectA.class);
    Archive<?> assembly2 =
        assembleArchive("bundle2", "/bundles/update/update-bundle101", ObjectB.class);
    Archive<?> assemblyy =
        assembleArchive("bundley", "/bundles/update/update-bundley", ObjectY.class);
    Bundle bundle1 = installBundle(assembly1);
    Bundle bundleY = installBundle(assemblyy);
    try {
      BundleContext systemContext = getFramework().getBundleContext();
      int beforeCount = systemContext.getBundles().length;

      bundleY.start();
      assertBundleState(Bundle.ACTIVE, bundleY.getState());

      bundle1.start();
      assertBundleState(Bundle.ACTIVE, bundle1.getState());
      assertEquals(Version.parseVersion("1.0.0"), bundle1.getVersion());
      assertEquals("update-bundle1", bundle1.getSymbolicName());
      assertLoadClass(bundle1, ObjectA.class.getName());
      assertLoadClassFail(bundle1, ObjectB.class.getName());

      Class<?> clsY = bundleY.loadClass(ObjectY.class.getName());

      bundle1.update(toInputStream(assembly2));
      assertBundleState(Bundle.ACTIVE, bundle1.getState());
      assertEquals(Version.parseVersion("1.0.1"), bundle1.getVersion());
      // Nobody depends on the packages, so we can update them straight away
      assertLoadClass(bundle1, ObjectB.class.getName());
      assertLoadClassFail(bundle1, ObjectA.class.getName());

      assertSame(clsY, bundleY.loadClass(ObjectY.class.getName()));
      assertBundleState(Bundle.ACTIVE, bundleY.getState());

      int afterCount = systemContext.getBundles().length;
      assertEquals("Bundle count", beforeCount, afterCount);
    } finally {
      bundleY.uninstall();
      bundle1.uninstall();
    }
  }
Example #10
0
  private void parseAttribute(String token) {
    int index = token.indexOf(Constants.ATTRIBUTE_EQUALS);
    String attributeName = token.substring(0, index).trim();
    if (attributeName.length() == 0) return;

    Object value = token.substring(index + Constants.ATTRIBUTE_EQUALS.length()).trim();

    if (attributeName.equals(Constants.VERSION_ATTRIBUTE))
      version = Version.parseVersion((String) value);
    attributes.put(attributeName, value);
  }
  @Test
  public void testUpdateReadError() throws Exception {
    Archive<?> assembly1 =
        assembleArchive("bundle1", "/bundles/update/update-bundle1", ObjectA.class);

    Bundle bundle = installBundle(assembly1);
    try {
      BundleContext systemContext = getFramework().getBundleContext();
      int beforeCount = systemContext.getBundles().length;

      bundle.start();
      assertBundleState(Bundle.ACTIVE, bundle.getState());
      assertEquals(Version.parseVersion("1.0.0"), bundle.getVersion());
      assertEquals("update-bundle1", bundle.getSymbolicName());
      assertLoadClass(bundle, ObjectA.class.getName());
      assertLoadClassFail(bundle, ObjectB.class.getName());

      InputStream ismock = mock(InputStream.class);
      when(ismock.read()).thenThrow(new IOException());
      when(ismock.read((byte[]) Mockito.anyObject())).thenThrow(new IOException());
      when(ismock.read((byte[]) Mockito.anyObject(), Mockito.anyInt(), Mockito.anyInt()))
          .thenThrow(new IOException());

      try {
        bundle.update(ismock);
        fail("Should have thrown a BundleException as the InputStream is unreadable");
      } catch (BundleException e) {
        // good
      }
      assertBundleState(Bundle.ACTIVE, bundle.getState());
      assertEquals(Version.parseVersion("1.0.0"), bundle.getVersion());
      assertEquals("update-bundle1", bundle.getSymbolicName());
      assertLoadClass(bundle, ObjectA.class.getName());
      assertLoadClassFail(bundle, ObjectB.class.getName());

      int afterCount = systemContext.getBundles().length;
      assertEquals("Bundle count", beforeCount, afterCount);
    } finally {
      bundle.uninstall();
    }
  }
Example #12
0
 private String getTestApplication(EquinoxInstallationDescription testRuntime) {
   if (useUIHarness) {
     ArtifactDescriptor systemBundle = testRuntime.getSystemBundle();
     Version osgiVersion = Version.parseVersion(systemBundle.getKey().getVersion());
     if (osgiVersion.compareTo(EquinoxInstallationDescription.EQUINOX_VERSION_3_3_0) < 0) {
       return "org.sonatype.tycho.surefire.osgibooter.uitest32";
     } else {
       return "org.sonatype.tycho.surefire.osgibooter.uitest";
     }
   } else {
     return "org.sonatype.tycho.surefire.osgibooter.headlesstest";
   }
 }
  @Test
  public void testUpdateExceptionStart() throws Exception {
    Archive<?> assembly1 =
        assembleArchive("update-bundle-start-exc1", "/bundles/update/update-bundle-start-exc1");
    Archive<?> assembly2 =
        assembleArchive(
            "update-bundle-start-exc2",
            "/bundles/update/update-bundle-start-exc2",
            BundleStartExActivator.class);
    Bundle bundle1 = installBundle(assembly1);
    try {
      bundle1.start();
      assertEquals(Version.parseVersion("1"), bundle1.getVersion());

      getSystemContext().addFrameworkListener(this);
      bundle1.update(toInputStream(assembly2));
      assertFrameworkEvent(FrameworkEvent.ERROR, bundle1, BundleException.class);
      assertEquals(Version.parseVersion("2"), bundle1.getVersion());
    } finally {
      getSystemContext().removeFrameworkListener(this);
      bundle1.uninstall();
    }
  }
 private void verifyResouceA(XResource resourceA) {
   List<Capability> caps = resourceA.getCapabilities("test");
   Assert.assertEquals(1, caps.size());
   Map<String, Object> atts = caps.get(0).getAttributes();
   List<String> keys = new ArrayList<String>(atts.keySet());
   Assert.assertEquals(6, keys.size());
   Assert.assertEquals("test", keys.get(0));
   Assert.assertEquals("aName", atts.get(keys.get(0)));
   Assert.assertEquals("version", keys.get(1));
   Assert.assertEquals(Version.parseVersion("1.1"), atts.get(keys.get(1)));
   Assert.assertEquals("long", keys.get(2));
   Assert.assertEquals(Long.valueOf("100"), atts.get(keys.get(2)));
   Assert.assertEquals("string", keys.get(3));
   Assert.assertEquals("aString", atts.get(keys.get(3)));
   Assert.assertEquals("version.list", keys.get(4));
   List<Version> versions =
       Arrays.asList(
           Version.parseVersion("1.0"), Version.parseVersion("1.1"), Version.parseVersion("1.2"));
   Assert.assertEquals(versions, atts.get(keys.get(4)));
   Assert.assertEquals("string.list2", keys.get(5));
   List<String> strings =
       Arrays.asList("a\"quote", "a,comma", " aSpace ", "\"start", ",start", "end\"", "end,");
   Assert.assertEquals(strings, atts.get(keys.get(5)));
 }
 @Override
 public Object getValue(
     EObject object, EStructuralFeature feature, Object value, String loadedVersion) {
   if (Version.parseVersion(loadedVersion)
           .compareTo(DiagramRepresentationsFileMigrationParticipantV700.MIGRATION_VERSION)
       < 0) {
     DiagramRepresentationsFileMigrationParticipantV700
         representationsFileMigrationParticipantV700 =
             new DiagramRepresentationsFileMigrationParticipantV700();
     Object result = representationsFileMigrationParticipantV700.getValue(object, feature, value);
     if (result != null) {
       return result;
     }
   }
   return super.getValue(object, feature, value, loadedVersion);
 }
  @Override
  public EClassifier getType(EPackage ePackage, String name, String loadedVersion) {

    if (Version.parseVersion(loadedVersion)
            .compareTo(DiagramRepresentationsFileMigrationParticipantV690.MIGRATION_VERSION)
        < 0) {
      DiagramRepresentationsFileMigrationParticipantV690
          representationsFileMigrationParticipantV690 =
              new DiagramRepresentationsFileMigrationParticipantV690();
      EClassifier classifier = representationsFileMigrationParticipantV690.getType(ePackage, name);
      if (classifier != null) {
        return classifier;
      }
    }

    return super.getType(ePackage, name, loadedVersion);
  }
Example #17
0
  public static Version readVersionFile(File versionInfoFile) {
    String versionContents = FileUtil.readContents(versionInfoFile);

    if (CoreUtil.isNullOrEmpty(versionContents)) {
      return Version.emptyVersion;
    }

    Version version = null;
    ;

    try {
      version = Version.parseVersion(versionContents.trim());
    } catch (NumberFormatException e) {
      version = Version.emptyVersion;
    }

    return version;
  }
  /** Returns approximate target platform version. */
  public static Version getEclipseVersion() {
    String location = EnvironmentUtil.getTargetPlatforn();

    DirectoryScanner ds = new DirectoryScanner();
    ds.setBasedir(new File(location, "plugins"));
    ds.setIncludes(new String[] {"org.eclipse.osgi_*.jar"});
    ds.scan();

    String[] files = ds.getIncludedFiles();
    if (files == null || files.length < 1) {
      throw new IllegalStateException(
          "Unable to determine version of the test target platform " + location);
    }

    String version =
        files[0].substring("org.eclipse.osgi_".length(), files[0].length() - ".jar".length());

    return Version.parseVersion(version);
  }
 @SuppressWarnings("unchecked")
 public static Long getBundleId(String symbolicName, Version version) throws IOException {
   Long result = null;
   cli.sendLine("/subsystem=osgi:read-resource(include-runtime=true,recursive=true)");
   CLIOpResult cliresult = cli.readAllAsOpResult(WAIT_TIMEOUT, WAIT_LINETIMEOUT);
   assertTrue(cliresult.isIsOutcomeSuccess());
   Map<String, Object> bundlemap = cliresult.getNamedResultAsMap("bundle");
   for (Entry<String, Object> entry : bundlemap.entrySet()) {
     String auxid = entry.getKey();
     Map<String, Object> bundle = (Map<String, Object>) entry.getValue();
     if (bundle.get("symbolic-name").equals(symbolicName)) {
       Version auxver = Version.parseVersion((String) bundle.get("version"));
       if (version == null || version.equals(auxver)) {
         result = Long.valueOf(auxid);
         break;
       }
     }
   }
   return result;
 }
 private BundleDescription[] getPluginModels() {
   ArrayList list = new ArrayList();
   State state = TargetPlatformHelper.getState();
   IProductPlugin[] plugins = product.getPlugins();
   for (int i = 0; i < plugins.length; i++) {
     BundleDescription bundle = null;
     String v = plugins[i].getVersion();
     if (v != null && v.length() > 0) {
       bundle = state.getBundle(plugins[i].getId(), Version.parseVersion(v));
     }
     // if there's no version, just grab a bundle like before
     if (bundle == null) {
       bundle = state.getBundle(plugins[i].getId(), null);
     }
     if (bundle != null) {
       list.add(bundle);
     }
   }
   Object[] bundleArray = list.toArray(new BundleDescription[list.size()]);
   return (BundleDescription[]) bundleArray;
 }
  protected BundleCapability buildNativeCapabilites() {
    String osArchitecture = (String) m_configMap.get(FelixConstants.FRAMEWORK_PROCESSOR);
    String osName = (String) m_configMap.get(FelixConstants.FRAMEWORK_OS_NAME);
    String osVersion = (String) m_configMap.get(FelixConstants.FRAMEWORK_OS_VERSION);
    String userLang = (String) m_configMap.get(FelixConstants.FRAMEWORK_LANGUAGE);
    Map<String, Object> attributes = new HashMap<String, Object>();

    // Add all startup properties so we can match selection-filters
    attributes.putAll(m_configMap);

    if (osArchitecture != null) {
      attributes.put(
          NativeNamespace.CAPABILITY_PROCESSOR_ATTRIBUTE,
          NativeLibraryClause.getProcessorWithAliases(osArchitecture));
    }

    if (osName != null) {
      attributes.put(
          NativeNamespace.CAPABILITY_OSNAME_ATTRIBUTE,
          NativeLibraryClause.getOsNameWithAliases(osName));
    }

    if (osVersion != null) {
      osVersion = NativeLibraryClause.formatOSVersion(osVersion);
      attributes.put(
          NativeNamespace.CAPABILITY_OSVERSION_ATTRIBUTE, Version.parseVersion(osVersion));
    }

    if (userLang != null) {
      attributes.put(NativeNamespace.CAPABILITY_LANGUAGE_ATTRIBUTE, userLang);
    }

    return new BundleCapabilityImpl(
        getRevision(),
        NativeNamespace.NATIVE_NAMESPACE,
        Collections.<String, String>emptyMap(),
        attributes);
  }
Example #22
0
 protected void findBundlesWithOptionalPackagesToRefresh(Set<Bundle> toRefresh) {
   // First pass: include all bundles contained in these features
   Set<Bundle> bundles = new HashSet<Bundle>(Arrays.asList(bundleContext.getBundles()));
   bundles.removeAll(toRefresh);
   if (bundles.isEmpty()) {
     return;
   }
   // Second pass: for each bundle, check if there is any unresolved optional package that could be
   // resolved
   Map<Bundle, List<Clause>> imports = new HashMap<Bundle, List<Clause>>();
   for (Iterator<Bundle> it = bundles.iterator(); it.hasNext(); ) {
     Bundle b = it.next();
     String importsStr = (String) b.getHeaders().get(Constants.IMPORT_PACKAGE);
     List<Clause> importsList = getOptionalImports(importsStr);
     if (importsList.isEmpty()) {
       it.remove();
     } else {
       imports.put(b, importsList);
     }
   }
   if (bundles.isEmpty()) {
     return;
   }
   // Third pass: compute a list of packages that are exported by our bundles and see if
   //             some exported packages can be wired to the optional imports
   List<Clause> exports = new ArrayList<Clause>();
   for (Bundle b : toRefresh) {
     if (b.getState() != Bundle.UNINSTALLED) {
       String exportsStr = (String) b.getHeaders().get(Constants.EXPORT_PACKAGE);
       if (exportsStr != null) {
         Clause[] exportsList = Parser.parseHeader(exportsStr);
         exports.addAll(Arrays.asList(exportsList));
       }
     }
   }
   for (Iterator<Bundle> it = bundles.iterator(); it.hasNext(); ) {
     Bundle b = it.next();
     List<Clause> importsList = imports.get(b);
     for (Iterator<Clause> itpi = importsList.iterator(); itpi.hasNext(); ) {
       Clause pi = itpi.next();
       boolean matching = false;
       for (Clause pe : exports) {
         if (pi.getName().equals(pe.getName())) {
           String evStr = pe.getAttribute(Constants.VERSION_ATTRIBUTE);
           String ivStr = pi.getAttribute(Constants.VERSION_ATTRIBUTE);
           Version exported = evStr != null ? Version.parseVersion(evStr) : Version.emptyVersion;
           VersionRange imported =
               ivStr != null ? VersionRange.parseVersionRange(ivStr) : VersionRange.ANY_VERSION;
           if (imported.contains(exported)) {
             matching = true;
             break;
           }
         }
       }
       if (!matching) {
         itpi.remove();
       }
     }
     if (importsList.isEmpty()) {
       it.remove();
     }
   }
   toRefresh.addAll(bundles);
 }
Example #23
0
  void rollback(Patch patch, boolean force) throws PatchException {
    Result result = patch.getResult();
    if (result == null) {
      throw new PatchException("Patch " + patch.getId() + " is not installed");
    }
    Bundle[] allBundles = bundleContext.getBundles();
    List<BundleUpdate> badUpdates = new ArrayList<BundleUpdate>();
    for (BundleUpdate update : result.getUpdates()) {
      boolean found = false;
      Version v = Version.parseVersion(update.getNewVersion());
      for (Bundle bundle : allBundles) {
        if (stripSymbolicName(bundle.getSymbolicName())
                .equals(stripSymbolicName(update.getSymbolicName()))
            && bundle.getVersion().equals(v)) {
          found = true;
          break;
        }
      }
      if (!found) {
        badUpdates.add(update);
      }
    }
    if (!badUpdates.isEmpty() && !force) {
      StringBuilder sb = new StringBuilder();
      sb.append("Unable to rollback patch ")
          .append(patch.getId())
          .append(" because of the following missing bundles:\n");
      for (BundleUpdate up : badUpdates) {
        sb.append("\t")
            .append(up.getSymbolicName())
            .append("/")
            .append(up.getNewVersion())
            .append("\n");
      }
      throw new PatchException(sb.toString());
    }

    Map<Bundle, String> toUpdate = new HashMap<Bundle, String>();
    for (BundleUpdate update : result.getUpdates()) {
      Version v = Version.parseVersion(update.getNewVersion());
      for (Bundle bundle : allBundles) {
        if (stripSymbolicName(bundle.getSymbolicName())
                .equals(stripSymbolicName(update.getSymbolicName()))
            && bundle.getVersion().equals(v)) {
          toUpdate.put(bundle, update.getPreviousLocation());
        }
      }
    }
    try {
      applyChanges(toUpdate);
      writeFully(
          new File(System.getProperty("karaf.base"), "etc/startup.properties"),
          ((ResultImpl) result).getStartup());
      writeFully(
          new File(System.getProperty("karaf.base"), "etc/overrides.properties"),
          ((ResultImpl) result).getOverrides());
    } catch (Exception e) {
      throw new PatchException(
          "Unable to rollback patch " + patch.getId() + ": " + e.getMessage(), e);
    }
    ((PatchImpl) patch).setResult(null);
    File file = new File(patchDir, result.getPatch().getId() + ".patch.result");
    file.delete();
  }
 /**
  * Returns the version for a given bundle manifest header.
  *
  * @param bundle OSGi bundle
  * @param header bundle manifest header
  * @return the header value
  */
 public static Version getHeaderAsVersion(Bundle bundle, String header) {
   Assert.notNull(bundle);
   return Version.parseVersion(bundle.getHeaders().get(header));
 }
  @Test
  public void testUpdateImportedPackages() throws Exception {
    Archive<?> assemblyx =
        assembleArchive("bundlex", "/bundles/update/update-bundlex", ObjectX.class);
    Archive<?> assembly1 =
        assembleArchive(
            "bundle1", new String[] {"/bundles/update/update-bundle1", "/bundles/update/classes1"});
    Archive<?> assembly2 =
        assembleArchive(
            "bundle2",
            new String[] {"/bundles/update/update-bundle102", "/bundles/update/classes2"});

    Bundle bundle1 = installBundle(assembly1);
    Bundle bundleX = installBundle(assemblyx);
    try {
      BundleContext systemContext = getFramework().getBundleContext();
      int beforeCount = systemContext.getBundles().length;

      bundle1.start();
      bundleX.start();

      assertBundleState(Bundle.ACTIVE, bundle1.getState());
      assertBundleState(Bundle.ACTIVE, bundleX.getState());
      assertEquals(Version.parseVersion("1.0.0"), bundle1.getVersion());
      assertEquals("update-bundle1", bundle1.getSymbolicName());
      assertLoadClass(bundle1, ObjectA.class.getName());
      assertLoadClassFail(bundle1, ObjectA2.class.getName());
      assertLoadClass(bundleX, ObjectA.class.getName());
      assertLoadClassFail(bundleX, ObjectA2.class.getName());

      Class<?> cls = bundleX.loadClass(ObjectX.class.getName());
      Object x1 = cls.newInstance();
      assertEquals("ObjectX contains reference: ObjectA", x1.toString());

      bundle1.update(toInputStream(assembly2));
      assertBundleState(Bundle.ACTIVE, bundle1.getState());
      assertBundleState(Bundle.ACTIVE, bundleX.getState());
      assertEquals(Version.parseVersion("1.0.2"), bundle1.getVersion());
      // Bundle A should see the new version of the packages
      assertLoadClass(bundle1, ObjectA2.class.getName());
      assertLoadClassFail(bundle1, ObjectA.class.getName());
      // Bundle X should still see the old packages of bundle A
      assertLoadClass(bundleX, ObjectA.class.getName());
      assertLoadClassFail(bundleX, ObjectA2.class.getName());
      assertSame(cls, bundleX.loadClass(ObjectX.class.getName()));

      FrameworkWiring frameworkWiring = getFramework().adapt(FrameworkWiring.class);
      frameworkWiring.refreshBundles(Arrays.asList(bundle1), this);
      assertFrameworkEvent(
          FrameworkEvent.PACKAGES_REFRESHED, getSystemContext().getBundle(0), null);

      assertBundleState(Bundle.ACTIVE, bundle1.getState());
      assertBundleState(Bundle.ACTIVE, bundleX.getState());
      assertEquals(Version.parseVersion("1.0.2"), bundle1.getVersion());
      assertLoadClass(bundle1, ObjectA2.class.getName());
      assertLoadClassFail(bundle1, ObjectA.class.getName());
      assertLoadClass(bundleX, ObjectA2.class.getName());
      assertLoadClassFail(bundleX, ObjectA.class.getName());

      Class<?> cls2 = bundleX.loadClass(ObjectX.class.getName());
      assertNotSame("Should have loaded a new class", cls, cls2);
      Object x2 = cls2.newInstance();
      assertEquals("ObjectX contains reference: ObjectA2", x2.toString());

      int afterCount = systemContext.getBundles().length;
      assertEquals("Bundle count", beforeCount, afterCount);
    } finally {
      bundleX.uninstall();
      bundle1.uninstall();
    }
  }
  private List<List<String>> getDiagnosticItems() {
    List<List<String>> result = new ArrayList<List<String>>();

    /* system information from JVM */
    ArrayList<String> infos = getSystemInformation();
    DiagnosticFactory.addDiagnosticItemToList(result, "Server", "", DiagnosticFactory.STATUS_TITLE);
    DiagnosticFactory.addDiagnosticItemToList(
        result, "Runtime Environment", infos.get(0), DiagnosticFactory.STATUS_INFO);
    DiagnosticFactory.addDiagnosticItemToList(
        result, "Application Directory", infos.get(1), DiagnosticFactory.STATUS_INFO);
    DiagnosticFactory.addDiagnosticItemToList(
        result,
        "JVM Memory Status",
        "Max: "
            + infos.get(2)
            + ", Reserved: "
            + infos.get(3)
            + ", Currently Used: "
            + infos.get(4),
        DiagnosticFactory.STATUS_INFO);
    DiagnosticFactory.addDiagnosticItemToList(
        result, "JVM Locale", infos.get(11), DiagnosticFactory.STATUS_INFO);
    DiagnosticFactory.addDiagnosticItemToList(
        result, "Operating System", infos.get(6), DiagnosticFactory.STATUS_INFO);
    DiagnosticFactory.addDiagnosticItemToList(
        result, "Architecture", infos.get(5), DiagnosticFactory.STATUS_INFO);
    DiagnosticFactory.addDiagnosticItemToList(
        result, "#CPUs available to JVM", infos.get(12), DiagnosticFactory.STATUS_INFO);
    DiagnosticFactory.addDiagnosticItemToList(
        result,
        "OS Country / Timezone",
        infos.get(9) + " / " + infos.get(10),
        DiagnosticFactory.STATUS_INFO);
    DiagnosticFactory.addDiagnosticItemToList(
        result,
        "Host Address / Name",
        infos.get(13) + " / " + infos.get(14),
        DiagnosticFactory.STATUS_INFO);

    IDiagnostic[] diagnosticServices = DiagnosticFactory.getDiagnosticProviders();
    for (IDiagnostic diagnosticService : diagnosticServices) {
      diagnosticService.addDiagnosticItemToList(result);
    }

    // system properties
    List<String> properties = new ArrayList<String>();
    for (Object property : System.getProperties().keySet()) {
      properties.add(property + "");
    }
    Collections.sort(properties);
    String sysprops = "";
    sysprops +=
        "<a href=\"#\" onClick=\"javascript:toggle_visibility('sysprops'); return false;\">(show / hide)</a>";
    sysprops +=
        "<div id=\"sysprops\" style=\"width:600px; margin: 0px; padding: 0px; display: none; word-wrap: break-word;\">";
    sysprops += "<dl>";
    for (String property : properties) {
      sysprops += "<dt>" + property + ":</b></dt><dd>" + System.getProperty(property) + "</dd>";
    }
    sysprops += "</dl>";
    sysprops += "</div>";
    DiagnosticFactory.addDiagnosticItemToList(
        result, "System properties", sysprops, DiagnosticFactory.STATUS_INFO);

    // environment
    List<String> envKeys = new ArrayList<String>();
    for (String envKey : System.getenv().keySet()) {
      envKeys.add(envKey);
    }
    Collections.sort(envKeys);
    String envList = "";
    envList +=
        "<a href=\"#\" onClick=\"javascript:toggle_visibility('env'); return false;\">(show / hide)</a>";
    envList +=
        "<div id=\"env\" style=\"width:600px; margin: 0px; padding: 0px; display: none; word-wrap: break-word;\">";
    envList += "<dl>";
    for (String envKey : envKeys) {
      envList += "<dt>" + envKey + ":</b></dt><dd>" + System.getenv(envKey) + "</dd>";
    }
    envList += "</dl>";
    envList += "</div>";
    DiagnosticFactory.addDiagnosticItemToList(
        result, "Environment variables", envList, DiagnosticFactory.STATUS_INFO);

    DiagnosticFactory.addDiagnosticItemToList(
        result, "Version", "", DiagnosticFactory.STATUS_TITLE);
    Version v = Version.emptyVersion;
    IProduct product = Platform.getProduct();
    String productId = "n/a";
    String productName = "n/a";
    String application = "n/a";
    String definingBundle = "n/a";
    if (product != null) {
      productId = product.getId();
      productName = product.getName();
      application = product.getApplication();
      definingBundle = product.getDefiningBundle().getSymbolicName();
      v = Version.parseVersion("" + product.getDefiningBundle().getHeaders().get("Bundle-Version"));
    }
    DiagnosticFactory.addDiagnosticItemToList(
        result, "Product ID", productId, DiagnosticFactory.STATUS_INFO);
    DiagnosticFactory.addDiagnosticItemToList(
        result, "Product Name", productName, DiagnosticFactory.STATUS_INFO);
    DiagnosticFactory.addDiagnosticItemToList(
        result, "Application", application, DiagnosticFactory.STATUS_INFO);
    DiagnosticFactory.addDiagnosticItemToList(
        result, "Defining Bundle", definingBundle, DiagnosticFactory.STATUS_INFO);
    DiagnosticFactory.addDiagnosticItemToList(
        result, "Defining Bundle Version", v.toString(), DiagnosticFactory.STATUS_INFO);

    DiagnosticFactory.addDiagnosticItemToList(
        result, "Change values", "", DiagnosticFactory.STATUS_TITLE);
    return result;
  }
  private void doHtmlResponse(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String errorMsg = "";

    /* run garbage collection for better estimation of current memory usage */
    String doGc = req.getParameter("gc");
    if (StringUtility.hasText(doGc)) {
      System.gc();
      errorMsg = "<font color='blue'> System.gc() triggered.</font>";
    }

    List<List<String>> result = getDiagnosticItems();

    IDiagnostic[] diagnosticServices = DiagnosticFactory.getDiagnosticProviders();
    for (IDiagnostic diagnosticService : diagnosticServices) {
      if (CollectionUtility.hasElements(diagnosticService.getPossibleActions())) {
        diagnosticService.addSubmitButtonsHTML(result);
      }
    }
    DiagnosticFactory.addDiagnosticItemToList(
        result, "System.gc()", "", "<input type='checkbox' name='gc' value='yes'/>");

    String diagnosticHTML = getDiagnosticItemsHTML(result);

    String title = "unknown";
    Version version = Version.emptyVersion;
    IProduct product = Platform.getProduct();
    if (product != null) {
      title = product.getName();
      version =
          Version.parseVersion("" + product.getDefiningBundle().getHeaders().get("Bundle-Version"));
    }

    resp.setContentType("text/html");
    ServletOutputStream out = resp.getOutputStream();
    out.println("<html>");
    out.println("<head>");
    out.println("<title>" + title + "</title>");
    out.println("<style>");
    out.println("body {font-family: sans-serif; font-size: 12; background-color : #F6F6F6;}");
    out.println("a,a:VISITED {color: #6666ff;text-decoration: none;}");
    out.println("table {font-size: 12; empty-cells: show;}");
    out.println(
        "th {text-align: left;vertical-align: top; padding-left: 2; background-color : #cccccc;}");
    out.println("td {text-align: left;vertical-align: top; padding-left: 2;}");
    out.println("p {margin-top: 4; margin-bottom: 4; padding-top: 4; padding-bottom: 4;}");
    out.println("dt {font-weight: bold;}");
    out.println("dd {margin-left: 20px; margin-bottom: 3px;}");
    out.println(".copyright {font-size: 10;}");
    out.println("</style>");
    out.println("<script type=\"text/javascript\">");
    out.println("function toggle_visibility(id) {");
    out.println("   var el = document.getElementById(id);");
    out.println("   el.style.display = (el.style.display != 'none' ? 'none' : 'block');");
    out.println("}");
    out.println("</script>");
    out.println("</head>");
    out.println("<body>");
    out.println("<h3>" + title + " " + version + "</h3>");
    out.println(
        "<form method='POST' action='"
            + StringUtility.join("?", req.getRequestURL().toString(), req.getQueryString())
            + "'>");
    out.print(diagnosticHTML);
    out.println("<p><input type='submit' value='submit'/></p>");
    out.println("</form>");
    out.print(errorMsg);
    out.println("<p class=\"copyright\">&copy; " + OfficialVersion.COPYRIGHT + "</p>");
    out.println("</body>");
    out.println("</html>");
  }
Example #28
0
  public void parseIndex(
      InputStream stream, URI baseUri, IRepositoryIndexProcessor listener, LogService log)
      throws Exception {
    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    inputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, true);
    inputFactory.setProperty(XMLInputFactory.IS_VALIDATING, false);
    inputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false);

    StreamSource source = new StreamSource(stream, baseUri.toString());
    XMLStreamReader reader = inputFactory.createXMLStreamReader(source);

    ResourceBuilder resourceBuilder = null;
    CapReqBuilder capReqBuilder = null;

    while (reader.hasNext()) {
      int type = reader.next();
      String localName;

      switch (type) {
        case START_ELEMENT:
          localName = reader.getLocalName();
          if (TAG_REFERRAL.equals(localName)) {
            Referral referral =
                new Referral(
                    reader.getAttributeValue(null, ATTR_REFERRAL_URL),
                    parseInt(reader.getAttributeValue(null, ATTR_REFERRAL_DEPTH)));
            listener.processReferral(baseUri, referral, referral.getDepth(), 1);
          } else if (TAG_RESOURCE.equals(localName)) {
            resourceBuilder = new ResourceBuilder();

            String bsn = reader.getAttributeValue(null, ATTR_RESOURCE_SYMBOLIC_NAME);
            String versionStr = reader.getAttributeValue(null, ATTR_RESOURCE_VERSION);
            Version version = Version.parseVersion(versionStr);
            String uri = reader.getAttributeValue(null, ATTR_RESOURCE_URI);
            URI resolvedUri = resolveUri(uri, baseUri);
            addBasicCapabilities(resourceBuilder, bsn, version, resolvedUri);
          } else if (TAG_CAPABILITY.equals(localName)) {
            String obrName = reader.getAttributeValue(null, ATTR_NAME);
            String namespace = mapObrNameToR5Namespace(obrName, false);
            capReqBuilder = new CapReqBuilder(namespace);
          } else if (TAG_REQUIRE.equals(localName)) {
            String obrName = reader.getAttributeValue(null, ATTR_NAME);
            boolean extend = "true".equalsIgnoreCase(reader.getAttributeValue(null, ATTR_EXTEND));
            String namespace = mapObrNameToR5Namespace(obrName, extend);
            boolean optional =
                "true".equalsIgnoreCase(reader.getAttributeValue(null, ATTR_OPTIONAL));

            capReqBuilder = new CapReqBuilder(namespace);
            if (optional)
              capReqBuilder.addDirective(
                  Namespace.REQUIREMENT_RESOLUTION_DIRECTIVE, Namespace.RESOLUTION_OPTIONAL);
            String filter =
                translateObrFilter(namespace, reader.getAttributeValue(null, ATTR_FILTER), log);
            capReqBuilder.addDirective(Namespace.REQUIREMENT_FILTER_DIRECTIVE, filter);
          } else if (TAG_PROPERTY.equals(localName)) {
            String name = reader.getAttributeValue(null, ATTR_PROPERTY_NAME);
            String typeStr = reader.getAttributeValue(null, ATTR_PROPERTY_TYPE);
            String valueStr = reader.getAttributeValue(null, ATTR_PROPERTY_VALUE);
            if (capReqBuilder != null) {
              name = mapObrPropertyToR5(capReqBuilder.getNamespace(), name);
              if (PROPERTY_USES.equals(name)) capReqBuilder.addDirective(PROPERTY_USES, valueStr);
              else {
                Object value = convertProperty(valueStr, typeStr);
                capReqBuilder.addAttribute(name, value);
              }
            }
          }
          break;
        case END_ELEMENT:
          localName = reader.getLocalName();
          if (TAG_RESOURCE.equals(localName)) {
            if (resourceBuilder != null) {
              Resource resource = resourceBuilder.build();
              listener.processResource(resource);
            }
          } else if (TAG_CAPABILITY.equals(localName)) {
            if (resourceBuilder != null && capReqBuilder != null)
              resourceBuilder.addCapability(capReqBuilder);
            capReqBuilder = null;
          } else if (TAG_REQUIRE.equals(localName)) {
            if (resourceBuilder != null && capReqBuilder != null)
              resourceBuilder.addRequirement(capReqBuilder);
            capReqBuilder = null;
          }
      }
    }
  }
Example #29
0
 private static Object convertProperty(String value, String typeName) {
   final Object result;
   if (TYPE_VERSION.equals(typeName)) result = Version.parseVersion(value);
   else result = value;
   return result;
 }
 static Version getFrameworkVersion() {
   String versionSpec = BundleManagerPlugin.class.getPackage().getImplementationVersion();
   return Version.parseVersion(versionSpec);
 }