net.lingala.zip4j.progress.ProgressMonitor Java Examples

The following examples show how to use net.lingala.zip4j.progress.ProgressMonitor. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ZipFile.java    From zip4j with Apache License 2.0 6 votes vote down vote up
/**
 * Extracts a specific file from the zip file to the destination path.
 * If destination path is invalid, then this method throws an exception.
 * <br><br>
 * If newFileName is not null or empty, newly created file name will be replaced by
 * the value in newFileName. If this value is null, then the file name will be the
 * value in FileHeader.getFileName. If file being extract is a directory, the directory name
 * will be replaced with the newFileName
 * <br><br>
 * If fileHeader is a directory, this method extracts all files under this directory.
 *
 * @param fileHeader
 * @param destinationPath
 * @param newFileName
 * @throws ZipException
 */
public void extractFile(FileHeader fileHeader, String destinationPath, String newFileName) throws ZipException {
  if (fileHeader == null) {
    throw new ZipException("input file header is null, cannot extract file");
  }

  if (!isStringNotNullAndNotEmpty(destinationPath)) {
    throw new ZipException("destination path is empty or null, cannot extract file");
  }

  if (progressMonitor.getState() == ProgressMonitor.State.BUSY) {
    throw new ZipException("invalid operation - Zip4j is in busy state");
  }

  readZipInfo();

  new ExtractFileTask(zipModel, password, buildAsyncParameters()).execute(
      new ExtractFileTaskParameters(destinationPath, fileHeader, newFileName, charset));
}
 
Example #2
Source File: AbstractAddFileToZipTask.java    From zip4j with Apache License 2.0 6 votes vote down vote up
private List<File> removeFilesIfExists(List<File> files, ZipParameters zipParameters, ProgressMonitor progressMonitor, Charset charset)
    throws ZipException {

  List<File> filesToAdd = new ArrayList<>(files);
  if (!zipModel.getZipFile().exists()) {
    return filesToAdd;
  }

  for (File file : files) {
    String fileName = getRelativeFileName(file, zipParameters);

    FileHeader fileHeader = getFileHeader(zipModel, fileName);
    if (fileHeader != null) {
      if (zipParameters.isOverrideExistingFilesInZip()) {
        progressMonitor.setCurrentTask(REMOVE_ENTRY);
        removeFile(fileHeader, progressMonitor, charset);
        verifyIfTaskIsCancelled();
        progressMonitor.setCurrentTask(ADD_ENTRY);
      } else {
        filesToAdd.remove(file);
      }
    }
  }

  return filesToAdd;
}
 
Example #3
Source File: AbstractAddFileToZipTask.java    From zip4j with Apache License 2.0 6 votes vote down vote up
private void addFileToZip(File fileToAdd, ZipOutputStream zipOutputStream, ZipParameters zipParameters,
                          SplitOutputStream splitOutputStream, ProgressMonitor progressMonitor) throws IOException {

  zipOutputStream.putNextEntry(zipParameters);

  if (!fileToAdd.isDirectory()) {
    try (InputStream inputStream = new FileInputStream(fileToAdd)) {
      while ((readLen = inputStream.read(readBuff)) != -1) {
        zipOutputStream.write(readBuff, 0, readLen);
        progressMonitor.updateWorkCompleted(readLen);
        verifyIfTaskIsCancelled();
      }
    }
  }

  closeEntry(zipOutputStream, splitOutputStream, fileToAdd, false);
}
 
Example #4
Source File: ZipFile.java    From AndroidZip with Apache License 2.0 6 votes vote down vote up
/**
 * Extracts a specific file from the zip file to the destination path.
 * If destination path is invalid, then this method throws an exception.
 * @param fileHeader
 * @param destPath
 * @param unzipParameters
 * @param newFileName
 * @throws ZipException
 */
public void extractFile(FileHeader fileHeader, String destPath, 
		UnzipParameters unzipParameters, String newFileName) throws ZipException {
	
	if (fileHeader == null) {
		throw new ZipException("input file header is null, cannot extract file");
	}
	
	if (!Zip4jUtil.isStringNotNullAndNotEmpty(destPath)) {
		throw new ZipException("destination path is empty or null, cannot extract file");
	}
	
	readZipInfo();
	
	if (progressMonitor.getState() == ProgressMonitor.STATE_BUSY) {
		throw new ZipException("invalid operation - Zip4j is in busy state");
	}
	
	fileHeader.extractFile(zipModel, destPath, unzipParameters, newFileName, progressMonitor, runInThread);
	
}
 
