net.lingala.zip4j.model.ZipParameters Java Examples

The following examples show how to use net.lingala.zip4j.model.ZipParameters. 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: MiscZipFileIT.java    From zip4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetInputStreamWithAesEncryptionAndSplitFileReturnsSuccessfully() throws IOException {
  ZipParameters zipParameters = createZipParameters(EncryptionMethod.AES, AesKeyStrength.KEY_STRENGTH_256);
  ZipFile zipFile = new ZipFile(generatedZipFile, PASSWORD);
  List<File> filesToAdd = new ArrayList<>(FILES_TO_ADD);
  filesToAdd.add(TestUtils.getTestFileFromResources("file_PDF_1MB.pdf"));
  zipFile.createSplitZipFile(filesToAdd, zipParameters, true, InternalZipConstants.MIN_SPLIT_LENGTH);

  try (InputStream inputStream = zipFile.getInputStream(zipFile.getFileHeader("file_PDF_1MB.pdf"))) {
    assertThat(inputStream).isNotNull();
    verifyInputStream(inputStream, TestUtils.getTestFileFromResources("file_PDF_1MB.pdf"));
  }

  //Check also with a new instance
  zipFile = new ZipFile(generatedZipFile, PASSWORD);
  try (InputStream inputStream = zipFile.getInputStream(zipFile.getFileHeader("file_PDF_1MB.pdf"))) {
    verifyInputStream(inputStream, TestUtils.getTestFileFromResources("file_PDF_1MB.pdf"));
  }
}
 
Example #2
Source File: Zip4j.java    From maven-framework-project with MIT License 6 votes vote down vote up
/**
 * 示例5 创建分卷压缩包
 */
@Test
public void example5(){
	try {
         
           ZipFile zipFile = new ZipFile("src/main/resources/CreateSplitZipFile.zip");

           ArrayList<File> filesToAdd = new ArrayList<File>();
           filesToAdd.add(new File("src/main/resources/sample.txt"));
           filesToAdd.add(new File("src/main/resources/zip4j.txt"));
           filesToAdd.add(new File("src/main/resources/zip4j-1.3.2.jar"));
            
           ZipParameters parameters = new ZipParameters();
           parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
            
           parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
            
           zipFile.createZipFile(filesToAdd, parameters, true, 65536);
       } catch (ZipException e) {
           e.printStackTrace();
       }
}
 
Example #3
Source File: ZipFile.java    From AndroidZip with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a zip file and adds the list of source file(s) to the zip file. If the zip file
 * exists then this method throws an exception. Parameters such as compression type, etc
 * can be set in the input parameters. While the method addFile/addFiles also creates the 
 * zip file if it does not exist, the main functionality of this method is to create a split
 * zip file. To create a split zip file, set the splitArchive parameter to true with a valid
 * splitLength. Split Length has to be more than 65536 bytes
 * @param sourceFileList - File to be added to the zip file
 * @param parameters - zip parameters for this file list
 * @param splitArchive - if archive has to be split or not
 * @param splitLength - if archive has to be split, then length in bytes at which it has to be split
 * @throws ZipException
 */
public void createZipFile(ArrayList sourceFileList, ZipParameters parameters, 
		boolean splitArchive, long splitLength) throws ZipException {
	
	if (!Zip4jUtil.isStringNotNullAndNotEmpty(file)) {
		throw new ZipException("zip file path is empty");
	}
	
	if (Zip4jUtil.checkFileExists(file)) {
		throw new ZipException("zip file: " + file + " already exists. To add files to existing zip file use addFile method");
	}
	
	if (sourceFileList == null) {
		throw new ZipException("input file ArrayList is null, cannot create zip file");
	}
	
	if (!Zip4jUtil.checkArrayListTypes(sourceFileList, InternalZipConstants.LIST_TYPE_FILE)) {
		throw new ZipException("One or more elements in the input ArrayList is not of type File");
	}
	
	createNewZipModel();
	this.zipModel.setSplitArchive(splitArchive);
	this.zipModel.setSplitLength(splitLength);
	addFiles(sourceFileList, parameters);
}
 
