@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();
 }
 /**
  * Finds native library entry.
  *
  * @param sLib Library name. For example for the library name "Native" the Windows returns entry
  *     "Native.dll", the Linux returns entry "libNative.so", the Mac returns entry
  *     "libNative.jnilib".
  * @return Native library entry.
  */
 private JarEntryInfo findJarNativeEntry(String sLib) {
   String sName = System.mapLibraryName(sLib);
   for (JarFileInfo jarFileInfo : lstJarFile) {
     JarFile jarFile = jarFileInfo.jarFile;
     Enumeration<JarEntry> en = jarFile.entries();
     while (en.hasMoreElements()) {
       JarEntry je = en.nextElement();
       if (je.isDirectory()) {
         continue;
       }
       // Example: sName is "Native.dll"
       String sEntry = je.getName(); // "Native.dll" or "abc/xyz/Native.dll"
       // sName "Native.dll" could be found, for example
       //   - in the path: abc/Native.dll/xyz/my.dll <-- do not load this one!
       //   - in the partial name: abc/aNative.dll   <-- do not load this one!
       String[] token = sEntry.split("/"); // the last token is library name
       if (token.length > 0 && token[token.length - 1].equals(sName)) {
         logInfo(
             LogArea.NATIVE,
             "Loading native library '%s' found as '%s' in JAR %s",
             sLib,
             sEntry,
             jarFileInfo.simpleName);
         return new JarEntryInfo(jarFileInfo, je);
       }
     }
   }
   return null;
 } // findJarNativeEntry()
  /** @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
    }
  }
 private Collection<JarEntry> findSubdeployments(String extension, JarFile jar)
     throws IOException {
   List<JarEntry> jars = new ArrayList<>();
   switch (extension) {
       // TODO only check specific locations
     case "ear":
       for (JarEntry entry : asIterable(jar.entries())) {
         String entryName = entry.getName();
         if (entryName.endsWith(".jar")
             || entryName.endsWith(".war")
             || entryName.endsWith(".rar")) {
           jars.add(entry);
         }
       }
       return jars;
     case "war":
     case "rar":
       for (JarEntry entry : asIterable(jar.entries())) {
         String entryName = entry.getName();
         if (entryName.endsWith(".jar")) {
           jars.add(entry);
         }
       }
       return jars;
     default:
       throw new IllegalArgumentException("uknown deployment container: " + extension);
   }
 }
Exemple #5
0
 protected void processJar(
     ClassResource classResource, Set<Class<?>> classes, String filter, Integer limit) {
   URL resource = classResource.getResource();
   String packageName = classResource.getPackageName();
   String relativePath = getPackageRelativePath(packageName);
   String jarPath = getJarPath(resource);
   JarFile jarFile;
   try {
     jarFile = new JarFile(jarPath);
   } catch (IOException e) {
     LOG.debug("IOException reading JAR '" + jarPath + ". Reason: " + e, e);
     return;
   }
   Enumeration<JarEntry> entries = jarFile.entries();
   while (entries.hasMoreElements() && withinLimit(limit, classes)) {
     JarEntry entry = entries.nextElement();
     String entryName = entry.getName();
     String className = null;
     if (entryName.endsWith(".class")
         && entryName.startsWith(relativePath)
         && entryName.length() > (relativePath.length() + 1)) {
       className = entryName.replace('/', '.').replace('\\', '.').replace(".class", "");
     }
     Class<?> aClass = tryFindClass(className, filter);
     if (aClass != null) {
       classes.add(aClass);
     }
   }
 }
Exemple #6
0
  /**
   * Removes an entry from a jar file
   *
   * @param jar The jar file
   * @param entryName The name of the entry to remove
   * @return The data of the jar with the entry removed
   * @throws IOException
   */
  public static byte[] removeJarEntry(JarFile jar, String entryName) throws IOException {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    JarOutputStream jarOut = new JarOutputStream(bytes);

    // copy all entries except the one with the matching name
    Set<String> copiedEntries = new HashSet<String>();
    Enumeration<JarEntry> jarEntries = jar.entries();
    while (jarEntries.hasMoreElements()) {
      JarEntry entry = jarEntries.nextElement();
      String name = entry.getName();
      if (!name.equals(entryName)) {
        if (!copiedEntries.contains(name)) {
          jarOut.putNextEntry(entry);
          InputStream entryStream = jar.getInputStream(entry);
          byte[] entryBytes = streamToBytes(entryStream);
          entryStream.close();
          jarOut.write(entryBytes);
          jarOut.closeEntry();
          copiedEntries.add(name);
        }
      }
    }
    jarOut.flush();
    jarOut.close();
    return bytes.toByteArray();
  }
  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;
  }
  /*
   * (non-Javadoc)
   *
   * @see
   * net.xeoh.plugins.base.impl.classpath.locator.AbstractClassPathLocation
   * #getInputStream(java.lang.String)
   */
  @Override
  public InputStream getInputStream(String file) {

    try {
      final JarURLConnection connection =
          (JarURLConnection) new URI("jar:" + this.location + "!/").toURL().openConnection();
      final JarFile jarFile = connection.getJarFile();

      final Enumeration<JarEntry> entries = jarFile.entries();

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

        // We only search for class file entries
        if (entry.isDirectory()) continue;

        String name = entry.getName();

        if (name.equals(file)) return jarFile.getInputStream(entry);
      }
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (URISyntaxException e) {
      e.printStackTrace();
    }

    return null;
  }
