Пример #1
0
  /**
   * tests case when Main-Class is not in the zip launched but in another zip referenced by
   * Class-Path
   *
   * @throws Exception in case of troubles
   */
  public void test_main_class_in_another_zip() throws Exception {
    File fooZip = File.createTempFile("hyts_", ".zip");
    File barZip = File.createTempFile("hyts_", ".zip");
    fooZip.deleteOnExit();
    barZip.deleteOnExit();

    // create the manifest
    Manifest man = new Manifest();
    Attributes att = man.getMainAttributes();
    att.put(Attributes.Name.MANIFEST_VERSION, "1.0");
    att.put(Attributes.Name.MAIN_CLASS, "foo.bar.execjartest.Foo");
    att.put(Attributes.Name.CLASS_PATH, fooZip.getName());

    File resources = Support_Resources.createTempFolder();

    ZipOutputStream zoutFoo = new ZipOutputStream(new FileOutputStream(fooZip));
    zoutFoo.putNextEntry(new ZipEntry("foo/bar/execjartest/Foo.class"));
    zoutFoo.write(getResource(resources, "hyts_Foo.ser"));
    zoutFoo.close();

    ZipOutputStream zoutBar = new ZipOutputStream(new FileOutputStream(barZip));
    zoutBar.putNextEntry(new ZipEntry("META-INF/MANIFEST.MF"));
    man.write(zoutBar);

    zoutBar.putNextEntry(new ZipEntry("foo/bar/execjartest/Bar.class"));
    zoutBar.write(getResource(resources, "hyts_Bar.ser"));
    zoutBar.close();

    String[] args = new String[] {"-jar", barZip.getAbsolutePath()};

    // execute the JAR and read the result
    String res = Support_Exec.execJava(args, null, false);

    assertTrue("Error executing JAR : result returned was incorrect.", res.startsWith("FOOBAR"));
  }
Пример #2
0
  @VisibleForTesting
  static void writeAar(
      Path aar, final MergedAndroidData data, Path manifest, Path rtxt, Path classes)
      throws IOException {
    try (final ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(aar.toFile()))) {
      ZipEntry manifestEntry = new ZipEntry("AndroidManifest.xml");
      zipOut.putNextEntry(manifestEntry);
      zipOut.write(Files.readAllBytes(manifest));
      zipOut.closeEntry();

      ZipEntry classJar = new ZipEntry("classes.jar");
      zipOut.putNextEntry(classJar);
      zipOut.write(Files.readAllBytes(classes));
      zipOut.closeEntry();

      Files.walkFileTree(
          data.getResourceDirFile().toPath(),
          new ZipDirectoryWriter(zipOut, data.getResourceDirFile().toPath(), "res"));

      ZipEntry r = new ZipEntry("R.txt");
      zipOut.putNextEntry(r);
      zipOut.write(Files.readAllBytes(rtxt));
      zipOut.closeEntry();

      if (data.getAssetDirFile().exists() && data.getAssetDirFile().list().length > 0) {
        Files.walkFileTree(
            data.getAssetDirFile().toPath(),
            new ZipDirectoryWriter(zipOut, data.getAssetDirFile().toPath(), "assets"));
      }
    }
    aar.toFile().setLastModified(EPOCH);
  }