Example #5
Source File: SetCommentTask.java    From zip4j with Apache License 2.0 6 votes vote down vote up
@Override
protected void executeTask(SetCommentTaskTaskParameters taskParameters, ProgressMonitor progressMonitor) throws IOException {
  if (taskParameters.comment == null) {
    throw new ZipException("comment is null, cannot update Zip file with comment");
  }

  EndOfCentralDirectoryRecord endOfCentralDirectoryRecord = zipModel.getEndOfCentralDirectoryRecord();
  endOfCentralDirectoryRecord.setComment(taskParameters.comment);

  try (SplitOutputStream outputStream = new SplitOutputStream(zipModel.getZipFile())) {
    if (zipModel.isZip64Format()) {
      outputStream.seek(zipModel.getZip64EndOfCentralDirectoryRecord()
          .getOffsetStartCentralDirectoryWRTStartDiskNumber());
    } else {
      outputStream.seek(endOfCentralDirectoryRecord.getOffsetOfStartOfCentralDirectory());
    }

    HeaderWriter headerWriter = new HeaderWriter();
    headerWriter.finalizeZipFileWithoutValidations(zipModel, outputStream, taskParameters.charset);
  }
}
 
Example #6
Source File: AsyncZipTask.java    From zip4j with Apache License 2.0 6 votes vote down vote up
public void execute(T taskParameters) throws ZipException {
  progressMonitor.fullReset();
  progressMonitor.setState(ProgressMonitor.State.BUSY);
  progressMonitor.setCurrentTask(getTask());

  if (runInThread) {
    long totalWorkToBeDone = calculateTotalWork(taskParameters);
    progressMonitor.setTotalWork(totalWorkToBeDone);

    executorService.execute(() -> {
      try {
        performTaskWithErrorHandling(taskParameters, progressMonitor);
      } catch (ZipException e) {
        //Do nothing. Exception will be passed through progress monitor
      }
    });
  } else {
    performTaskWithErrorHandling(taskParameters, progressMonitor);
  }
}
 
Example #7
Source File: ArchiveMaintainer.java    From AndroidZip with Apache License 2.0 6 votes vote down vote up
/**
 * Merges split Zip files into a single Zip file
 * @param zipModel
 * @throws ZipException
 */
public void mergeSplitZipFiles(final ZipModel zipModel, final File outputZipFile, 
		final ProgressMonitor progressMonitor, boolean runInThread) throws ZipException {
	if (runInThread) {
		Thread thread = new Thread(InternalZipConstants.THREAD_NAME) {
			public void run() {
				try {
					initMergeSplitZipFile(zipModel, outputZipFile, progressMonitor);
				} catch (ZipException e) {
				}
			}
		};
		thread.start();
	} else {
		initMergeSplitZipFile(zipModel, outputZipFile, progressMonitor);
	}
}
 
Example #8
Source File: FileHeader.java    From AndroidZip with Apache License 2.0 6 votes vote down vote up
/**
 * Extracts file to the specified directory using any 
 * user defined parameters in UnzipParameters. Output file name
 * will be overwritten with the value in newFileName. If this 
 * parameter is null, then file name will be the same as in 
 * FileHeader.getFileName
 * @param zipModel
 * @param outPath
 * @param unzipParameters
 * @throws ZipException
 */
public void extractFile(ZipModel zipModel, String outPath, 
		UnzipParameters unzipParameters, String newFileName, 
		ProgressMonitor progressMonitor, boolean runInThread) throws ZipException {
	if (zipModel == null) {
		throw new ZipException("input zipModel is null");
	}
	
	if (!Zip4jUtil.checkOutputFolder(outPath)) {
		throw new ZipException("Invalid output path");
	}
	
	if (this == null) {
		throw new ZipException("invalid file header");
	}
	Unzip unzip = new Unzip(zipModel);
	unzip.extractFile(this, outPath, unzipParameters, newFileName, progressMonitor, runInThread);
}
 
