/**
   * Load the policies from the specified file. Also checks that the policies are correctly signed.
   */
  private static void loadPolicies(
      File jarPathName, CryptoPermissions defaultPolicy, CryptoPermissions exemptPolicy)
      throws Exception {

    JarFile jf = new JarFile(jarPathName);

    Enumeration<JarEntry> entries = jf.entries();
    while (entries.hasMoreElements()) {
      JarEntry je = entries.nextElement();
      InputStream is = null;
      try {
        if (je.getName().startsWith("default_")) {
          is = jf.getInputStream(je);
          defaultPolicy.load(is);
        } else if (je.getName().startsWith("exempt_")) {
          is = jf.getInputStream(je);
          exemptPolicy.load(is);
        } else {
          continue;
        }
      } finally {
        if (is != null) {
          is.close();
        }
      }

      // Enforce the signer restraint, i.e. signer of JCE framework
      // jar should also be the signer of the two jurisdiction policy
      // jar files.
      JarVerifier.verifyPolicySigned(je.getCertificates());
    }
    // Close and nullify the JarFile reference to help GC.
    jf.close();
    jf = null;
  }
Beispiel #2
1
 @Test
 public void verifySignedJar() throws Exception {
   String classpath = System.getProperty("java.class.path");
   String[] entries = classpath.split(System.getProperty("path.separator"));
   String signedJarFile = null;
   for (String entry : entries) {
     if (entry.contains("bcprov")) {
       signedJarFile = entry;
     }
   }
   assertThat(signedJarFile).isNotNull();
   java.util.jar.JarFile jarFile = new JarFile(new File(signedJarFile));
   jarFile.getManifest();
   Enumeration<JarEntry> jarEntries = jarFile.entries();
   while (jarEntries.hasMoreElements()) {
     JarEntry jarEntry = jarEntries.nextElement();
     InputStream inputStream = jarFile.getInputStream(jarEntry);
     inputStream.skip(Long.MAX_VALUE);
     inputStream.close();
     if (!jarEntry.getName().startsWith("META-INF")
         && !jarEntry.isDirectory()
         && !jarEntry.getName().endsWith("TigerDigest.class")) {
       assertThat(jarEntry.getCertificates()).isNotNull();
     }
   }
   jarFile.close();
 }
Beispiel #3
0
  protected boolean jarUpToDate(String source, String target, boolean verbose) {
    JarFile targetJar, sourceJar;

    try {
      targetJar = new JarFile(target);
    } catch (IOException e) {
      if (verbose) err.println(target + " does not exist yet");
      return false;
    }
    try {
      sourceJar = new JarFile(source);
    } catch (IOException e) {
      return true;
    }

    for (JarEntry entry : Collections.list(sourceJar.entries())) {
      JarEntry other = (JarEntry) targetJar.getEntry(entry.getName());
      if (other == null) {
        if (verbose) err.println(target + " lacks the file " + entry.getName());
        return false;
      }
      if (entry.getTime() > other.getTime()) {
        if (verbose) err.println(target + " is not " + "up-to-date because of " + entry.getName());
        return false;
      }
    }
    try {
      targetJar.close();
      sourceJar.close();
    } catch (IOException e) {
    }

    return true;
  }
  /** @throws IOException java.util.jar.JarFile#getJarEntry(java.lang.String) */
  public void test_getJarEntryLjava_lang_String() throws IOException {
    try {
      Support_Resources.copyFile(resources, null, jarName);
      JarFile jarFile = new JarFile(new File(resources, jarName));
      assertEquals("Error in returned entry", 311, jarFile.getJarEntry(entryName).getSize());
      jarFile.close();
    } catch (Exception e) {
      fail("Exception during test: " + e.toString());
    }

    Support_Resources.copyFile(resources, null, jarName);
    JarFile jarFile = new JarFile(new File(resources, jarName));
    Enumeration<JarEntry> enumeration = jarFile.entries();
    assertTrue(enumeration.hasMoreElements());
    while (enumeration.hasMoreElements()) {
      JarEntry je = enumeration.nextElement();
      jarFile.getJarEntry(je.getName());
    }

    enumeration = jarFile.entries();
    assertTrue(enumeration.hasMoreElements());
    JarEntry je = enumeration.nextElement();
    try {
      jarFile.close();
      jarFile.getJarEntry(je.getName());
      // fail("IllegalStateException expected.");
    } catch (IllegalStateException ee) { // Per documentation exception
      // may be thrown.
      // expected
    }
  }
