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();
  }
Exemplo n.º 2
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;
  }
Exemplo n.º 3
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();
    }
  }
Exemplo n.º 4
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;
 }
Exemplo n.º 5
0
 /**
  * load from specified JarInputStream
  *
  * @param fis Jar Input Stream
  * @param mnemo the name for the text file
  */
 private void addToCache(JarInputStream fis, String mnemo) {
   String text = "";
   byte[] buf = new byte[4096];
   int i = 0;
   try {
     while ((i = fis.read(buf)) != -1) {
       text += new String(buf, 0, i);
     }
   } catch (IOException ignored) {
   }
   helpcache.put(mnemo, text);
 }
Exemplo n.º 6
0
  /**
   * Attempt to verify that a Jar file is signed. All files (aside from ones in META-INF) must be
   * signed and trusted.
   *
   * @param in input stream
   * @throws SecurityException throw on verification failure
   * @throws IOException on I/O error
   */
  @SuppressWarnings("resource")
  public void verifyJar(InputStream in) throws IOException {
    JarInputStream jarFile = null;

    try {
      jarFile = new JarInputStream(in);
      Manifest manifest = jarFile.getManifest();
      if (manifest == null) {
        throw new SecurityException("The given file was not digitally signed");
      }

      // Ensure all the entries' signatures verify correctly
      byte[] buffer = new byte[8192];
      JarEntry entry;
      while ((entry = jarFile.getNextJarEntry()) != null) {
        if (entry.isDirectory()) continue;

        do {} while (jarFile.read(buffer, 0, buffer.length) != -1);

        Certificate[] certs = entry.getCertificates();
        if (isMetaInf(entry.getName())) {
          continue;
        } else if (certs == null || certs.length == 0) {
          throw new SecurityException("The archive contains files that are not digitally signed");
        } else {
          int i = 0;
          boolean verified = false;
          while (i < certs.length) {
            X509Certificate[] chain = findChain(certs, i);
            try {
              verify(chain);
              verified = true;
              break;
            } catch (SecurityException e) {
            }
            i += chain.length;
          }

          if (!verified) {
            throw new SecurityException(
                "The file(s) are signed by an entity that is not registered as 'trusted' with the launcher");
          }
        }
      }
    } finally {
      LauncherUtils.close(jarFile);
    }
  }
Exemplo n.º 7
0
  /** deletes the META-INF */
  public static void killMetaInf() {
    File inputFile =
        new File(
            Settings.getSettings().getInstallPath()
                + "/"
                + ModPack.getSelectedPack().getDir()
                + "/minecraft/bin",
            "minecraft.jar");
    File outputTmpFile =
        new File(
            Settings.getSettings().getInstallPath()
                + "/"
                + ModPack.getSelectedPack().getDir()
                + "/minecraft/bin",
            "minecraft.jar.tmp");
    try {
      JarInputStream input = new JarInputStream(new FileInputStream(inputFile));
      JarOutputStream output = new JarOutputStream(new FileOutputStream(outputTmpFile));
      JarEntry entry;

      while ((entry = input.getNextJarEntry()) != null) {
        if (entry.getName().contains("META-INF")) {
          continue;
        }
        output.putNextEntry(entry);
        byte buffer[] = new byte[1024];
        int amo;
        while ((amo = input.read(buffer, 0, 1024)) != -1) {
          output.write(buffer, 0, amo);
        }
        output.closeEntry();
      }

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

      if (!inputFile.delete()) {
        Logger.logError("Failed to delete Minecraft.jar.");
        return;
      }
      outputTmpFile.renameTo(inputFile);
    } catch (FileNotFoundException e) {
      Logger.logError(e.getMessage(), e);
    } catch (IOException e) {
      Logger.logError(e.getMessage(), e);
    }
  }
