// 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();
    }
  }
Exemple #2
0
 private byte[] serialize() {
   byte[] result = null;
   ByteArrayOutputStream bos = new ByteArrayOutputStream(150000);
   try {
     //			GZIPOutputStream zos = new GZIPOutputStream(bos);
     ZipOutputStream zos = new ZipOutputStream(bos);
     // zos.setLevel(4);
     zos.putNextEntry(new ZipEntry("Object"));
     ObjectOutputStream oos = new ObjectOutputStream(zos);
     //			oos.writeInt(1);
     oos.writeObject(this);
     oos.flush();
     oos.reset();
     zos.closeEntry();
     zos.flush();
     result = bos.toByteArray();
     bos.reset();
     bos.close();
     zos.close();
     oos.close();
   } catch (IOException e) {
     log.severe("Failed to serialize MemoStorable: " + e.getMessage());
     log.severe(e.getCause().getMessage());
   }
   return result;
 }
  /** Compress the given directory with all its files. */
  private byte[] zipFiles(File directory, String[] files) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);
    byte bytes[] = new byte[2048];

    for (String fileName : files) {
      FileInputStream fis =
          new FileInputStream(
              directory.getPath() + BeTTyFacadeZipGenerator.FILE_SEPARATOR + fileName);
      BufferedInputStream bis = new BufferedInputStream(fis);

      zos.putNextEntry(new ZipEntry(fileName));

      int bytesRead;
      while ((bytesRead = bis.read(bytes)) != -1) {
        zos.write(bytes, 0, bytesRead);
      }
      zos.closeEntry();
      bis.close();
      fis.close();
    }
    zos.flush();
    baos.flush();
    zos.close();
    baos.close();
    return baos.toByteArray();
  }
  /**
   * Generates configuration file with name taken from variable CONFIG_FILE_NAME Returns the created
   * file name.
   */
  protected String generateConfigFile()
      throws JAXBException, LocalRepositoryException, IOException {
    ZipOutputStream zos = null;
    try {
      PropertyInfoExt properties =
          new PropertyInfoExt(coordinator.getPropertyInfo().getProperties());
      zos = new ZipOutputStream(new FileOutputStream(CONFIG_FILE_PATH));
      ZipEntry ze = new ZipEntry(CONFIG_FILE_NAME + getFileExtension());
      zos.putNextEntry(ze);

      if (MediaType.APPLICATION_JSON_TYPE.equals(mediaType)) {
        (new ObjectMapper()).writeValue(zos, properties); // gson should not be used any more
      } else {
        JAXBContext jaxbContext = JAXBContext.newInstance(PropertyInfo.class);
        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(properties, zos);
      }
      zos.flush();
    } finally {
      if (zos != null) {
        zos.close();
      }
    }

    return CONFIG_FILE_PATH;
  }
Exemple #5
0
 @Override
 public Void call() throws Exception {
   try {
     state.reset();
     List<CollectRecord> recordSummaries = loadAllSummaries();
     if (recordSummaries != null && stepNumbers != null) {
       state.setRunning(true);
       String fileName = FILE_NAME;
       File file = new File(directory, fileName);
       if (file.exists()) {
         file.delete();
       }
       FileOutputStream fileOutputStream = new FileOutputStream(file);
       BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
       ZipOutputStream zipOutputStream = new ZipOutputStream(bufferedOutputStream);
       backup(zipOutputStream, recordSummaries);
       zipOutputStream.flush();
       zipOutputStream.close();
       if (!state.isCancelled()) {
         state.setComplete(true);
       }
     }
   } catch (Exception e) {
     state.setError(true);
     LOG.error("Error during data export", e);
   } finally {
     state.setRunning(false);
   }
   return null;
 }
Exemple #6
0
  public static byte[] generateZip(final Map<String, byte[]> resources) throws IOException {
    if (resources == null || resources.size() == 0) {
      final String message = "No resources available";
      throw new IOException(message);
    }

    ByteArrayOutputStream baos = null;
    ZipOutputStream zipOutStream = null;

    try {
      baos = new ByteArrayOutputStream();
      zipOutStream = new ZipOutputStream(new BufferedOutputStream(baos));
      for (final Map.Entry<String, byte[]> resource : resources.entrySet()) {
        zipOutStream.putNextEntry(new ZipEntry(resource.getKey()));
        zipOutStream.write(resource.getValue());
      }
      zipOutStream.flush();
      baos.flush();
    } finally {
      if (zipOutStream != null) {
        zipOutStream.close();
      }
      if (baos != null) {
        baos.close();
      }
    }

    return baos.toByteArray();
  }
