Example #1
0
  public static void testBumpSubBuilders() throws Exception {
    File tmp = new File("tmp-ws");
    if (tmp.exists()) IO.deleteWithException(tmp);
    tmp.mkdir();
    assertTrue(tmp.isDirectory());

    try {
      IO.copy(new File("test/ws"), tmp);
      Workspace ws = Workspace.getWorkspace(tmp);
      Project project = ws.getProject("bump-sub");
      project.setTrace(true);

      assertNull(project.getProperty("Bundle-Version"));

      project.bump("=+0");

      assertNull(project.getProperty("Bundle-Version"));

      for (Builder b : project.getSubBuilders()) {
        assertEquals(new Version(1, 1, 0), new Version(b.getVersion()));
      }
    } finally {
      IO.deleteWithException(tmp);
    }
  }
Example #2
0
 public void setUp() throws Exception {
   tmp = new File("generated/tmp/test/" + getName());
   tmp.mkdirs();
   IO.copy(IO.getFile("testdata/ws"), tmp);
   ws = new Workspace(tmp);
   assertTrue(ws.check());
 }
Example #3
0
  public static void testBumpIncludeFile() throws Exception {
    File tmp = new File("tmp-ws");
    if (tmp.exists()) IO.deleteWithException(tmp);
    tmp.mkdir();
    assertTrue(tmp.isDirectory());

    try {
      IO.copy(new File("test/ws"), tmp);
      Workspace ws = Workspace.getWorkspace(tmp);
      Project project = ws.getProject("bump-included");
      project.setTrace(true);
      Version old = new Version(project.getProperty("Bundle-Version"));
      assertEquals(new Version(1, 0, 0), old);
      project.bump("=+0");

      Processor processor = new Processor();
      processor.setProperties(project.getFile("include.txt"));

      Version newv = new Version(processor.getProperty("Bundle-Version"));
      System.err.println("New version " + newv);
      assertEquals(1, newv.getMajor());
      assertEquals(1, newv.getMinor());
      assertEquals(0, newv.getMicro());
    } finally {
      IO.deleteWithException(tmp);
    }
  }
Example #4
0
  @Override
  protected void setUp() throws Exception {
    tmp = IO.getFile("generated/tmp");
    tmp.mkdirs();

    configuration = new HashMap<String, Object>();
    configuration.put(
        Constants.FRAMEWORK_STORAGE_CLEAN, Constants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT);
    configuration.put(Constants.FRAMEWORK_STORAGE, new File(tmp, "fwstorage").getAbsolutePath());
    configuration.put(
        Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, "org.osgi.framework.launch;version=1.4");
    framework = new org.apache.felix.framework.FrameworkFactory().newFramework(configuration);
    framework.init();
    framework.start();
    BundleContext context = framework.getBundleContext();

    String[] bundles = {
      "../cnf/repo/osgi.cmpn/osgi.cmpn-4.3.1.jar", "testdata/slf4j-simple-1.7.12.jar",
      "testdata/slf4j-api-1.7.12.jar", "testdata/org.apache.aries.util-1.1.0.jar",
      "testdata/org.apache.aries.jmx-1.1.1.jar", "generated/biz.aQute.remote.test.jmx.jar"
    };

    for (String bundle : bundles) {
      String location = "reference:" + IO.getFile(bundle).toURI().toString();
      Bundle b = context.installBundle(location);
      if (!bundle.contains("slf4j-simple")) {
        b.start();
      }
    }

    super.setUp();
  }
Example #5
0
  public static void testBump() throws Exception {
    File tmp = new File("tmp-ws");
    if (tmp.exists()) IO.deleteWithException(tmp);
    tmp.mkdir();
    assertTrue(tmp.isDirectory());

    try {
      IO.copy(new File("test/ws"), tmp);
      Workspace ws = Workspace.getWorkspace(tmp);
      Project project = ws.getProject("p1");
      int size = project.getProperties().size();
      Version old = new Version(project.getProperty("Bundle-Version"));
      System.err.println("Old version " + old);
      project.bump("=+0");
      Version newv = new Version(project.getProperty("Bundle-Version"));
      System.err.println("New version " + newv);
      assertEquals(old.getMajor(), newv.getMajor());
      assertEquals(old.getMinor() + 1, newv.getMinor());
      assertEquals(0, newv.getMicro());
      assertEquals(size, project.getProperties().size());
      assertEquals("sometime", newv.getQualifier());
    } finally {
      IO.deleteWithException(tmp);
    }
  }