Exemplo n.º 8
0
 public static byte[] addJarEntry(byte[] jarToUpdate, String entryName, byte[] entryContent)
     throws IOException {
   ByteArrayOutputStream out = null;
   ByteArrayInputStream bais = null;
   JarOutputStream jos = null;
   JarInputStream jis = null;
   byte[] buffer = new byte[4096];
   try {
     bais = new ByteArrayInputStream(jarToUpdate);
     jis = new JarInputStream(bais);
     out = new ByteArrayOutputStream();
     jos = new JarOutputStream(out);
     JarEntry inEntry;
     while ((inEntry = (JarEntry) jis.getNextEntry()) != null) {
       if (!inEntry.getName().equals(entryName)) {
         jos.putNextEntry(new JarEntry(inEntry));
       } else {
         throw new IllegalArgumentException(
             "Jar entry " + entryName + " already exists in jar to update");
       }
       int len;
       while ((len = jis.read(buffer)) > 0) {
         jos.write(buffer, 0, len);
       }
       jos.flush();
     }
     JarEntry entry = new JarEntry(entryName);
     jos.putNextEntry(entry);
     jos.write(entryContent);
     jos.closeEntry();
     jos.finish();
     out.flush();
     return out.toByteArray();
   } finally {
     if (jos != null) {
       jos.close();
     }
     if (out != null) {
       out.close();
     }
     if (jis != null) {
       jis.close();
     }
   }
 }
 /**
  * Internally compute the hash used for jar comparison.
  *
  * <p>https://github.com/beachhouse/jboss-beach-jar-digest
  *
  * <p>TODO we also need a way to do something similar for modules, since a hash for jar is not
  * enough. We probably need to include all .jars, resources and parts of module.xml (not
  * <resources /> which are by name changes).
  *
  * @param file the jar file
  * @return the hash
  * @throws NoSuchAlgorithmException
  * @throws IOException
  */
 protected static byte[] internalJarComparison(final File file)
     throws NoSuchAlgorithmException, IOException {
   // TODO: make the algorithm choice configurable
   final MessageDigest jarDigest = MessageDigest.getInstance("SHA1");
   final MessageDigest digest = MessageDigest.getInstance("SHA1");
   final JarInputStream in =
       new JarInputStream(new BufferedInputStream(new FileInputStream(file)));
   try {
     JarEntry entry;
     while ((entry = in.getNextJarEntry()) != null) {
       // do not hash directories
       if (entry.isDirectory()) {
         continue;
       }
       final String name = entry.getName();
       // do not hash information added by jarsigner
       if (name.startsWith("META-INF/")) {
         if (name.endsWith(".SF") || name.endsWith(".DSA")) continue;
       }
       if (name.equals("META-INF/INDEX.LIST")) {
         continue;
       }
       // do not hash timestamped maven artifacts
       // TODO: make this optional, enabled by default
       if (name.startsWith("META-INF/maven/") && name.endsWith("/pom.properties")) {
         continue;
       }
       digest.reset();
       final byte[] buf = new byte[4096];
       int l;
       while ((l = in.read(buf)) > 0) {
         digest.update(buf, 0, l);
       }
       final byte[] d = digest.digest();
       jarDigest.update(d);
     }
   } finally {
     in.close();
   }
   return jarDigest.digest();
 }
Exemplo n.º 10
0
  /** Given an InputStream on a jar file, unjars the contents into the given directory. */
  public void unjar(InputStream in, File destDir) throws IOException {
    BufferedOutputStream dest = null;
    JarInputStream jis = new JarInputStream(in);
    JarEntry entry;
    while ((entry = jis.getNextJarEntry()) != null) {
      if (entry.isDirectory()) {
        File dir = new File(destDir, entry.getName());
        dir.mkdir();
        if (entry.getTime() != -1) dir.setLastModified(entry.getTime());
        continue;
      }
      // /////////////////////////////////////////
      String name = entry.getName();
      while (name.contains("/") || name.contains("//")) {
        File fdir = new File(destDir.getCanonicalPath() + "/" + name.split("/")[0]);
        // System.out.println(name.split("/")[0]);
        int index = name.indexOf("/");
        if (!fdir.exists()) fdir.mkdir();
        name = name.substring(index + 1);
      }

      // ////////////////////////////////////////////
      int count;
      byte data[] = new byte[BUFFER_SIZE];
      File destFile = new File(destDir, entry.getName());
      if (mVerbose) System.out.println("unjarring " + destFile + " from " + entry.getName());
      FileOutputStream fos = new FileOutputStream(destFile);
      dest = new BufferedOutputStream(fos, BUFFER_SIZE);
      while ((count = jis.read(data, 0, BUFFER_SIZE)) != -1) {
        dest.write(data, 0, count);
      }
      dest.flush();
      dest.close();
      if (entry.getTime() != -1) destFile.setLastModified(entry.getTime());
    }
    jis.close();
  }
