Пример #1
0
 /** Creates a new JAR file. */
 void create(OutputStream out, Manifest manifest) throws IOException {
   ZipOutputStream zos = new JarOutputStream(out);
   if (flag0) {
     zos.setMethod(ZipOutputStream.STORED);
   }
   if (manifest != null) {
     if (vflag) {
       output(getMsg("out.added.manifest"));
     }
     ZipEntry e = new ZipEntry(MANIFEST_DIR);
     e.setTime(System.currentTimeMillis());
     e.setSize(0);
     e.setCrc(0);
     zos.putNextEntry(e);
     e = new ZipEntry(MANIFEST_NAME);
     e.setTime(System.currentTimeMillis());
     if (flag0) {
       crc32Manifest(e, manifest);
     }
     zos.putNextEntry(e);
     manifest.write(zos);
     zos.closeEntry();
   }
   for (File file : entries) {
     addFile(zos, file);
   }
   zos.close();
 }
Пример #2
0
  @Test
  public void shouldSetTimestampOfEntries() throws IOException {
    Calendar cal = Calendar.getInstance();
    cal.set(1999, SEPTEMBER, 10);
    long old = getTimeRoundedToSeconds(cal.getTime());

    long now = getTimeRoundedToSeconds(new Date());

    try (CustomZipOutputStream out = ZipOutputStreams.newOutputStream(output)) {
      ZipEntry oldAndValid = new ZipEntry("oldAndValid");
      oldAndValid.setTime(old);
      out.putNextEntry(oldAndValid);

      ZipEntry current = new ZipEntry("current");
      current.setTime(now);
      out.putNextEntry(current);
    }

    try (ZipInputStream in = new ZipInputStream(Files.newInputStream(output))) {
      ZipEntry entry = in.getNextEntry();
      assertEquals("oldAndValid", entry.getName());
      assertEquals(old, entry.getTime());

      entry = in.getNextEntry();
      assertEquals("current", entry.getName());
      assertEquals(now, entry.getTime());
    }
  }
Пример #3
0
 /*
  * (non-Javadoc)
  *
  * @see org.xmind.core.io.IOutputTarget#setEntryTime(java.lang.String, long)
  */
 public void setEntryTime(String entryName, long time) {
   if (entryName != null) {
     if (currentEntry != null && currentEntry.getName().equals(entryName)) {
       currentEntry.setTime(time);
     }
   }
 }
Пример #4
0
  public void addTozip(ContentItem inContent, String inName, ZipOutputStream finalZip)
      throws IOException {
    InputStream is = inContent.getInputStream();
    if (is == null) {
      log.error("Couldn't add file to zip: " + inContent.getAbsolutePath());
      return;
    }
    ZipEntry entry = null;
    if (getFolderToStripOnZip() != null) {
      if (inName.contains(getFolderToStripOnZip())) {
        String stripped = inName.substring(getFolderToStripOnZip().length(), inName.length());
        entry = new ZipEntry(stripped);
      } else {
        entry = new ZipEntry(inName);
      }

    } else {

      entry = new ZipEntry(inName);
    }
    entry.setSize(inContent.getLength());
    entry.setTime(inContent.lastModified().getTime());

    finalZip.putNextEntry(entry);
    try {
      new OutputFiller().fill(is, finalZip);
    } finally {
      is.close();
    }
    finalZip.closeEntry();
  }
Пример #5
0
  /** Adds byte content into the zip as a file. */
  public static void addToZip(ZipOutputStream zos, byte[] content, String path, String comment)
      throws IOException {
    while (path.length() != 0 && path.charAt(0) == '/') {
      path = path.substring(1);
    }

    if (StringUtil.endsWithChar(path, '/')) {
      path = path.substring(0, path.length() - 1);
    }

    ZipEntry zipEntry = new ZipEntry(path);
    zipEntry.setTime(System.currentTimeMillis());

    if (comment != null) {
      zipEntry.setComment(comment);
    }

    zos.putNextEntry(zipEntry);

    InputStream is = new ByteArrayInputStream(content);
    try {
      StreamUtil.copy(is, zos);
    } finally {
      StreamUtil.close(is);
    }

    zos.closeEntry();
  }
  public void testCryptRoundtrip() throws Exception {
    ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
    ZipOutputStream zipOut = new ZipOutputStream(byteOut);

    ZipEntry dataEntry = new ZipEntry("Data");
    dataEntry.setTime(1000000L);
    zipOut.putNextEntry(dataEntry);

    DataOutputStream out = new DataOutputStream(zipOut);
    for (int i = 0; i < 100; i++) {
      out.writeInt(i);
      out.writeUTF(" ");
    }
    out.close();

    byte[] bytes = byteOut.toByteArray();

    ZipInputStream zipIn = new ZipInputStream(new ByteArrayInputStream(bytes));

    ZipEntry entry = zipIn.getNextEntry();
    while (entry != null && !entry.getName().equals("Data")) {
      entry = zipIn.getNextEntry();
    }

    if (entry == null) fail("Could not find the data entry");

    DataInputStream in = new DataInputStream(zipIn);
    for (int i = 0; i < 100; i++) {
      assertEquals(i, in.readInt());
      assertEquals("Expected an empty string here.", in.readUTF(), " ");
    }
    in.close();
  }