Пример #3
0
  private static void writeScriptDocumentation(
      Context context, ZipOutputStream out, String path, int templateType) {
    String[] components = path.split("/");

    String language = components[components.length - 1];

    byte[] indexPage =
        BootstrapSiteExporter.fetchContent(context, language, null, true, templateType);

    try {
      ZipEntry entry = new ZipEntry(path + "/index.html");
      out.putNextEntry(entry);
      out.write(indexPage);
      out.closeEntry();

      JSONArray methods = BootstrapSiteExporter.methodsForLanguage(context, language);

      HashSet<String> loaded = new HashSet<>();

      for (int i = 0; i < methods.length(); i++) {
        try {
          JSONObject methodDef = methods.getJSONObject(i);

          if (methodDef.has(BootstrapSiteExporter.METHOD_ASSET_PATH)) {
            String[] methodComponents =
                methodDef.getString(BootstrapSiteExporter.METHOD_ASSET_PATH).split("/");

            String page = methodComponents[methodComponents.length - 1];

            if (loaded.contains(page) == false) {
              String pageLanguage = language;

              if (page.startsWith("all_")) pageLanguage = "all";

              byte[] methodContent =
                  BootstrapSiteExporter.fetchContent(
                      context, pageLanguage, page, true, templateType);

              try {
                ZipEntry methodEntry = new ZipEntry(path + "/" + page);
                out.putNextEntry(methodEntry);
                out.write(methodContent);
                out.closeEntry();
              } catch (ZipException e) {
                e.printStackTrace();
              }

              loaded.add(page);
            }
          }
        } catch (JSONException e) {
          e.printStackTrace();
        }
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  /**
   * Loop through the ZIP file, copying its entries into a new, temporary ZIP file, skipping the
   * entry to be deleted. Then replace the original file with the new one.
   */
  protected Integer deleteEntry() throws XMLDataStoreException {
    try {
      ZipInputStream inStream = this.buildZipInputStream();
      File outFile = this.buildTempFile();
      ZipOutputStream outStream = new ZipOutputStream(new FileOutputStream(outFile));

      byte[] buffer = new byte[32768];
      int inCount = 0;
      int outCount = 0;

      // copy all the entries except the one to be deleted
      ZipEntry entry = inStream.getNextEntry();
      while (entry != null) {
        inCount++;
        if (!this.getZipEntryName().equals(entry.getName())) {
          outCount++;
          outStream.putNextEntry(entry);
          int byteCount;
          while ((byteCount = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, byteCount);
          }
          outStream.closeEntry();
        }
        entry = inStream.getNextEntry();
      }
      inStream.close();
      if (outCount == 0) {
        // add a dummy record to an empty file so we can close it
        // this is required by ZipOutputStream
        outStream.putNextEntry(new ZipEntry("delete.txt"));
        outStream.write(
            "This file is a place-holder. The containing ZIP file should be deleted.".getBytes());
        outStream.closeEntry();
      }
      outStream.close();
      if (outCount == inCount) {
        // no entries were removed - just delete the temp file
        outFile.delete();
      } else {
        // at least one entry removed - delete the original file
        this.getFile().delete();
        if (outCount == 0) {
          // NO entries remain - just delete the temp file too
          outFile.delete();
        } else {
          // entries remain - replace original file with temp file
          outFile.renameTo(this.getFile());
        }
      }
      return new Integer(inCount - outCount); // should be 0 or 1
    } catch (IOException ex) {
      throw XMLDataStoreException.ioException(ex);
    }
  }
  public void testStream() 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 zipfile = new File(tempDir, "zipfile");
    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipfile));
    String dummy1 = "dummy";
    zos.putNextEntry(new ZipEntry(dummy1));
    zos.write(data.getBytes());
    zos.closeEntry();
    String dummy2 = "dummy2";
    zos.putNextEntry(new ZipEntry(dummy2));
    zos.write(data.getBytes());
    zos.closeEntry();
    zos.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(zipfile), index, dir);
    byte[] buffer = new byte[2];
    int read = stream.read(buffer);
    while (read != -1) {
      read = stream.read(buffer);
    }
    stream.close();

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

    // cleanup
    zipfile.delete();
    index.delete();
    d1.delete();
    d2.delete();
    dir.delete();
    tempDir.delete();
  }
  /**
   * Puts the uninstaller.
   *
   * @exception Exception Description of the Exception
   */
  private void putUninstaller() throws Exception {
    // Me make the .uninstaller directory
    String dest = translatePath("$INSTALL_PATH") + File.separator + "Uninstaller";
    String jar = dest + File.separator + "uninstaller.jar";
    File pathMaker = new File(dest);
    pathMaker.mkdirs();

    // We log the uninstaller deletion information
    UninstallData udata = UninstallData.getInstance();
    udata.setUninstallerJarFilename(jar);
    udata.setUninstallerPath(dest);

    // We open our final jar file
    FileOutputStream out = new FileOutputStream(jar);
    ZipOutputStream outJar = new ZipOutputStream(out);
    idata.uninstallOutJar = outJar;
    outJar.setLevel(9);
    udata.addFile(jar);

    // We copy the uninstaller
    InputStream in = getClass().getResourceAsStream("/res/IzPack.uninstaller");
    ZipInputStream inRes = new ZipInputStream(in);
    ZipEntry zentry = inRes.getNextEntry();
    while (zentry != null) {
      // Puts a new entry
      outJar.putNextEntry(new ZipEntry(zentry.getName()));

      // Byte to byte copy
      int unc = inRes.read();
      while (unc != -1) {
        outJar.write(unc);
        unc = inRes.read();
      }

      // Next one please
      inRes.closeEntry();
      outJar.closeEntry();
      zentry = inRes.getNextEntry();
    }
    inRes.close();

    // We put the langpack
    in = getClass().getResourceAsStream("/langpacks/" + idata.localeISO3 + ".xml");
    outJar.putNextEntry(new ZipEntry("langpack.xml"));
    int read = in.read();
    while (read != -1) {
      outJar.write(read);
      read = in.read();
    }
    outJar.closeEntry();
  }