Exemplo n.º 11
0
  /** Load the jar contents from InputStream */
  private void loadJar(InputStream jarStream, ProtectionDomain protectionDomain) {

    BufferedInputStream bis = null;
    JarInputStream jis = null;

    try {
      bis = new BufferedInputStream(jarStream);
      jis = new JarInputStream(bis);

      JarEntry jarEntry = null;
      while ((jarEntry = jis.getNextJarEntry()) != null) {
        if (logger.isLoggable(Level.FINEST)) logger.finest(dump(jarEntry));

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

        if (jarEntryContents.containsKey(jarEntry.getName())) {
          if (!collisionAllowed)
            throw new JclException("Class/Resource " + jarEntry.getName() + " already loaded");
          else {
            if (logger.isLoggable(Level.FINEST))
              logger.finest(
                  "Class/Resource " + jarEntry.getName() + " already loaded; ignoring entry...");
            continue;
          }
        }

        if (logger.isLoggable(Level.FINEST))
          logger.finest(
              "Entry Name: " + jarEntry.getName() + ", " + "Entry Size: " + jarEntry.getSize());

        byte[] b = new byte[2048];
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        int len = 0;
        while ((len = jis.read(b)) > 0) {
          out.write(b, 0, len);
        }

        // add to internal resource HashMap
        jarEntryContents.put(
            jarEntry.getName(), new JarResource(out.toByteArray(), protectionDomain));

        if (logger.isLoggable(Level.FINEST))
          logger.finest(
              jarEntry.getName()
                  + ": size="
                  + out.size()
                  + " ,csize="
                  + jarEntry.getCompressedSize());

        out.close();
      }
    } catch (IOException e) {
      throw new JclException(e);
    } catch (NullPointerException e) {
      if (logger.isLoggable(Level.FINEST)) logger.finest("Done loading.");
    } finally {
      if (jis != null)
        try {
          jis.close();
        } catch (IOException e) {
          throw new JclException(e);
        }

      if (bis != null)
        try {
          bis.close();
        } catch (IOException e) {
          throw new JclException(e);
        }
    }
  }