Example #4
Source File: AbstractAddFileToZipTask.java    From zip4j with Apache License 2.0 6 votes vote down vote up
long calculateWorkForFiles(List<File> filesToAdd, ZipParameters zipParameters) throws ZipException {
  long totalWork = 0;

  for (File fileToAdd : filesToAdd) {
    if (!fileToAdd.exists()) {
      continue;
    }

    if (zipParameters.isEncryptFiles() && zipParameters.getEncryptionMethod() == EncryptionMethod.ZIP_STANDARD) {
      totalWork += (fileToAdd.length() * 2); // for CRC calculation
    } else {
      totalWork += fileToAdd.length();
    }

    //If an entry already exists, we have to remove that entry first and then add content again.
    //In this case, add corresponding work
    String relativeFileName = getRelativeFileName(fileToAdd, zipParameters);
    FileHeader fileHeader = getFileHeader(getZipModel(), relativeFileName);
    if (fileHeader != null) {
      totalWork += (getZipModel().getZipFile().length() - fileHeader.getCompressedSize());
    }
  }

  return totalWork;
}
 
Example #5
Source File: AddFilesToZipIT.java    From zip4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddFolderWithNotNormalizedPath() throws IOException {
  ZipFile zipFile = new ZipFile(generatedZipFile);
  ZipParameters parameters = new ZipParameters();

  String folderToAddPath = TestUtils.getTestFileFromResources("").getPath()
      + InternalZipConstants.FILE_SEPARATOR + ".."
      + InternalZipConstants.FILE_SEPARATOR
      + TestUtils.getTestFileFromResources("").getName();
  File folderToAdd = new File(folderToAddPath);
  zipFile.addFolder(folderToAdd, parameters);

  File fileToAdd = TestUtils.getTestFileFromResources("file_PDF_1MB.pdf");
  zipFile.addFile(fileToAdd, parameters);

  ZipFileVerifier.verifyZipFileByExtractingAllFiles(generatedZipFile, outputFolder, 13);
}
 
Example #6
Source File: ZipUtil.java    From MonitorClient with Apache License 2.0 6 votes vote down vote up
/**
 * 添加多个文件到zip中指定的文件夹中
 * @param inPath
 * @param storagePath
 * @param outPath
 * @param password
 * @return
 */
public static boolean addFilesInZip(ArrayList<File> inFiles,String storagePath,String outPath,String password) {
	try {
		ArrayList filesToAdd = new ArrayList();  
		ZipFile zipFile = new ZipFile(outPath);
		ZipParameters parameters = new ZipParameters();
		parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); // set compression method to deflate compression
		parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL); 
		parameters.setRootFolderInZip(storagePath);  
		if(password!=null&&!password.equals("")){
			parameters.setEncryptFiles(true);  
			parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);  
			parameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);  
			parameters.setPassword(password); 
		}
		zipFile.addFiles(inFiles, parameters);
		return true;
	} catch (ZipException e) {
		e.printStackTrace();
		return false;
	}
}
 
Example #7
Source File: CreateZipFileIT.java    From zip4j with Apache License 2.0 6 votes vote down vote up
private void testCreateZipFileWithFileEntryComment(String fileCommentPrefix, Charset charset) throws IOException {
  ZipParameters zipParameters = new ZipParameters();
  ZipFile zipFile = initializeZipFileWithCharset(charset);

  for (int i = 0; i < FILES_TO_ADD.size(); i++) {
    if (i == 0) {
      zipParameters.setFileComment(fileCommentPrefix + i);
    } else {
      zipParameters.setFileComment(null);
    }
    zipFile.addFile(FILES_TO_ADD.get(i), zipParameters);
  }

  verifyZipFileByExtractingAllFiles(generatedZipFile, outputFolder, FILES_TO_ADD.size());
  verifyFileEntryComment(fileCommentPrefix, charset);
}
 