Beispiel #5
0
 /**
  * Create an OAR
  *
  * @param url The URL for the OperationalString Archive
  * @throws OARException If the manifest cannot be read
  * @throws IllegalArgumentException If the url is null
  */
 public OAR(URL url) throws OARException {
   if (url == null) throw new IllegalArgumentException("url cannot be null");
   JarFile jar = null;
   try {
     URL oarURL;
     if (url.getProtocol().equals("jar")) {
       oarURL = url;
     } else {
       StringBuilder sb = new StringBuilder();
       sb.append("jar:").append(url.toExternalForm()).append("!/");
       oarURL = new URL(sb.toString());
     }
     JarURLConnection conn = (JarURLConnection) oarURL.openConnection();
     jar = conn.getJarFile();
     Manifest man = jar.getManifest();
     getManifestAttributes(man);
     loadRepositories(jar);
     jar.close();
     this.url = url;
   } catch (Exception e) {
     throw new OARException("Problem processing " + url.toExternalForm(), e);
   } finally {
     try {
       if (jar != null) jar.close();
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
 }
  public static boolean extractFromJar(final String fileName, final String dest)
      throws IOException {
    if (getRunningJar() == null) {
      return false;
    }
    final File file = new File(dest);
    if (file.isDirectory()) {
      file.mkdir();
      return false;
    }
    if (!file.exists()) {
      file.getParentFile().mkdirs();
    }

    final JarFile jar = getRunningJar();
    final Enumeration<JarEntry> e = jar.entries();
    while (e.hasMoreElements()) {
      final JarEntry je = e.nextElement();
      if (!je.getName().contains(fileName)) {
        continue;
      }
      final InputStream in = new BufferedInputStream(jar.getInputStream(je));
      final OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
      copyInputStream(in, out);
      jar.close();
      return true;
    }
    jar.close();
    return false;
  }
    public void process(File f) throws Exception {
      if (f.isDirectory()) {
        File[] files =
            f.listFiles(
                new FilenameFilter() {

                  @Override
                  public boolean accept(File dir, String name) {
                    return name.matches(FILE_PATTERN);
                  }
                });
        for (File ff : files) {
          byte[] bindingBytes = Files.toByteArray(ff);
          this.addCurrentBinding(bindingBytes, ff.getName(), "file:" + ff.getAbsolutePath());
        }
      } else {
        String digest = new BigInteger(Files.getDigest(f, Digest.MD5.get())).abs().toString(16);
        CURRENT_PROPS.put(BINDING_CACHE_JAR_PREFIX + f.getName(), digest);
        final JarFile jar = new JarFile(f);
        final List<JarEntry> jarList = Collections.list(jar.entries());
        for (final JarEntry j : jarList) {
          try {
            if (j.getName().matches(FILE_PATTERN)) {
              byte[] bindingBytes = ByteStreams.toByteArray(jar.getInputStream(j));
              String bindingName = j.getName();
              String bindingFullPath = "jar:file:" + f.getAbsolutePath() + "!/" + bindingName;
              this.addCurrentBinding(bindingBytes, bindingName, bindingFullPath);
            } else if (j.getName().matches(".*\\.class.{0,1}")) {
              final String classGuess =
                  j.getName().replaceAll("/", ".").replaceAll("\\.class.{0,1}", "");
              final Class candidate = ClassLoader.getSystemClassLoader().loadClass(classGuess);
              if (MSG_BASE_CLASS.isAssignableFrom(candidate)
                  || MSG_DATA_CLASS.isAssignableFrom(candidate)) {
                InputSupplier<InputStream> classSupplier =
                    Resources.newInputStreamSupplier(ClassLoader.getSystemResource(j.getName()));
                File destClassFile = SubDirectory.CLASSCACHE.getChildFile(j.getName());
                if (!destClassFile.exists()) {
                  Files.createParentDirs(destClassFile);
                  Files.copy(classSupplier, destClassFile);
                  Logs.extreme()
                      .debug("Caching: " + j.getName() + " => " + destClassFile.getAbsolutePath());
                }
                BINDING_CLASS_MAP.putIfAbsent(classGuess, candidate);
              }
            }
          } catch (RuntimeException ex) {
            LOG.error(ex, ex);
            jar.close();
            throw ex;
          }
        }
        jar.close();
      }
    }
 private boolean isNotSignedJar(File file) throws IOException {
   JarFile jar = new JarFile(file);
   Enumeration<JarEntry> entries = jar.entries();
   while (entries.hasMoreElements()) {
     JarEntry entry = entries.nextElement();
     if (entry.getName().startsWith("META-INF") && entry.getName().endsWith(".SF")) {
       jar.close();
       return false;
     }
   }
   jar.close();
   return true;
 }
Beispiel #9
0
 public static LinkedHashMap readJarFileEntries(File jarFile) throws Exception {
   LinkedHashMap entries = new LinkedHashMap();
   JarFile jarFileWrapper = null;
   if (jarFile != null) {
     logger.debug("Reading jar entries from " + jarFile.getAbsolutePath());
     try {
       jarFileWrapper = new JarFile(jarFile);
       Enumeration iter = jarFileWrapper.entries();
       while (iter.hasMoreElements()) {
         ZipEntry zipEntry = (ZipEntry) iter.nextElement();
         InputStream entryStream = jarFileWrapper.getInputStream(zipEntry);
         ByteArrayOutputStream byteArrayStream = new ByteArrayOutputStream();
         try {
           IOUtils.copy(entryStream, byteArrayStream);
           entries.put(zipEntry.getName(), byteArrayStream.toByteArray());
           logger.debug(
               "Read jar entry " + zipEntry.getName() + " from " + jarFile.getAbsolutePath());
         } finally {
           byteArrayStream.close();
         }
       }
     } finally {
       if (jarFileWrapper != null) {
         try {
           jarFileWrapper.close();
         } catch (Exception ignore) {
           logger.debug(ignore);
         }
       }
     }
   }
   return entries;
 }
Beispiel #10
0
  private void findPackagesInJar(String packageRoot, Set<String> list, File jar)
      throws IOException {

    Set<String> paths = new HashSet<String>();
    JarFile jf = null;
    try {
      jf = new JarFile(jar);

      String packagePath = packageRoot.replaceAll("\\.", "/");

      Enumeration<JarEntry> entries = jf.entries();

      while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();

        if (entry.getName().startsWith(packagePath)) {
          String match = entry.getName().substring(0, entry.getName().lastIndexOf("/"));
          paths.add(match.replaceAll("/", "\\."));
        }
      }
      list.addAll(paths);
    } finally {
      try {
        if (jf != null) {
          jf.close();
        }
      } catch (IOException e) {

      }
    }
  }
  /** Copies all entries under the path specified by the jarPath to the JarOutputStream. */
  private void copyJarEntries(URL jarPath, Set<String> entries, JarOutputStream jarOut)
      throws IOException {
    String spec = new URL(jarPath.getFile()).getFile();
    String entryRoot = spec.substring(spec.lastIndexOf('!') + 1);
    if (entryRoot.charAt(0) == '/') {
      entryRoot = entryRoot.substring(1);
    }
    JarFile jarFile = new JarFile(spec.substring(0, spec.lastIndexOf('!')));

    try {
      Enumeration<JarEntry> jarEntries = jarFile.entries();
      while (jarEntries.hasMoreElements()) {
        JarEntry jarEntry = jarEntries.nextElement();
        String name = jarEntry.getName();
        if (name == null || !name.startsWith(entryRoot)) {
          continue;
        }
        if (entries.add(name)) {
          jarOut.putNextEntry(new JarEntry(jarEntry));
          ByteStreams.copy(jarFile.getInputStream(jarEntry), jarOut);
          jarOut.closeEntry();
        }
      }
    } finally {
      jarFile.close();
    }
  }
Beispiel #12
0
  private void _dovV() throws IOException {
    if (z_aString.endsWith(".jar")) {
      try {
        JarFile jarfile = new JarFile(z_aString, false);
        for (Enumeration enumeration = jarfile.entries(); enumeration.hasMoreElements(); ) {
          ZipEntry zipentry = (ZipEntry) enumeration.nextElement();
          String s = zipentry.getName();
          if (s.endsWith(".class")) {
            InputStream inputstream = jarfile.getInputStream(zipentry);
            _aInputStreamStringV(inputstream, (int) zipentry.getSize(), s);
            inputstream.close();
          }
        }

        jarfile.close();
        z_newZ = true;
      } catch (IOException ioexception) {
        throw new IOException(ioexception.getMessage() + ": " + z_aString);
      }
    } else {
      File file = new File(z_aString);
      FileInputStream fileinputstream = new FileInputStream(file);
      _aInputStreamStringV(fileinputstream, (int) file.length(), z_aString);
      fileinputstream.close();
    }
  }
Beispiel #13
0
    public void run() {
      // run this first, ie shutdown the container before closing jarFiles to avoid errors with
      // classes missing
      if (callMethod != null) {
        try {
          callMethod.invoke(callObject);
        } catch (Exception e) {
          System.out.println("Error in shutdown: " + e.toString());
        }
      }

      // give things a couple seconds to destroy; this way of running is mostly for dev/test where
      // this should be sufficient
      try {
        synchronized (this) {
          this.wait(2000);
        }
      } catch (Exception e) {
        System.out.println("Shutdown wait interrupted");
      }
      System.out.println(
          "========== Shutting down Moqui Executable (closing jars, etc) ==========");

      // close all jarFiles so they will "deleteOnExit"
      for (JarFile jarFile : jarFileList) {
        try {
          jarFile.close();
        } catch (IOException e) {
          System.out.println("Error closing jar [" + jarFile + "]: " + e.toString());
        }
      }
    }
 private Map<String, URLClassLoader> createClassLoaderMap(File dir, String[] files)
     throws IOException {
   Map<String, URLClassLoader> m = new TreeMap<String, URLClassLoader>();
   for (int i = 0; i < files.length; i++) {
     File moduleJar = new File(dir, files[i]);
     Manifest manifest;
     JarFile jar = new JarFile(moduleJar);
     try {
       manifest = jar.getManifest();
     } finally {
       jar.close();
     }
     if (manifest == null) {
       log(moduleJar + " has no manifest", Project.MSG_WARN);
       continue;
     }
     String codename = JarWithModuleAttributes.extractCodeName(manifest.getMainAttributes());
     if (codename == null) {
       log(moduleJar + " is not a module", Project.MSG_WARN);
       continue;
     }
     m.put(
         codename.replaceFirst("/[0-9]+$", ""),
         new URLClassLoader(
             new URL[] {moduleJar.toURI().toURL()},
             ClassLoader.getSystemClassLoader().getParent(),
             new NbDocsStreamHandler.Factory()));
   }
   return m;
 }
    private Class<?> loadClassFromJar(String className) throws ClassNotFoundException {
      Class<?> result = null;

      result = classes.get(className); // checks in cached classes
      if (result != null) {
        return result;
      }

      try {
        final JarFile jar = new JarFile(jarFile);
        try {
          final String path = className.replace('.', '/');
          final JarEntry entry = jar.getJarEntry(path + ".class");
          final InputStream in = jar.getInputStream(entry);
          try {
            final byte[] classBytes = IOUtils.toByteArray(in);
            result = defineClass(className, classBytes, 0, classBytes.length, null);
            classes.put(className, result);
            return result;
          } finally {
            in.close();
          }
        } finally {
          jar.close();
        }
      } catch (Exception e) {
        throw new ClassNotFoundException("Can't find class " + className + " in jar " + jarFile, e);
      }
    }
Beispiel #16
0
  public static void copyJarContents(String prefix, String pathToJar) throws IOException {
    LOG.info("Copying jar (location: " + pathToJar + ") to prefix " + prefix);

    JarFile jar = null;
    jar = new JarFile(pathToJar);
    Enumeration<JarEntry> enumr = jar.entries();
    byte[] bytes = new byte[1024];
    while (enumr.hasMoreElements()) {
      JarEntry entry = enumr.nextElement();
      if (entry.getName().startsWith(prefix)) {
        if (entry.isDirectory()) {
          File cr = new File(entry.getName());
          cr.mkdirs();
          continue;
        }
        InputStream inStream = jar.getInputStream(entry);
        File outFile = new File(entry.getName());
        if (outFile.exists()) {
          throw new RuntimeException("File unexpectedly exists");
        }
        FileOutputStream outputStream = new FileOutputStream(outFile);
        int read = 0;
        while ((read = inStream.read(bytes)) != -1) {
          outputStream.write(bytes, 0, read);
        }
        inStream.close();
        outputStream.close();
      }
    }
    jar.close();
  }
  public static void extractFileFromJar(String archive, List<String> filenames, String destination)
      throws IOException {
    // open the jar (zip) file
    JarFile jar = new JarFile(archive);

    // parse the entries
    Enumeration<JarEntry> entryEnum = jar.entries();
    while (entryEnum.hasMoreElements()) {
      JarEntry file = entryEnum.nextElement();
      if (filenames.contains(file.getName())) {
        // match found
        File f = new File(destination + File.separator + file.getName());
        InputStream in = jar.getInputStream(file);
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(f));

        byte[] byteBuffer = new byte[1024];

        int numRead;
        while ((numRead = in.read(byteBuffer)) != -1) {
          out.write(byteBuffer, 0, numRead);
        }

        in.close();
        out.close();
      }
    }
    jar.close();
  }
  JarFile get(URL url, boolean useCaches) throws IOException {

    JarFile result = null;
    JarFile local_result = null;

    if (useCaches) {
      synchronized (this) {
        result = getCachedJarFile(url);
      }
      if (result == null) {
        local_result = URLJarFile.getJarFile(url);
        synchronized (this) {
          result = getCachedJarFile(url);
          if (result == null) {
            fileCache.put(url, local_result);
            urlCache.put(local_result, url);
            result = local_result;
          } else {
            if (local_result != null) {
              local_result.close();
            }
          }
        }
      }
    } else {
      result = URLJarFile.getJarFile(url);
    }
    if (result == null) throw new FileNotFoundException(url.toString());

    return result;
  }
  public static String generateJpaDependencies(
      final URLClassLoader classLoader, final URL jarUrl, final UmlOptions options) {
    JpaDependencyDiagramModel dependencyModel = new JpaDependencyDiagramModel();
    try {
      List<String> classes = new ArrayList<String>();
      final JarFile jarFile = new JarFile(jarUrl.getFile());
      if (jarFile != null) {
        Enumeration<JarEntry> entries = jarFile.entries();
        while (entries.hasMoreElements()) {
          JarEntry jarEntry = entries.nextElement();
          String jarEntryName = jarEntry.getName();
          if (jarEntryName.endsWith(".class") && !jarEntryName.contains("Test")) {
            String className = jarEntryName.replace('/', '.').replace(".class", "");
            classes.add(className);
          }
        }
        jarFile.close();
      }

      // Parse all the classes for UML
      extractJpaClasses(
          classLoader,
          classes,
          dependencyModel,
          options.getIncludePatterns(),
          options.getExcludePatterns());

    } catch (Exception e) {
      e.printStackTrace();
    }
    return dependencyModel.getUml();
  }