Exemplo n.º 12
0
  /**
   * Reads the jar found at the specified URL and stores the entries in the jar_entry table.
   *
   * @param jarId The id used for the foreign key to the jar_repository table
   * @param urlStream An InputStream (opened on what may have been a URL)
   * @param sz The expected size of the stream, used as a worst-case mark/reset limit. The caller
   *     might pass -1 if the URLConnection can't determine a size in advance (a generous guess will
   *     be made in that case).
   * @throws SQLException
   */
  public static void addClassImages(int jarId, InputStream urlStream, int sz) throws SQLException {
    PreparedStatement stmt = null;
    PreparedStatement descIdFetchStmt = null;
    PreparedStatement descIdStoreStmt = null;
    ResultSet rs = null;

    try {
      byte[] buf = new byte[1024];
      ByteArrayOutputStream img = new ByteArrayOutputStream();
      stmt =
          SQLUtils.getDefaultConnection()
              .prepareStatement(
                  "INSERT INTO sqlj.jar_entry(entryName, jarId, entryImage) VALUES(?, ?, ?)");

      BufferedInputStream bis = new BufferedInputStream(urlStream);
      String manifest = rawManifest(bis, sz);
      JarInputStream jis = new JarInputStream(bis);
      if (manifest != null) {
        PreparedStatement us =
            SQLUtils.getDefaultConnection()
                .prepareStatement("UPDATE sqlj.jar_repository SET jarManifest = ? WHERE jarId = ?");
        try {
          us.setString(1, manifest);
          us.setInt(2, jarId);
          if (us.executeUpdate() != 1)
            throw new SQLException("Jar repository update did not update 1 row");
        } finally {
          SQLUtils.close(us);
        }
      }

      for (; ; ) {
        JarEntry je = jis.getNextJarEntry();
        if (je == null) break;

        if (je.isDirectory()) continue;

        String entryName = je.getName();

        int nBytes;
        img.reset();
        while ((nBytes = jis.read(buf)) > 0) img.write(buf, 0, nBytes);
        jis.closeEntry();

        stmt.setString(1, entryName);
        stmt.setInt(2, jarId);
        stmt.setBytes(3, img.toByteArray());
        if (stmt.executeUpdate() != 1)
          throw new SQLException("Jar entry insert did not insert 1 row");
      }

      Matcher ddr = ddrSection.matcher(null != manifest ? manifest : "");
      Matcher cnt = mfCont.matcher("");
      for (int ordinal = 0; ddr.find(); ++ordinal) {
        String entryName = cnt.reset(ddr.group(1)).replaceAll("");
        if (descIdFetchStmt == null)
          descIdFetchStmt =
              SQLUtils.getDefaultConnection()
                  .prepareStatement(
                      "SELECT entryId FROM sqlj.jar_entry" + " WHERE jarId = ? AND entryName = ?");
        descIdFetchStmt.setInt(1, jarId);
        descIdFetchStmt.setString(2, entryName);
        rs = descIdFetchStmt.executeQuery();
        if (!rs.next()) throw new SQLException("Failed to refetch row in sqlj.jar_entry");

        int deployImageId = rs.getInt(1);

        if (descIdStoreStmt == null)
          descIdStoreStmt =
              SQLUtils.getDefaultConnection()
                  .prepareStatement(
                      "INSERT INTO sqlj.jar_descriptor"
                          + " (jarId, entryId, ordinal) VALUES"
                          + " ( ?, ?, ? )");
        descIdStoreStmt.setInt(1, jarId);
        descIdStoreStmt.setInt(2, deployImageId);
        descIdStoreStmt.setInt(3, ordinal);
        if (descIdStoreStmt.executeUpdate() != 1)
          throw new SQLException("Jar deployment descriptor insert did not insert " + "1 row");
      }
    } catch (IOException e) {
      throw new SQLException("I/O exception reading jar file: " + e.getMessage());
    } finally {
      SQLUtils.close(rs);
      SQLUtils.close(descIdStoreStmt);
      SQLUtils.close(descIdFetchStmt);
      SQLUtils.close(stmt);
    }
  }
