private static List<Class<?>> getClassesInJarFile(String jar, String packageName)
     throws IOException {
   List<Class<?>> classes = new ArrayList<Class<?>>();
   JarInputStream jarFile = null;
   jarFile = new JarInputStream(new FileInputStream(jar));
   JarEntry jarEntry;
   while ((jarEntry = jarFile.getNextJarEntry()) != null) {
     if (jarEntry != null) {
       String className = jarEntry.getName();
       if (className.endsWith(".class")) {
         className =
             className.substring(0, className.length() - ".class".length()).replace('/', '.');
         if (className.startsWith(packageName)) {
           // CHECKSTYLE:OFF
           try {
             classes.add(Class.forName(className.replace('/', '.')));
           } catch (Throwable e) {
             // do nothing. this class hasn't been found by the loader, and we don't care.
           }
           // CHECKSTYLE:ON
         }
       }
     }
   }
   closeJarFile(jarFile);
   return classes;
 }
Пример #2
0
 private Hashtable<String, String> getJarManifestAttributes(String path) {
   Hashtable<String, String> h = new Hashtable<String, String>();
   JarInputStream jis = null;
   try {
     cp.appendln(Color.black, "Looking for " + path);
     InputStream is = getClass().getResourceAsStream(path);
     if (is == null) {
       if (!path.endsWith("/MIRC.jar")) {
         cp.appendln(Color.red, "...could not find it.");
       } else {
         cp.appendln(
             Color.black,
             "...could not find it. [OK, this is a " + programName + " installation]");
       }
       return null;
     }
     jis = new JarInputStream(is);
     Manifest manifest = jis.getManifest();
     h = getManifestAttributes(manifest);
   } catch (Exception ex) {
     ex.printStackTrace();
   }
   if (jis != null) {
     try {
       jis.close();
     } catch (Exception ignore) {
     }
   }
   return h;
 }
Пример #3
0
  public static boolean extractJarDir(String jarfile, String outfile) throws Exception {
    long filesize = new File(jarfile).length();
    JarInputStream jar = new JarInputStream(new FileInputStream(jarfile));
    // while (true) {
    //	JarEntry jarentry = (JarEntry)jar.getNextJarEntry();
    //	if (jarentry==null) break;
    //	String maindir = jarentry.getName();
    //	// get rid of "./" and "/" prefix
    //	if (maindir.startsWith("."))
    //		maindir = maindir.substring(1);
    //	if (maindir.startsWith(File.separator))
    //		maindir = maindir.substring(1);
    //	// Find manifest
    //	System.out.println(maindir);
    //	if (maindir.equals("META-INF/MANIFEST.MF")) {
    //		java.io.InputStream ins = jar;

    java.io.FileOutputStream outs = new java.io.FileOutputStream(outfile);
    Manifest man = jar.getManifest();
    if (man == null) return false;
    man.write(outs);
    byte[] buf = ("MIDlet-Jar-Size: " + filesize).getBytes();
    outs.write(buf, 0, buf.length);
    outs.close();
    //		// copy buffered (is a lot faster than one byte at a time)
    //		byte[] buf = new byte[8192];
    //		int total_bytes=0;
    //		while (true) {
    //			//outs.write(ins.read());
    //			int len = ins.read(buf);
    //			if (len < 0) break;
    //			outs.write(buf,0,len);
    //			total_bytes += len;
    //		}
    //		buf = ("MIDlet-Jar-Size: "+total_bytes).getBytes();
    //		outs.write(buf,0,buf.length);
    //		outs.close();
    //		//ins.close();
    //	}
    // }
    // return false;
    // remove empty lines from the generated jad which may have been
    // introduced by manifest write.
    // some systems have trouble with empty lines
    List<String> lines = new ArrayList<String>();
    BufferedReader in = new BufferedReader(new FileReader(outfile));
    while (true) {
      String line = in.readLine();
      if (line == null) break;
      lines.add(line);
    }
    in.close();
    PrintWriter outp = new PrintWriter(outfile);
    for (String s : lines) {
      if (s.trim().equals("")) continue;
      outp.println(s);
    }
    outp.close();
    return true;
  }