Example #6
0
 /** Delete a cache entry */
 public boolean deleteCache(byte[] id) throws Exception {
   File dir = IO.getFile(cache, Hex.toHexString(id));
   if (dir.isDirectory()) {
     IO.delete(dir);
     return true;
   }
   return false;
 }
Example #7
0
 private static void checkPackageInfoFiles(
     Project project, String packageName, boolean expectPackageInfo, boolean expectPackageInfoJava)
     throws Exception {
   File pkgInfo = IO.getFile(project.getSrc(), packageName + "/packageinfo");
   File pkgInfoJava = IO.getFile(project.getSrc(), packageName + "/package-info.java");
   assertEquals(expectPackageInfo, pkgInfo.exists());
   assertEquals(expectPackageInfoJava, pkgInfoJava.exists());
 }
Example #8
0
 @Override
 public void delete(Project p) throws IOException {
   File root = p.getWorkspace().getFile("pom.xml");
   String rootPom = IO.collect(root);
   if (rootPom.contains(getTag(p))) {
     rootPom = rootPom.replaceAll("\n\\s*" + getTag(p) + "\\s*", "\n");
     IO.store(rootPom, root);
   }
 }
Example #9
0
 @Override
 protected void tearDown() throws Exception {
   super.tearDown();
   framework.stop();
   IO.delete(tmp);
   Main.stop();
   IO.delete(IO.getFile("generated/cache"));
   IO.delete(IO.getFile("generated/storage"));
   framework.waitForStop(100000);
   super.tearDown();
 }
Example #10
0
  void download0(URI url, File path, byte[] sha) throws Exception {
    path.getParentFile().mkdirs();
    File tmp = IO.createTempFile(path.getParentFile(), "tmp", ".jar");
    URL u = url.toURL();

    URLConnection conn = u.openConnection();
    InputStream in;
    if (conn instanceof HttpURLConnection) {
      HttpURLConnection http = (HttpURLConnection) conn;
      http.setRequestProperty("Accept-Encoding", "deflate");
      http.setInstanceFollowRedirects(true);

      connector.handle(conn);

      int result = http.getResponseCode();
      if (result / 100 != 2) {
        String s = "";
        InputStream err = http.getErrorStream();
        try {
          if (err != null) s = IO.collect(err);
          if (result == 404) {
            reporter.trace("not found ");
            throw new FileNotFoundException("Cannot find " + url + " : " + s);
          }
          throw new IOException(
              "Failed request " + result + ":" + http.getResponseMessage() + " " + s);
        } finally {
          if (err != null) err.close();
        }
      }

      String deflate = http.getHeaderField("Content-Encoding");
      in = http.getInputStream();
      if (deflate != null && deflate.toLowerCase().contains("deflate")) {
        in = new InflaterInputStream(in);
        reporter.trace("inflate");
      }
    } else {
      connector.handle(conn);
      in = conn.getInputStream();
    }

    IO.copy(in, tmp);

    byte[] digest = SHA1.digest(tmp).digest();
    if (Arrays.equals(digest, sha)) {
      IO.rename(tmp, path);
    } else {
      reporter.trace(
          "sha's did not match %s, expected %s, got %s", tmp, Hex.toHexString(sha), digest);
      throw new IllegalArgumentException("Invalid sha downloaded");
    }
  }
Example #11
0
  /** @throws Exception */
  File[] getBundleClasspathFiles() throws Exception {

    if (this.bundleClasspathExpansion != null) return bundleClasspathExpansion;

    File file = getFile();

    Manifest m = getManifest();
    String bundleClassPath;
    if (m == null
        || (bundleClassPath = m.getMainAttributes().getValue(Constants.BUNDLE_CLASSPATH)) == null) {
      this.bundleClasspathExpansion = new File[] {file};
    } else {

      File bundleClasspathDirectory =
          IO.getFile(file.getParentFile(), "." + file.getName() + "-bcp");
      Parameters header = new Parameters(bundleClassPath);
      this.bundleClasspathExpansion = new File[header.size()];
      bundleClasspathDirectory.mkdir();

      int n = 0;
      Jar jar = null;
      try {
        for (Map.Entry<String, Attrs> entry : header.entrySet()) {
          if (".".equals(entry.getKey())) {
            this.bundleClasspathExpansion[n] = file;
          } else {
            File member = new File(bundleClasspathDirectory, n + "-" + toName(entry.getKey()));
            if (!isCurrent(file, member)) {

              if (jar == null) {
                jar = new Jar(file);
              }

              Resource resource = jar.getResource(entry.getKey());
              if (resource == null) {
                warning += "Invalid bcp entry: " + entry.getKey() + "\n";
              } else {
                IO.copy(resource.openInputStream(), member);
                member.setLastModified(file.lastModified());
              }
            }
            this.bundleClasspathExpansion[n] = member;
          }
          n++;
        }
      } finally {
        if (jar != null) jar.close();
      }
    }

    return this.bundleClasspathExpansion;
  }