Exemple #9
0
  public MoquiStart(ClassLoader parent, boolean loadWebInf) {
    super(parent);
    this.loadWebInf = loadWebInf;

    URL wrapperWarUrl = null;
    try {
      // get outer file (the war file)
      pd = getClass().getProtectionDomain();
      CodeSource cs = pd.getCodeSource();
      wrapperWarUrl = cs.getLocation();
      outerFile = new JarFile(new File(wrapperWarUrl.toURI()));

      // allow for classes in the outerFile as well
      jarFileList.add(outerFile);

      Enumeration<JarEntry> jarEntries = outerFile.entries();
      while (jarEntries.hasMoreElements()) {
        JarEntry je = jarEntries.nextElement();
        if (je.isDirectory()) continue;
        // if we aren't loading the WEB-INF files and it is one, skip it
        if (!loadWebInf && je.getName().startsWith("WEB-INF")) continue;
        // get jars, can be anywhere in the file
        String jeName = je.getName().toLowerCase();
        if (jeName.lastIndexOf(".jar") == jeName.length() - 4) {
          File file = createTempFile(je);
          jarFileList.add(new JarFile(file));
        }
      }
    } catch (Exception e) {
      System.out.println("Error loading jars in war file [" + wrapperWarUrl + "]: " + e.toString());
    }
  }
Exemple #10
0
 /**
  * Unpacks a jar file to a temporary directory that will be removed when the VM exits.
  *
  * @param jarfilePath the path of the jar to unpack
  * @return the path of the temporary directory
  */
 private static String explodeJarToTempDir(File jarfilePath) {
   try {
     final Path jarfileDir = Files.createTempDirectory(jarfilePath.getName());
     Runtime.getRuntime()
         .addShutdownHook(
             new Thread() {
               @Override
               public void run() {
                 delete(jarfileDir.toFile());
               }
             });
     jarfileDir.toFile().deleteOnExit();
     JarFile jarfile = new JarFile(jarfilePath);
     Enumeration<JarEntry> entries = jarfile.entries();
     while (entries.hasMoreElements()) {
       JarEntry e = entries.nextElement();
       if (!e.isDirectory()) {
         File path = new File(jarfileDir.toFile(), e.getName().replace('/', File.separatorChar));
         File dir = path.getParentFile();
         dir.mkdirs();
         assert dir.exists();
         Files.copy(jarfile.getInputStream(e), path.toPath());
       }
     }
     return jarfileDir.toFile().getAbsolutePath();
   } catch (IOException e) {
     throw new AssertionError(e);
   }
 }
  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;
  }
  private static void scanJar(File jarfile, File root, List<GenerationTarget> targets) {
    JarFile jar = null;
    try {
      jar = new JarFile(jarfile);
    } catch (IOException e1) {
    }
    if (jar == null) return;
    Enumeration<JarEntry> entries = jar.entries();
    while (entries.hasMoreElements()) {
      JarEntry jarEntry = (JarEntry) entries.nextElement();
      if (jarEntry.isDirectory()) {
        continue;
      }
      // expand .vm also but do not create a target.  They are needed during generation.
      if (jarEntry.getName().endsWith("templates.xml") || jarEntry.getName().endsWith(".vm")) {
        File tempfile = null;
        try {
          tempfile = JarUtil.createTemporaryFile(jar, jarEntry);
        } catch (IOException e) {
        }

        if (tempfile != null && jarEntry.getName().endsWith("templates.xml")) {
          GenerationTarget target = createTarget(tempfile, root);
          if (target != null) {
            targets.add(target);
          }
        }
      }
    }
  } // end scanJar
  private List<ResourceProxy> extractResourcesFromJar(File file) {
    List<ResourceProxy> jarResources = new LinkedList<ResourceProxy>();

    try {
      JarFile jarPluginOrFeature = new JarFile(file);

      Enumeration<JarEntry> jarEntries = jarPluginOrFeature.entries();

      JarEntry jarEntry = jarEntries.nextElement();
      while (jarEntry != null) {
        String resourceEntryName = jarEntry.getName();

        if (isValidResource(resourceEntryName)) {
          jarResources.add(
              new ResourceProxy(
                  new File(file.getAbsolutePath() + File.separator + resourceEntryName),
                  resourceEntryName));
        }

        if (jarEntries.hasMoreElements()) {
          jarEntry = jarEntries.nextElement();
        } else {
          jarEntry = null;
        }
      }

    } catch (Exception e) {
      System.out.println(e.getMessage());
    }

    return jarResources;
  }
 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();
   }
 }
    public static List<String> listFiles(File archive, String[] extensions) throws IOException {
      if (!archive.exists() || !archive.isFile()) {
        throw new IllegalArgumentException(archive.getPath() + " is not a file");
      }

      List<String> files = new ArrayList<String>();

      JarFile file = new JarFile(archive);
      Enumeration<JarEntry> entries = file.entries();
      while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        String name = entry.getName();
        for (String ext : extensions) {
          if (name.endsWith(ext)) {
            if (CLASS_EXT.equals(ext)) {
              files.add(name.replace("/", "."));
            } else {
              files.add(name);
            }
            break;
          }
        }
      }

      return files;
    }