Beispiel #20
0
  public static List<JarFileItem> listJarFile(String jarPath, JarFileFilter filter, String ext)
      throws IOException {
    List<JarFileItem> result = new ArrayList<JarFileItem>();
    JarFile jar = null;
    try {
      jar = new JarFile(jarPath);
      Enumeration<JarEntry> en = jar.entries();
      while (en.hasMoreElements()) {
        JarEntry entry = en.nextElement();
        if (entry.isDirectory() || !entry.getName().endsWith("." + ext)) {
          continue;
        }

        if (filter == null) {
          continue;
        } else if (filter.accept(entry)) {
          result.add(new JarFileItem(jarPath, entry.getName()));
        }
      }

      jar.close();
    } catch (IOException e) {
      log.error(e, e);
      throw e;
    }

    return result;
  }
Beispiel #21
0
  public boolean isDirectory(URI uri) {
    try {
      if (uri.getPath() != null && uri.getPath().endsWith(".jar!")) {
        // if the uri is the root of a jar, and it ends with a !, it should be considered a
        // directory
        return true;
      }
      String jar = getJar(uri);
      String path = getPath(uri);

      if (!path.endsWith("/")) {
        path = path + "/";
      }

      JarFile jarFile = new JarFile(jar);
      try {
        JarEntry jarEntry = jarFile.getJarEntry(path);
        if (jarEntry != null && jarEntry.isDirectory()) {
          return true;
        }
        // maybe the path is not in the jar as a seperate entry, but there are files in the path
        Enumeration<JarEntry> entries = jarFile.entries();
        while (entries.hasMoreElements()) {
          if (entries.nextElement().getName().startsWith(path)) {
            return true;
          }
        }
        return false;
      } finally {
        jarFile.close();
      }
    } catch (IOException e) {
      return false;
    }
  }
  private Map<String, byte[]> digestJar(final File file) throws IOException {
    Map<String, byte[]> digest = CACHE.get(file);
    if (digest == null) {
      digest = new HashMap<String, byte[]>();
      JarFile jar = new JarFile(file);
      try {
        for (Enumeration<JarEntry> entries = jar.entries(); entries.hasMoreElements(); ) {
          JarEntry entry = entries.nextElement();
          String path = entry.getName();
          if (path.endsWith(".class")) {
            String type = toJavaType(path);
            try {
              digest.put(type, digester.digest(ClassFileReader.read(jar, path)));
            } catch (ClassFormatException e) {
              // the class file is old for sure, according to jdt
            }
          }
        }
      } finally {
        jar.close();
      }
      CACHE.put(file, digest);
    }

    return digest;
  }
  public static Set<Class<?>> getClassFromJar(String jarPath) throws IOException {
    // read jar file
    JarFile jarFile = new JarFile(jarPath);
    Enumeration<JarEntry> jarEntries = jarFile.entries();
    Set<Class<?>> classes = new LinkedHashSet<Class<?>>();
    while (jarEntries.hasMoreElements()) {
      JarEntry jarEntry = jarEntries.nextElement();
      String name = jarEntry.getName();
      if (name.endsWith(".class")) {
        String className = name.replaceAll(".class", "").replaceAll("/", ".");
        Class<?> type = null;

        try {
          type = ClassLoader.getSystemClassLoader().loadClass(className);
        } catch (Error e) {
        } catch (ClassNotFoundException e) {
        }

        if (type != null) {
          classes.add(type);
        }
      }
    }
    jarFile.close();
    return classes;
  }