Example #8
Source File: ZipInputStreamIT.java    From zip4j with Apache License 2.0 6 votes vote down vote up
private File createZipFile(CompressionMethod compressionMethod, boolean encryptFiles,
                           EncryptionMethod encryptionMethod, AesKeyStrength aesKeyStrength, char[] password,
                           AesVersion aesVersion)
    throws IOException {

  File outputFile = temporaryFolder.newFile("output.zip");
  deleteFileIfExists(outputFile);

  ZipFile zipFile = new ZipFile(outputFile, password);

  ZipParameters zipParameters = new ZipParameters();
  zipParameters.setCompressionMethod(compressionMethod);
  zipParameters.setEncryptFiles(encryptFiles);
  zipParameters.setEncryptionMethod(encryptionMethod);
  zipParameters.setAesKeyStrength(aesKeyStrength);
  zipParameters.setAesVersion(aesVersion);

  zipFile.addFiles(AbstractIT.FILES_TO_ADD, zipParameters);

  return outputFile;
}
 
Example #9
Source File: CreateZipFileIT.java    From zip4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddSymlinkWithLinkAndLinkedFile() throws IOException {
  File targetFile = getTestFileFromResources("sample.pdf");
  File symlink = createSymlink(targetFile, temporaryFolder.getRoot());
  ZipFile zipFile = new ZipFile(generatedZipFile);

  ZipParameters zipParameters = new ZipParameters();
  zipParameters.setSymbolicLinkAction(ZipParameters.SymbolicLinkAction.INCLUDE_LINK_AND_LINKED_FILE);

  zipFile.addFile(symlink, zipParameters);

  List<FileHeader> fileHeaders = zipFile.getFileHeaders();
  assertThat(fileHeaders).hasSize(2);
  assertThat(fileHeaders.get(0).getFileName()).isEqualTo(symlink.getName());
  assertThat(fileHeaders.get(1).getFileName()).isEqualTo(targetFile.getName());
  verifyZipFileByExtractingAllFiles(generatedZipFile, null, outputFolder, 2, false);

  verifyGeneratedSymlink(symlink, targetFile);
  File generatedTargetFile = Paths.get(outputFolder.getAbsolutePath(), targetFile.getName()).toFile();
  ZipFileVerifier.verifyFileCrc(targetFile, generatedTargetFile);
}
 
Example #10
Source File: FileHeaderFactory.java    From zip4j with Apache License 2.0 6 votes vote down vote up
private AESExtraDataRecord generateAESExtraDataRecord(ZipParameters parameters) throws ZipException {
  AESExtraDataRecord aesExtraDataRecord = new AESExtraDataRecord();

  if (parameters.getAesVersion() != null) {
    aesExtraDataRecord.setAesVersion(parameters.getAesVersion());
  }

  if (parameters.getAesKeyStrength() == AesKeyStrength.KEY_STRENGTH_128) {
    aesExtraDataRecord.setAesKeyStrength(AesKeyStrength.KEY_STRENGTH_128);
  } else if (parameters.getAesKeyStrength() == AesKeyStrength.KEY_STRENGTH_192) {
    aesExtraDataRecord.setAesKeyStrength(AesKeyStrength.KEY_STRENGTH_192);
  } else if (parameters.getAesKeyStrength() == AesKeyStrength.KEY_STRENGTH_256) {
    aesExtraDataRecord.setAesKeyStrength(AesKeyStrength.KEY_STRENGTH_256);
  } else {
    throw new ZipException("invalid AES key strength");
  }

  aesExtraDataRecord.setCompressionMethod(parameters.getCompressionMethod());
  return aesExtraDataRecord;
}
 
Example #11
Source File: Zip4j.java    From maven-framework-project with MIT License 6 votes vote down vote up
/**
 * 示例1 创建压缩包添加文件到压缩包中(未设置加密)
 */