Пример #7
0
  /**
   * Adds a file to the Zip file
   *
   * @param file The file to add
   * @param entryName
   * @param zOut
   * @throws IOException
   */
  public static void addFileToZip(File file, String entryName, ZipOutputStream zOut)
      throws IOException {
    // Don't add directories
    if (file.isDirectory()) {
      return;
    }

    int bytesRead;
    final int bufSize = 1024;
    byte buf[] = new byte[bufSize];

    ZipEntry zipEntry = new ZipEntry(entryName);
    // Set time stamp to file's
    zipEntry.setTime(file.lastModified());

    try {
      zOut.putNextEntry(zipEntry);
    } catch (IOException ex) {
      /*
       * Ignore things like duplicate entries and just carry on
       */
      return;
    }

    BufferedInputStream in = new BufferedInputStream(new FileInputStream(file), bufSize);
    while ((bytesRead = in.read(buf)) != -1) {
      zOut.write(buf, 0, bytesRead);
    }
    zOut.closeEntry();
    in.close();
  }
Пример #8
0
 /*
  * public void zipFilesIn( File inDir,String inIncludePath, OutputStream
  * inToBrowser ) throws IOException, OpenEditException {
  *
  * String startingdir = inDir.getAbsolutePath(); if (
  * !startingdir.endsWith(File.separator)) { startingdir = startingdir +
  * File.separator; } if( inIncludePath.length() > 1) { inDir = new File(
  * inDir, inIncludePath); }
  *
  * ZipOutputStream finalZip = new ZipOutputStream(inToBrowser);
  *
  * File[] children = inDir.listFiles(); if ( children != null) { for (int i
  * = 0; i < children.length; i++) { addToZip( children[i], startingdir,
  * finalZip); } } finalZip.close(); }
  */
 public void addTozip(String inContent, String inName, ZipOutputStream finalZip)
     throws IOException {
   ZipEntry entry = new ZipEntry(inName);
   entry.setSize(inContent.length());
   entry.setTime(new Date().getTime());
   finalZip.putNextEntry(entry);
   finalZip.write(inContent.getBytes("UTF-8"));
   finalZip.closeEntry();
 }
Пример #9
0
  public AesZipEntry(ZipEntry zipEntry) {
    super(zipEntry.getName());
    super.setMethod(zipEntry.getMethod());
    super.setSize(zipEntry.getSize());
    super.setCompressedSize(zipEntry.getCompressedSize() + 28);
    super.setTime(zipEntry.getTime());

    flag |= 1; // bit0 - encrypted
    // flag |= 8;  // bit3 - use data descriptor
  }