Beispiel #24
0
  private boolean pack200(final File sourceFile, final File targetFile) throws IOException {
    JarFile jarFile = new JarFile(sourceFile);
    try {
      if (isSigned(jarFile)) {
        return false;
      }

      try {
        String pack200Executable =
            new File(System.getProperty("java.home"), "bin/pack200" + (isWindows() ? ".exe" : ""))
                .getAbsolutePath();

        ProcessBuilder pb =
            new ProcessBuilder(
                pack200Executable, targetFile.getAbsolutePath(), sourceFile.getAbsolutePath());

        pb.directory(sourceFile.getParentFile());
        int result;
        Process process = pb.start();
        result = process.waitFor();
        process.destroy();
        return result == 0;
      } catch (InterruptedException e) {
        return false;
      } finally {
        if (targetFile.exists()) {
          targetFile.setLastModified(sourceFile.lastModified());
        }
      }
    } finally {
      jarFile.close();
    }
  }
  /**
   * Return the directories in a jar URI, relative to the jar entry, if any. . Jar URLS have several
   * forms, the most common being: <code>jar:file:///foo/bar.jar/!/bif/baz</code>, which means that
   * the jar file /foo/bar.jar has a directory or file name bif/baz. If such a file is passed to
   * this method, then any directories in the jar file directory bif/baz will be returned.
   *
   * @param jarURL The Jar URL for which we are to look for directories.
   * @return An list of Strings that name the directories
   * @exception IOException If opening the connection fails or if getting the jar file from the
   *     connection fails
   */
  public static List<String> jarURLDirectories(URL jarURL) throws IOException {
    List<String> directories = new LinkedList<String>();
    JarURLConnection connection = (JarURLConnection) (jarURL.openConnection());
    String jarEntryName = connection.getEntryName();
    if (jarEntryName.endsWith("/")) {
      jarEntryName = jarEntryName.substring(0, jarEntryName.length() - 1);
    }
    JarFile jarFile = connection.getJarFile();
    Enumeration<JarEntry> entries = jarFile.entries();
    while (entries.hasMoreElements()) {
      JarEntry entry = entries.nextElement();
      String name = entry.getName();
      int jarEntryIndex = name.indexOf(jarEntryName + "/");
      int jarEntrySlashIndex = jarEntryIndex + jarEntryName.length() + 1;

      int nextSlashIndex = name.indexOf("/", jarEntrySlashIndex);
      int lastSlashIndex = name.indexOf("/", jarEntrySlashIndex);

      if (jarEntryIndex > -1
          && jarEntrySlashIndex > -1
          && nextSlashIndex > -1
          && nextSlashIndex == lastSlashIndex
          && nextSlashIndex == name.length() - 1
          && entry.isDirectory()) {
        directories.add(name);
      }
    }
    jarFile.close();
    return directories;
  }
 public static void unjar(File dest, String jar) throws IOException {
   dest.mkdirs();
   JarFile jf = new JarFile(jar);
   try {
     Enumeration es = jf.entries();
     while (es.hasMoreElements()) {
       JarEntry je = (JarEntry) es.nextElement();
       String n = je.getName();
       File f = new File(dest, n);
       if (je.isDirectory()) {
         f.mkdirs();
       } else {
         if (f.exists()) {
           f.delete();
         } else {
           f.getParentFile().mkdirs();
         }
         InputStream is = jf.getInputStream(je);
         FileOutputStream os = new FileOutputStream(f);
         try {
           copyStream(is, os);
         } finally {
           os.close();
         }
       }
       long time = je.getTime();
       if (time != -1) f.setLastModified(time);
     }
   } finally {
     jf.close();
   }
 }