@Test
public void example1(){
	try {
           
           ZipFile zipFile = new ZipFile("src/main/resources/AddFilesDeflateComp.zip");
            
           ArrayList<File> filesToAdd = new ArrayList<File>();
           filesToAdd.add(new File("src/main/resources/sample.txt"));
           filesToAdd.add(new File("src/main/resources/zip4j.txt"));
           filesToAdd.add(new File("src/main/resources/zip4j-1.3.2.jar"));
            
           ZipParameters parameters = new ZipParameters();
           parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); // set compression method to deflate compression
           parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL); 
           zipFile.addFiles(filesToAdd, parameters);
           
           CompressUtil.printZipInfo("src/main/resources/AddFilesDeflateComp.zip");
           
           
       } catch (ZipException e) {
           e.printStackTrace();
       }
}
 
Example #12
Source File: AddFilesToZipIT.java    From zip4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddStreamToZipWithAesEncryptionV1ForExistingZipAddsSuccessfully() throws IOException {
  File fileToAdd = TestUtils.getTestFileFromResources("가나다.abc");
  ZipParameters zipParameters = createZipParameters(EncryptionMethod.AES, AesKeyStrength.KEY_STRENGTH_256);
  zipParameters.setAesVersion(AesVersion.ONE);
  zipParameters.setFileNameInZip(fileToAdd.getName());
  ZipFile zipFile = new ZipFile(generatedZipFile, PASSWORD);
  zipFile.addFiles(FILES_TO_ADD);
  InputStream inputStream = new FileInputStream(fileToAdd);

  zipFile.addStream(inputStream, zipParameters);

  ZipFileVerifier.verifyZipFileByExtractingAllFiles(generatedZipFile, PASSWORD, outputFolder, 4);
  verifyFileIsOf(generatedZipFile, "가나다.abc", CompressionMethod.DEFLATE, EncryptionMethod.AES,
      AesKeyStrength.KEY_STRENGTH_256, AesVersion.ONE);
}
 
Example #13
Source File: Zip4j.java    From maven-framework-project with MIT License 6 votes vote down vote up
/**
 * 示例2 创建压缩包添加文件到指定目录中进行压缩
 */
@Test
public void example2(){
	try {
           ZipFile zipFile = new ZipFile("src/main/resources/AddFilesDeflateComp.zip");
           ArrayList<File> filesToAdd = new ArrayList<File>();
           filesToAdd.add(new File("src/main/resources/sample.txt"));
           filesToAdd.add(new File("src/main/resources/zip4j.txt"));
           filesToAdd.add(new File("src/main/resources/zip4j-1.3.2.jar"));
            
           ZipParameters parameters = new ZipParameters();
           parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
            
           parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
           parameters.setRootFolderInZip("target/");

           zipFile.addFiles(filesToAdd, parameters);
       } catch (ZipException e) {
           e.printStackTrace();
       } 
}
 
Example #14
Source File: CompressionHandler.java    From butterfly with MIT License 6 votes vote down vote up
void compress(TransformationResult transformationResult) {
    File inputFile = transformationResult.getTransformedApplicationDir().getAbsoluteFile();
    File compressedFile = new File(transformationResult.getTransformedApplicationDir().getAbsolutePath() + ".zip");

    logger.info("Compressing transformed application");

    try {
        ZipFile zipFile = new ZipFile(compressedFile);
        ZipParameters parameters = new ZipParameters();

        parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
        parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);

        zipFile.addFolder(inputFile, parameters);
        FileUtils.deleteDirectory(transformationResult.getTransformedApplicationDir());

        logger.info("Transformed application has been compressed to {}", compressedFile.getAbsoluteFile());
    } catch (Exception e) {
        logger.error("An exception happened when compressing transformed application", e);
    }
}
 