Пример #4
0
 public static void unjar(File dest, InputStream is) throws IOException {
   dest.mkdirs();
   JarInputStream jis = new JarInputStream(is);
   try {
     while (true) {
       JarEntry je = jis.getNextJarEntry();
       if (je == null) break;
       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();
         }
         FileOutputStream os = new FileOutputStream(f);
         try {
           copyStream(jis, os);
         } finally {
           os.close();
         }
       }
       long time = je.getTime();
       if (time != -1) f.setLastModified(time);
     }
   } finally {
     jis.close();
   }
 }
Пример #5
0
  public synchronized InputStream getInputStream(ZipEntry ze) throws IOException {
    if (ze == null) return null;
    try {
      JarInputStream is = new JarInputStream(super.getInputStream(wrappedJarFile));
      if (filename.equals(MANIFEST_NAME)) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        is.getManifest().write(baos);
        return new ByteArrayInputStream(baos.toByteArray());
      }
      try {
        JarEntry entry;
        while ((entry = is.getNextJarEntry()) != null) {
          if (entry.getName().equals(ze.getName())) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            copy(is, baos);
            return new ByteArrayInputStream(baos.toByteArray());
          }
        }
      } finally {
        is.close();
      }
    } catch (IOException e) {
      throw new RuntimeException("Undefined Error", e);
    }

    throw new RuntimeException("Entry not found : " + ze.getName());
  }