Пример #10
0
  /**
   * Writes an entity to a given ZIP output stream with a given ZIP entry name.
   *
   * @param entity The entity to write.
   * @param out The ZIP output stream.
   * @param entryName The ZIP entry name.
   * @return True if the writing was successful.
   * @throws IOException
   */
  private boolean writeEntityStream(Representation entity, ZipOutputStream out, String entryName)
      throws IOException {
    if (entity != null && !entryName.endsWith("/")) {
      ZipEntry entry = new ZipEntry(entryName);
      if (entity.getModificationDate() != null)
        entry.setTime(entity.getModificationDate().getTime());
      else {
        entry.setTime(System.currentTimeMillis());
      }
      out.putNextEntry(entry);
      BioUtils.copy(new BufferedInputStream(entity.getStream()), out);
      out.closeEntry();
      return true;
    }

    out.putNextEntry(new ZipEntry(entryName));
    out.closeEntry();
    return false;
  }
  protected void packBundle(ZipOutputStream output, Bundle bundle, String path, Filter filter)
      throws IOException {
    if (filter != null && !filter.accept(path)) {
      log(Level.FINE, "exclude {0}/{1}", new Object[] {bundle.getBundleID(), path});
      return;
    }
    BundleFile bundleFile = bundle.getBundleFile();
    if (bundleFile.isDirectory(path)) {
      List<String> entries = bundleFile.getEntryPaths(path);
      for (String entry : entries) {
        packBundle(output, bundle, entry, filter);
      }
      return;
    }

    // pack the JAR/ZIP
    BundleEntry bundleEntry = bundleFile.getEntry(path);
    if (path.endsWith(".jar") || path.endsWith(".zip")) {
      File tempZipFile = createTempFile(bundleEntry);
      try {
        ZipFile zipFile = new ZipFile(tempZipFile);
        try {
          packZip(output, bundleEntry, zipFile, filter);
        } finally {
          zipFile.close();
        }
      } finally {
        tempZipFile.delete();
      }
      return;
    }

    // pack the normal entry
    if (existingEntries.contains(path)) {
      log(Level.WARNING, "duplicate {0}/{1}", new Object[] {bundle.getBundleID(), path});
      return;
    }
    existingEntries.add(path);

    InputStream input = bundleEntry.getInputStream();
    try {
      ZipEntry zipEntry = new ZipEntry(bundleEntry.getName());
      zipEntry.setTime(bundleEntry.getTime());
      zipEntry.setSize(bundleEntry.getSize());
      output.putNextEntry(zipEntry);
      try {
        copyStream(input, output);
      } finally {
        output.closeEntry();
      }
    } finally {
      input.close();
    }
  }
Пример #12
0
 private void addIndex(JarIndex index, ZipOutputStream zos) throws IOException {
   ZipEntry e = new ZipEntry(INDEX_NAME);
   e.setTime(System.currentTimeMillis());
   if (flag0) {
     CRC32OutputStream os = new CRC32OutputStream();
     index.write(os);
     os.updateEntry(e);
   }
   zos.putNextEntry(e);
   index.write(zos);
   zos.closeEntry();
 }
Пример #13
0
  /** Adds a new file entry to the ZIP output stream. */
  void addFile(ZipOutputStream zos, File file) throws IOException {
    String name = file.getPath();
    boolean isDir = file.isDirectory();
    if (isDir) {
      name = name.endsWith(File.separator) ? name : (name + File.separator);
    }
    name = entryName(name);

    if (name.equals("") || name.equals(".") || name.equals(zname)) {
      return;
    } else if ((name.equals(MANIFEST_DIR) || name.equals(MANIFEST_NAME)) && !Mflag) {
      if (vflag) {
        output(formatMsg("out.ignore.entry", name));
      }
      return;
    }

    long size = isDir ? 0 : file.length();

    if (vflag) {
      out.print(formatMsg("out.adding", name));
    }
    ZipEntry e = new ZipEntry(name);
    e.setTime(file.lastModified());
    if (size == 0) {
      e.setMethod(ZipEntry.STORED);
      e.setSize(0);
      e.setCrc(0);
    } else if (flag0) {
      crc32File(e, file);
    }
    zos.putNextEntry(e);
    if (!isDir) {
      copy(file, zos);
    }
    zos.closeEntry();
    /* report how much compression occurred. */
    if (vflag) {
      size = e.getSize();
      long csize = e.getCompressedSize();
      out.print(formatMsg2("out.size", String.valueOf(size), String.valueOf(csize)));
      if (e.getMethod() == ZipEntry.DEFLATED) {
        long ratio = 0;
        if (size != 0) {
          ratio = ((size - csize) * 100) / size;
        }
        output(formatMsg("out.deflated", String.valueOf(ratio)));
      } else {
        output(getMsg("out.stored"));
      }
    }
  }