Exemple #7
0
  /**
   * See {@link #zipDirectory(File, ZipOutputStream, FilenameFilter)}, this version handles the
   * prefix needed to recursively zip data preserving the relative path of each
   */
  private static void zipDirectory(
      File directory, String prefix, ZipOutputStream zipout, final FilenameFilter filter)
      throws IOException, FileNotFoundException {
    File[] files = directory.listFiles(filter);
    // copy file by reading 4k at a time (faster than buffered reading)
    byte[] buffer = new byte[4 * 1024];
    for (File file : files) {
      if (file.exists()) {
        if (file.isDirectory()) {
          // recurse and append
          zipDirectory(file, prefix + file.getName() + "/", zipout, filter);
        } else {
          ZipEntry entry = new ZipEntry(prefix + file.getName());
          zipout.putNextEntry(entry);

          InputStream in = new FileInputStream(file);
          int c;
          try {
            while (-1 != (c = in.read(buffer))) {
              zipout.write(buffer, 0, c);
            }
            zipout.closeEntry();
          } finally {
            in.close();
          }
        }
      }
    }
    zipout.flush();
  }
Exemple #8
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;
   }
 }
 /*
  * (non-Javadoc)
  *
  * @see org.xmind.core.io.IOutputTarget#close()
  */
 public void close() {
   try {
     zip.flush();
     zip.close();
     return;
   } catch (IOException e) {
     Core.getLogger().log(e);
   }
 }
Exemple #10
0
 /**
  * Add new entry to the output stream and entries group.
  *
  * @param zipOutput stream
  * @param entryName zip entry
  * @param input input stream (entry content, may be null)
  * @param entries the group of currently existed entries
  * @throws IOException .
  */
 private static void putEntry(ZipOutputStream zipOutput, String entryName, InputStream input)
     throws IOException {
   zipOutput.putNextEntry(new ZipEntry(entryName));
   if (input != null) {
     IOUtils.copy(input, zipOutput);
   }
   zipOutput.closeEntry();
   zipOutput.flush();
 }
Exemple #11
0
 public static void packConfig(OutputStream outputStream, String rootPath, File... inputDirs)
     throws IOException {
   ZipOutputStream out = new ZipOutputStream(outputStream);
   try {
     zipDirectory(out, rootPath, inputDirs);
   } finally {
     out.finish();
     out.flush();
   }
 }
  /**
   * This method uses puts the new content of the differenceFile into the Jar targetFile, replacing
   * the files as necessary.
   *
   * @param targetFile
   * @param differenceFile - zip containing the files you want to add into the targetFile. This
   *     differenceFile must exsit and have at least 1 entry, or a ZipException will be thrown.
   * @throws ZipException - if a ZIP error has occurred
   * @throws IOException - if an I/O error has occurred
   */
  public static void putDifsInJar(File targetFile, File differenceFile)
      throws ZipException, IOException {
    File temp = new File(targetFile.getAbsolutePath() + ".temp");
    ZipFile sourceZipFile = new ZipFile(targetFile);
    ZipFile diffZipFile = new ZipFile(differenceFile);

    HashMap<String, ZipEntry> map = new HashMap<String, ZipEntry>();
    Enumeration diffEntries = diffZipFile.entries();
    while (diffEntries.hasMoreElements()) {
      ZipEntry entry = (ZipEntry) diffEntries.nextElement();
      map.put(entry.getName(), entry);
    }

    Enumeration sourceEntries = sourceZipFile.entries();
    while (sourceEntries.hasMoreElements()) {
      ZipEntry entry = (ZipEntry) sourceEntries.nextElement();
      if (map.get(entry.getName()) == null) {
        map.put(entry.getName(), entry);
      }
    }

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

    Set<Entry<String, ZipEntry>> set = map.entrySet();
    Iterator<Entry<String, ZipEntry>> it = set.iterator();
    while (it.hasNext()) {
      Entry<String, ZipEntry> entry = it.next();
      zos.putNextEntry(entry.getValue());
      InputStream is = null;
      if (diffZipFile.getEntry(entry.getKey()) != null) {
        is = diffZipFile.getInputStream(entry.getValue());
      } else {
        is = sourceZipFile.getInputStream(entry.getValue());
      }
      copyInputStream(is, zos);
      is.close();
    }

    zos.close();
    zos.flush();

    sourceZipFile.close();
    diffZipFile.close();

    FileOutputStream fos = new FileOutputStream(targetFile);
    FileInputStream fis = new FileInputStream(temp);

    copyInputStream(fis, fos);

    fis.close();
    fos.close();

    temp.delete();
    temp.deleteOnExit();
  }