Example #9
Source File: ExtractAllFilesTask.java    From zip4j with Apache License 2.0 6 votes vote down vote up
@Override
protected void executeTask(ExtractAllFilesTaskParameters taskParameters, ProgressMonitor progressMonitor)
    throws IOException {
  try (ZipInputStream zipInputStream = prepareZipInputStream(taskParameters.charset)) {
    for (FileHeader fileHeader : getZipModel().getCentralDirectory().getFileHeaders()) {
      if (fileHeader.getFileName().startsWith("__MACOSX")) {
        progressMonitor.updateWorkCompleted(fileHeader.getUncompressedSize());
        continue;
      }

      splitInputStream.prepareExtractionForFileHeader(fileHeader);

      extractFile(zipInputStream, fileHeader, taskParameters.outputPath, null, progressMonitor);
      verifyIfTaskIsCancelled();
    }
  } finally {
    if (splitInputStream != null) {
      splitInputStream.close();
    }
  }
}
 
Example #10
Source File: AbstractExtractFileTask.java    From zip4j with Apache License 2.0 6 votes vote down vote up
private void createSymLink(ZipInputStream zipInputStream, FileHeader fileHeader, File outputFile,
                           ProgressMonitor progressMonitor) throws IOException {

  String symLinkPath = new String(readCompleteEntry(zipInputStream, fileHeader, progressMonitor));

  if (!outputFile.getParentFile().exists() && !outputFile.getParentFile().mkdirs()) {
    throw new ZipException("Could not create parent directories");
  }

  try {
    Path linkTarget = Paths.get(symLinkPath);
    Files.createSymbolicLink(outputFile.toPath(), linkTarget);
    UnzipUtil.applyFileAttributes(fileHeader, outputFile);
  } catch (NoSuchMethodError error) {
    try (OutputStream outputStream = new FileOutputStream(outputFile)) {
      outputStream.write(symLinkPath.getBytes());
    }
  }
}
 
Example #11
Source File: AbstractExtractFileTask.java    From zip4j with Apache License 2.0 6 votes vote down vote up
private void unzipFile(ZipInputStream inputStream, FileHeader fileHeader, File outputFile,
                       ProgressMonitor progressMonitor) throws IOException {
  int readLength;
  try (OutputStream outputStream = new FileOutputStream(outputFile)) {
    while ((readLength = inputStream.read(buff)) != -1) {
      outputStream.write(buff, 0, readLength);
      progressMonitor.updateWorkCompleted(readLength);
      verifyIfTaskIsCancelled();
    }
  } catch (Exception e) {
    if (outputFile.exists()) {
      outputFile.delete();
    }
    throw  e;
  }

  UnzipUtil.applyFileAttributes(fileHeader, outputFile);
}
 
Example #12
Source File: ZipManager.java    From AndroidZip with Apache License 2.0 6 votes vote down vote up
private static void timerMsg(final IZipCallback callback, ZipFile zipFile) {
    if (callback == null) return;
    mUIHandler.obtainMessage(WHAT_START, callback).sendToTarget();
    final ProgressMonitor progressMonitor = zipFile.getProgressMonitor();
    final Timer           timer           = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            mUIHandler.obtainMessage(WHAT_PROGRESS, progressMonitor.getPercentDone(), 0, callback).sendToTarget();
            if (progressMonitor.getResult() == ProgressMonitor.RESULT_SUCCESS) {
                mUIHandler.obtainMessage(WHAT_FINISH, callback).sendToTarget();
                this.cancel();
                timer.purge();
            }
        }
    }, 0, 300);
}
 
Example #13
Source File: ArchiveMaintainer.java    From AndroidZip with Apache License 2.0 6 votes vote down vote up
public HashMap removeZipFile(final ZipModel zipModel, 
		final FileHeader fileHeader, final ProgressMonitor progressMonitor, boolean runInThread) throws ZipException {
	
	if (runInThread) {
		Thread thread = new Thread(InternalZipConstants.THREAD_NAME) {
			public void run() {
				try {
					initRemoveZipFile(zipModel, fileHeader, progressMonitor);
					progressMonitor.endProgressMonitorSuccess();
				} catch (ZipException e) {
				}
			}
		};
		thread.start();
		return null;
	} else {
		HashMap retMap = initRemoveZipFile(zipModel, fileHeader, progressMonitor);
		progressMonitor.endProgressMonitorSuccess();
		return retMap;
	}
	
}
 
