Java源码示例:net.lingala.zip4j.progress.ProgressMonitor
示例1
@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();
}
}
}
示例2
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);
}
示例3
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;
}
示例4
@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);
}
}
示例5
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);
}
}
示例6
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);
}
示例7
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());
}
}
}
示例8
/**
* 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));
}
示例9
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);
}
示例10
/**
* 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);
}
示例11
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;
}
}
示例12
/**
* 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);
}
}
示例13
/**
* 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);
}
示例14
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);
}
}
}
示例15
private ZipParameters cloneAndAdjustZipParameters(ZipParameters zipParameters, File fileToAdd,
ProgressMonitor progressMonitor) throws IOException {
ZipParameters clonedZipParameters = new ZipParameters(zipParameters);
clonedZipParameters.setLastModifiedFileTime(javaToDosTime((fileToAdd.lastModified())));
if (fileToAdd.isDirectory()) {
clonedZipParameters.setEntrySize(0);
} else {
clonedZipParameters.setEntrySize(fileToAdd.length());
}
clonedZipParameters.setWriteExtendedLocalFileHeader(false);
clonedZipParameters.setLastModifiedFileTime(fileToAdd.lastModified());
if (!Zip4jUtil.isStringNotNullAndNotEmpty(zipParameters.getFileNameInZip())) {
String relativeFileName = getRelativeFileName(fileToAdd, zipParameters);
clonedZipParameters.setFileNameInZip(relativeFileName);
}
if (fileToAdd.isDirectory()) {
clonedZipParameters.setCompressionMethod(CompressionMethod.STORE);
clonedZipParameters.setEncryptionMethod(EncryptionMethod.NONE);
clonedZipParameters.setEncryptFiles(false);
} else {
if (clonedZipParameters.isEncryptFiles() && clonedZipParameters.getEncryptionMethod() == ZIP_STANDARD) {
progressMonitor.setCurrentTask(CALCULATE_CRC);
clonedZipParameters.setEntryCRC(computeFileCrc(fileToAdd, progressMonitor));
progressMonitor.setCurrentTask(ADD_ENTRY);
}
if (fileToAdd.length() == 0) {
clonedZipParameters.setCompressionMethod(CompressionMethod.STORE);
}
}
return clonedZipParameters;
}
示例16
@Override
protected void executeTask(AddFilesToZipTaskParameters taskParameters, ProgressMonitor progressMonitor)
throws IOException {
verifyZipParameters(taskParameters.zipParameters);
addFilesToZip(taskParameters.filesToAdd, progressMonitor, taskParameters.zipParameters, taskParameters.charset);
}
示例17
protected void verifyIfTaskIsCancelled() throws ZipException {
if (!progressMonitor.isCancelAllTasks()) {
return;
}
progressMonitor.setResult(ProgressMonitor.Result.CANCELLED);
progressMonitor.setState(ProgressMonitor.State.READY);
throw new ZipException("Task cancelled", ZipException.Type.TASK_CANCELLED_EXCEPTION);
}
示例18
@Override
protected void executeTask(AddFolderToZipTaskParameters taskParameters, ProgressMonitor progressMonitor)
throws IOException {
List<File> filesToAdd = getFilesToAdd(taskParameters);
setDefaultFolderPath(taskParameters);
addFilesToZip(filesToAdd, progressMonitor, taskParameters.zipParameters, taskParameters.charset);
}
示例19
protected void extractFile(ZipInputStream zipInputStream, FileHeader fileHeader, String outputPath,
String newFileName, ProgressMonitor progressMonitor) throws IOException {
if (!outputPath.endsWith(FILE_SEPARATOR)) {
outputPath += FILE_SEPARATOR;
}
File outputFile = determineOutputFile(fileHeader, outputPath, newFileName);
progressMonitor.setFileName(outputFile.getAbsolutePath());
// make sure no file is extracted outside of the target directory (a.k.a zip slip)
String outputCanonicalPath = (new File(outputPath).getCanonicalPath()) + File.separator;
if (!outputFile.getCanonicalPath().startsWith(outputCanonicalPath)) {
throw new ZipException("illegal file name that breaks out of the target directory: "
+ fileHeader.getFileName());
}
verifyNextEntry(zipInputStream, fileHeader);
if (fileHeader.isDirectory()) {
if (!outputFile.exists()) {
if (!outputFile.mkdirs()) {
throw new ZipException("Could not create directory: " + outputFile);
}
}
} else if (isSymbolicLink(fileHeader)) {
createSymLink(zipInputStream, fileHeader, outputFile, progressMonitor);
} else {
checkOutputDirectoryStructure(outputFile);
unzipFile(zipInputStream, fileHeader, outputFile, progressMonitor);
}
}
示例20
private byte[] readCompleteEntry(ZipInputStream zipInputStream, FileHeader fileHeader,
ProgressMonitor progressMonitor) throws IOException {
byte[] b = new byte[(int) fileHeader.getUncompressedSize()];
int readLength = zipInputStream.read(b);
if (readLength != b.length) {
throw new ZipException("Could not read complete entry");
}
progressMonitor.updateWorkCompleted(b.length);
return b;
}
示例21
private void removeFileIfExists(ZipModel zipModel, Charset charset, String fileNameInZip, ProgressMonitor progressMonitor)
throws ZipException {
FileHeader fileHeader = HeaderUtil.getFileHeader(zipModel, fileNameInZip);
if (fileHeader != null) {
removeFile(fileHeader, progressMonitor, charset);
}
}
示例22
/**
* 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 filesToAdd
* @param parameters
* @throws ZipException
*/
public void addFiles(List<File> filesToAdd, ZipParameters parameters) throws ZipException {
if (filesToAdd == null || filesToAdd.size() == 0) {
throw new ZipException("input file List is null or empty");
}
if (parameters == null) {
throw new ZipException("input parameters are null");
}
if (progressMonitor.getState() == ProgressMonitor.State.BUSY) {
throw new ZipException("invalid operation - Zip4j is in busy state");
}
readZipInfo();
if (zipModel == null) {
throw new ZipException("internal error: zip model is null");
}
if (zipFile.exists() && zipModel.isSplitArchive()) {
throw new ZipException("Zip file already exists. Zip file format does not allow updating split/spanned files");
}
new AddFilesToZipTask(zipModel, password, headerWriter, buildAsyncParameters()).execute(
new AddFilesToZipTaskParameters(filesToAdd, parameters, charset));
}
示例23
/**
* 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 destinationPath
* @throws ZipException
*/
public void extractAll(String destinationPath) throws ZipException {
if (!isStringNotNullAndNotEmpty(destinationPath)) {
throw new ZipException("output path is null or invalid");
}
if (!Zip4jUtil.createDirectoryIfNotExists(new File(destinationPath))) {
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");
}
new ExtractAllFilesTask(zipModel, password, buildAsyncParameters()).execute(
new ExtractAllFilesTaskParameters(destinationPath, charset));
}
示例24
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();
}
}
示例25
@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"));
}
示例26
@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);
}
示例27
@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());
}
示例28
@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")));
}
示例29
@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());
}
示例30
@Test
public void testExtractFileWithFileHeaderWhenBusyStateThrowsException() throws ZipException {
zipFile.getProgressMonitor().setState(ProgressMonitor.State.BUSY);
expectedException.expectMessage("invalid operation - Zip4j is in busy state");
expectedException.expect(ZipException.class);
zipFile.extractFile(new FileHeader(), "SOME_DESTINATION");
}