/**
  * 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()
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();
 }
  /**
   * Gets the build teimstamp from the jar manifest
   *
   * @return build timestamp
   */
  private static String getManifestBuildTimestamp() {
    JarURLConnection connection = null;
    JarFile jarFile = null;
    URL url = Commons.class.getClassLoader().getResource("jaligner");
    try {
      // Get jar connection
      connection = (JarURLConnection) url.openConnection();

      // Get the jar file
      jarFile = connection.getJarFile();

      // Get the manifest
      Manifest manifest = jarFile.getManifest();

      // Get the manifest entries
      Attributes attributes = manifest.getMainAttributes();

      Attributes.Name name = new Attributes.Name(BUILD_TIMESTAMP);
      return attributes.getValue(name);
    } catch (Exception e) {
      String message = "Failed getting the current release info: " + e.getMessage();
      logger.log(Level.WARNING, message);
    }
    return null;
  }
  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
Beispiel #5
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;
    }
  }
Beispiel #6
0
  /*
   * (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;
  }
Beispiel #7
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();
 }
  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 byte[] read(String path) throws IOException {
   ZipEntry entry = m_source.getEntry(getInternalPath(path));
   if (entry == null) {
     throw new IOException("Jar Entry is not found for class " + path + ".");
   }
   return Streams.readBytes(m_source.getInputStream(entry));
 }
Beispiel #10
0
  private static void copyFiles(Manifest manifest, JarFile in, JarOutputStream out, long timestamp)
      throws IOException {
    byte[] buffer = new byte[4096];
    int num;
    Map<String, Attributes> entries = manifest.getEntries();
    List<String> names = new ArrayList<String>(entries.keySet());
    Collections.sort(names);
    for (String name : names) {
      JarEntry inEntry = in.getJarEntry(name);
      JarEntry outEntry = null;
      if (inEntry.getMethod() == ZipEntry.STORED) {
        outEntry = new JarEntry(inEntry);
      } else {
        outEntry = new JarEntry(name);
      }
      outEntry.setTime(timestamp);
      out.putNextEntry(outEntry);

      InputStream data = in.getInputStream(inEntry);
      while ((num = data.read(buffer)) > 0) {
        out.write(buffer, 0, num);
      }
      out.flush();
    }
  }
 private void determineNameMapping(JarFile paramJarFile, Set paramSet, Map paramMap)
     throws IOException {
   InputStream localInputStream =
       paramJarFile.getInputStream(paramJarFile.getEntry("META-INF/INDEX.JD"));
   if (localInputStream == null) handleException("jardiff.error.noindex", null);
   LineNumberReader localLineNumberReader =
       new LineNumberReader(new InputStreamReader(localInputStream, "UTF-8"));
   String str = localLineNumberReader.readLine();
   if ((str == null) || (!str.equals("version 1.0")))
     handleException("jardiff.error.badheader", str);
   while ((str = localLineNumberReader.readLine()) != null) {
     List localList;
     if (str.startsWith("remove")) {
       localList = getSubpaths(str.substring("remove".length()));
       if (localList.size() != 1) handleException("jardiff.error.badremove", str);
       paramSet.add(localList.get(0));
       continue;
     }
     if (str.startsWith("move")) {
       localList = getSubpaths(str.substring("move".length()));
       if (localList.size() != 2) handleException("jardiff.error.badmove", str);
       if (paramMap.put(localList.get(1), localList.get(0)) != null)
         handleException("jardiff.error.badmove", str);
       continue;
     }
     if (str.length() <= 0) continue;
     handleException("jardiff.error.badcommand", str);
   }
   localLineNumberReader.close();
   localInputStream.close();
 }
  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;
  }
Beispiel #13
0
 public static boolean isJarDirectory(String path) {
   if (isJarFile()) {
     try {
       JarFile jar = new JarFile(getJarFile());
       ZipEntry entry = jar.getEntry(path);
       return entry != null && entry.isDirectory();
     } catch (Exception e) {
       e.printStackTrace();
     }
   } else {
     try {
       URL url = FileUtilities.class.getResource("/" + path);
       if (url != null) {
         URI uri = url.toURI();
         File classpath = new File(uri);
         return classpath.isDirectory();
       } else {
         return false;
       }
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
   return false;
 }
Beispiel #14
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 #15
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) {

      }
    }
  }
Beispiel #16
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 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;
  }
 @SuppressWarnings("resource")
 private InitStep loadInitStep(Path jar) {
   try {
     URLClassLoader pluginLoader =
         new URLClassLoader(
             new URL[] {jar.toUri().toURL()}, InitPluginStepsLoader.class.getClassLoader());
     try (JarFile jarFile = new JarFile(jar.toFile())) {
       Attributes jarFileAttributes = jarFile.getManifest().getMainAttributes();
       String initClassName = jarFileAttributes.getValue("Gerrit-InitStep");
       if (initClassName == null) {
         return null;
       }
       @SuppressWarnings("unchecked")
       Class<? extends InitStep> initStepClass =
           (Class<? extends InitStep>) pluginLoader.loadClass(initClassName);
       return getPluginInjector(jar).getInstance(initStepClass);
     } catch (ClassCastException e) {
       ui.message(
           "WARN: InitStep from plugin %s does not implement %s (Exception: %s)\n",
           jar.getFileName(), InitStep.class.getName(), e.getMessage());
       return null;
     } catch (NoClassDefFoundError e) {
       ui.message(
           "WARN: Failed to run InitStep from plugin %s (Missing class: %s)\n",
           jar.getFileName(), e.getMessage());
       return null;
     }
   } catch (Exception e) {
     ui.message(
         "WARN: Cannot load and get plugin init step for %s (Exception: %s)\n",
         jar, e.getMessage());
     return null;
   }
 }
 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;
 }
Beispiel #20
0
 /** @see java.lang.ClassLoader#findResources(java.lang.String) */
 @Override
 public Enumeration<URL> findResources(String resourceName) throws IOException {
   String webInfResourceName = "WEB-INF/classes/" + resourceName;
   List<URL> urlList = new ArrayList<URL>();
   int jarFileListSize = jarFileList.size();
   for (int i = 0; i < jarFileListSize; i++) {
     JarFile jarFile = jarFileList.get(i);
     JarEntry jarEntry = jarFile.getJarEntry(resourceName);
     // to better support war format, look for the resourceName in the WEB-INF/classes directory
     if (loadWebInf && jarEntry == null) jarEntry = jarFile.getJarEntry(webInfResourceName);
     if (jarEntry != null) {
       try {
         String jarFileName = jarFile.getName();
         if (jarFileName.contains("\\")) jarFileName = jarFileName.replace('\\', '/');
         urlList.add(new URL("jar:file:" + jarFileName + "!/" + jarEntry));
       } catch (MalformedURLException e) {
         System.out.println(
             "Error making URL for ["
                 + resourceName
                 + "] in jar ["
                 + jarFile
                 + "] in war file ["
                 + outerFile
                 + "]: "
                 + e.toString());
       }
     }
   }
   // add all resources found in parent loader too
   Enumeration<URL> superResources = super.findResources(resourceName);
   while (superResources.hasMoreElements()) urlList.add(superResources.nextElement());
   return Collections.enumeration(urlList);
 }