Example #14
Source File: ZipFileTest.java    From zip4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddFilesWithParametersThrowsExceptionWhenProgressMonitorStateIsBusy() throws ZipException {
  zipFile.getProgressMonitor().setState(ProgressMonitor.State.BUSY);

  expectedException.expect(ZipException.class);
  expectedException.expectMessage("invalid operation - Zip4j is in busy state");

  zipFile.addFiles(Collections.singletonList(new File("Some_File")), new ZipParameters());
}
 
Example #15
Source File: ZipEngine.java    From AndroidZip with Apache License 2.0 5 votes vote down vote up
public void addFiles(final ArrayList fileList, final ZipParameters parameters,
		final ProgressMonitor progressMonitor, boolean runInThread) throws ZipException {
	
	if (fileList == null || parameters == null) {
		throw new ZipException("one of the input parameters is null when adding files");
	}
	
	if(fileList.size() <= 0) {
		throw new ZipException("no files to add");
	}
	
	progressMonitor.setCurrentOperation(ProgressMonitor.OPERATION_ADD);
	progressMonitor.setState(ProgressMonitor.STATE_BUSY);
	progressMonitor.setResult(ProgressMonitor.RESULT_WORKING);
	
	if (runInThread) {
		progressMonitor.setTotalWork(calculateTotalWork(fileList, parameters));
		progressMonitor.setFileName(((File)fileList.get(0)).getAbsolutePath());
		
		Thread thread = new Thread(InternalZipConstants.THREAD_NAME) {
			public void run() {
				try {
					initAddFiles(fileList, parameters, progressMonitor);
				} catch (ZipException e) {
				}
			}
		};
		thread.start();
		
	} else {
		initAddFiles(fileList, parameters, progressMonitor);
	}
}
 
Example #16
Source File: ZipFileVerifier.java    From zip4j with Apache License 2.0 5 votes vote down vote up
public static void verifyFileCrc(File sourceFile, File extractedFile) throws IOException {
  ProgressMonitor progressMonitor = new ProgressMonitor();
  long sourceFileCrc = CrcUtil.computeFileCrc(sourceFile, progressMonitor);
  long extractedFileCrc = CrcUtil.computeFileCrc(extractedFile, progressMonitor);

  assertThat(sourceFileCrc).isEqualTo(extractedFileCrc);
}
 
Example #17
Source File: Unzip.java    From AndroidZip with Apache License 2.0 5 votes vote down vote up
public void extractAll(final UnzipParameters unzipParameters, final String outPath,
		final ProgressMonitor progressMonitor, boolean runInThread) throws ZipException {
	
	CentralDirectory centralDirectory = zipModel.getCentralDirectory();
	
	if (centralDirectory == null || 
			centralDirectory.getFileHeaders() == null) {
		throw new ZipException("invalid central directory in zipModel");
	}
	
	final ArrayList fileHeaders = centralDirectory.getFileHeaders();
	
	progressMonitor.setCurrentOperation(ProgressMonitor.OPERATION_EXTRACT);
	progressMonitor.setTotalWork(calculateTotalWork(fileHeaders));
	progressMonitor.setState(ProgressMonitor.STATE_BUSY);
	
	if (runInThread) {
		Thread thread = new Thread(InternalZipConstants.THREAD_NAME) {
			public void run() {
				try {
					initExtractAll(fileHeaders, unzipParameters, progressMonitor, outPath);
					progressMonitor.endProgressMonitorSuccess();
				} catch (ZipException e) {
				}
			}
		};
		thread.start();
	} else {
		initExtractAll(fileHeaders, unzipParameters, progressMonitor, outPath);
	}
	
}
 
Example #18
Source File: ZipFile.java    From AndroidZip with Apache License 2.0 5 votes vote down vote up
/**
 * Extracts all the files in the given zip file to the input destination path.
 * If zip file does not exist or destination path is invalid then an 
 * exception is thrown.
 * @param destPath
 * @param unzipParameters
 * @throws ZipException
 */
public void extractAll(String destPath, 
		UnzipParameters unzipParameters) throws ZipException {
	
	if (!Zip4jUtil.isStringNotNullAndNotEmpty(destPath)) {
		throw new ZipException("output path is null or invalid");
	}
	
	if (!Zip4jUtil.checkOutputFolder(destPath)) {
		throw new ZipException("invalid output path");
	}
	
	if (zipModel == null) {
		readZipInfo();
	}
	
	// Throw an exception if zipModel is still null
	if (zipModel == null) {
		throw new ZipException("Internal error occurred when extracting zip file");
	}
	
	if (progressMonitor.getState() == ProgressMonitor.STATE_BUSY) {
		throw new ZipException("invalid operation - Zip4j is in busy state");
	}
	
	Unzip unzip = new Unzip(zipModel);
	unzip.extractAll(unzipParameters, destPath, progressMonitor, runInThread);
	
}
 