Пример #14
0
  @Test
  public void shouldBeAbleToAddTwoZeroLengthFiles() throws IOException {
    File reference = File.createTempFile("reference", ".zip");

    try (CustomZipOutputStream out = ZipOutputStreams.newOutputStream(output);
        ZipOutputStream ref = new ZipOutputStream(new FileOutputStream(reference))) {
      ZipEntry entry = new ZipEntry("example.txt");
      entry.setTime(System.currentTimeMillis());
      out.putNextEntry(entry);
      ref.putNextEntry(entry);

      ZipEntry entry2 = new ZipEntry("example2.txt");
      entry2.setTime(System.currentTimeMillis());
      out.putNextEntry(entry2);
      ref.putNextEntry(entry2);
    }

    byte[] seen = Files.readAllBytes(output);
    byte[] expected = Files.readAllBytes(reference.toPath());

    assertArrayEquals(expected, seen);
  }
  // Used to investigate date roundtrip behaviour across zip versions
  public void testZipStuff() throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);
    // name the file inside the zip  file
    final File oddFile = new File("src/test/resources/zip-timestamp/file-with-odd-time.txt");
    final File evenFile = new File("src/test/resources/zip-timestamp/file-with-even-time.txt");
    final ZipEntry oddZe = new ZipEntry(oddFile.getName());
    oddZe.setTime(oddFile.lastModified());
    zos.putNextEntry(oddZe);
    final ZipEntry evenZe = new ZipEntry(evenFile.getName());
    evenZe.setTime(evenFile.lastModified());
    zos.putNextEntry(evenZe);
    zos.close();

    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    ZipInputStream zipInputStream = new ZipInputStream(bais);
    final java.util.zip.ZipEntry oddEntry = zipInputStream.getNextEntry();
    System.out.println("oddEntry.getTime() = " + new Date(oddEntry.getTime()).toString());
    System.out.println("oddEntry.getName() = " + oddEntry.getName());
    final java.util.zip.ZipEntry evenEntry = zipInputStream.getNextEntry();
    System.out.println("evenEntry.getName() = " + evenEntry.getName());
    System.out.println("evenEntry.getTime() = " + new Date(evenEntry.getTime()).toString());
  }
Пример #16
0
  private HashCode writeSimpleJarAndGetHash() throws Exception {
    try (FileOutputStream fileOutputStream = new FileOutputStream(output.toFile());
        ZipOutputStream out = new JarOutputStream(fileOutputStream)) {
      ZipEntry entry = new CustomZipEntry("test");
      out.putNextEntry(entry);
      out.write(new byte[0]);
      entry = new ZipEntry("test1");
      entry.setTime(ZipConstants.getFakeTime());
      out.putNextEntry(entry);
      out.write(new byte[0]);
    }

    return Hashing.sha1().hashBytes(Files.readAllBytes(output));
  }
Пример #17
0
 private static void zipDirectory(ZipOutputStream out, String rootPath, File... inputDirs)
     throws IOException {
   LinkedHashMap<String, File> files = newLinkedHashMap();
   for (File inputDir : Lists.reverse(Arrays.asList(inputDirs))) {
     listFilesRecursive(rootPath, files, inputDir);
   }
   for (Entry<String, File> entry : files.entrySet()) {
     String path = entry.getKey();
     File file = entry.getValue();
     if (file.isDirectory()) {
       if (!path.endsWith("/")) {
         path = path + "/";
       }
       ZipEntry dirEntry = new ZipEntry(path);
       dirEntry.setTime(file.lastModified());
       out.putNextEntry(dirEntry);
     } else {
       ZipEntry fileEntry = new ZipEntry(path);
       fileEntry.setTime(file.lastModified());
       out.putNextEntry(fileEntry);
       Files.copy(file, out);
     }
   }
 }
Пример #18
0
  private static void addToZip(
      IPath path, IResource resource, ZipOutputStream zip, boolean adjustGMTOffset)
      throws IOException, CoreException {

    switch (resource.getType()) {
      case IResource.FILE:
        ZipEntry zipEntry = new ZipEntry(path.toString());

        zip.putNextEntry(zipEntry);

        InputStream contents = ((IFile) resource).getContents();

        if (adjustGMTOffset) {
          TimeZone currentTimeZone = TimeZone.getDefault();
          Calendar currentDt = new GregorianCalendar(currentTimeZone, Locale.getDefault());

          // Get the Offset from GMT taking current TZ into account
          int gmtOffset =
              currentTimeZone.getOffset(
                  currentDt.get(Calendar.ERA), currentDt.get(Calendar.YEAR),
                  currentDt.get(Calendar.MONTH), currentDt.get(Calendar.DAY_OF_MONTH),
                  currentDt.get(Calendar.DAY_OF_WEEK), currentDt.get(Calendar.MILLISECOND));

          zipEntry.setTime(System.currentTimeMillis() + (gmtOffset * -1));
        }

        try {
          IOUtils.copy(contents, zip);
        } finally {
          contents.close();
        }

        break;

      case IResource.FOLDER:
      case IResource.PROJECT:
        IContainer container = (IContainer) resource;

        IResource[] members = container.members();

        for (IResource res : members) {
          addToZip(path.append(res.getName()), res, zip, adjustGMTOffset);
        }
    }
  }
  public void zip(File from, String to) throws FITTESTException {
    File toFile = new File(to);
    try {
      FileOutputStream fos = new FileOutputStream(toFile);
      ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(fos));
      byte data[] = new byte[BUFFER];

      Vector<File> files = collectFiles(from);
      URI base = null;
      if (from.isDirectory()) {
        base = from.toURI();
      }

      for (File f : files) {
        String name = null;
        if (base != null) {
          name = from.getName() + "/" + base.relativize(f.toURI()).getPath();
        } else {
          name = f.getName();
        }

        if (f.isDirectory()) {
          name = name.endsWith("/") ? name : name + "/";
        }

        ZipEntry entry = new ZipEntry(name);
        entry.setTime(f.lastModified());
        zos.putNextEntry(entry);

        if (f.isFile()) {
          BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f), BUFFER);
          int count;
          while ((count = bis.read(data, 0, BUFFER)) != -1) {
            zos.write(data, 0, count);
          }
          bis.close();
        }
        zos.closeEntry();
      }
      zos.close();
    } catch (Exception e) {
      throw new FITTESTException(e.getMessage());
    }
  }