Пример #7
0
  public static void main(String[] args) throws IOException {
    boolean exist = false;
    String fileName = args[0];
    String zipName = args[1];
    Map<ZipEntry, byte[]> map = new HashMap<>();

    String fileWithoutPathName = new File(fileName).getName();

    FileInputStream fis = new FileInputStream(zipName);
    ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
    ZipEntry ze;
    while ((ze = zis.getNextEntry()) != null) {
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      byte[] buffer = new byte[1024];
      int count;
      while ((count = zis.read(buffer)) != -1) {
        baos.write(buffer, 0, count);
      }
      map.put(ze, baos.toByteArray());
    }
    zis.close();

    FileOutputStream fos = new FileOutputStream(zipName);
    ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(fos));
    for (Map.Entry<ZipEntry, byte[]> pair : map.entrySet()) {
      if (fileWithoutPathName.equals(pair.getKey().getName())) {
        exist = true;
        continue;
      }
      zos.putNextEntry(pair.getKey());
      zos.write(pair.getValue());
      zos.closeEntry();
    }

    if (exist) {
      FileInputStream fis2 = new FileInputStream(fileName);
      byte[] fileBytes = new byte[fis2.available()];
      fis2.read(fileBytes);
      fis2.close();

      ZipEntry zipEntry = new ZipEntry("new/" + fileWithoutPathName);
      zos.putNextEntry(zipEntry);
      zos.write(fileBytes);
      zos.closeEntry();
      zos.close();
    } else {
      zos.closeEntry();
      zos.close();
    }
  }
Пример #8
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));
  }
 /**
  * @param zip
  * @throws UnsupportedEncodingException (subclass of IOException)
  * @throws IOException
  */
 private static void writeMeta(ZipOutputStream zip) throws IOException {
   ZipEntry entry = new ZipEntry(META_FOLDER + File.separator + CONTAINER_XML);
   zip.putNextEntry(entry);
   zip.write("<?xml version=\"1.0\"?>\r\n".getBytes(UTF8_CHARSET));
   zip.write(
       "<container version=\"1.0\" xmlns=\"urn:oasis:names:tc:opendocument:xmlns:container\">\r\n"
           .getBytes(UTF8_CHARSET));
   zip.write("<rootfiles>\r\n".getBytes(UTF8_CHARSET));
   zip.write(
       "<rootfile full-path=\"content.opf\" media-type=\"application/oebps-package+xml\"/>\r\n"
           .getBytes(UTF8_CHARSET));
   zip.write("</rootfiles>\r\n".getBytes(UTF8_CHARSET));
   zip.write("</container>\r\n".getBytes(UTF8_CHARSET));
   zip.closeEntry();
 }