Example #19
Source File: ZipFile.java    From AndroidZip with Apache License 2.0 5 votes vote down vote up
/**
 * Adds the list of input files to the zip file. If zip file does not exist, then 
 * this method creates a new zip file. Parameters such as compression type, etc
 * can be set in the input parameters.
 * @param sourceFileList
 * @param parameters
 * @throws ZipException
 */
public void addFiles(ArrayList sourceFileList, ZipParameters parameters) throws ZipException {
	
	checkZipModel();
	
	if (this.zipModel == null) {
		throw new ZipException("internal error: zip model is null");
	}
	
	if (sourceFileList == null) {
		throw new ZipException("input file ArrayList is null, cannot add files");
	}
	
	if (!Zip4jUtil.checkArrayListTypes(sourceFileList, InternalZipConstants.LIST_TYPE_FILE)) {
		throw new ZipException("One or more elements in the input ArrayList is not of type File");
	}
	
	if (parameters == null) {
		throw new ZipException("input parameters are null, cannot add files to zip");
	}
	
	if (progressMonitor.getState() == ProgressMonitor.STATE_BUSY) {
		throw new ZipException("invalid operation - Zip4j is in busy state");
	}
	
	if (Zip4jUtil.checkFileExists(file)) {
		if (zipModel.isSplitArchive()) {
			throw new ZipException("Zip file already exists. Zip file format does not allow updating split/spanned files");
		}
	}
	
	ZipEngine zipEngine = new ZipEngine(zipModel);
	zipEngine.addFiles(sourceFileList, parameters, progressMonitor, runInThread);
}
 
Example #20
Source File: ArchiveMaintainer.java    From AndroidZip with Apache License 2.0 5 votes vote down vote up
public void initProgressMonitorForRemoveOp(ZipModel zipModel, 
		FileHeader fileHeader, ProgressMonitor progressMonitor) throws ZipException {
	if (zipModel == null || fileHeader == null || progressMonitor == null) {
		throw new ZipException("one of the input parameters is null, cannot calculate total work");
	}
	
	progressMonitor.setCurrentOperation(ProgressMonitor.OPERATION_REMOVE);
	progressMonitor.setFileName(fileHeader.getFileName());
	progressMonitor.setTotalWork(calculateTotalWorkForRemoveOp(zipModel, fileHeader));
	progressMonitor.setState(ProgressMonitor.STATE_BUSY);
}
 
Example #21
Source File: ArchiveMaintainer.java    From AndroidZip with Apache License 2.0 5 votes vote down vote up
public void initProgressMonitorForMergeOp(ZipModel zipModel, ProgressMonitor progressMonitor) throws ZipException {
	if (zipModel == null) {
		throw new ZipException("zip model is null, cannot calculate total work for merge op");
	}
	
	progressMonitor.setCurrentOperation(ProgressMonitor.OPERATION_MERGE);
	progressMonitor.setFileName(zipModel.getZipFile());
	progressMonitor.setTotalWork(calculateTotalWorkForMergeOp(zipModel));
	progressMonitor.setState(ProgressMonitor.STATE_BUSY);
}
 
Example #22
Source File: Unzip.java    From AndroidZip with Apache License 2.0 5 votes vote down vote up
public void extractFile(final FileHeader fileHeader, final String outPath,
		final UnzipParameters unzipParameters, final String newFileName, 
		final ProgressMonitor progressMonitor, boolean runInThread) throws ZipException {
	if (fileHeader == null) {
		throw new ZipException("fileHeader is null");
	}
	
	progressMonitor.setCurrentOperation(ProgressMonitor.OPERATION_EXTRACT);
	progressMonitor.setTotalWork(fileHeader.getCompressedSize());
	progressMonitor.setState(ProgressMonitor.STATE_BUSY);
	progressMonitor.setPercentDone(0);
	progressMonitor.setFileName(fileHeader.getFileName());
	
	if (runInThread) {
		Thread thread = new Thread(InternalZipConstants.THREAD_NAME) {
			public void run() {
				try {
					initExtractFile(fileHeader, outPath, unzipParameters, newFileName, progressMonitor);
					progressMonitor.endProgressMonitorSuccess();
				} catch (ZipException e) {
				}
			}
		};
		thread.start();
	} else {
		initExtractFile(fileHeader, outPath, unzipParameters, newFileName, progressMonitor);
		progressMonitor.endProgressMonitorSuccess();
	}
	
}
 