Beispiel #21
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);
   }
 }
Beispiel #22
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();
    }
  }
Beispiel #23
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());
        }
      }
    }
Beispiel #24
0
 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);
       }
     }
   }
 }
Beispiel #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;
  }
Beispiel #26
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);
     }
   }
 }
Beispiel #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;
  }
Beispiel #28
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 #29
0
  /**
   * Take the name of a jar file and extract the plugin.xml file, if possible, to a temporary file.
   *
   * @param f The jar file to extract from.
   * @return a temporary file to which the plugin.xml file has been copied.
   */
  public static File unpackPluginXML(File f) {
    InputStream in = null;
    OutputStream out = null;

    try {
      JarFile jar = new JarFile(f);
      ZipEntry entry = jar.getEntry(PLUGIN_XML_FILE);
      if (entry == null) {
        return null;
      }
      File dest = File.createTempFile("jabref_plugin", ".xml");
      dest.deleteOnExit();

      in = new BufferedInputStream(jar.getInputStream(entry));
      out = new BufferedOutputStream(new FileOutputStream(dest));
      byte[] buffer = new byte[2048];
      for (; ; ) {
        int nBytes = in.read(buffer);
        if (nBytes <= 0) break;
        out.write(buffer, 0, nBytes);
      }
      out.flush();
      return dest;
    } catch (IOException ex) {
      ex.printStackTrace();
      return null;
    } finally {
      try {
        if (out != null) out.close();
        if (in != null) in.close();
      } catch (IOException ex) {
        ex.printStackTrace();
      }
    }
  }
  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;
  }