Beispiel #27
0
 @Test
 public void getEntryTime() throws Exception {
   java.util.jar.JarFile jdkJarFile = new java.util.jar.JarFile(this.rootJarFile);
   assertThat(this.jarFile.getEntry("META-INF/MANIFEST.MF").getTime())
       .isEqualTo(jdkJarFile.getEntry("META-INF/MANIFEST.MF").getTime());
   jdkJarFile.close();
 }
Beispiel #28
0
 public boolean canHandle(File artifact) {
   JarFile jar = null;
   try {
     // Handle OSGi bundles with the default deployer
     String name = artifact.getName();
     if (!artifact.canRead()
         || name.endsWith(".txt")
         || name.endsWith(".xml")
         || name.endsWith(".properties")
         || name.endsWith(".cfg")) {
       // that's file type which is not supported as bundle and avoid
       // exception in the log
       return false;
     }
     jar = new JarFile(artifact);
     Manifest m = jar.getManifest();
     if (m != null
         && m.getMainAttributes().getValue(new Attributes.Name("Bundle-SymbolicName")) != null) {
       return true;
     }
   } catch (Exception e) {
     // Ignore
   } finally {
     if (jar != null) {
       try {
         jar.close();
       } catch (IOException e) {
         // Ignore
       }
     }
   }
   return false;
 }