Example #23
Source File: AddFilesToZipIT.java    From zip4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddFileProgressMonitorThrowsExceptionWhenPerformingActionInBusyState() throws ZipException {
  expectedException.expectMessage("invalid operation - Zip4j is in busy state");
  expectedException.expect(ZipException.class);

  ZipFile zipFile = new ZipFile(generatedZipFile);
  ProgressMonitor progressMonitor = zipFile.getProgressMonitor();
  progressMonitor.setState(ProgressMonitor.State.BUSY);

  zipFile.addFile(TestUtils.getTestFileFromResources("file_PDF_1MB.pdf"));
}
 
Example #24
Source File: ZipFile.java    From AndroidZip with Apache License 2.0 5 votes vote down vote up
/**
 * Extracts a specific file from the zip file to the destination path. 
 * This method first finds the necessary file header from the input file name.
 * <br><br>
 * File name is relative file name in the zip file. For example if a zip file contains
 * a file "a.txt", then to extract this file, input file name has to be "a.txt". Another
 * example is if there is a file "b.txt" in a folder "abc" in the zip file, then the
 * input file name has to be abc/b.txt
 * <br><br>
 * If newFileName is not null or empty, newly created file name will be replaced by 
 * the value in newFileName. If this value is null, then the file name will be the 
 * value in FileHeader.getFileName
 * <br><br>
 * Throws an exception if file header could not be found for the given file name or if 
 * the destination path is invalid
 * @param fileName
 * @param destPath
 * @param unzipParameters
 * @param newFileName
 * @throws ZipException
 */
public void extractFile(String fileName, String destPath, 
		UnzipParameters unzipParameters, String newFileName) throws ZipException {
	
	if (!Zip4jUtil.isStringNotNullAndNotEmpty(fileName)) {
		throw new ZipException("file to extract is null or empty, cannot extract file");
	}
	
	if (!Zip4jUtil.isStringNotNullAndNotEmpty(destPath)) {
		throw new ZipException("destination string path is empty or null, cannot extract file");
	}
	
	readZipInfo();
	
	FileHeader fileHeader = Zip4jUtil.getFileHeader(zipModel, fileName);
	
	if (fileHeader == null) {
		throw new ZipException("file header not found for given file name, cannot extract file");
	}
	
	if (progressMonitor.getState() == ProgressMonitor.STATE_BUSY) {
		throw new ZipException("invalid operation - Zip4j is in busy state");
	}
	
	fileHeader.extractFile(zipModel, destPath, unzipParameters, newFileName, progressMonitor, runInThread);
	
}
 
Example #25
Source File: AbstractAddFileToZipTask.java    From zip4j with Apache License 2.0 5 votes vote down vote up
void addFilesToZip(List<File> filesToAdd, ProgressMonitor progressMonitor, ZipParameters zipParameters, Charset charset)
    throws IOException {

  assertFilesExist(filesToAdd, zipParameters.getSymbolicLinkAction());

  List<File> updatedFilesToAdd = removeFilesIfExists(filesToAdd, zipParameters, progressMonitor, charset);

  try (SplitOutputStream splitOutputStream = new SplitOutputStream(zipModel.getZipFile(), zipModel.getSplitLength());
       ZipOutputStream zipOutputStream = initializeOutputStream(splitOutputStream, charset)) {

    for (File fileToAdd : updatedFilesToAdd) {
      verifyIfTaskIsCancelled();
      ZipParameters clonedZipParameters = cloneAndAdjustZipParameters(zipParameters, fileToAdd, progressMonitor);
      progressMonitor.setFileName(fileToAdd.getAbsolutePath());

      if (FileUtils.isSymbolicLink(fileToAdd)) {
        if (addSymlink(clonedZipParameters)) {
          addSymlinkToZip(fileToAdd, zipOutputStream, clonedZipParameters, splitOutputStream);

          if (INCLUDE_LINK_ONLY.equals(clonedZipParameters.getSymbolicLinkAction())) {
            continue;
          }
        }
      }

      addFileToZip(fileToAdd, zipOutputStream, clonedZipParameters, splitOutputStream, progressMonitor);
    }
  }
}
 
