Esempio n. 1
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();
  }
Esempio n. 2
0
    @Override
    public void execute() throws IOException {
      if (offset < 0) throw new IllegalArgumentException("Offset cannot be less than 0.");

      System.out.println("Getting file paths...");

      final Path[] sequenceFiles = SequenceFileUtility.getFilePaths(inputPathOrUri, "part");
      final ExtractionState nps = new ExtractionState();
      nps.setMaxFileExtract(max);

      if (random >= 0) {
        System.out.println("Counting records");

        int totalRecords = 0;
        for (final Path path : sequenceFiles) {
          System.out.println("... Counting from file: " + path);
          final SequenceFileUtility<Text, BytesWritable> utility =
              new TextBytesSequenceFileUtility(path.toUri(), true);
          totalRecords += utility.getNumberRecords();
        }

        System.out.println("Selecting random subset of " + random + " from " + totalRecords);

        nps.setRandomSelection(random, totalRecords);
      }

      ZipOutputStream zos = null;
      if (zipMode) {
        zos = SequenceFileUtility.openZipOutputStream(outputPathOrUri);
      }

      for (final Path path : sequenceFiles) {
        System.out.println("Extracting from " + path.getName());

        final SequenceFileUtility<Text, BytesWritable> utility =
            new TextBytesSequenceFileUtility(path.toUri(), true);
        if (queryKey == null) {
          if (zipMode) {
            utility.exportDataToZip(zos, np, nps, autoExtension, offset);
          } else {
            utility.exportData(outputPathOrUri, np, nps, autoExtension, offset);
          }
        } else {
          if (zipMode) {
            throw new UnsupportedOperationException("Not implemented yet");
          } else {
            if (!utility.findAndExport(new Text(queryKey), outputPathOrUri, offset)) {
              if (offset == 0) System.err.format("Key '%s' was not found in the file.\n", queryKey);
              else
                System.err.format(
                    "Key '%s' was not found in the file after offset %d.\n", queryKey, offset);
            }
          }
        }

        if (nps.isFinished()) break;
      }

      if (zos != null) zos.close();
    }
Esempio n. 3
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();
    }
  }
Esempio n. 4
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);
     }
   }
 }
Esempio n. 5
0
 private static void zipDir(File dir, String relativePath, ZipOutputStream zos, boolean start)
     throws IOException {
   String[] dirList = dir.list();
   for (String aDirList : dirList) {
     File f = new File(dir, aDirList);
     if (!f.isHidden()) {
       if (f.isDirectory()) {
         if (!start) {
           ZipEntry dirEntry = new ZipEntry(relativePath + f.getName() + "/");
           zos.putNextEntry(dirEntry);
           zos.closeEntry();
         }
         String filePath = f.getPath();
         File file = new File(filePath);
         zipDir(file, relativePath + f.getName() + "/", zos, false);
       } else {
         String path = relativePath + f.getName();
         if (!path.equals(JarFile.MANIFEST_NAME)) {
           ZipEntry anEntry = new ZipEntry(path);
           InputStream is = new FileInputStream(f);
           copyToZipStream(is, anEntry, zos);
         }
       }
     }
   }
 }
Esempio n. 6
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;
    }
  }
Esempio n. 7
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);
  }
  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();
    }
  }
Esempio n. 9
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();
   }
 }
  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);
        }
      }
    }
  }
Esempio n. 11
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();
    }
  }
Esempio n. 12
0
  public static void writeBinaries(
      Map<CLDevice, byte[]> binaries,
      String source,
      String contentSignatureString,
      OutputStream out)
      throws IOException {
    Map<String, byte[]> binaryBySignature = new HashMap<String, byte[]>();
    for (Map.Entry<CLDevice, byte[]> e : binaries.entrySet())
      binaryBySignature.put(
          e.getKey().createSignature(),
          e.getValue()); // Maybe multiple devices will have the same signature : too bad, we
    // don't care and just write one binary per signature.

    ZipOutputStream zout = new ZipOutputStream(new GZIPOutputStream(new BufferedOutputStream(out)));
    if (contentSignatureString != null)
      addStoredEntry(
          zout, BinariesSignatureZipEntryName, contentSignatureString.getBytes(textEncoding));

    if (source != null) addStoredEntry(zout, SourceZipEntryName, source.getBytes(textEncoding));

    for (Map.Entry<String, byte[]> e : binaryBySignature.entrySet())
      addStoredEntry(zout, e.getKey(), e.getValue());

    zout.close();
  }