Exemple #16
0
    public static void copyJarResourcesRecursively(File destination, JarURLConnection jarConnection) {
        JarFile jarFile;
        try {
            jarFile = jarConnection.getJarFile();
        } catch (Exception e) {
            _.die("Failed to get jar file)");
            return;
        }

        Enumeration<JarEntry> em = jarFile.entries();
        while (em.hasMoreElements()) {
            JarEntry entry = em.nextElement();
            if (entry.getName().startsWith(jarConnection.getEntryName())) {
                String fileName = StringUtils.removeStart(entry.getName(), jarConnection.getEntryName());
                if (!fileName.equals("/")) {  // exclude the directory
                    InputStream entryInputStream = null;
                    try {
                        entryInputStream = jarFile.getInputStream(entry);
                        FileUtils.copyInputStreamToFile(entryInputStream, new File(destination, fileName));
                    } catch (Exception e) {
                        die("Failed to copy resource: " + fileName);
                    } finally {
                        if (entryInputStream != null) {
                            try {
                                entryInputStream.close();
                            } catch (Exception e) {
                            }
                        }
                    }
                }
            }
        }
    }
Exemple #17
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;
  }
Exemple #18
0
  /** Load all the classes in the current jar file so it can be overwritten */
  private void loadAllClasses() {
    LWC lwc = LWC.getInstance();

    try {
      // Load the jar
      JarFile jar = new JarFile(lwc.getPlugin().getFile());

      // Walk through all of the entries
      Enumeration<JarEntry> enumeration = jar.entries();

      while (enumeration.hasMoreElements()) {
        JarEntry entry = enumeration.nextElement();
        String name = entry.getName();

        // is it a class file?
        if (name.endsWith(".class")) {
          // convert to package
          String path = name.replaceAll("/", ".");
          path = path.substring(0, path.length() - ".class".length());

          // Load it
          this.getClass().getClassLoader().loadClass(path);
        }
      }
    } catch (IOException e) {
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    }
  }
Exemple #19
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;
    }
  }
Exemple #20
0
  /**
   * 通过流将jar中的一个文件的内容输出
   *
   * @param jarPaht jar文件存放的位置
   * @param filePaht 指定的文件目录
   */
  private void getStream(String jarPath, String filePath) {
    JarFile jarFile = null;
    try {
      jarFile = new JarFile(jarPath);
    } catch (IOException e1) {
      e1.printStackTrace();
    }
    Enumeration<JarEntry> ee = jarFile.entries();

    List<JarEntry> jarEntryList = new ArrayList<JarEntry>();
    while (ee.hasMoreElements()) {
      JarEntry entry = ee.nextElement();
      // 过滤我们出满足我们需求的东西,这里的fileName是指向一个具体的文件的对象的完整包路径,比如com/mypackage/test.txt
      if (entry.getName().startsWith(filePath)) {
        jarEntryList.add(entry);
      }
    }
    try {
      InputStream in = jarFile.getInputStream(jarEntryList.get(0));
      BufferedReader br = new BufferedReader(new InputStreamReader(in));
      String s = "";

      while ((s = br.readLine()) != null) {
        System.out.println(s);
      }
    } 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;
  }
  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) {

      }
    }
  }