Example #12
0
  @Override
  public void setUp() {
    System.setProperty("jpm4j.in.test", "true");

    tmp = IO.getFile("generated/tmp");
    IO.delete(tmp);
    tmp.mkdirs();

    repo = new Repository();
    Map<String, String> props = new HashMap<String, String>();
    props.put("location", new File(tmp, "loc").getAbsolutePath());
    props.put("index", new File(tmp, "index").getAbsolutePath());
    repo.setProperties(props);
  }
  private void copyRunBundles(ProjectLauncher launcher, File folder, MultiStatus status) {
    Collection<String> bundles = launcher.getRunBundles();
    List<String> names = new ArrayList<String>(bundles.size());

    for (String bundle : bundles) {
      File bundleFile = new File(bundle);
      String name = "bundles/" + bundleFile.getName();
      File destFile = new File(folder, name);

      try {
        IO.copy(bundleFile, destFile);
        names.add(name);
      } catch (IOException e) {
        status.add(
            new Status(
                IStatus.ERROR, Plugin.PLUGIN_ID, 0, "Error copying run bundle: " + bundle, e));
      }
    }

    try {
      Properties launcherProps = new Properties();
      launcherProps.put(aQute.lib.osgi.Constants.RUNBUNDLES, Processor.join(names, ",\\\n  "));
      launcherProps.store(
          new FileOutputStream(new File(folder, "launch.properties")), "launch.properties");
    } catch (IOException e) {
      status.add(
          new Status(
              IStatus.ERROR, Plugin.PLUGIN_ID, 0, "Error generating launch properties file.", e));
    }
  }
  @Override
  public void correctProblems(File file, List<Problem> problems) throws AutoMigrateException {
    try {
      String contents = new String(IO.read(file));

      IFile propertiesFile = WorkspaceUtil.getFileFromWorkspace(file, new WorkspaceHelper());

      for (Problem problem : problems) {
        if (problem.autoCorrectContext instanceof String) {
          final String propertyData = problem.autoCorrectContext;

          if (propertyData != null && propertyData.startsWith(PREFIX)) {
            final String propertyValue = propertyData.substring(PREFIX.length());

            contents = contents.replaceAll(propertyValue + ".*", propertyValue + "=7.0.0+");
          }
        }
      }

      propertiesFile.setContents(
          new ByteArrayInputStream(contents.getBytes()), IResource.FORCE, null);

    } catch (CoreException | IOException e) {
      e.printStackTrace();
    }
  }
Example #15
0
  private Builder newBuilder() throws IOException {
    Builder b = new Builder();
    b.addClasspath(IO.getFile("jar/osgi.jar"));
    b.addClasspath(new File("bin"));

    return b;
  }
Example #16
0
 @Override
 protected void tearDown() throws Exception {
   framework.stop();
   framework.waitForStop(10000);
   IO.delete(tmp);
   super.tearDown();
 }
Example #17
0
  public void testSimple() throws Exception {
    File tmp = new File("tmp");
    PersistentMap<String> pm = new PersistentMap<String>(new File(tmp, "simple"), String.class);
    try {

      assertNull(pm.put("abc", "def"));
      assertEquals("def", pm.get("abc"));

      pm.close();

      PersistentMap<String> pm2 = new PersistentMap<String>(new File(tmp, "simple"), String.class);
      assertEquals("def", pm2.get("abc"));

      assertEquals(Arrays.asList("abc"), new ArrayList<String>(pm2.keySet()));

      for (Map.Entry<String, String> e : pm2.entrySet()) {
        e.setValue("XXX");
      }
      assertEquals("XXX", pm2.get("abc"));
      pm2.close();
    } finally {
      pm.close();
      IO.delete(tmp);
    }
  }