Beispiel #29
0
  /**
   * Gets the manifest.
   *
   * @param jarName the jar name
   * @param lineSeparator the line separator
   * @return the manifest
   */
  public String getManifest(final String jarName, final String lineSeparator) {
    StringBuilder sb = new StringBuilder();

    String lib = getLibraryPathName(jarBaseName);
    if (!isEmpty(lib)) {
      lib = lib.replaceAll("file:", "");
      final File[] files = new File(lib).listFiles(new FilenameFilterJar());
      if ((files != null) && (files.length > 0)) {
        for (File jar : files) {
          if (jar.getName().matches(".*" + jarName + ".*") && jar.exists()) {
            try {
              JarFile jarFile = new JarFile(jar);
              final JarEntry entry = jarFile.getJarEntry("META-INF/MANIFEST.MF");
              final InputStream is = jarFile.getInputStream(entry);
              final BufferedReader br = new BufferedReader(new InputStreamReader(is));
              String line;
              while ((line = br.readLine()) != null) {
                sb.append(lineSeparator).append(line);
              }
              if (jarFile != null) {
                jarFile.close();
                jarFile = null;
              }
            } catch (final Exception e) {
            }
          }
        }
      }
    }
    return sb.toString();
  }
  /**
   * Scan manifest classpath entries of a jar, adding all found jar files to the set of manifest
   * jars.
   */
  private static void _recursiveGetManifestJars(File jarFile, Set<File> manifestJars) {
    if (!jarFile.exists()) return;

    JarFile jar = null;
    try {
      jar = new JarFile(jarFile);
      Manifest mf = jar.getManifest();
      if (mf == null) return;
      String classpath = mf.getMainAttributes().getValue(Attributes.Name.CLASS_PATH);
      if (classpath == null) return;

      // We've got some entries
      File parent = jarFile.getParentFile();

      String[] rgPaths = classpath.split(" "); // $NON-NLS-1$
      for (String path : rgPaths) {
        if (path.length() == 0) continue;
        File file = new File(parent, path);
        // If we haven't seen this, we need to get its manifest jars as well
        if (!manifestJars.contains(file) && file.exists()) {
          manifestJars.add(file);
          _recursiveGetManifestJars(file, manifestJars);
        }
      }
    } catch (IOException ioe) {
    } finally {
      if (jar != null) {
        try {
          jar.close();
        } catch (IOException ioe) {
        }
      }
    }
  }