Пример #10
0
 /**
  * Zip up a directory path
  *
  * @param directory
  * @param zos
  * @param path
  * @throws IOException
  */
 private static void zipDir(String directory, ZipOutputStream zos, String path)
     throws IOException {
   File zipDir = new File(directory);
   // get a listing of the directory content
   String[] dirList = zipDir.list();
   byte[] readBuffer = new byte[2156];
   int bytesIn = 0;
   // loop through dirList, and zip the files
   for (int i = 0; i < dirList.length; ++i) {
     File f = new File(zipDir, dirList[i]);
     if (f.isDirectory()) {
       zipDir(f.getPath(), zos, path.concat(f.getName()).concat(FILE_SEPARATOR));
       continue;
     }
     FileInputStream fis = new FileInputStream(f);
     try {
       zos.putNextEntry(new ZipEntry(path.concat(f.getName())));
       bytesIn = fis.read(readBuffer);
       while (bytesIn != -1) {
         zos.write(readBuffer, 0, bytesIn);
         bytesIn = fis.read(readBuffer);
       }
     } finally {
       closeQuietly(fis);
     }
   }
 }
Пример #11
0
  public static void main(String argv[]) {
    try {
      BufferedInputStream origin = null;
      FileOutputStream dest = new FileOutputStream("c:\\zip\\myfigs.zip");
      CheckedOutputStream checksum = new CheckedOutputStream(dest, new Adler32());
      ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(checksum));
      // out.setMethod(ZipOutputStream.DEFLATED);
      byte data[] = new byte[BUFFER];
      // get a list of files from current directory
      File f = new File(".");
      String files[] = f.list();

      for (int i = 0; i < files.length; i++) {
        try {
          System.out.println("Adding: " + files[i]);
          FileInputStream fi = new FileInputStream(files[i]);
          origin = new BufferedInputStream(fi, BUFFER);
          ZipEntry entry = new ZipEntry(files[i]);
          out.putNextEntry(entry);
          int count;
          while ((count = origin.read(data, 0, BUFFER)) != -1) {
            out.write(data, 0, count);
          }
          origin.close();
        } catch (Exception e) {
          // Ignore
        }
      }
      out.close();
      System.out.println("checksum:    " + checksum.getChecksum().getValue());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Пример #12
0
 private static void writeZipEntry(ZipOutputStream out, String name, byte[] data)
     throws IOException {
   final ZipEntry entry = new ZipEntry(StringUtils.removeStart(name, "/"));
   out.putNextEntry(entry);
   out.write(data, 0, data.length);
   out.closeEntry();
 }
Пример #13
0
 public void putNextEntry(String path, String content) throws IOException {
   ZipEntry entry = new ZipEntry(path);
   zipOutputStream.putNextEntry(entry);
   zipOutputStream.write(content.getBytes(encoding));
   zipOutputStream.closeEntry();
   checkSize(entry);
 }
Пример #14
0
  private static void writeStaticAssets(AssetManager assets, ZipOutputStream out, String path) {
    try {
      for (String item : assets.list(path)) {
        try {
          InputStream fileIn = assets.open(path + "/" + item);

          ByteArrayOutputStream baos = new ByteArrayOutputStream();
          BufferedInputStream bin = new BufferedInputStream(fileIn);

          byte[] buffer = new byte[8192];
          int read = 0;

          while ((read = bin.read(buffer, 0, buffer.length)) != -1) {
            baos.write(buffer, 0, read);
          }

          bin.close();
          baos.close();

          ZipEntry entry = new ZipEntry(path + "/" + item);
          out.putNextEntry(entry);
          out.write(baos.toByteArray());
          out.closeEntry();
        } catch (IOException e) {
          BootstrapSiteExporter.writeStaticAssets(assets, out, path + "/" + item);
        }
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Пример #15
0
  private void createZipFile(File jarFile, File sourceDir) {
    try {
      BufferedInputStream origin = null;
      FileOutputStream dest = new FileOutputStream(jarFile);
      ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));
      // out.setMethod(ZipOutputStream.DEFLATED);
      byte data[] = new byte[JAR_BUFFER_SIZE];
      // get a list of files from current directory
      File files[] = sourceDir.listFiles();

      for (int i = 0; i < files.length; i++) {
        System.out.println("Adding: " + files[i]);
        FileInputStream fi = new FileInputStream(files[i]);
        origin = new BufferedInputStream(fi, JAR_BUFFER_SIZE);
        ZipEntry entry = new ZipEntry(files[i].getName());
        out.putNextEntry(entry);
        int count;
        while ((count = origin.read(data, 0, JAR_BUFFER_SIZE)) != -1) {
          out.write(data, 0, count);
        }
        origin.close();
      }
      out.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Пример #16
0
  // make zip of reports
  public static void zip(String filepath) {
    try {
      File inFolder = new File(filepath);
      File outFolder = new File("Reports.zip");
      ZipOutputStream out =
          new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(outFolder)));
      BufferedInputStream in = null;
      byte[] data = new byte[1000];
      String files[] = inFolder.list();
      for (int i = 0; i < files.length; i++) {
        in =
            new BufferedInputStream(new FileInputStream(inFolder.getPath() + "/" + files[i]), 1000);
        out.putNextEntry(new ZipEntry(files[i]));
        int count;
        while ((count = in.read(data, 0, 1000)) != -1) {
          out.write(data, 0, count);
        }
        out.closeEntry();
      }
      out.flush();
      out.close();

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Пример #17
0
  /** create zip file of ssh keys */
  public void createZip(String publicKey, String privateKey) {
    // These are the files to include in the ZIP file
    String[] source = new String[] {publicKey, privateKey};

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

    try {
      // Create the ZIP file
      String target = privateKey + ".zip";
      ZipOutputStream out = new ZipOutputStream(new FileOutputStream(target));

      // Compress the files
      for (int i = 0; i < source.length; i++) {
        FileInputStream in = new FileInputStream(source[i]);
        // Add ZIP entry to output stream.
        out.putNextEntry(new ZipEntry(source[i]));
        // 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();
    } catch (IOException e) {
    }
  }
  public void addFromZip(String zipFilename) throws IOException {
    byte[] buf = new byte[1024];

    ZipInputStream zin = new ZipInputStream(new FileInputStream(zipFilename));

    try {
      ZipEntry entry = zin.getNextEntry();
      while (entry != null) {
        String name = entry.getName();

        names.add(name);
        // Add ZIP entry to output stream.
        out.putNextEntry(new ZipEntry(name));
        // Transfer bytes from the ZIP file to the output file
        int len;
        while ((len = zin.read(buf)) > 0) {
          out.write(buf, 0, len);
        }

        entry = zin.getNextEntry();
      }
    } finally {
      zin.close();
    }
  }
Пример #19
0
  public void zip(ArrayList<String> fileList, File destFile, int compressionLevel)
      throws Exception {

    if (destFile.exists()) throw new Exception("File " + destFile.getName() + " already exists!!");

    int fileLength;
    byte[] buffer = new byte[4096];

    FileOutputStream fos = new FileOutputStream(destFile);
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    ZipOutputStream zipFile = new ZipOutputStream(bos);
    zipFile.setLevel(compressionLevel);

    for (int i = 0; i < fileList.size(); i++) {

      FileInputStream fis = new FileInputStream(fileList.get(i));
      BufferedInputStream bis = new BufferedInputStream(fis);
      ZipEntry ze = new ZipEntry(FilenameUtils.getName(fileList.get(i)));
      zipFile.putNextEntry(ze);

      while ((fileLength = bis.read(buffer, 0, 4096)) > 0) zipFile.write(buffer, 0, fileLength);

      zipFile.closeEntry();
      bis.close();
    }

    zipFile.close();
  }
Пример #20
0
  public void zip() {
    try {
      BufferedInputStream origin = null;
      FileOutputStream dest = new FileOutputStream(_zipFile);

      ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));

      byte data[] = new byte[BUFFER];

      for (int i = 0; i < _files.length; i++) {
        Log.v("Compress", "Adding: " + _files[i]);
        FileInputStream fi = new FileInputStream(_files[i]);
        origin = new BufferedInputStream(fi, BUFFER);
        ZipEntry entry = new ZipEntry(_files[i].substring(_files[i].lastIndexOf("/") + 1));
        out.putNextEntry(entry);
        int count;
        while ((count = origin.read(data, 0, BUFFER)) != -1) {
          out.write(data, 0, count);
        }
        origin.close();
      }

      out.close();
      Log.v("Compressed", _zipFile);

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Пример #21
0
  private void addToZipFile(String fileName, ZipOutputStream zos) throws IOException {

    File zipRootPath = new File(System.getProperty(BPELDeployer.Constants.TEMP_DIR_PROPERTY));
    File file = new File(fileName);
    String relativePath = zipRootPath.toURI().relativize(file.toURI()).getPath();
    ZipEntry zipEntry = new ZipEntry(relativePath);
    zos.putNextEntry(zipEntry);
    FileInputStream fis = null;
    try {
      fis = new FileInputStream(fileName);
      byte[] bytes = new byte[1024];
      int length;
      while ((length = fis.read(bytes)) >= 0) {
        zos.write(bytes, 0, length);
      }
    } finally {
      zos.closeEntry();
      if (fis != null) {
        try {
          fis.close();
        } catch (IOException e) {
          log.error("Error when closing the file input stream for " + fileName);
        }
      }
    }
  }
Пример #22
0
  public void test_1562() throws Exception {
    Manifest man = new Manifest();
    Attributes att = man.getMainAttributes();
    att.put(Attributes.Name.MANIFEST_VERSION, "1.0");
    att.put(Attributes.Name.MAIN_CLASS, "foo.bar.execjartest.Foo");

    File outputZip = File.createTempFile("hyts_", ".zip");
    outputZip.deleteOnExit();
    ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(outputZip));
    File resources = Support_Resources.createTempFolder();

    for (String zipClass : new String[] {"Foo", "Bar"}) {
      zout.putNextEntry(new ZipEntry("foo/bar/execjartest/" + zipClass + ".class"));
      zout.write(getResource(resources, "hyts_" + zipClass + ".ser"));
    }

    zout.putNextEntry(new ZipEntry("META-INF/MANIFEST.MF"));
    man.write(zout);
    zout.close();

    // set up the VM parameters
    String[] args = new String[] {"-jar", outputZip.getAbsolutePath()};

    // execute the JAR and read the result
    String res = Support_Exec.execJava(args, null, false);

    assertTrue("Error executing ZIP : result returned was incorrect.", res.startsWith("FOOBAR"));
  }
Пример #23
0
  /**
   * Write the ZIP entry to the given Zip output stream.
   *
   * @param pOutput the stream where to write the entry data.
   */
  public void writeContentToZip(ZipOutputStream pOutput) {

    BufferedInputStream origin = null;
    try {
      FileInputStream fi = new FileInputStream(mResource);
      origin = new BufferedInputStream(fi, BUFFER_SIZE);

      ZipEntry entry = new ZipEntry(mEntryName);
      pOutput.putNextEntry(entry);

      int count;
      byte data[] = new byte[BUFFER_SIZE];

      while ((count = origin.read(data, 0, BUFFER_SIZE)) != -1) {
        pOutput.write(data, 0, count);
      }

      pOutput.closeEntry();

    } catch (IOException e) {
      System.err.println(
          "Problem when writing file to zip: " + mEntryName + " (" + e.getLocalizedMessage() + ")");
    } finally {
      // Close the file entry stream
      try {
        if (origin != null) {
          origin.close();
        }
      } catch (IOException e) {
      }
    }
  }
 /**
  * 浣跨敤zip杩涜鍘嬬缉
  *
  * @param str 鍘嬬缉鍓嶇殑鏂囨湰
  * @return 杩斿洖鍘嬬缉鍚庣殑鏂囨湰
  */
 public static final String zip(String str) {
   if (str == null) return null;
   byte[] compressed;
   ByteArrayOutputStream out = null;
   ZipOutputStream zout = null;
   String compressedStr = null;
   try {
     out = new ByteArrayOutputStream();
     zout = new ZipOutputStream(out);
     zout.putNextEntry(new ZipEntry("0"));
     zout.write(str.getBytes());
     zout.closeEntry();
     compressed = out.toByteArray();
     compressedStr = new sun.misc.BASE64Encoder().encodeBuffer(compressed);
   } catch (IOException e) {
     compressed = null;
   } finally {
     if (zout != null) {
       try {
         zout.close();
       } catch (IOException e) {
       }
     }
     if (out != null) {
       try {
         out.close();
       } catch (IOException e) {
       }
     }
   }
   return compressedStr;
 }
Пример #25
0
  /**
   * Compress temporary directory and save it on given path.
   *
   * @param exportPath
   * @return
   * @throws IOException
   */
  private boolean packageAll(String exportPath) {
    if (!exportPath.endsWith(".zip")) exportPath = exportPath + ".zip";

    BufferedInputStream origin = null;
    ZipOutputStream out;
    boolean result = true;
    try {
      FileOutputStream dest = new FileOutputStream(exportPath);
      out = new ZipOutputStream(new BufferedOutputStream(dest));
      byte data[] = new byte[BUFFER];
      // get a list of files from current directory

      String files[] = tmpDir.list();

      for (int i = 0; i < files.length; i++) {
        //				System.out.println( "Adding: " + files[i] );
        FileInputStream fi = new FileInputStream(new File(tmpDir, files[i]));
        origin = new BufferedInputStream(fi, BUFFER);
        ZipEntry entry = new ZipEntry(files[i]);
        out.putNextEntry(entry);
        int count;
        while ((count = origin.read(data, 0, BUFFER)) != -1) {
          out.write(data, 0, count);
        }
        origin.close();
      }
      out.close();
    } catch (IOException e) {
      // TODO: handle exception
      result = false;
      SoapUI.logError(e, "Error packaging export");
    }
    return result;
  }
Пример #26
0
  public static boolean zip(File[] _files, File _zipFile) {
    try {
      BufferedInputStream origin = null;
      FileOutputStream dest = new FileOutputStream(_zipFile);

      ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));

      byte data[] = new byte[BUFFER];

      for (int i = 0; i < _files.length; i++) {
        Log.d("Compress", "Adding: " + _files[i]);
        FileInputStream fi = new FileInputStream(_files[i]);
        origin = new BufferedInputStream(fi, BUFFER);
        ZipEntry entry = new ZipEntry(_files[i].getName());
        out.putNextEntry(entry);
        int count;
        while ((count = origin.read(data, 0, BUFFER)) != -1) {
          out.write(data, 0, count);
        }
        origin.close();
      }
      out.close();
      return true;
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }
Пример #27
0
  public static String CreateZip(String[] filesToZip, String zipFileName) {

    byte[] buffer = new byte[18024];

    try {

      ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));
      out.setLevel(Deflater.BEST_COMPRESSION);
      for (int i = 0; i < filesToZip.length; i++) {
        FileInputStream in = new FileInputStream(filesToZip[i]);
        String fileName = null;
        for (int X = filesToZip[i].length() - 1; X >= 0; X--) {
          if (filesToZip[i].charAt(X) == '\\' || filesToZip[i].charAt(X) == '/') {
            fileName = filesToZip[i].substring(X + 1);
            break;
          } else if (X == 0) fileName = filesToZip[i];
        }
        out.putNextEntry(new ZipEntry(fileName));
        int len;
        while ((len = in.read(buffer)) > 0) out.write(buffer, 0, len);
        out.closeEntry();
        in.close();
      }
      out.close();
    } catch (IllegalArgumentException e) {
      return "Failed to create zip: " + e.toString();
    } catch (FileNotFoundException e) {
      return "Failed to create zip: " + e.toString();
    } catch (IOException e) {
      return "Failed to create zip: " + e.toString();
    }
    return "Success";
  }
Пример #28
0
  @Test
  public void packingALargeFileShouldGenerateTheSameOutputWhenOverwritingAsWhenAppending()
      throws IOException {
    File reference = File.createTempFile("reference", ".zip");
    String packageName = getClass().getPackage().getName().replace(".", "/");
    URL sample = Resources.getResource(packageName + "/macbeth.properties");
    byte[] input = Resources.toByteArray(sample);

    try (CustomZipOutputStream out = ZipOutputStreams.newOutputStream(output, OVERWRITE_EXISTING);
        ZipOutputStream ref = new ZipOutputStream(new FileOutputStream(reference))) {
      CustomZipEntry entry = new CustomZipEntry("macbeth.properties");
      entry.setTime(System.currentTimeMillis());
      out.putNextEntry(entry);
      ref.putNextEntry(entry);
      out.write(input);
      ref.write(input);
    }

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

    // Make sure the output is valid.
    try (ZipInputStream in = new ZipInputStream(Files.newInputStream(output))) {
      ZipEntry entry = in.getNextEntry();
      assertEquals("macbeth.properties", entry.getName());
      assertNull(in.getNextEntry());
    }

    assertArrayEquals(expected, seen);
  }
Пример #29
0
 void outputRawTraceBuf2s(
     WinstonUtil winston, WinstonSCNL channel, ZipOutputStream zip, String dir)
     throws SeisFileException, SQLException, DataFormatException, FileNotFoundException,
         IOException, URISyntaxException {
   List<TraceBuf2> tbList = winston.extractData(channel, params.getBegin(), params.getEnd());
   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH_mm_ss.SSS");
   sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
   for (TraceBuf2 tb : tbList) {
     ZipEntry tbzip =
         new ZipEntry(
             dir
                 + "/"
                 + tb.getNetwork().trim()
                 + "."
                 + tb.getStation().trim()
                 + "."
                 + tb.getLocId().trim()
                 + "."
                 + tb.getChannel().trim()
                 + "."
                 + sdf.format(tb.getStartDate())
                 + ".tb");
     zip.putNextEntry(tbzip);
     byte[] outBytes = tb.toByteArray();
     zip.write(outBytes, 0, outBytes.length);
     zip.closeEntry();
   }
 }
Пример #30
0
  @SuppressWarnings("ConvertToTryWithResources")
  public static void main(String[] args) throws FileNotFoundException, IOException {

    File file = new File("test.txt");

    FileOutputStream outStream = new FileOutputStream("test.zip");

    ZipOutputStream zipStream = new ZipOutputStream(outStream);

    ZipEntry zipEntry = new ZipEntry(file.getName());

    zipStream.putNextEntry(zipEntry);

    FileInputStream fileInputStream = new FileInputStream(file);

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

    while ((bytesRead = fileInputStream.read(buf)) > 0) {
      zipStream.write(buf, 0, bytesRead);
    }

    zipStream.closeEntry();

    zipStream.close();
    fileInputStream.close();
  }