Exemple #13
0
  private static boolean zipFolder(ZipOutputStream zos, File folder, int baseLength) {
    FileInputStream fis;
    BufferedInputStream bis = null;

    if (zos == null || folder == null) {
      Log.e(TAG, "zipFolder failed.");
      return false;
    }

    File[] fileList = folder.listFiles();
    if (fileList == null || fileList.length == 0) {
      Log.e(TAG, "zipFolder failed.");
      return false;
    }

    for (File file : fileList) {
      if (file.isDirectory()) {
        zipFolder(zos, file, baseLength);
      } else {
        byte data[] = new byte[BUFFER_SIZE];
        String unmodifiedFilePath = file.getPath();
        String realPath = unmodifiedFilePath.substring(baseLength);

        if (Jbasx.mLog == Jbasx.LogMode.ALL) {
          Log.i(TAG, "Zipping: " + realPath);
        }

        try {
          fis = new FileInputStream(unmodifiedFilePath);
          bis = new BufferedInputStream(fis, BUFFER_SIZE);
          ZipEntry entry = new ZipEntry(realPath);
          zos.putNextEntry(entry);
          int count;
          while ((count = bis.read(data, 0, BUFFER_SIZE)) != -1) {
            zos.write(data, 0, count);
          }
        } catch (IOException e) {
          e.printStackTrace();
          return false;
        } finally {
          try {
            if (bis != null) {
              bis.close();
            }
            zos.flush();
            zos.close();
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
      }
    }
    return true;
  }
Exemple #14
0
  public static void zipDir(String srcFolder, String destZipFile) throws Exception {
    ZipOutputStream zip = null;
    FileOutputStream fileWriter = null;

    fileWriter = new FileOutputStream(destZipFile);
    zip = new ZipOutputStream(fileWriter);

    addFolderToZip("", srcFolder, zip);
    zip.flush();
    zip.close();
  }
Exemple #15
0
 /**
  * Creating Zip file
  *
  * @param outFilename - name of zip file
  * @param resDir - dir where zip file is sutuated
  * @param filenames - array of files
  * @throws FileNotFoundException
  * @throws IOException
  */
 private static void createZipFile(final String outFilename, final String resDir)
     throws FileNotFoundException, IOException {
   final ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outFilename));
   final String zipPath = "";
   // Create a buffer for reading the files
   try {
     zipAny(out, resDir, zipPath);
   } finally {
     out.flush();
     StreamHelper.close(out);
   }
 }