Example #26
Source File: ZipFileTest.java    From zip4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddFilesThrowsExceptionWhenProgressMonitorStateIsBusy() throws ZipException {
  zipFile.getProgressMonitor().setState(ProgressMonitor.State.BUSY);

  expectedException.expect(ZipException.class);
  expectedException.expectMessage("invalid operation - Zip4j is in busy state");

  zipFile.addFiles(Collections.singletonList(new File("Some_File")));
}
 
Example #27
Source File: ZipFileTest.java    From zip4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddFileAsFileThrowsExceptionWhenProgressMonitorStateIsBusy() throws ZipException {
  File fileToAdd = mockFile(true);
  zipFile.getProgressMonitor().setState(ProgressMonitor.State.BUSY);

  expectedException.expect(ZipException.class);
  expectedException.expectMessage("invalid operation - Zip4j is in busy state");

  zipFile.addFile(fileToAdd, new ZipParameters());
}
 
Example #28
Source File: ZipFile.java    From AndroidZip with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new Zip File Object with the input file.
 * If the zip file does not exist, it is not created at this point.
 * @param zipFile
 * @throws ZipException
 */
public ZipFile(File zipFile) throws ZipException {
	if (zipFile == null) {
		throw new ZipException("Input zip file parameter is not null", 
				ZipExceptionConstants.inputZipParamIsNull);
	}
	
	this.file = zipFile.getPath();
	this.mode = InternalZipConstants.MODE_UNZIP;
	this.progressMonitor = new ProgressMonitor();
	this.runInThread = false;
}
 
Example #29
Source File: AddFilesToZipIT.java    From zip4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddFolderWithProgressMonitor() throws IOException, InterruptedException {
  ZipFile zipFile = new ZipFile(generatedZipFile, PASSWORD);
  ProgressMonitor progressMonitor = zipFile.getProgressMonitor();
  boolean percentBetweenZeroAndHundred = false;
  boolean fileNameSet = false;

  zipFile.setRunInThread(true);
  zipFile.addFolder(TestUtils.getTestFileFromResources(""),
      createZipParameters(EncryptionMethod.AES, AesKeyStrength.KEY_STRENGTH_256));

  while (!progressMonitor.getState().equals(ProgressMonitor.State.READY)) {
    int percentDone = progressMonitor.getPercentDone();
    String fileName = progressMonitor.getFileName();

    if (percentDone > 0 && percentDone < 100) {
      percentBetweenZeroAndHundred = true;
    }

    if (fileName != null) {
      fileNameSet = true;
    }

    Thread.sleep(10);
  }

  assertThat(progressMonitor.getResult()).isEqualTo(ProgressMonitor.Result.SUCCESS);
  assertThat(progressMonitor.getState().equals(ProgressMonitor.State.READY));
  assertThat(progressMonitor.getException()).isNull();
  assertThat(percentBetweenZeroAndHundred).isTrue();
  assertThat(fileNameSet).isTrue();
  ZipFileVerifier.verifyZipFileByExtractingAllFiles(generatedZipFile, PASSWORD, outputFolder, 13);
}
 
Example #30
Source File: CrcUtil.java    From zip4j with Apache License 2.0 5 votes vote down vote up
public static long computeFileCrc(File inputFile, ProgressMonitor progressMonitor) throws IOException {

    if (inputFile == null || !inputFile.exists() || !inputFile.canRead()) {
      throw new ZipException("input file is null or does not exist or cannot read. " +
          "Cannot calculate CRC for the file");
    }

    byte[] buff = new byte[BUF_SIZE];
    CRC32 crc32 = new CRC32();

    try(InputStream inputStream = new FileInputStream(inputFile)) {
      int readLen;
      while ((readLen = inputStream.read(buff)) != -1) {
        crc32.update(buff, 0, readLen);

        if (progressMonitor != null) {
          progressMonitor.updateWorkCompleted(readLen);
          if (progressMonitor.isCancelAllTasks()) {
            progressMonitor.setResult(ProgressMonitor.Result.CANCELLED);
            progressMonitor.setState(ProgressMonitor.State.READY);
            return 0;
          }
        }
      }
      return crc32.getValue();
    }
  }