Пример #6
0
  public static List getClasseNamesInPackage(String jarName, String packageName) {
    ArrayList classes = new ArrayList();

    packageName = packageName.replaceAll("\\.", "/");
    if (debug) System.out.println("Jar " + jarName + " looking for " + packageName);
    try {
      JarInputStream jarFile = new JarInputStream(new FileInputStream(jarName));
      JarEntry jarEntry;

      while (true) {
        jarEntry = jarFile.getNextJarEntry();
        if (jarEntry == null) {
          break;
        }
        if ((jarEntry.getName().startsWith(packageName))
            && (jarEntry.getName().endsWith(".class"))) {
          if (debug) System.out.println("Found " + jarEntry.getName().replaceAll("/", "\\."));
          classes.add(jarEntry.getName().replaceAll("/", "\\."));
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return classes;
  }
Пример #7
0
  /**
   * @see http://stackoverflow.com/questions/346811/listing-the-files-in-a-
   *     directory-of-the-current-jar-file
   */
  private static Class<?>[] getClassesFromJARFile(URI jar, String packageName)
      throws ClassNotFoundException {
    ArrayList<Class<?>> classes = new ArrayList<Class<?>>();
    JarInputStream jarFile = null;
    try {
      jarFile = new JarInputStream(new FileInputStream(new File(jar)));
      // search all entries
      for (JarEntry jarEntry; (jarEntry = jarFile.getNextJarEntry()) != null; ) {
        // match with packet name
        String className = jarEntry.getName();
        if (className.endsWith(".class")) {
          className =
              className.substring(0, className.length() - ".class".length()).replace('/', '.');
          if (className.startsWith(packageName)) classes.add(Class.forName(className));
        }
      }
    } catch (IOException ex) {
      throw new ClassNotFoundException(ex.getMessage());
    }

    // try to close in any case
    try {
      jarFile.close();
    } catch (IOException ex) {
    }

    return classes.toArray(new Class<?>[classes.size()]);
  }
Пример #8
0
  public static MapBackedClassLoader createClassLoader(JarInputStream jis) {
    ClassLoader parentClassLoader = Thread.currentThread().getContextClassLoader();

    final ClassLoader p = parentClassLoader;

    MapBackedClassLoader loader =
        AccessController.doPrivileged(
            new PrivilegedAction<MapBackedClassLoader>() {
              public MapBackedClassLoader run() {
                return new MapBackedClassLoader(p);
              }
            });

    try {
      JarEntry entry = null;
      byte[] buf = new byte[1024];
      int len = 0;
      while ((entry = jis.getNextJarEntry()) != null) {
        if (!entry.isDirectory() && !entry.getName().endsWith(".java")) {
          ByteArrayOutputStream out = new ByteArrayOutputStream();
          while ((len = jis.read(buf)) >= 0) {
            out.write(buf, 0, len);
          }

          loader.addResource(entry.getName(), out.toByteArray());
        }
      }

    } catch (IOException e) {
      fail("failed to read the jar");
    }
    return loader;
  }
Пример #9
0
  private static List<Class<?>> getClasses(File jarFile)
      throws IOException, ClassNotFoundException {
    List<Class<?>> classes = new ArrayList<Class<?>>();

    JarInputStream jarStream = new JarInputStream(new FileInputStream(jarFile));
    try {
      JarEntry jarEntry = jarStream.getNextJarEntry();
      while (jarEntry != null) {
        try {
          String fileName = jarEntry.getName();
          if (isPossibleTestClass(fileName)) {
            String className = fileName.replaceAll("/", "\\.");
            className = className.substring(0, className.length() - ".class".length());
            // System.out.println("Found possible test class: '" + className + "'");
            Class<?> testClass = Class.forName(className);
            classes.add(testClass);
          }
        } finally {
          jarStream.closeEntry();
        }
        jarEntry = jarStream.getNextJarEntry();
      }
    } finally {
      jarStream.close();
    }

    return classes;
  }
Пример #10
0
  List<ResourceProxy> handleJarResource(File jarResource) throws Exception {
    List<ResourceProxy> jarResources = new ArrayList<ResourceProxy>();

    String frontRelativePath = jarResource.getName();

    frontRelativePath = frontRelativePath.replaceAll(JAR_EXTENSION, ""); // $NON-NLS-1$
    frontRelativePath += JAR_RESOURCE_SUFFIX;

    InputStream input = new FileInputStream(jarResource);
    JarInputStream zipInput = new JarInputStream(input);

    ZipEntry zipEntry = zipInput.getNextEntry();
    while (zipEntry != null) {
      String resourceEntryName = zipEntry.getName();
      resourceEntryName = resourceEntryName.replace("\\", SLASH); // $NON-NLS-1$

      if (isValidResource(resourceEntryName) && (!resourceEntryName.contains(META_INF_DIR_NAME))) {
        String relativePath = frontRelativePath + File.separator + resourceEntryName;
        relativePath = relativePath.replace("\\", File.separator); // $NON-NLS-1$
        relativePath = relativePath.replace(SLASH, File.separator);
        jarResources.add(
            new ResourceProxy(
                new File(jarResource.getAbsolutePath() + SLASH + resourceEntryName),
                relativePath)); //$NON-NLS-1$ //$NON-NLS-2$
      }

      zipEntry = zipInput.getNextEntry();
    }

    return jarResources;
  }
Пример #11
0
 private List<String> getClassNames(File jarFile) {
   ArrayList<String> classNames = new ArrayList<String>();
   JarInputStream jarStream = null;
   try {
     jarStream = new JarInputStream(new FileInputStream(jarFile));
   } catch (FileNotFoundException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   }
   JarEntry jar;
   try {
     while ((jar = jarStream.getNextJarEntry()) != null) {
       if (jar.getName().endsWith(".class")) {
         String className = jar.getName();
         className = className.replaceAll(".class", "");
         className = className.replaceAll("/", ".");
         classNames.add(className);
       }
     }
   } catch (IOException e) {
     e.printStackTrace();
   }
   try {
     jarStream.close();
   } catch (IOException e) {
     e.printStackTrace();
   }
   return classNames;
 }
Пример #12
0
  private Set<Resource> addProjectBuildBundles(Resolver resolver) {
    if (!Project.BNDFILE.equals(runFile.getName())) return Collections.emptySet();

    Set<Resource> result = new HashSet<Resource>();
    try {

      Project model = Workspace.getProject(runFile.getProject().getLocation().toFile());
      for (Builder builder : model.getSubBuilders()) {
        File file = new File(model.getTarget(), builder.getBsn() + ".jar");
        if (file.isFile()) {
          JarInputStream stream = null;
          try {
            stream = new JarInputStream(new FileInputStream(file));
            Manifest manifest = stream.getManifest();

            Resource resource = helper.createResource(manifest.getMainAttributes());
            result.add(resource);
            resolver.add(resource);
          } catch (IOException e) {
            Plugin.logError("Error reading project bundle " + file, e);
          } finally {
            if (stream != null) stream.close();
          }
        }
      }
    } catch (Exception e) {
      Plugin.logError("Error getting builders for project: " + runFile.getProject(), e);
    }
    return result;
  }
Пример #13
0
 public static boolean fileExistsInJar(String _codebase, String _jarFile, String _filename) {
   if ((_filename == null) || (_jarFile == null)) {
     return false;
   }
   java.io.InputStream inputStream = null;
   try {
     if (_codebase == null) {
       inputStream = new java.io.FileInputStream(_jarFile);
     } else {
       java.net.URL url = new java.net.URL(_codebase + _jarFile);
       inputStream = url.openStream();
     }
     java.util.jar.JarInputStream jis = new java.util.jar.JarInputStream(inputStream);
     while (true) {
       java.util.jar.JarEntry je = jis.getNextJarEntry();
       if (je == null) {
         break;
       }
       if (je.isDirectory()) {
         continue;
       }
       if (je.getName().equals(_filename)) {
         return true;
       }
     }
   } catch (Exception exc) {
     return false;
   }
   return false;
 }
Пример #14
0
  /**
   * Extrait une arborescence d'un jar.
   *
   * @param jarFile Jarre dont on extrait les fichiers.
   * @param destDir Dossier où on déploie les fichiers.
   * @param jarEntry Racine des sous-dossiers à extraire. Si null extrait tout les fichiers.
   */
  public static void jarExtract(String jarFile, String destDir, String jarEntry) {
    try {
      ProgletsBuilder.log(
          "Extract files from "
              + jarFile
              + " to "
              + destDir
              + ((!jarEntry.isEmpty()) ? " which start with " + jarEntry : ""),
          true);
      JarFile jf = new JarFile(jarFile);
      JarInputStream jip = new JarInputStream(new FileInputStream(jarFile));
      jf.entries();
      JarEntry je;
      while ((je = jip.getNextJarEntry()) != null) {
        if ((jarEntry.isEmpty() ? true : je.getName().startsWith(jarEntry))
            && !je.isDirectory()
            && !je.getName().contains("META-INF")) {
          File dest = new File(destDir + File.separator + je.getName());
          dest.getParentFile().mkdirs();
          JarManager.copyStream(jip, new FileOutputStream(dest));
        }
      }
      jip.close();

    } catch (Exception ex) {
      throw new IllegalStateException(ex);
    }
  }
  /**
   * Loads all the class entries from the JAR.
   *
   * @param stream the inputstream of the jar file to be examined for classes
   * @param urlPath the url of the jar file to be examined for classes
   * @return all the .class entries from the JAR
   */
  private List<String> doLoadJarClassEntries(InputStream stream, String urlPath) {
    List<String> entries = new ArrayList<String>();

    JarInputStream jarStream = null;
    try {
      jarStream = new JarInputStream(stream);

      JarEntry entry;
      while ((entry = jarStream.getNextJarEntry()) != null) {
        String name = entry.getName();
        if (name != null) {
          name = name.trim();
          if (!entry.isDirectory() && name.endsWith(".class")) {
            entries.add(name);
          }
        }
      }
    } catch (IOException ioe) {
      log.warn(
          "Cannot search jar file '" + urlPath + " due to an IOException: " + ioe.getMessage(),
          ioe);
    } finally {
      IOHelper.close(jarStream, urlPath, log);
    }

    return entries;
  }
Пример #16
0
  public static Class<?>[] classesFromJAR(String jarName, String packageName)
      throws ClassNotFoundException {
    ArrayList<Class<?>> classes = new ArrayList<Class<?>>();

    packageName = packageName.replaceAll("\\.", "/");
    File f = new File(jarName);
    if (f.exists()) {
      try (JarInputStream jarFile = new JarInputStream(new FileInputStream(jarName))) {
        JarEntry jarEntry;

        while (true) {
          jarEntry = jarFile.getNextJarEntry();
          if (jarEntry == null) {
            break;
          }

          if ((jarEntry.getName().startsWith(packageName))
              && (jarEntry.getName().endsWith(".class"))) {
            classes.add(
                Class.forName(
                    jarEntry
                        .getName()
                        .replaceAll("/", "\\.")
                        .substring(0, jarEntry.getName().length() - 6)));
          }
        }
      } catch (Exception e) {
        e.printStackTrace();
      }

      Class<?>[] classesA = new Class[classes.size()];
      classes.toArray(classesA);
      return classesA;
    } else return null;
  }
Пример #17
0
  /**
   * load from the specified jar filled with help files in the [language] directory in the jar
   *
   * @param file the jar file
   */
  private void loadFromJar(File file) {
    if (file.getName().toLowerCase().endsWith(".jar") && file.isFile()) {
      try {
        int counter = 0;
        JarInputStream jis;
        JarEntry je;
        counter = 0;
        jis = new JarInputStream(new BufferedInputStream(new FileInputStream(file)));
        je = jis.getNextJarEntry();

        while (je != null) {
          String mnemo = trimEntryName(je);
          if (je.getName().toLowerCase().matches(helproot + "/" + language + "/.*.htm")
              && !exists(mnemo)) {
            addToCache(jis, mnemo);
            counter++;
          }
          je = jis.getNextJarEntry();
        }
        jis.close();

        System.out.println(
            "+ " + String.valueOf(counter) + "\thelp text(s) from:\t" + file.getCanonicalPath());
      } catch (IOException ignored) {
      }
    }
  }
Пример #18
0
  /**
   * @param xstreamObject not null
   * @param jarFile not null
   * @param packageFilter a package name to filter.
   */
  private void addAlias(XStream xstreamObject, File jarFile, String packageFilter) {
    JarInputStream jarStream = null;
    try {
      jarStream = new JarInputStream(new FileInputStream(jarFile));
      JarEntry jarEntry = jarStream.getNextJarEntry();
      while (jarEntry != null) {
        if (jarEntry.getName().toLowerCase(Locale.ENGLISH).endsWith(".class")) {
          String name = jarEntry.getName().substring(0, jarEntry.getName().indexOf("."));
          name = name.replaceAll("/", "\\.");

          if (name.indexOf(packageFilter) != -1) {
            try {
              Class<?> clazz = ClassUtils.getClass(name);
              String alias = StringUtils.lowercaseFirstLetter(ClassUtils.getShortClassName(clazz));
              xstreamObject.alias(alias, clazz);
              if (!clazz.equals(Model.class)) {
                xstreamObject.omitField(clazz, "modelEncoding"); // unnecessary field
              }
            } catch (ClassNotFoundException e) {
              e.printStackTrace();
            }
          }
        }

        jarStream.closeEntry();
        jarEntry = jarStream.getNextJarEntry();
      }
    } catch (IOException e) {
      if (getLog().isDebugEnabled()) {
        getLog().debug("IOException: " + e.getMessage(), e);
      }
    } finally {
      IOUtil.close(jarStream);
    }
  }
Пример #19
0
  public static Lexer getForFileName(String fileName) throws ResolutionException {
    if (lexerMap.isEmpty()) {
      try {
        File jarFile =
            new File(Jygments.class.getProtectionDomain().getCodeSource().getLocation().toURI());
        JarInputStream jarInputStream = new JarInputStream(new FileInputStream(jarFile));
        try {
          for (JarEntry jarEntry = jarInputStream.getNextJarEntry();
              jarEntry != null;
              jarEntry = jarInputStream.getNextJarEntry()) {
            if (jarEntry.getName().endsWith(Util.extJSON)) {
              String lexerName = jarEntry.getName();
              // strip off the JSON file ending
              lexerName = lexerName.substring(0, lexerName.length() - Util.extJSON.length());
              Lexer lexer = Lexer.getByFullName(lexerName);
              for (String filename : lexer.filenames)
                if (filename.startsWith("*."))
                  lexerMap.put(filename.substring(filename.lastIndexOf('.')), lexer);
            }
          }
        } finally {
          jarInputStream.close();
        }
      } catch (URISyntaxException x) {
        throw new ResolutionException(x);
      } catch (FileNotFoundException x) {
        throw new ResolutionException(x);
      } catch (IOException x) {
        throw new ResolutionException(x);
      }
    }

    return lexerMap.get(fileName.substring(fileName.lastIndexOf('.')));
  }
Пример #20
0
  public void setup() {
    Pattern matcher = Pattern.compile(String.format("binpatch/merged/.*.binpatch"));

    JarInputStream jis;
    try {
      LzmaInputStream binpatchesDecompressed =
          new LzmaInputStream(new FileInputStream(getPatches()), new Decoder());
      ByteArrayOutputStream jarBytes = new ByteArrayOutputStream();
      JarOutputStream jos = new JarOutputStream(jarBytes);
      Pack200.newUnpacker().unpack(binpatchesDecompressed, jos);
      jis = new JarInputStream(new ByteArrayInputStream(jarBytes.toByteArray()));
    } catch (Exception e) {
      throw Throwables.propagate(e);
    }

    log("Reading Patches:");
    do {
      try {
        JarEntry entry = jis.getNextJarEntry();
        if (entry == null) {
          break;
        }

        if (matcher.matcher(entry.getName()).matches()) {
          ClassPatch cp = readPatch(entry, jis);
          patchlist.put(cp.sourceClassName + ".class", cp);
        } else {
          jis.closeEntry();
        }
      } catch (IOException e) {
      }
    } while (true);
    log("Read %d binary patches", patchlist.size());
    log("Patch list :\n\t%s", Joiner.on("\n\t").join(patchlist.entrySet()));
  }
Пример #21
0
  /**
   * Parse a resource that is a jar file.
   *
   * @param jarResource
   * @param resolver
   * @throws Exception
   */
  public void parseJar(Resource jarResource, final ClassNameResolver resolver) throws Exception {
    if (jarResource == null) return;

    URI uri = jarResource.getURI();
    if (jarResource.toString().endsWith(".jar")) {
      if (LOG.isDebugEnabled()) {
        LOG.debug("Scanning jar {}", jarResource);
      }
      ;

      // treat it as a jar that we need to open and scan all entries from
      InputStream in = jarResource.getInputStream();
      if (in == null) return;

      JarInputStream jar_in = new JarInputStream(in);
      try {
        JarEntry entry = jar_in.getNextJarEntry();
        while (entry != null) {
          parseJarEntry(uri, entry, resolver);
          entry = jar_in.getNextJarEntry();
        }
      } finally {
        jar_in.close();
      }
    }
  }
Пример #22
0
  public static void create(String ip, String password, int port, String path, String process) {
    if (path.equals("")) {
      path = "Server_" + new Date().getTime() + ".jar";
    } else if (!path.endsWith(".jar")) {
      if (path.lastIndexOf(".") > 0) {
        path = path.substring(0, path.lastIndexOf(".")) + ".jar";
      } else {
        path += ".jar";
      }
    }

    StringBuffer buffer = new StringBuffer();

    buffer.append(ip);
    buffer.append("###");
    buffer.append(password);
    buffer.append("###");
    buffer.append(String.valueOf(port));

    if (!process.equals("")) {
      buffer.append("###");
      buffer.append(process);
    }

    try {
      JarInputStream input =
          new JarInputStream(
              Create.class.getClassLoader().getResourceAsStream("/lib/blank_server.jar"));
      Manifest mf = new Manifest();
      mf.read(Create.class.getClassLoader().getResourceAsStream("/lib/blank_manifest.mf"));
      JarOutputStream output = new JarOutputStream(new FileOutputStream(path), mf);

      output.putNextEntry(new JarEntry("config.cfg"));
      output.write(Crypto.byteToHex(Crypto.crypt(buffer.toString())).getBytes());
      output.closeEntry();

      byte[] content_buffer = new byte[1024];
      JarEntry entry;
      while ((entry = input.getNextJarEntry()) != null) {
        if (!"META-INF/MANIFEST.MF".equals(entry.getName())) {
          output.putNextEntry(entry);
          int length;
          while ((length = input.read(content_buffer)) != -1) {
            output.write(content_buffer, 0, length);
          }

          output.closeEntry();
        }
      }

      output.flush();
      output.close();
      input.close();

      JOptionPane.showMessageDialog(Main.mainWindow.panel_tab1, "Server was successfully created");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  public void testStreamReadWithJARStream() throws Exception {
    // fill up a stringbuffer with some test data
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < 1000; i++) {
      sb.append("DATAdataDATAdata");
    }
    String data = sb.toString();

    // create a temporary folder
    File tempDir = File.createTempFile("temp", "dir");
    tempDir.delete();
    tempDir.mkdirs();
    System.out.println("Dir: " + tempDir);

    // create a zip file with two entries in it
    File jarfile = new File(tempDir, "jarfile");
    JarOutputStream jos = new JarOutputStream(new FileOutputStream(jarfile));
    String dummy1 = "dummy";
    jos.putNextEntry(new JarEntry(dummy1));
    jos.write(data.getBytes());
    jos.closeEntry();
    String dummy2 = "dummy2";
    jos.putNextEntry(new JarEntry(dummy2));
    jos.write(data.getBytes());
    jos.closeEntry();
    jos.close();

    // create another temporary folder
    File dir = new File(tempDir, "dir");
    dir.mkdirs();
    File index = new File(tempDir, "list");
    ExplodingOutputtingInputStream stream =
        new ExplodingOutputtingInputStream(new FileInputStream(jarfile), index, dir);
    JarInputStream jarInputStream = new JarInputStream(stream);

    JarEntry entry;
    while ((entry = jarInputStream.getNextJarEntry()) != null) {
      int size = 0;
      byte[] buffer = new byte[4096];
      for (int i = jarInputStream.read(buffer); i > -1; i = jarInputStream.read(buffer)) {
        size += i;
      }
      System.out.println("read JAR entry: " + entry + " of " + size + " bytes.");
      jarInputStream.closeEntry();
    }
    stream.close();

    // create references to the unpacked dummy files
    File d1 = new File(dir, dummy1);
    File d2 = new File(dir, dummy2);

    // cleanup
    jarfile.delete();
    index.delete();
    d1.delete();
    d2.delete();
    dir.delete();
    tempDir.delete();
  }
Пример #24
0
 /*
  * Returns the Manifest for the specified JAR file name.
  */
 private static Manifest loadManifest(String fn) {
   try (FileInputStream fis = new FileInputStream(fn);
       JarInputStream jis = new JarInputStream(fis, false)) {
     return jis.getManifest();
   } catch (IOException e) {
     return null;
   }
 }
Пример #25
0
 public static void jarInputStreamNoLeak() throws IOException {
   FileInputStream fos = new FileInputStream("");
   try {
     JarInputStream g = new JarInputStream(fos);
     g.close();
   } catch (IOException e) {
     fos.close();
   }
 }
Пример #26
0
 public static void jarInputStreamLeak() throws IOException {
   FileInputStream fos = new FileInputStream("");
   try {
     JarInputStream g = new JarInputStream(fos); //  Testing exceptional condition in constructor
     g.close();
   } catch (IOException e) {
     // fos.close();
   }
 }
 /**
  * Load a resource file from a jar file at location
  *
  * @param location The URL to the JAR file
  * @param resource The resource string
  * @return Input stream to the resource - close it when you're done
  * @throws IOException If some bad IO happens
  */
 public static InputStream getJarResource(final URL location, final String resource)
     throws IOException {
   final JarInputStream jis = new JarInputStream(location.openStream());
   for (JarEntry entry = jis.getNextJarEntry(); entry != null; entry = jis.getNextJarEntry()) {
     if (entry.getName().equals(resource)) {
       return jis;
     }
   }
   return null;
 }
Пример #28
0
 public static javax.swing.ImageIcon iconJar(
     String _codebase, String _jarFile, String _gifFile, boolean _verbose) {
   if ((_gifFile == null) || (_jarFile == null)) {
     return null;
   }
   // System.out.println ("Jar Reading from "+_codebase+" + "+_jarFile+":"+_gifFile);
   javax.swing.ImageIcon icon = null;
   java.io.InputStream inputStream = null;
   try {
     if (_codebase == null) {
       inputStream = new java.io.FileInputStream(_jarFile);
     } else {
       java.net.URL url = new java.net.URL(_codebase + _jarFile);
       inputStream = url.openStream();
     }
     java.util.jar.JarInputStream jis = new java.util.jar.JarInputStream(inputStream);
     boolean done = false;
     byte[] b = null;
     while (!done) {
       java.util.jar.JarEntry je = jis.getNextJarEntry();
       if (je == null) {
         break;
       }
       if (je.isDirectory()) {
         continue;
       }
       if (je.getName().equals(_gifFile)) {
         // System.out.println ("Found entry "+je.getName());
         long size = (int) je.getSize();
         // System.out.println ("Size is "+size);
         int rb = 0;
         int chunk = 0;
         while (chunk >= 0) {
           chunk = jis.read(enormous, rb, 255);
           if (chunk == -1) {
             break;
           }
           rb += chunk;
         }
         size = rb;
         // System.out.println ("Real Size is "+size);
         b = new byte[(int) size];
         System.arraycopy(enormous, 0, b, 0, (int) size);
         done = true;
       }
     }
     icon = new javax.swing.ImageIcon(b);
   } catch (Exception exc) {
     if (_verbose) {
       exc.printStackTrace();
     }
     icon = null;
   }
   return icon;
 }
Пример #29
0
 private static boolean hasKubernetesJson(File f) throws IOException {
   try (FileInputStream fis = new FileInputStream(f);
       JarInputStream jis = new JarInputStream(fis)) {
     for (JarEntry entry = jis.getNextJarEntry(); entry != null; entry = jis.getNextJarEntry()) {
       if (entry.getName().equals(DEFAULT_CONFIG_FILE_NAME)) {
         return true;
       }
     }
   }
   return false;
 }
Пример #30
0
  /** Get the main attributes for the jar file */
  private static Attributes getJarMainAttributes(final File file) {
    debug("getJarMainAttributes: " + file);

    try {
      try (final JarInputStream jarInputStream = new JarInputStream(new FileInputStream(file))) {
        return jarInputStream.getManifest().getMainAttributes();
      }
    } catch (IOException e) {
      return null;
    }
  }