Exemple #16
0
  /**
   * Zip a file.
   *
   * @param filePath The path of the source file.
   * @param zipPath The path where the zipped file should be stored.
   * @return Whenever the operation was successful.
   */
  public static boolean zip(String filePath, String zipPath) {
    FileInputStream fis = null;
    BufferedInputStream bis = null;
    ZipOutputStream zos = null;

    try {
      File file = new File(filePath);
      FileOutputStream fos = new FileOutputStream(zipPath);
      zos = new ZipOutputStream(new BufferedOutputStream(fos));

      if (file.isDirectory()) {
        int baseLength = file.getParent().length() + 1;
        zipFolder(zos, file, baseLength);
      } else {
        byte data[] = new byte[BUFFER_SIZE];
        fis = new FileInputStream(filePath);
        bis = new BufferedInputStream(fis, BUFFER_SIZE);

        String entryName = file.getName();

        if (Jbasx.mLog == Jbasx.LogMode.ALL) {
          Log.i(TAG, "Zipping: " + entryName);
        }

        ZipEntry entry = new ZipEntry(entryName);
        zos.putNextEntry(entry);
        int count;
        while ((count = bis.read(data, 0, BUFFER_SIZE)) != -1) {
          zos.write(data, 0, count);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    } finally {
      try {
        if (fis != null) {
          fis.close();
        }
        if (bis != null) {
          bis.close();
        }
        if (zos != null) {
          zos.flush();
          zos.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return true;
  }
  public static File convertRpmToZip(File file) throws Exception {
    LOG.info("File: " + file.getAbsolutePath());

    FileInputStream fis = new FileInputStream(file);
    ReadableChannelWrapper in = new ReadableChannelWrapper(Channels.newChannel(fis));

    InputStream uncompressed = new GZIPInputStream(fis);
    in = new ReadableChannelWrapper(Channels.newChannel(uncompressed));

    String rpmZipName = file.getName();
    rpmZipName = StringUtils.replace(rpmZipName, ".", "-");
    rpmZipName = rpmZipName + ".zip";
    String rpmZipPath = FilenameUtils.getFullPath(file.getAbsolutePath());

    File rpmZipOutput = new File(rpmZipPath + File.separator + rpmZipName);
    LOG.info("Converting RPM: " + file.getName() + " to ZIP: " + rpmZipOutput.getName());
    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(rpmZipOutput));

    String rpmName = file.getName();
    rpmName = StringUtils.replace(rpmName, ".", "-");

    CpioHeader header;
    int total = 0;
    do {
      header = new CpioHeader();
      total = header.read(in, total);

      if (header.getFileSize() > 0) {
        BoundedInputStream bis = new BoundedInputStream(uncompressed, header.getFileSize());

        String relPath = FilenameUtils.separatorsToSystem(header.getName());
        relPath = StringUtils.removeStart(relPath, ".");
        relPath = StringUtils.removeStart(relPath, "/");
        relPath = rpmName + File.separator + relPath;
        relPath = StringUtils.replace(relPath, "\\", "/");

        ZipEntry zipEntry = new ZipEntry(relPath);
        zos.putNextEntry(zipEntry);
        IOUtils.copy(bis, zos);
      } else {
        final int skip = header.getFileSize();
        if (uncompressed.skip(skip) != skip) throw new RuntimeException("Skip failed.");
      }

      total += header.getFileSize();
    } while (!header.isLast());

    zos.flush();
    zos.close();

    return rpmZipOutput;
  }
Exemple #18
0
 /**
  * Function name: zipFolder
  *
  * <p>Pointed folder will compressed into zip file and store in the same directory.
  *
  * <p>
  *
  * @param srcDir Folder directory to be zip.
  *     <p>Example:
  *     <p>Function.zipFolder("C://test1");
  */
 public static void zipFolder(String srcDir) throws Exception {
   String destZipFile = srcDir + ".zip";
   ZipOutputStream zip = null;
   FileOutputStream writeOut = null;
   // Declare output method
   writeOut = new FileOutputStream(destZipFile);
   zip = new ZipOutputStream(writeOut);
   // Zipping execution
   ZipFolder("", srcDir, zip);
   zip.flush();
   zip.close();
   System.out.println("Executed: Folder " + srcDir + " compressed.");
 }
 public static void exportData(final Context context, final File dst, final int flags)
     throws IOException {
   if (dst == null) throw new FileNotFoundException();
   dst.delete();
   final FileOutputStream fos = new FileOutputStream(dst);
   final ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(fos));
   if (hasFlag(flags, FLAG_PREFERENCES)) {
     exportSharedPreferencesData(
         zos,
         context,
         SHARED_PREFERENCES_NAME,
         ENTRY_PREFERENCES,
         new AnnotationProcessStrategy(SharedPreferenceConstants.class));
   }
   if (hasFlag(flags, FLAG_NICKNAMES)) {
     exportSharedPreferencesData(
         zos,
         context,
         USER_NICKNAME_PREFERENCES_NAME,
         ENTRY_NICKNAMES,
         ConvertToStringProcessStrategy.SINGLETON);
   }
   if (hasFlag(flags, FLAG_USER_COLORS)) {
     exportSharedPreferencesData(
         zos,
         context,
         USER_COLOR_PREFERENCES_NAME,
         ENTRY_USER_COLORS,
         ConvertToIntProcessStrategy.SINGLETON);
   }
   if (hasFlag(flags, FLAG_HOST_MAPPING)) {
     exportSharedPreferencesData(
         zos,
         context,
         HOST_MAPPING_PREFERENCES_NAME,
         ENTRY_HOST_MAPPING,
         ConvertToStringProcessStrategy.SINGLETON);
   }
   if (hasFlag(flags, FLAG_KEYBOARD_SHORTCUTS)) {
     exportSharedPreferencesData(
         zos,
         context,
         KEYBOARD_SHORTCUTS_PREFERENCES_NAME,
         ENTRY_KEYBOARD_SHORTCUTS,
         ConvertToStringProcessStrategy.SINGLETON);
   }
   zos.finish();
   zos.flush();
   Utils.closeSilently(zos);
   Utils.closeSilently(fos);
 }
  /**
   * This method calculates the differences between the files inside a Jar file and generates an
   * output file. The output only contains the files that have difference in their CRC.
   *
   * @param olderVersionJar - file to be compared to.
   * @param newerVersionJar - source file of the comparisson.
   * @param outputDestination - path to the file that will contain the differences in those Jars.
   * @throws ZipException - if a ZIP error has occurred
   * @throws IOException - if an I/O error has occurred
   * @return true if the output file was generated AND has at least one entry inside it, false
   *     otherwise.
   */
  private static boolean calculate(
      File olderVersionJar, File newerVersionJar, String outputDestination)
      throws ZipException, IOException {
    ZipFile oldZip = new ZipFile(olderVersionJar);
    ZipFile newZip = new ZipFile(newerVersionJar);
    Enumeration oldEntries = oldZip.entries();
    Enumeration newEntries = newZip.entries();

    HashMap<String, Long> map = new HashMap<String, Long>();
    while (newEntries.hasMoreElements()) {
      ZipEntry entry = (ZipEntry) newEntries.nextElement();
      map.put(entry.getName(), entry.getCrc());
    }

    while (oldEntries.hasMoreElements()) {
      ZipEntry entry = (ZipEntry) oldEntries.nextElement();
      Long l = map.get(entry.getName());
      if (l != null && l.longValue() == entry.getCrc()) {
        map.remove(entry.getName());
      }
    }

    if (!map.isEmpty()) {
      ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(outputDestination));

      Set<Entry<String, Long>> set = map.entrySet();
      Iterator<Entry<String, Long>> it = set.iterator();
      while (it.hasNext()) {
        Entry<String, Long> entry = it.next();
        ZipEntry zipEntry = newZip.getEntry(entry.getKey());
        InputStream is = newZip.getInputStream(zipEntry);
        zos.putNextEntry(zipEntry);
        copyInputStream(is, zos);
        zos.closeEntry();
        is.close();
      }

      zos.flush();
      zos.close();
    }

    oldZip.close();
    newZip.close();

    if (map.isEmpty()) {
      return false;
    } else {
      return true;
    }
  }
Exemple #21
0
  private void doPost(OutputStream os, String request) throws IOException {
    // String content = "Test POST reply";
    String boundary = "";

    int boundaryStart = request.indexOf("boundary=") + "boundary=".length();
    if (boundaryStart != -1)
      boundary = request.substring(boundaryStart, request.indexOf("\r\n", boundaryStart));

    boundary = "--" + boundary;
    int payloadStart = request.indexOf(boundary);
    payloadStart += ((boundary).length() + 2);
    int payloadEnd = request.indexOf(boundary + "--") - 3;
    String[] payloads = request.substring(payloadStart, payloadEnd).split(boundary);
    String[] fileNames = new String[payloads.length];
    for (int i = 0; i < payloads.length; i++) fileNames[i] = getFileName(payloads[i]);
    int contentLength = 0;
    for (int i = 0; i < payloads.length; i++) {
      int payLoadBeginIndex = payloads[i].indexOf("\r\n\r\n") + 4;
      if (payLoadBeginIndex != -1) {
        payloads[i] = payloads[i].substring(payLoadBeginIndex, payloads[i].length());
        contentLength += payloads[i].length();
      }
    }

    ByteArrayOutputStream zipData = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(zipData);

    for (int i = 0; i < payloads.length; i++) {
      zos.putNextEntry(new ZipEntry(fileNames[i]));
      zos.write(payloads[i].getBytes(), 0, payloads[i].length());
      zos.closeEntry();
    }
    zos.flush();
    zos.close();
    byte[] content = zipData.toByteArray();

    List<String> headers = new ArrayList<String>();
    headers.add("HTTP/1.1 200 OK\r\n");
    headers.add("Content-Transfer-Encoding:binary\r\n");
    headers.add("Content-Type:application/zip\r\n");
    headers.add("Content-Disposition:attachment; filename=\"_" + fileNames[0] + ".zip\"\r\n");
    ProcessorsList pl = new ProcessorsList();
    pl.add(new Compressor(9));
    pl.add(new Chunker(30));
    content = pl.process(content, headers);

    headers.add("Connection: close\r\n\r\n");
    os.write(getBinaryHeaders(headers));
    os.write(content);
  }
 private void addAdditionalInformation(ZipOutputStream outputStream) throws IOException {
   for (IContextContributor contributor : getContextContributor()) {
     InputStream additionalContextInformation = contributor.getSerializedContextInformation();
     if (additionalContextInformation != null) {
       String encoded =
           URLEncoder.encode(
               contributor.getIdentifier(), InteractionContextManager.CONTEXT_FILENAME_ENCODING);
       ZipEntry zipEntry = new ZipEntry(encoded);
       outputStream.putNextEntry(zipEntry);
       IOUtils.copy(additionalContextInformation, outputStream);
       outputStream.flush();
       outputStream.closeEntry();
     }
   }
 }
Exemple #23
0
  private static void packZip(File output, List<File> sources) throws IOException {
    ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(output));
    zipOut.setLevel(Deflater.DEFAULT_COMPRESSION);

    for (File source : sources) {
      if (source.isDirectory()) {
        zipDir(zipOut, "", source);
      } else {
        zipFile(zipOut, "", source);
      }
    }

    zipOut.flush();
    zipOut.close();
    mcMMO.p.getLogger().info("Backup Completed.");
  }
Exemple #24
0
  /**
   * Create an archive of the specified name and containing entries for the data contained in the
   * streams supplied entries arg. specifying the entry name and the value is a InputStream
   * containing the entry data.
   *
   * @param archiveStream The archive output stream.
   * @throws java.io.IOException Write failure.
   */
  public void toOutputStream(ZipOutputStream archiveStream) throws IOException {
    AssertArgument.isNotNull(archiveStream, "archiveStream");

    try {
      writeEntriesToArchive(archiveStream);
    } finally {
      try {
        archiveStream.flush();
      } finally {
        try {
          archiveStream.close();
        } catch (IOException e) {
          logger.info("Unable to close archive output stream.");
        }
      }
    }
  }
  /** For testing */
  public void writeContext(
      IInteractionContext context, ZipOutputStream outputStream, IInteractionContextWriter writer)
      throws IOException {
    String handleIdentifier = context.getHandleIdentifier();
    String encoded =
        URLEncoder.encode(handleIdentifier, InteractionContextManager.CONTEXT_FILENAME_ENCODING);
    ZipEntry zipEntry =
        new ZipEntry(encoded + InteractionContextManager.CONTEXT_FILE_EXTENSION_OLD);
    outputStream.putNextEntry(zipEntry);
    outputStream.setMethod(ZipOutputStream.DEFLATED);

    writer.setOutputStream(outputStream);
    writer.writeContextToStream(context);
    outputStream.flush();
    outputStream.closeEntry();

    addAdditionalInformation(outputStream);
  }
Exemple #26
0
 public static long zipAndCopyDir(
     File baseDir, OutputStream baseOutputStream, Progressable progressable) throws IOException {
   long size = 0L;
   try (ZipOutputStream outputStream = new ZipOutputStream(baseOutputStream)) {
     List<String> filesToCopy = Arrays.asList(baseDir.list());
     for (String fileName : filesToCopy) {
       final File fileToCopy = new File(baseDir, fileName);
       if (java.nio.file.Files.isRegularFile(fileToCopy.toPath())) {
         size += copyFileToZipStream(fileToCopy, outputStream, progressable);
       } else {
         log.warn(
             "File at [%s] is not a regular file! skipping as part of zip", fileToCopy.getPath());
       }
     }
     outputStream.flush();
   }
   return size;
 }
  /**
   * Apply export and create the ZIP package.
   *
   * @param context the XWiki context used to render pages.
   * @throws IOException error when creating the package.
   * @throws XWikiException error when render the pages.
   */
  public void export(XWikiContext context) throws IOException, XWikiException {
    context.getResponse().setContentType("application/zip");
    context
        .getResponse()
        .addHeader(
            "Content-disposition",
            "attachment; filename=" + Util.encodeURI(this.name, context) + ".zip");
    context.setFinished(true);

    ZipOutputStream zos = new ZipOutputStream(context.getResponse().getOutputStream());

    File dir = context.getWiki().getTempDirectory(context);
    File tempdir = new File(dir, RandomStringUtils.randomAlphanumeric(8));
    tempdir.mkdirs();
    File attachmentDir = new File(tempdir, "attachment");
    attachmentDir.mkdirs();

    // Create custom URL factory
    ExportURLFactory urlf = new ExportURLFactory();

    // Render pages to export
    renderDocuments(zos, tempdir, urlf, context);

    // Add required skins to ZIP file
    for (String skinName : urlf.getNeededSkins()) {
      addSkinToZip(skinName, zos, urlf.getExportedSkinFiles(), context);
    }

    // add "resources" folder
    File file = new File(context.getWiki().getEngineContext().getRealPath("/resources/"));
    addDirToZip(file, zos, "resources" + ZIPPATH_SEPARATOR, urlf.getExportedSkinFiles());

    // Add attachments and generated skin files files to ZIP file
    addDirToZip(tempdir, zos, "", null);

    zos.setComment(this.description);

    // Finish ZIP file
    zos.finish();
    zos.flush();

    // Delete temporary directory
    deleteDirectory(tempdir);
  }
Exemple #28
0
 private void backup(ZipOutputStream zipOutputStream, CollectRecord summary, int stepNumber) {
   Integer id = summary.getId();
   try {
     CollectRecord record = recordManager.load(survey, id, stepNumber);
     String entryFileName = buildEntryFileName(record, stepNumber);
     ZipEntry entry = new ZipEntry(entryFileName);
     zipOutputStream.putNextEntry(entry);
     OutputStreamWriter writer = new OutputStreamWriter(zipOutputStream);
     dataMarshaller.write(record, writer);
     zipOutputStream.closeEntry();
     zipOutputStream.flush();
   } catch (Exception e) {
     String message = "Error while backing up " + id + " " + e.getMessage();
     if (LOG.isErrorEnabled()) {
       LOG.error(message, e);
     }
     throw new RuntimeException(message, e);
   }
 }
  @Override
  protected boolean writeMoreData() throws IOException {

    // Write data from the current stream if possible
    int count = entryStream.read(buffer);
    if (count != -1) {
      zipStream.write(buffer, 0, count);
      return true;
    }

    // Close any open entry
    if (entryStream != EMPTY_STREAM) {
      zipStream.closeEntry();
      entryStream.close();
      entryStream = EMPTY_STREAM;
    }

    // Move to the next entry if there is one (no need to write data as returning true causes
    // another call)
    if (entries.hasNext()) {
      fileCount++;
      Entry entry = entries.next();
      zipStream.putNextEntry(new ZipEntry(entry.getName()));
      entryStream = entry.getInputStream();
      if (entryStream == null) {
        entryStream = EMPTY_STREAM;
      }
      return true;
    }

    // If no files were added to the archive add an empty one
    if (fileCount == 0) {
      fileCount++;
      zipStream.putNextEntry(new ZipEntry("__empty__"));
      entryStream = EMPTY_STREAM;
      return true;
    }

    // No more entries, close and flush the stream
    zipStream.flush();
    zipStream.close();
    return false;
  }
  @Override
  public void marshal(ExportResourceModel model, OutputStream outputStream, boolean pretty)
      throws BindingException {
    File file;
    ZipOutputStream zos = null;
    try {
      file = File.createTempFile("gatein-export", ".zip");
      zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
    } catch (IOException e) {
      throw new BindingException("Could not create temp file for export.", e);
    }

    try {
      if (model.getTasks().isEmpty()) {
        zos.putNextEntry(new ZipEntry(""));
      } else {
        for (ExportTask task : model.getTasks()) {
          String entry = task.getEntry();
          zos.putNextEntry(new ZipEntry(entry));

          // Call export task responsible for writing the data.
          task.export(zos);

          zos.closeEntry();
        }
      }
      zos.flush();
      zos.finish();
    } catch (Throwable t) {
      throw new BindingException("Exception writing data to zip.", t);
    } finally {
      IOTools.safeClose(zos);
    }

    try {
      InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
      IOTools.copy(inputStream, outputStream);
    } catch (FileNotFoundException e) {
      throw new BindingException("Could not read from temporary zip file " + file, e);
    } catch (IOException e) {
      throw new BindingException("IOException writing data to final output stream.", e);
    }
  }