Пример #20
0
  /**
   * Adds the specified entry to the output stream.
   *
   * @param entry entry descriptor
   * @param con contents
   * @param out output archive
   * @param level default compression level
   * @throws QueryException query exception
   * @throws IOException I/O exception
   */
  private void add(final Item entry, final Item con, final ArchiveOut out, final int level)
      throws QueryException, IOException {

    // create new zip entry
    final String name = string(entry.string(info));
    if (name.isEmpty()) ARCH_EMPTY.thrw(info);
    final ZipEntry ze = new ZipEntry(name);
    String en = null;

    // compression level
    byte[] lvl = null;
    if (entry instanceof ANode) {
      final ANode el = (ANode) entry;
      lvl = el.attribute(Q_LEVEL);

      // last modified
      final byte[] mod = el.attribute(Q_LAST_MOD);
      if (mod != null) {
        try {
          ze.setTime(new Int(new Dtm(mod, info)).itr());
        } catch (final QueryException qe) {
          ARCH_DATETIME.thrw(info, mod);
        }
      }

      // encoding
      final byte[] enc = el.attribute(Q_ENCODING);
      if (enc != null) {
        en = string(enc);
        if (!Charset.isSupported(en)) ARCH_ENCODING.thrw(info, enc);
      }
    }

    // data to be compressed
    byte[] val = checkStrBin(con);
    if (con instanceof AStr && en != null && en != Token.UTF8) val = encode(val, en);

    try {
      out.level(lvl == null ? level : toInt(lvl));
    } catch (final IllegalArgumentException ex) {
      ARCH_LEVEL.thrw(info, lvl);
    }
    out.write(ze, val);
  }
  /**
   * Write the contents of the file to the tar archive.
   *
   * @param entry
   * @param contents
   * @exception java.io.IOException
   * @exception org.eclipse.core.runtime.CoreException
   */
  private void write(ZipEntry entry, IFile contents) throws IOException, CoreException {
    byte[] readBuffer = new byte[4096];

    // If the contents are being compressed then we get the below for free.
    if (!useCompression) {
      entry.setMethod(ZipEntry.STORED);
      InputStream contentStream = contents.getContents(false);
      int length = 0;
      CRC32 checksumCalculator = new CRC32();
      try {
        int n;
        while ((n = contentStream.read(readBuffer)) > 0) {
          checksumCalculator.update(readBuffer, 0, n);
          length += n;
        }
      } finally {
        if (contentStream != null) {
          contentStream.close();
        }
      }

      entry.setSize(length);
      entry.setCrc(checksumCalculator.getValue());
    }

    // set the timestamp
    long localTimeStamp = contents.getLocalTimeStamp();
    if (localTimeStamp != IResource.NULL_STAMP) entry.setTime(localTimeStamp);

    outputStream.putNextEntry(entry);
    InputStream contentStream = contents.getContents(false);
    try {
      int n;
      while ((n = contentStream.read(readBuffer)) > 0) {
        outputStream.write(readBuffer, 0, n);
      }
    } finally {
      if (contentStream != null) {
        contentStream.close();
      }
    }
    outputStream.closeEntry();
  }
  protected void packZip(
      ZipOutputStream output, BundleEntry bundleEntry, ZipFile zipFile, Filter filter)
      throws IOException {
    Enumeration<? extends ZipEntry> entries = zipFile.entries();
    while (entries.hasMoreElements()) {
      ZipEntry srcEntry = entries.nextElement();
      String entryName = srcEntry.getName();
      if (filter != null && !filter.accept(bundleEntry.getName() + "/" + entryName)) {
        log(
            Level.FINE,
            "exclude {0}/{1}/{2}",
            new Object[] {bundleEntry.getBundleID(), bundleEntry.getName(), entryName});
        continue;
      }
      if (entryName.endsWith("/")) {
        continue;
      }
      if (existingEntries.contains(entryName)) {
        log(
            Level.WARNING,
            "duplicate {0}/{1}/{2}",
            new Object[] {bundleEntry.getBundleID(), bundleEntry.getName(), entryName});
        continue;
      }
      existingEntries.add(entryName);

      ZipEntry tgtEntry = new ZipEntry(entryName);
      tgtEntry.setTime(srcEntry.getTime());
      output.putNextEntry(tgtEntry);
      try {
        InputStream input = zipFile.getInputStream(srcEntry);
        try {
          copyStream(input, output);
        } finally {
          input.close();
        }
      } finally {
        output.closeEntry();
      }
    }
  }