Esempio n. 13
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();
    }
  }
Esempio n. 14
0
  @Override
  public boolean onCommandOption(CommandSender sender, String[] args) {
    try {
      File ticketFile = new File(MyPetApi.getPlugin().getDataFolder(), "ticket.zip");
      ZipOutputStream out = new ZipOutputStream(new FileOutputStream(ticketFile));

      addFileToZip(new File(MyPetApi.getPlugin().getDataFolder(), "config.yml"), out, "");
      addFileToZip(new File(MyPetApi.getPlugin().getDataFolder(), "pet-config.yml"), out, "");
      addFileToZip(new File(MyPetApi.getPlugin().getDataFolder(), "My.Pets.old"), out, "");
      addFileToZip(new File(MyPetApi.getPlugin().getDataFolder(), "pets.db"), out, "");
      addFileToZip(new File(MyPetApi.getPlugin().getDataFolder(), "worldgroups.yml"), out, "");
      addFileToZip(new File(MyPetApi.getPlugin().getDataFolder(), "skilltrees"), out, "");
      addFileToZip(
          new File(MyPetApi.getPlugin().getDataFolder(), "logs" + File.separator + "MyPet.log"),
          out,
          "");
      addFileToZip(
          new File(
              MyPetApi.getPlugin().getDataFolder().getParentFile().getParentFile(),
              "logs" + File.separator + "latest.log"),
          out,
          "");

      out.close();

      sender.sendMessage(ChatColor.RED + "------------------------------------------------");
      sender.sendMessage(
          "Ticket file created. Please upload this file somewhere and add the link to your ticket.");
      sender.sendMessage("  " + ticketFile.getAbsoluteFile());
      sender.sendMessage(ChatColor.RED + "------------------------------------------------");
    } catch (IOException e) {
      e.printStackTrace();
    }
    return true;
  }
 private static void addResourceFile(String name, String resource, ZipOutputStream out)
     throws IOException {
   ZipEntry zipEntry = new ZipEntry(name);
   out.putNextEntry(zipEntry);
   OpenDocumentSpreadsheetCreator.addFromResource(resource, out);
   out.closeEntry();
 }
Esempio n. 16
0
  /** @param path */
  public void createZipFile(String path) {
    File dir = new File(path);
    String[] list = dir.list();
    String name = path.substring(path.lastIndexOf("/"), path.length());
    String _path;

    if (!dir.canRead() || !dir.canWrite()) return;

    int len = list.length;

    if (path.charAt(path.length() - 1) != '/') _path = path + "/";
    else _path = path;

    try {
      ZipOutputStream zip_out =
          new ZipOutputStream(
              new BufferedOutputStream(new FileOutputStream(_path + name + ".zip"), BUFFER));

      for (int i = 0; i < len; i++) zip_folder(new File(_path + list[i]), zip_out);

      zip_out.close();

    } catch (FileNotFoundException e) {
      Log.e("File not found", e.getMessage());

    } catch (IOException e) {
      Log.e("IOException", e.getMessage());
    }
  }