Exemplo n.º 13
0
  /** Unzips a file in the file directory */
  public static final void unjar(final String filenamePath) throws IOException {
    final int BUFFER = 2048;
    int count;
    byte data[] = new byte[BUFFER];

    if (filenamePath == null || filenamePath.length() == 0) {
      throw new IllegalArgumentException("No file to unjar!");
    }

    String baseJarDirName = getFilepath(filenamePath);
    String unjaredDirName = getNakedFilename(filenamePath);
    String baseUnjaredDirName = getFilepath(filenamePath) + DIRECTORY_SEPARATOR + unjaredDirName;
    File baseUnjaredDir = new File(baseUnjaredDirName);
    if (!baseUnjaredDir.exists()) {
      baseUnjaredDir.mkdirs();
    }

    FileInputStream fileInputstream = null;
    JarInputStream jarIn = null;
    try {
      fileInputstream = new FileInputStream(filenamePath);
      jarIn = new JarInputStream(new BufferedInputStream(fileInputstream));
      JarEntry entry;
      while ((entry = jarIn.getNextJarEntry()) != null) {
        String entryFilenamePath = entry.getName();
        if (!entryFilenamePath.startsWith(unjaredDirName)) {
          entryFilenamePath = unjaredDirName + DIRECTORY_SEPARATOR + entryFilenamePath;
        }

        // Check entry sub directory
        String entryPathname = getFilepath(entryFilenamePath);
        if (entryPathname != null && entryPathname.length() > 0) {
          File entryPath = new File(baseJarDirName + DIRECTORY_SEPARATOR + entryPathname);
          if (!entryPath.exists()) {
            entryPath.mkdirs();
          }
        }

        // Check entry file
        String entryFilename = getFilename(entryFilenamePath);
        if (entryFilename != null & entryFilename.length() > 0) {
          File outputFile = new File(baseJarDirName + DIRECTORY_SEPARATOR + entryFilenamePath);
          if (!outputFile.exists()) {
            outputFile.createNewFile();
          }

          // write the files to the disk();
          BufferedOutputStream dest = null;
          FileOutputStream fileOutputstream = null;
          try {
            fileOutputstream = new FileOutputStream(outputFile);
            dest = new BufferedOutputStream(fileOutputstream, BUFFER);
            while ((count = jarIn.read(data, 0, BUFFER)) != -1) {
              dest.write(data, 0, count);
            }
            dest.flush();
          } finally {
            if (fileOutputstream != null) {
              fileOutputstream.close();
            }
            if (dest != null) {
              dest.close();
            }
          }
        }
      }
    } finally {
      if (fileInputstream != null) {
        fileInputstream.close();
      }
      if (jarIn != null) {
        jarIn.close();
      }
    }
  }
  private File writeIndexes(
      File jar, String entryName, List<LameSubDeploymentIndex> subDeploymentIndices)
      throws IOException {
    int dotIndex = entryName.lastIndexOf('.');
    if (dotIndex == -1) {
      throw new AssertionError("missing extension from: " + entryName);
    }
    String suffix = entryName.substring(dotIndex);
    int slashIndex = entryName.lastIndexOf('/');
    String prefix;
    if (slashIndex == -1) {
      prefix = entryName.substring(0, dotIndex);
    } else {
      prefix = entryName.substring(slashIndex + 1, dotIndex);
    }
    File indexedJar = File.createTempFile(prefix, suffix);

    try (JarInputStream inputStream = new JarInputStream(new FileInputStream(jar))) {
      Manifest manifest = inputStream.getManifest();
      Map<String, File> replacementMap = this.buildReplacementMap(subDeploymentIndices);
      try (FileOutputStream fileOutputStream = new FileOutputStream(indexedJar);
          JarOutputStream outputStream =
              manifest != null
                  ? new JarOutputStream(fileOutputStream, manifest)
                  : new JarOutputStream(fileOutputStream)) {
        JarEntry entry = inputStream.getNextJarEntry();
        byte[] buffer = new byte[8192];
        ByteArrayOutputStream bos = null;
        while (entry != null) {
          // TODO should we keep META-INF/INDEX.LIST or drop it? should be first entry
          boolean isFuckedUpIbm = isFuckedUpIbmMqSeriesEntry(entryName, entry);
          if (!isFuckedUpIbm) {
            File replacement = replacementMap.get(entryName);
            if (replacement == null) {
              outputStream.putNextEntry(entry);
              if (entry.getSize() != 0L) {
                int read;
                while ((read = inputStream.read(buffer)) != -1) {
                  outputStream.write(buffer, 0, read);
                }
              }

            } else {
              // some subdeployments (eg WAR in EAR) have changed and we need to replace them
              JarEntry replaced = safeCopy(entry);
              replaced.setSize(replacement.length());
              outputStream.putNextEntry(replaced);
              try (InputStream input = new FileInputStream(replacement)) {
                int read;
                while ((read = inputStream.read(buffer)) != -1) {
                  outputStream.write(buffer, 0, read);
                }
              }
            }

          } else {
            // some JARs in the IBM RAR are f****d up
            // the size of certain file in the central directory index is wrong
            if (bos == null) {
              bos = new ByteArrayOutputStream(1024);
            } else {
              bos.reset();
            }

            long actualSize = 0L;
            int read;
            while ((read = inputStream.read(buffer)) != -1) {
              bos.write(buffer, 0, read);
              actualSize += read;
            }

            System.out.println(
                "encountered f****d up entry: "
                    + entry.getName()
                    + " in: "
                    + entryName
                    + " reported size: "
                    + entry.getSize()
                    + " actual size: "
                    + actualSize);

            JarEntry unfucked = safeCopy(entry);
            unfucked.setSize(actualSize);
            outputStream.putNextEntry(unfucked);
            bos.writeTo(outputStream);
          }
          entry = inputStream.getNextJarEntry();
        }

        // REVIEW: more or less reuse?
        IndexWriter indexWriter = new IndexWriter(outputStream);
        for (LameSubDeploymentIndex subDeploymentIndex : subDeploymentIndices) {
          String indexFile = subDeploymentIndex.name + ".index";
          JarEntry indexEntry = new JarEntry(indexFile);
          indexEntry.setMethod(ZipEntry.DEFLATED);
          outputStream.putNextEntry(indexEntry);
          // IndexWriter does buffering
          indexWriter.write(subDeploymentIndex.index);
        }
      }
    }
    return indexedJar;
  }