Example #18
0
  public void testStructs() throws Exception {
    File tmp = new File("tmp");
    PersistentMap<X> pm = new PersistentMap<X>(new File(tmp, "simple"), X.class);
    try {
      X x = new X();
      x.abc = "def";
      x.def = 5;
      x.list.add("abc");
      assertNull(pm.put("abc", x));
      pm.close();

      PersistentMap<X> pm2 = new PersistentMap<X>(new File(tmp, "simple"), X.class);

      X x2 = pm2.get("abc");
      assertEquals("def", x2.abc);
      assertEquals(5, x2.def);

      pm2.remove("abc");

      assertEquals(0, pm2.size());

      pm2.close();
    } finally {
      pm.close();
      IO.delete(tmp);
    }
  }
    @Override
    protected IStatus run(IProgressMonitor monitor) {
      String tmp = NO_HELP_CONTENT;
      if (template != null) {
        URI uri = template.getHelpContent();
        if (uri != null) {
          try {
            URLConnection conn = uri.toURL().openConnection();
            conn.setUseCaches(false);
            tmp = IO.collect(conn.getInputStream());
          } catch (IOException e) {
            log.log(
                new Status(
                    IStatus.ERROR, Plugin.PLUGIN_ID, 0, "Error loading template help content.", e));
          }
        }
      }

      final String text = tmp;
      if (control != null && !control.isDisposed()) {
        control
            .getDisplay()
            .asyncExec(
                new Runnable() {
                  @Override
                  public void run() {
                    if (!control.isDisposed()) control.setText(text);
                  }
                });
      }

      return Status.OK_STATUS;
    }
Example #20
0
  private void addJREPackageCapabilities(Resolver resolver, EE ee) throws IOException {
    // EE Package Capabilities
    Properties pkgProps = new Properties();
    URL pkgsResource = ResolveOperation.class.getResource(ee.name() + ".properties");
    if (pkgsResource == null)
      throw new IOException(
          String.format(
              "No JRE package definition available for Execution Env %s.", ee.getEEName()));

    InputStream stream = null;
    try {
      stream = pkgsResource.openStream();
      pkgProps.load(stream);
    } finally {
      if (stream != null) IO.close(stream);
    }
    String pkgsStr = pkgProps.getProperty(Constants.FRAMEWORK_SYSTEMPACKAGES);

    Map<String, Map<String, String>> header = OSGiHeader.parseHeader(pkgsStr);
    for (Entry<String, Map<String, String>> entry : header.entrySet()) {
      String pkgName = Processor.removeDuplicateMarker(entry.getKey());
      String version = entry.getValue().get(Constants.VERSION_ATTRIBUTE);

      Map<String, String> capabilityProps = new HashMap<String, String>();
      capabilityProps.put(ObrConstants.FILTER_PACKAGE, pkgName);
      if (version != null) capabilityProps.put(ObrConstants.FILTER_VERSION, version);

      Capability capability = helper.capability(ObrConstants.REQUIREMENT_PACKAGE, capabilityProps);
      resolver.addGlobalCapability(capability);
    }
  }
Example #21
0
  @Override
  protected void tearDown() throws Exception {
    repo.close();
    IO.delete(tmp);

    super.tearDown();
  }
Example #22
0
  private void copy(File workspaceDir, InputStream in, Pattern glob, boolean overwrite)
      throws Exception {

    Jar jar = new Jar("dot", in);
    try {
      for (Entry<String, Resource> e : jar.getResources().entrySet()) {

        String path = e.getKey();
        bnd.trace("path %s", path);

        if (glob != null && !glob.matcher(path).matches()) continue;

        Resource r = e.getValue();
        File dest = Processor.getFile(workspaceDir, path);
        if (overwrite
            || !dest.isFile()
            || dest.lastModified() < r.lastModified()
            || r.lastModified() <= 0) {

          bnd.trace("copy %s to %s", path, dest);

          File dp = dest.getParentFile();
          if (!dp.exists() && !dp.mkdirs()) {
            throw new IOException("Could not create directory " + dp);
          }

          IO.copy(r.openInputStream(), dest);
        }
      }
    } finally {
      jar.close();
    }
  }