Esempio n. 17
0
 /**
  * Prepare a Research Object to be sent as a package in a zip format to dArceo.
  *
  * @param researchObject Research Object
  * @return input stream with zipped ro.
  * @throws IOException
  */
 public static InputStream toZipInputStream(ResearchObjectSerializable researchObject) {
   File tmpFile = null;
   Set<String> entries = new HashSet<>();
   try {
     tmpFile = File.createTempFile("dArceoArtefact", ".zip");
     tmpFile.deleteOnExit();
     ZipOutputStream zipOutput = new ZipOutputStream(new FileOutputStream(tmpFile));
     for (ResearchObjectComponentSerializable component :
         researchObject.getSerializables().values()) {
       Path componentPath = Paths.get(CONTENT_PATH, component.getPath());
       putEntryAndDirectoriesPath(
           zipOutput, componentPath.toString(), component.getSerialization(), entries);
     }
     // add metadata
     putMetadataId(zipOutput, entries, researchObject.getUri());
     zipOutput.flush();
     zipOutput.close();
     InputStream result = new FileInputStream(tmpFile);
     tmpFile.delete();
     return result;
   } catch (IOException e) {
     LOGGER.error("Can't prepare a RO " + researchObject.getUri() + " for dArceo", e);
     if (tmpFile != null) {
       tmpFile.delete();
     }
     return null;
   }
 }
Esempio n. 18
0
 /**
  * 压缩
  *
  * @param file 要压缩的文件
  * @param outFile 压缩后的输出文件
  * @throws IOException
  */
 public static void zip(File file, File outFile) throws IOException {
   // 提供了一个数据项压缩成一个ZIP归档输出流
   ZipOutputStream out = null;
   try {
     out = new ZipOutputStream(new FileOutputStream(outFile));
     // 如果此文件是一个文件,否则为false。
     if (file.isFile()) {
       zipFileOrDirectory(out, file, "");
     } else {
       // 返回一个文件或空阵列。
       File[] entries = file.listFiles();
       if (entries != null) {
         for (int i = 0; i < entries.length; i++) {
           // 递归压缩,更新curPaths
           zipFileOrDirectory(out, entries[i], "");
         }
       }
     }
   } catch (IOException ex) {
     Log.e(TAG, "压缩文件失败", ex);
   } finally {
     // 关闭输出流
     if (out != null) {
       try {
         out.close();
       } catch (IOException ex) {
         Log.e(TAG, "关闭流失败", ex);
       }
     }
   }
 }
  private static String getArtifactResolverJar(boolean isMaven3) throws IOException {
    Class marker =
        isMaven3 ? MavenArtifactResolvedM3RtMarker.class : MavenArtifactResolvedM2RtMarker.class;

    File classDirOrJar = new File(PathUtil.getJarPathForClass(marker));

    if (!classDirOrJar.isDirectory()) {
      return classDirOrJar.getAbsolutePath(); // it's a jar in IDEA installation.
    }

    // it's a classes directory, we are in development mode.
    File tempFile = FileUtil.createTempFile("idea-", "-artifactResolver.jar");
    tempFile.deleteOnExit();

    ZipOutputStream zipOutput = new ZipOutputStream(new FileOutputStream(tempFile));
    try {
      ZipUtil.addDirToZipRecursively(zipOutput, null, classDirOrJar, "", null, null);

      if (isMaven3) {
        File m2Module = new File(PathUtil.getJarPathForClass(MavenModuleMap.class));

        String commonClassesPath = MavenModuleMap.class.getPackage().getName().replace('.', '/');
        ZipUtil.addDirToZipRecursively(
            zipOutput, null, new File(m2Module, commonClassesPath), commonClassesPath, null, null);
      }
    } finally {
      zipOutput.close();
    }

    return tempFile.getAbsolutePath();
  }
Esempio n. 20
0
  private static void addFolderToZip(
      final File folder, final ZipOutputStream zip, final String baseName) throws IOException {
    final File[] files = folder.listFiles();
    /* For each child (subdirectory/child-file). */
    for (final File file : files) {
      if (file.isDirectory()) {
        /* If the file is a folder, do recursrion with this folder.*/
        addFolderToZip(file, zip, baseName);
      } else {
        /* Otherwise zip it as usual. */
        String name;

        if (baseName == null) {
          name = file.getAbsolutePath();
        } else {
          name = file.getAbsolutePath().substring(baseName.length());
        }

        final ZipEntry zipEntry = new ZipEntry(name);
        zip.putNextEntry(zipEntry);
        final FileInputStream fileIn = new FileInputStream(file);
        StreamUtils.copy(fileIn, zip);
        //				StreamUtils.closeStream(fileIn);
        fileIn.close();
        zip.closeEntry();
      }
    }
  }