Exemplo n.º 15
0
  /**
   * Unpacks the Archive from the input file to the output file
   *
   * @throws Pack200Exception
   * @throws IOException
   */
  public void unpack() throws Pack200Exception, IOException {
    outputStream.setComment("PACK200");
    try {
      if (!inputStream.markSupported()) {
        inputStream = new BufferedInputStream(inputStream);
        if (!inputStream.markSupported()) throw new IllegalStateException();
      }
      inputStream.mark(2);
      if (((inputStream.read() & 0xFF) | (inputStream.read() & 0xFF) << 8)
          == GZIPInputStream.GZIP_MAGIC) {
        inputStream.reset();
        inputStream = new BufferedInputStream(new GZIPInputStream(inputStream));
      } else {
        inputStream.reset();
      }
      inputStream.mark(4);
      int[] magic = {0xCA, 0xFE, 0xD0, 0x0D}; // Magic word for
      // pack200
      int word[] = new int[4];
      for (int i = 0; i < word.length; i++) {
        word[i] = inputStream.read();
      }
      boolean compressedWithE0 = false;
      for (int m = 0; m < magic.length; m++) {
        if (word[m] != magic[m]) {
          compressedWithE0 = true;
        }
      }
      inputStream.reset();
      if (compressedWithE0) { // The original Jar was not packed, so just
        // copy it across
        JarInputStream jarInputStream = new JarInputStream(inputStream);
        JarEntry jarEntry;
        while ((jarEntry = jarInputStream.getNextJarEntry()) != null) {
          outputStream.putNextEntry(jarEntry);
          byte[] bytes = new byte[16384];
          int bytesRead = jarInputStream.read(bytes);
          while (bytesRead != -1) {
            outputStream.write(bytes, 0, bytesRead);
            bytesRead = jarInputStream.read(bytes);
          }
          outputStream.closeEntry();
        }
      } else {
        int i = 0;
        while (available(inputStream)) {
          i++;
          Segment segment = new Segment();
          segment.setLogLevel(logLevel);
          segment.setLogStream(
              logFile != null ? (OutputStream) logFile : (OutputStream) System.out);
          segment.setPreRead(false);

          if (i == 1) {
            segment.log(
                Segment.LOG_LEVEL_VERBOSE,
                "Unpacking from " + inputFileName + " to " + outputFileName);
          }
          segment.log(Segment.LOG_LEVEL_VERBOSE, "Reading segment " + i);
          if (overrideDeflateHint) {
            segment.overrideDeflateHint(deflateHint);
          }
          segment.unpack(inputStream, outputStream);
          outputStream.flush();

          if (inputStream instanceof FileInputStream) {
            inputFileName = ((FileInputStream) inputStream).getFD().toString();
          }
        }
      }
    } finally {
      try {
        inputStream.close();
      } catch (Exception e) {
      }
      try {
        outputStream.close();
      } catch (Exception e) {
      }
      if (logFile != null) {
        try {
          logFile.close();
        } catch (Exception e) {
        }
      }
    }
    if (removePackFile) {
      File file = new File(inputFileName);
      boolean deleted = file.delete();
      if (!deleted) {
        throw new Pack200Exception("Failed to delete the input file.");
      }
    }
  }
Exemplo n.º 16
0
 public int read(byte b[], int off, int len) throws IOException {
   return jis.read(b, off, len);
 }
Exemplo n.º 17
0
 public int read() throws IOException {
   return jis.read();
 }