Пример #23
0
 /**
  * Stores all the files in the given JAR file. Also attempts to root the paths of the filenames to
  * each element of a list of classpaths.
  *
  * @param jarFile the JAR file to create
  * @param classPath an array of paths to try to use as root for classes
  * @param files a list of files to store in the JAR file
  * @throws IOException
  */
 void createJar(File jarFile, String[] classPath, File... files) throws IOException {
   logger.info("Creating " + jarFile);
   JarOutputStream jos = new JarOutputStream(new FileOutputStream(jarFile));
   for (File f : files) {
     String name = f.getPath();
     if (classPath != null) {
       // Store only the path relative to the classpath so that
       // our Loader may use the package name of the associated
       // class to get the file as a resource from the ClassLoader.
       String[] names = new String[classPath.length];
       for (int i = 0; i < classPath.length; i++) {
         String path = new File(classPath[i]).getCanonicalPath();
         if (name.startsWith(path)) {
           names[i] = name.substring(path.length() + 1);
         }
       }
       // Retain only the shortest relative name.
       for (int i = 0; i < names.length; i++) {
         if (names[i] != null && names[i].length() < name.length()) {
           name = names[i];
         }
       }
     }
     ZipEntry e = new ZipEntry(name.replace(File.separatorChar, '/'));
     e.setTime(f.lastModified());
     jos.putNextEntry(e);
     FileInputStream fis = new FileInputStream(f);
     byte[] buffer = new byte[1024];
     int length;
     while ((length = fis.read(buffer)) != -1) {
       jos.write(buffer, 0, length);
     }
     fis.close();
     jos.closeEntry();
     //            f.delete();
     //            f.getParentFile().delete();
   }
   jos.close();
 }
Пример #24
0
 private boolean updateManifest(Manifest m, ZipOutputStream zos) throws IOException {
   addVersion(m);
   addCreatedBy(m);
   if (ename != null) {
     addMainClass(m, ename);
   }
   if (pname != null) {
     if (!addProfileName(m, pname)) {
       return false;
     }
   }
   ZipEntry e = new ZipEntry(MANIFEST_NAME);
   e.setTime(System.currentTimeMillis());
   if (flag0) {
     crc32Manifest(e, m);
   }
   zos.putNextEntry(e);
   m.write(zos);
   if (vflag) {
     output(getMsg("out.update.manifest"));
   }
   return true;
 }
Пример #25
0
  @Test
  public void shouldBeAbleToSimplyStoreInputFilesWithoutCompressing() throws IOException {
    File reference = File.createTempFile("reference", ".zip");

    try (CustomZipOutputStream out = ZipOutputStreams.newOutputStream(output);
        ZipOutputStream ref = new ZipOutputStream(new FileOutputStream(reference))) {
      byte[] bytes = "cheese".getBytes();
      ZipEntry entry = new ZipEntry("example.txt");
      entry.setMethod(ZipEntry.STORED);
      entry.setTime(System.currentTimeMillis());
      entry.setSize(bytes.length);
      entry.setCrc(Hashing.crc32().hashBytes(bytes).padToLong());
      out.putNextEntry(entry);
      ref.putNextEntry(entry);
      out.write(bytes);
      ref.write(bytes);
    }

    byte[] seen = Files.readAllBytes(output);
    byte[] expected = Files.readAllBytes(reference.toPath());

    assertArrayEquals(expected, seen);
  }
Пример #26
0
  public static void addFolderToZip(ZipOutputStream zos, String path, String comment)
      throws IOException {
    while (path.length() != 0 && path.charAt(0) == '/') {
      path = path.substring(1);
    }

    // add folder record
    if (!StringUtil.endsWithChar(path, '/')) {
      path += '/';
    }

    ZipEntry zipEntry = new ZipEntry(path);
    zipEntry.setTime(System.currentTimeMillis());

    if (comment != null) {
      zipEntry.setComment(comment);
    }

    zipEntry.setSize(0);
    zipEntry.setCrc(0);

    zos.putNextEntry(zipEntry);
    zos.closeEntry();
  }