Esempio n. 21
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);
 }
 /**
  * 浣跨敤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;
 }
Esempio n. 23
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();
    }
  }
Esempio n. 24
0
  // Component interface
  public File getComponentFile(Project project) throws BuildException {
    if (generateName && zipFile == null) {
      // Use an autogenerated name.
      try {
        zipFile = File.createTempFile(getComponentType(), ".jar");
        zipFile.deleteOnExit();

        // Create the ZIP file entry table, else the ANT Jar task
        // grumbles loudly and generates lots of spam warning
        // messages when it tries to open a completely empty file
        // as a ZIP file.

        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));

        // Add an empty directory - ZIP files must have at least one
        // entry.
        ZipEntry ze = new ZipEntry("META-INF/");
        ze.setSize(0);
        ze.setMethod(ZipEntry.STORED);
        // An empty CRC for the directory.
        ze.setCrc(new CRC32().getValue());
        zos.putNextEntry(ze);
        zos.close();

      } catch (IOException ioe) {
        throw new BuildException(ioe);
      }
    }

    return zipFile;
  }
Esempio n. 25
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) {
      }
    }
  }
Esempio n. 26
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();
  }
Esempio n. 27
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) {
    }
  }
  @Test
  public void testLoadFromJar() throws Exception {
    File jar = Files.createTempFile("battlecode-test", ".jar").toFile();

    jar.deleteOnExit();

    ZipOutputStream z = new ZipOutputStream(new FileOutputStream(jar));

    ZipEntry classEntry = new ZipEntry("instrumentertest/Nothing.class");

    z.putNextEntry(classEntry);

    IOUtils.copy(
        getClass().getClassLoader().getResourceAsStream("instrumentertest/Nothing.class"), z);

    z.closeEntry();
    z.close();

    IndividualClassLoader jarLoader =
        new IndividualClassLoader(
            "instrumentertest", new IndividualClassLoader.Cache(jar.toURI().toURL()));

    Class<?> jarClass = jarLoader.loadClass("instrumentertest.Nothing");

    URL jarClassLocation = jarClass.getResource("Nothing.class");

    // EXTREMELY scientific

    assertTrue(jarClassLocation.toString().startsWith("jar:"));
    assertTrue(jarClassLocation.toString().contains(jar.toURI().toURL().toString()));
  }
Esempio n. 29
0
  public static Uri exportJekyllPages(Context context) {
    File exportDirectory = context.getExternalFilesDir(null);

    String filename = System.currentTimeMillis() + "_jekyll.zip";

    File exportedFile = new File(exportDirectory, filename);

    try {
      FileOutputStream out = new FileOutputStream(exportedFile);

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

      try {
        BootstrapSiteExporter.writeScriptDocumentation(
            context, zos, "embedded_website/docs/all", BootstrapSiteExporter.TEMPLATE_TYPE_JEKYLL);
        BootstrapSiteExporter.writeScriptDocumentation(
            context,
            zos,
            "embedded_website/docs/scheme",
            BootstrapSiteExporter.TEMPLATE_TYPE_JEKYLL);
        BootstrapSiteExporter.writeScriptDocumentation(
            context,
            zos,
            "embedded_website/docs/javascript",
            BootstrapSiteExporter.TEMPLATE_TYPE_JEKYLL);
      } finally {
        zos.close();
      }
    } catch (java.io.IOException e) {
      e.printStackTrace();
    }

    return Uri.fromFile(exportedFile);
  }
Esempio n. 30
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"));
  }