Example #15
Source File: ZipArchive.java    From Mzip-Android with Apache License 2.0 6 votes vote down vote up
public static void zip(String targetPath, String destinationFilePath, String password) {
    try {
        ZipParameters parameters = new ZipParameters();
        parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
        parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);

        if (password.length() > 0) {
            parameters.setEncryptFiles(true);
            parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);
            parameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
            parameters.setPassword(password);
        }

        ZipFile zipFile = new ZipFile(destinationFilePath);

        File targetFile = new File(targetPath);
        if (targetFile.isFile()) {
            zipFile.addFile(targetFile, parameters);
        } else if (targetFile.isDirectory()) {
            zipFile.addFolder(targetFile, parameters);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #16
Source File: GenerateFinalZip.java    From apk-decompiler with GNU General Public License v2.0 6 votes vote down vote up
private void generateZipFile() {
	try {
		File outputFile = new File(this.workFolder.getName() + ".zip");
		if (outputFile.exists()) {
			Logger.info(outputFile.getAbsolutePath() + " already exists. Deleting.");
			outputFile.delete();
		}
		ZipFile output = new net.lingala.zip4j.core.ZipFile(outputFile);
		Logger.info("Generating " + output.getFile().getAbsolutePath());

		ZipParameters params = new ZipParameters();
		params.setIncludeRootFolder(false);
		params.setRootFolderInZip("");
		output.addFolder(this.workFolder.getAbsolutePath() + File.separator + "apktool", params);
		params.setRootFolderInZip("classes");
		output.addFolder(this.workFolder.getAbsolutePath() + File.separator + "classes", params);
	} catch (Throwable t) {
		Logger.error("Unable to generate final zip file.", t);
	}
}
 
Example #17
Source File: ZipFile.java    From AndroidZip with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a zip file and adds the files/folders from the specified folder to the zip file.
 * This method does the same functionality as in addFolder method except that this method
 * can also create split zip files when adding a folder. To create a split zip file, set the 
 * splitArchive parameter to true and specify the splitLength. Split length has to be more than
 * or equal to 65536 bytes. Note that this method throws an exception if the zip file already 
 * exists.
 * @param folderToAdd
 * @param parameters
 * @param splitArchive
 * @param splitLength
 * @throws ZipException
 */
public void createZipFileFromFolder(File folderToAdd, ZipParameters parameters, 
		boolean splitArchive, long splitLength) throws ZipException {
	
	if (folderToAdd == null) {
		throw new ZipException("folderToAdd is null, cannot create zip file from folder");
	}
	
	if (parameters == null) {
		throw new ZipException("input parameters are null, cannot create zip file from folder");
	}
	
	if (Zip4jUtil.checkFileExists(file)) {
		throw new ZipException("zip file: " + file + " already exists. To add files to existing zip file use addFolder method");
	}
	
	createNewZipModel();
	this.zipModel.setSplitArchive(splitArchive);
	if (splitArchive)
		this.zipModel.setSplitLength(splitLength);
	
	addFolder(folderToAdd, parameters, false);
}
 
Example #18
Source File: DesaElementVisitor.java    From proarc with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Archives the list of files to a zip archive
 *
 * @param zipFileName
 * @param fileList
 * @param desaElement
 * @throws MetsExportException
 */
private void zip(String zipFileName, ArrayList<File> fileList, IDesaElement desaElement) throws MetsExportException {
    try {
        File file = new File(zipFileName);
        if (file.exists()) {
            file.delete();
            file = null;
            LOG.log(Level.FINE, "File:" + zipFileName + " exists, so it was deleted");
        }
        ZipFile zipFile = new ZipFile(zipFileName);
        ZipParameters zip4jZipParameters = new ZipParameters();
        zip4jZipParameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
        zip4jZipParameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
        zipFile.addFiles(fileList, zip4jZipParameters);
        LOG.log(Level.FINE, "Zip archive created:" + zipFileName + " for " + desaElement.getElementType());
    } catch (ZipException e) {
        throw new MetsExportException(desaElement.getOriginalPid(), "Unable to create a zip file:" + zipFileName, false, e);
    }

}
 
Example #19
Source File: UserModelService.java    From KOMORAN with Apache License 2.0 6 votes vote down vote up
public File deployUserModel(String modelDir) {
    ModelValidator.CheckValidModelName(modelDir);

    String dirNameToArchive = String.join(File.separator, MODELS_BASEDIR, modelDir);
    String zipNameToArchive = "UserModel" + modelDir + ".zip";

    ZipFile zipFileToDeploy = new ZipFile(zipNameToArchive);
    ZipParameters zipFileParams = new ZipParameters();

    zipFileParams.setReadHiddenFiles(false);
    zipFileParams.setReadHiddenFolders(false);
    zipFileParams.setIncludeRootFolder(false);

    try {
        zipFileToDeploy.addFolder(new File(dirNameToArchive), zipFileParams);
    } catch (ZipException e) {
        throw new ServerErrorException("모델 배포를 위한 압축 파일 생성에 실패했습니다.");
    }

    return zipFileToDeploy.getFile();
}
 
Example #20
Source File: ZipFile.java    From zip4j with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new entry in the zip file and adds the content of the input stream to the
 * zip file. ZipParameters.isSourceExternalStream and ZipParameters.fileNameInZip have to be
 * set before in the input parameters. If the file name ends with / or \, this method treats the
 * content as a directory. Setting the flag ProgressMonitor.setRunInThread to true will have
 * no effect for this method and hence this method cannot be used to add content to zip in
 * thread mode
 *
 * @param inputStream
 * @param parameters
 * @throws ZipException
 */
public void addStream(InputStream inputStream, ZipParameters parameters) throws ZipException {
  if (inputStream == null) {
    throw new ZipException("inputstream is null, cannot add file to zip");
  }

  if (parameters == null) {
    throw new ZipException("zip parameters are null");
  }

  this.setRunInThread(false);

  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 AddStreamToZipTask(zipModel, password, headerWriter, buildAsyncParameters()).execute(
      new AddStreamToZipTaskParameters(inputStream, parameters, charset));
}
 
Example #21
Source File: AddFilesToZipIT.java    From zip4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddFilesToSplitZipThrowsException() throws ZipException {
  ZipFile zipFile = new ZipFile(generatedZipFile);
  zipFile.createSplitZipFile(singletonList(TestUtils.getTestFileFromResources("file_PDF_1MB.pdf")), new ZipParameters(),
      true, InternalZipConstants.MIN_SPLIT_LENGTH);

  expectedException.expect(ZipException.class);
  expectedException.expectMessage("Zip file already exists. " +
      "Zip file format does not allow updating split/spanned files");

  zipFile.addFiles(singletonList(TestUtils.getTestFileFromResources("sample.pdf")));
}
 
Example #22
Source File: ZipVersionUtilsTest.java    From zip4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testDetermineVersionNeededToExtractAES() {
  ZipParameters zipParameters = new ZipParameters();
  zipParameters.setEncryptFiles(true);
  zipParameters.setEncryptionMethod(EncryptionMethod.AES);
  assertThat(ZipVersionUtils.determineVersionNeededToExtract(zipParameters)).isEqualTo(VersionNeededToExtract.AES_ENCRYPTED);
}
 
Example #23
Source File: AddFilesToZipIT.java    From zip4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddStreamToZipThrowsExceptionWhenFileNameIsNull() throws IOException {
  ZipFile zipFile = new ZipFile(generatedZipFile);
  InputStream inputStream = new FileInputStream(TestUtils.getTestFileFromResources("бореиская.txt"));
  ZipParameters zipParameters = new ZipParameters();
  zipParameters.setFileNameInZip(null);

  expectedException.expectMessage("fileNameInZip has to be set in zipParameters when adding stream");
  expectedException.expect(ZipException.class);

  zipFile.addStream(inputStream, zipParameters);
}
 
Example #24
Source File: ExtractZipFileIT.java    From zip4j with Apache License 2.0 5 votes vote down vote up
private void createNestedZip(File innerSourceZipFile, File outerSourceZipFile, EncryptionMethod innerEncryption,
                             EncryptionMethod outerEncryption) throws ZipException {

  ZipFile innerZipFile = new ZipFile(innerSourceZipFile, PASSWORD);
  ZipParameters innerZipParameters = createZipParametersForNestedZip(innerEncryption);
  innerZipFile.addFiles(FILES_TO_ADD, innerZipParameters);

  ZipFile outerZipFile = new ZipFile(outerSourceZipFile, PASSWORD);
  ZipParameters outerZipParameters = createZipParametersForNestedZip(outerEncryption);
  outerZipFile.addFile(innerSourceZipFile, outerZipParameters);
}
 
Example #25
Source File: CreateZipFileIT.java    From zip4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateSplitZipFileNotSplitArchiveWithZipNameAsStringWithAESEncryption128() throws IOException {
  ZipParameters zipParameters = createZipParameters(EncryptionMethod.AES,
      AesKeyStrength.KEY_STRENGTH_128);
  ZipFile zipFile = new ZipFile(generatedZipFile.getPath(), PASSWORD);
  zipFile.createSplitZipFile(FILES_TO_ADD, zipParameters, false, -1);

  ZipFileVerifier.verifyZipFileByExtractingAllFiles(generatedZipFile, PASSWORD, outputFolder, FILES_TO_ADD.size());
  verifyFileHeadersEncrypted(zipFile.getFileHeaders(), EncryptionMethod.AES, AesKeyStrength.KEY_STRENGTH_128,
      CompressionMethod.DEFLATE);
}
 
Example #26
Source File: AddFilesToZipIT.java    From zip4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddFileWithAfterDeflateRemainingBytesTestFile() throws IOException {
  ZipParameters zipParameters = createZipParameters(EncryptionMethod.AES, AesKeyStrength.KEY_STRENGTH_256);
  zipParameters.setAesVersion(AesVersion.TWO);
  ZipFile zipFile = new ZipFile(generatedZipFile, PASSWORD);

  zipFile.addFile(TestUtils.getTestFileFromResources("after_deflate_remaining_bytes.bin"), zipParameters);

  ZipFileVerifier.verifyZipFileByExtractingAllFiles(generatedZipFile, PASSWORD, outputFolder, 1);
  verifyZipFileContainsFiles(generatedZipFile, singletonList("after_deflate_remaining_bytes.bin"),
      CompressionMethod.DEFLATE, EncryptionMethod.AES, AesKeyStrength.KEY_STRENGTH_256);
}
 
Example #27
Source File: CreateZipFileIT.java    From zip4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateSplitZipFileThrowsExceptionWhenSplitSizeLessThanMinimumAllowed() throws ZipException {
  expectedException.expectMessage("split length less than minimum allowed split length of "
      + InternalZipConstants.MIN_SPLIT_LENGTH + " Bytes");
  expectedException.expect(ZipException.class);

  ZipFile zipFile = new ZipFile(generatedZipFile);
  zipFile.createSplitZipFile(FILES_TO_ADD, new ZipParameters(), true, InternalZipConstants.MIN_SPLIT_LENGTH - 1);
}
 
Example #28
Source File: AddFilesToZipIT.java    From zip4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddFileAsStringWithZipParametersStoreAndStandardEncryptionAndCharsetCp949() throws IOException {
  ZipParameters zipParameters = createZipParameters(EncryptionMethod.ZIP_STANDARD, null);
  zipParameters.setCompressionMethod(CompressionMethod.STORE);
  ZipFile zipFile = new ZipFile(generatedZipFile, PASSWORD);

  zipFile.setCharset(CHARSET_CP_949);
  String koreanFileName = "가나다.abc";
  zipFile.addFile(TestUtils.getTestFileFromResources(koreanFileName).getPath(), zipParameters);

  ZipFileVerifier.verifyZipFileByExtractingAllFiles(generatedZipFile, PASSWORD, outputFolder, 1, true, CHARSET_CP_949);
  assertThat(zipFile.getFileHeaders().get(0).getFileName()).isEqualTo(koreanFileName);
  verifyZipVersions(zipFile.getFileHeaders().get(0), zipParameters);
}
 
Example #29
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 #30
Source File: ZipStandardCipherOutputStream.java    From zip4j with Apache License 2.0 5 votes vote down vote up
private long getEncryptionKey(ZipParameters zipParameters) {
  if (zipParameters.isWriteExtendedLocalFileHeader()) {
    long dosTime = Zip4jUtil.javaToDosTime(zipParameters.getLastModifiedFileTime());
    return (dosTime & 0x0000ffff) << 16;
  }

  return zipParameters.getEntryCRC();
}