Exemple #23
0
  /**
   * Unpack files from jar by path
   *
   * @param jar jar to unpack
   * @param path path in jar to be unpacked
   * @param outputDirectory unpack to this directory
   * @throws IOException
   */
  private static void unpackReport(JarFile jar, String path, File outputDirectory)
      throws IOException {
    Enumeration entries = jar.entries();
    while (entries.hasMoreElements()) {
      JarEntry file = (JarEntry) entries.nextElement();
      if (file.getName().startsWith(path)) {
        System.out.println("copy " + file.getName());
        String newFileName = file.getName().replace(path, "");
        if (newFileName.length() > 0) {
          String newFilePath = outputDirectory + newFileName;
          System.out.println("copy to " + newFilePath);

          File f = new File(newFilePath);

          if (f.exists()) {
            continue;
          }

          if (file.isDirectory() && !f.mkdirs()) {
            throw new RuntimeException(String.format("Can't create directory <%s>", f.getPath()));
          }

          if (file.isDirectory()) {
            continue;
          }

          copy(jar, file, f);
        }
      }
    }
  }
Exemple #24
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;
 }
Exemple #25
0
  /**
   * Lists all entries for the given JAR.
   *
   * @param uri
   * @return .
   */
  public static Collection<String> listAllEntriesFor(URI uri) {
    final Collection<String> rval = new ArrayList<String>();

    try {
      final JarURLConnection connection =
          (JarURLConnection) new URI("jar:" + uri + "!/").toURL().openConnection();
      final JarFile jarFile = connection.getJarFile();

      final Enumeration<JarEntry> entries = jarFile.entries();

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

        // We only search for class file entries
        if (entry.isDirectory()) continue;

        String name = entry.getName();

        rval.add(name);
      }
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (URISyntaxException e) {
      e.printStackTrace();
    }
    return rval;
  }
Exemple #26
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();
  }
Exemple #27
0
  protected Set<Class> processJarUrl(URL url, String basepath, Class clazz) throws IOException {
    Set<Class> set = new HashSet<Class>();
    String path = url.getFile().substring(5, url.getFile().indexOf("!"));
    JarFile jar = new JarFile(path);

    for (Enumeration entries = jar.entries(); entries.hasMoreElements(); ) {
      JarEntry entry = (JarEntry) entries.nextElement();
      if (entry.getName().startsWith(basepath) && entry.getName().endsWith(".class")) {
        try {
          String name = entry.getName();
          // Ignore anonymous
          // TODO RM what about the other anonymous classes like $2, $3 ?
          if (name.contains("$1")) {
            continue;
          }
          URL classURL = classLoader.getResource(name);
          ClassReader reader = new ClassReader(classURL.openStream());
          ClassScanner visitor = getScanner(clazz);
          reader.accept(visitor, 0);
          if (visitor.isMatch()) {
            Class c = loadClass(visitor.getClassName());
            if (c != null) {
              set.add(c);
            }
          }
        } catch (Exception e) {
          if (logger.isDebugEnabled()) {
            Throwable t = ExceptionHelper.getRootException(e);
            logger.debug(String.format("%s: caused by: %s", e.toString(), t.toString()));
          }
        }
      }
    }
    return set;
  }
 private void checkShading() {
   if (logLevel.ordinal() < LogLevel.WARN.ordinal()) {
     // Do not waste time if no logging.
     return;
   }
   Map<String, JarFileInfo> hm = new HashMap<String, JarFileInfo>();
   for (JarFileInfo jarFileInfo : lstJarFile) {
     JarFile jarFile = jarFileInfo.jarFile;
     Enumeration<JarEntry> en = jarFile.entries();
     while (en.hasMoreElements()) {
       JarEntry je = en.nextElement();
       if (je.isDirectory()) {
         continue;
       }
       String sEntry = je.getName(); // "Some.txt" or "abc/xyz/Some.txt"
       if ("META-INF/MANIFEST.MF".equals(sEntry)) {
         continue;
       }
       JarFileInfo jar = hm.get(sEntry);
       if (jar == null) {
         hm.put(sEntry, jarFileInfo);
       } else {
         logWarn(
             LogArea.JAR,
             "ENTRY %s IN %s SHADES %s",
             sEntry,
             jar.simpleName,
             jarFileInfo.simpleName);
       }
     }
   }
 }
Exemple #29
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;
  }
Exemple #30
0
  private static void readJarEntries(URL location, String basePath, Map<String, URL> resources)
      throws IOException {
    JarURLConnection conn = (JarURLConnection) location.openConnection();
    JarFile jarfile = null;
    jarfile = conn.getJarFile();

    Enumeration<JarEntry> entries = jarfile.entries();
    while (entries != null && entries.hasMoreElements()) {
      JarEntry entry = entries.nextElement();
      String name = entry.getName();

      if (entry.isDirectory() || !name.startsWith(basePath) || name.length() == basePath.length()) {
        continue;
      }

      name = name.substring(basePath.length());

      if (name.contains("/")) {
        continue;
      }

      URL resource = new URL(location, name);
      resources.put(name, resource);
    }
  }