Пример #27
0
  @TaskAction
  public void doTask() throws IOException {
    setup();

    if (getOutJar().exists()) {
      getOutJar().delete();
    }

    ZipFile in = new ZipFile(getInJar());
    ZipInputStream classesIn = new ZipInputStream(new FileInputStream(getClassesJar()));
    ZipOutputStream out =
        new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(getOutJar())));

    try {
      // DO PATCHES
      log("Patching Class:");
      for (ZipEntry e : Collections.list(in.entries())) {
        if (e.isDirectory()) {
          out.putNextEntry(e);
        } else {
          ZipEntry n = new ZipEntry(e.getName());
          n.setTime(e.getTime());
          out.putNextEntry(n);

          byte[] data = ByteStreams.toByteArray(in.getInputStream(e));
          ClassPatch patch = patchlist.get(e.getName().replace('\\', '/'));

          if (patch != null) {
            log(
                "\t%s (%s) (input size %d)",
                patch.targetClassName, patch.sourceClassName, data.length);
            int inputChecksum = adlerHash(data);
            if (patch.inputChecksum != inputChecksum) {
              throw new RuntimeException(
                  String.format(
                      "There is a binary discrepency between the expected input class %s (%s) and the actual class. Checksum on disk is %x, in patch %x. Things are probably about to go very wrong. Did you put something into the jar file?",
                      patch.targetClassName,
                      patch.sourceClassName,
                      inputChecksum,
                      patch.inputChecksum));
            }
            synchronized (patcher) {
              data = patcher.patch(data, patch.patch);
            }
          }

          out.write(data);
        }
      }

      // COPY DATA
      ZipEntry entry = null;
      while ((entry = classesIn.getNextEntry()) != null) {
        // no META or dirs. wel take care of dirs later.
        if (entry.getName().contains("META-INF")
            || entry.getName().equals("cpw/mods/fml/relauncher/Side.class")
            || entry.getName().equals("cpw/mods/fml/relauncher/SideOnly.class")) {
          continue;
        }

        out.putNextEntry(entry);
        out.write(ByteStreams.toByteArray(classesIn));
      }

    } finally {
      classesIn.close();
      in.close();
      out.close();
    }
  }
  /**
   * Creates a zip archive of the currently serialized files in getCurrentDirectory(), placing the
   * archive in getArchiveDirectory().
   *
   * @throws RuntimeException if clazz cannot be serialized. This exception has an informative
   *     message and wraps the originally thrown exception as root cause.
   * @see #getCurrentDirectory()
   * @see #getArchiveDirectory()
   */
  public void archiveCurrentDirectory() throws RuntimeException {
    System.out.println(
        "Making zip archive of files in "
            + getCurrentDirectory()
            + ", putting it in "
            + getArchiveDirectory()
            + ".");

    File current = new File(getCurrentDirectory());

    if (!current.exists() || !current.isDirectory()) {
      throw new IllegalArgumentException(
          "There is no "
              + current.getAbsolutePath()
              + " directory. "
              + "\nThis is where the serialized classes should be. "
              + "Please run serializeCurrentDirectory() first.");
    }

    File archive = new File(getArchiveDirectory());
    if (archive.exists() && !archive.isDirectory()) {
      throw new IllegalArgumentException(
          "Output directory " + archive.getAbsolutePath() + " is not a directory.");
    }

    if (!archive.exists()) {
      boolean success = archive.mkdirs();
    }

    String[] filenames = current.list();

    // Create a buffer for reading the files
    byte[] buf = new byte[1024];

    try {
      String version = Version.currentRepositoryVersion().toString();

      // Create the ZIP file
      String outFilename = "serializedclasses-" + version + ".zip";
      File _file = new File(getArchiveDirectory(), outFilename);
      FileOutputStream fileOut = new FileOutputStream(_file);
      ZipOutputStream out = new ZipOutputStream(fileOut);

      // Compress the files
      for (String filename : filenames) {
        File file = new File(current, filename);

        FileInputStream in = new FileInputStream(file);

        // Add ZIP entry to output stream.
        ZipEntry entry = new ZipEntry(filename);
        entry.setSize(file.length());
        entry.setTime(file.lastModified());

        out.putNextEntry(entry);

        // Transfer bytes from the file to the ZIP file
        int len;
        while ((len = in.read(buf)) > 0) {
          out.write(buf, 0, len);
        }

        // Complete the entry
        out.closeEntry();
        in.close();
      }

      // Complete the ZIP file
      out.close();

      System.out.println("Finished writing zip file " + outFilename + ".");
    } catch (IOException e) {
      throw new RuntimeException(
          "There was an I/O error associated with "
              + "the process of zipping up files in "
              + getCurrentDirectory()
              + ".",
          e);
    }
  }
  /**
   * Export the object (Item, Collection, or Community) to a package file on the indicated
   * OutputStream. Gets an exception of the object cannot be packaged or there is a failure creating
   * the package.
   *
   * @param context - DSpace context.
   * @param dso - DSpace object (item, collection, etc)
   * @param pkg - output stream on which to write package
   * @throws PackageException if package cannot be created or there is a fatal error in creating it.
   */
  public void disseminate(
      Context context, DSpaceObject dso, PackageParameters params, OutputStream pkg)
      throws PackageValidationException, CrosswalkException, AuthorizeException, SQLException,
          IOException {
    if (dso.getType() == Constants.ITEM) {
      Item item = (Item) dso;
      long lmTime = item.getLastModified().getTime();

      // how to handle unauthorized bundle/bitstream:
      String unauth = (params == null) ? null : params.getProperty("unauthorized");

      if (params != null && params.getProperty("manifestOnly") != null) {
        extraFiles = null;
        writeManifest(context, item, params, pkg);
      } else {
        extraFiles = new HashMap();
        ZipOutputStream zip = new ZipOutputStream(pkg);
        zip.setComment("METS archive created by DSpace METSDisseminationCrosswalk");

        // write manifest first.
        ZipEntry me = new ZipEntry(MANIFEST_FILE);
        me.setTime(lmTime);
        zip.putNextEntry(me);
        writeManifest(context, item, params, zip);
        zip.closeEntry();

        // copy extra (meta?) bitstreams into zip
        Iterator fi = extraFiles.keySet().iterator();
        while (fi.hasNext()) {
          String fname = (String) fi.next();
          ZipEntry ze = new ZipEntry(fname);
          ze.setTime(lmTime);
          zip.putNextEntry(ze);
          Utils.copy((InputStream) extraFiles.get(fname), zip);
          zip.closeEntry();
        }

        // copy all non-meta bitstreams into zip
        Bundle bundles[] = item.getBundles();
        for (int i = 0; i < bundles.length; i++) {
          if (!PackageUtils.isMetaInfoBundle(bundles[i])) {
            // unauthorized bundle?
            if (!AuthorizeManager.authorizeActionBoolean(context, bundles[i], Constants.READ)) {
              if (unauth != null && (unauth.equalsIgnoreCase("skip"))) {
                log.warn(
                    "Skipping Bundle[\""
                        + bundles[i].getName()
                        + "\"] because you are not authorized to read it.");
                continue;
              } else
                throw new AuthorizeException(
                    "Not authorized to read Bundle named \"" + bundles[i].getName() + "\"");
            }
            Bitstream[] bitstreams = bundles[i].getBitstreams();
            for (int k = 0; k < bitstreams.length; k++) {
              boolean auth =
                  AuthorizeManager.authorizeActionBoolean(context, bitstreams[k], Constants.READ);
              if (auth || (unauth != null && unauth.equalsIgnoreCase("zero"))) {
                ZipEntry ze = new ZipEntry(makeBitstreamName(bitstreams[k]));
                ze.setTime(lmTime);
                ze.setSize(auth ? bitstreams[k].getSize() : 0);
                zip.putNextEntry(ze);
                if (auth) Utils.copy(bitstreams[k].retrieve(), zip);
                else
                  log.warn(
                      "Adding zero-length file for Bitstream, SID="
                          + String.valueOf(bitstreams[k].getSequenceID())
                          + ", not authorized for READ.");
                zip.closeEntry();
              } else if (unauth != null && unauth.equalsIgnoreCase("skip")) {
                log.warn(
                    "Skipping Bitstream, SID="
                        + String.valueOf(bitstreams[k].getSequenceID())
                        + ", not authorized for READ.");
              } else {
                throw new AuthorizeException(
                    "Not authorized to read Bitstream, SID="
                        + String.valueOf(bitstreams[k].getSequenceID()));
              }
            }
          }
        }
        zip.close();
        extraFiles = null;
      }

    } else throw new PackageValidationException("Can only disseminate an Item now.");
  }
Пример #30
0
 private ZipEntry entryFor(final String name, final FileContent content)
     throws FileSystemException {
   final ZipEntry entry = new ZipEntry(name);
   entry.setTime(content.getLastModifiedTime());
   return entry;
 }