Example #23
0
  public static void testEnum() throws Exception {
    Builder b = new Builder();
    b.addClasspath(new File("bin"));
    b.setProperty("Export-Package", "test.metatype");
    b.setProperty("-metatype", "*");
    b.build();
    assertEquals(0, b.getErrors().size());
    assertEquals(0, b.getWarnings().size());

    Resource r = b.getJar().getResource("OSGI-INF/metatype/test.metatype.MetatypeTest$Enums.xml");
    IO.copy(r.openInputStream(), System.err);

    Document d = db.parse(r.openInputStream());
    assertEquals(
        "http://www.osgi.org/xmlns/metatype/v1.1.0", d.getDocumentElement().getNamespaceURI());

    Properties p = new Properties();
    p.setProperty("r", "requireConfiguration");
    p.setProperty("i", "ignoreConfiguration");
    p.setProperty("o", "optionalConfiguration");
    Enums enums = Configurable.createConfigurable(Enums.class, (Map<Object, Object>) p);
    assertEquals(Enums.X.requireConfiguration, enums.r());
    assertEquals(Enums.X.ignoreConfiguration, enums.i());
    assertEquals(Enums.X.optionalConfiguration, enums.o());
  }
Example #24
0
File: Macro.java Project: bramk/bnd
  /**
   * System command. Execute a command and insert the result.
   *
   * @param args
   * @param help
   * @param patterns
   * @param low
   * @param high
   */
  public String system_internal(boolean allowFail, String args[]) throws Exception {
    verifyCommand(
        args,
        "${"
            + (allowFail ? "system-allow-fail" : "system")
            + ";<command>[;<in>]}, execute a system command",
        null,
        2,
        3);
    String command = args[1];
    String input = null;

    if (args.length > 2) {
      input = args[2];
    }

    Process process = Runtime.getRuntime().exec(command, null, domain.getBase());
    if (input != null) {
      process.getOutputStream().write(input.getBytes("UTF-8"));
    }
    process.getOutputStream().close();

    String s = IO.collect(process.getInputStream(), "UTF-8");
    int exitValue = process.waitFor();
    if (exitValue != 0) return exitValue + "";

    if (!allowFail && (exitValue != 0)) {
      domain.error("System command " + command + " failed with " + exitValue);
    }
    return s.trim();
  }
Example #25
0
 /** The default policy is truncate micro. Check if this is applied to the import. */
 public static void testImportMicroTruncated() throws Exception {
   Builder b = new Builder();
   b.addClasspath(IO.getFile("jar/osgi.jar"));
   b.setProperty("Import-Package", "org.osgi.service.event");
   b.build();
   String s = b.getImports().getByFQN("org.osgi.service.event").get("version");
   assertEquals("[1.0,2)", s);
 }
Example #26
0
File: Macro.java Project: bramk/bnd
 /**
  * Get the contents of a file.
  *
  * @param in
  * @return
  * @throws IOException
  */
 public String _cat(String args[]) throws IOException {
   verifyCommand(args, "${cat;<in>}, get the content of a file", null, 2, 2);
   File f = domain.getFile(args[1]);
   if (f.isFile()) {
     return IO.collect(f);
   } else if (f.isDirectory()) {
     return Arrays.toString(f.list());
   } else {
     try {
       URL url = new URL(args[1]);
       return IO.collect(url, "UTF-8");
     } catch (MalformedURLException mfue) {
       // Ignore here
     }
     return null;
   }
 }
  public void deleteCommand(String name) throws Exception {
    CommandData cmd = getCommand(name);
    if (cmd == null) throw new IllegalArgumentException("No such command " + name);

    platform.deleteCommand(cmd);
    File tobedel = new File(commandDir, name);
    IO.deleteWithException(tobedel);
  }
 public void init() throws IOException {
   URL s = getClass().getClassLoader().getResource(SERVICE_JAR_FILE);
   if (s == null)
     if (underTest) return;
     else throw new Error("No " + SERVICE_JAR_FILE + " resource in jar");
   service.getParentFile().mkdirs();
   IO.copy(s, service);
 }
Example #29
0
 @Override
 public void close() throws IOException {
   File tempDir = null;
   synchronized (this) {
     if (checkedOut != null) tempDir = checkedOut.getWorkTree();
   }
   if (tempDir != null) IO.delete(tempDir);
 }
Example #30
0
 @Override
 protected void setUp() throws Exception {
   super.setUp();
   reporter.setTrace(true);
   Config config = new Config();
   fnx = new FakeNexus(config, remote);
   fnx.start();
   IO.delete(remote);
   IO.delete(local);
   IO.copy(IO.getFile("testresources/mavenrepo"), remote);
   remote.mkdirs();
   local.mkdirs();
   repo =
       new MavenRemoteRepository(local, new HttpClient(), fnx.getBaseURI() + "/repo/", reporter);
   storage =
       new MavenRepository(
           local, "fnexus", this.repo, null, null, new ReporterAdapter(System.out), null);
 }