net.lingala.zip4j.model.FileHeader Java Examples

The following examples show how to use net.lingala.zip4j.model.FileHeader. 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: HeaderUtilTest.java    From zip4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetFileHeadersUnderDirectoryReturnsFileHeadersUnderDirectory() {
  List<FileHeader> allFileHeaders = generateFileHeaderWithFileNames("some_name/header", 5);
  allFileHeaders.add(generateFileHeader("some_name/"));
  allFileHeaders.add(generateFileHeader("some_other_name.txt"));
  FileHeader rootFileHeader = generateFileHeader("some_name/");
  rootFileHeader.setDirectory(true);

  List<FileHeader> filHeadersUnderDirectory = HeaderUtil.getFileHeadersUnderDirectory(allFileHeaders, rootFileHeader);
  assertThat(filHeadersUnderDirectory).hasSize(6);
  for (FileHeader fileHeader : filHeadersUnderDirectory) {
    assertThat(fileHeader)
        .withFailMessage("file header with name some_other_name.txt should not exist")
        .isNotEqualTo("some_other_name.txt");
  }
}
 
Example #2
Source File: HeaderWriter.java    From AndroidZip with Apache License 2.0 6 votes vote down vote up
/**
 * Writes central directory header data to an array list
 * @param zipModel
 * @param outputStream
 * @param headerBytesList
 * @return size of central directory
 * @throws ZipException
 */
private int writeCentralDirectory(ZipModel zipModel, 
		OutputStream outputStream, List headerBytesList) throws ZipException {
	if (zipModel == null || outputStream == null) {
		throw new ZipException("input parameters is null, cannot write central directory");
	}
	
	if (zipModel.getCentralDirectory() == null || 
			zipModel.getCentralDirectory().getFileHeaders() == null || 
			zipModel.getCentralDirectory().getFileHeaders().size() <= 0) {
		return 0;
	}
	
	int sizeOfCentralDir = 0;
	for (int i = 0; i < zipModel.getCentralDirectory().getFileHeaders().size(); i++) {
		FileHeader fileHeader = (FileHeader)zipModel.getCentralDirectory().getFileHeaders().get(i);
		int sizeOfFileHeader = writeFileHeader(zipModel, fileHeader, outputStream, headerBytesList);
		sizeOfCentralDir += sizeOfFileHeader;
	}
	return sizeOfCentralDir;
}
 
Example #3
Source File: Zip4jUtil.java    From AndroidZip with Apache License 2.0 6 votes vote down vote up
public static FileHeader getFileHeader(ZipModel zipModel, String fileName) throws ZipException {
	if (zipModel == null) {
		throw new ZipException("zip model is null, cannot determine file header for fileName: " + fileName);
	}
	
	if (!isStringNotNullAndNotEmpty(fileName)) {
		throw new ZipException("file name is null, cannot determine file header for fileName: " + fileName);
	}
	
	FileHeader fileHeader = null;
	fileHeader = getFileHeaderWithExactMatch(zipModel, fileName);
	
	if (fileHeader == null) {
		fileName = fileName.replaceAll("\\\\", "/");
		fileHeader = getFileHeaderWithExactMatch(zipModel, fileName);
		
		if (fileHeader == null) {
			fileName = fileName.replaceAll("/", "\\\\");
			fileHeader = getFileHeaderWithExactMatch(zipModel, fileName);
		}
	}
	
	return fileHeader;
}
 
Example #4
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 #5
Source File: UnzipUtilIT.java    From zip4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testApplyFileFileAttributesSetsLastModifiedTimeWithoutNio() {
  byte[] externalFileAttributes = new byte[] {12, 34, 0, 0};
  long currentTime = System.currentTimeMillis();
  FileHeader fileHeader = new FileHeader();
  fileHeader.setExternalFileAttributes(externalFileAttributes);
  fileHeader.setLastModifiedTime(currentTime);

  File file = mock(File.class);
  Path path = mock(Path.class);
  when(file.toPath()).thenThrow(new NoSuchMethodError("No method"));

  PowerMockito.mockStatic(FileUtils.class);

  UnzipUtil.applyFileAttributes(fileHeader, file);

  verifyStatic(FileUtils.class, never());
  FileUtils.setFileLastModifiedTime(path, currentTime);

  verifyStatic(FileUtils.class, never());
  FileUtils.setFileAttributes(path, externalFileAttributes);

  verifyStatic(FileUtils.class);
  FileUtils.setFileLastModifiedTimeWithoutNio(file, currentTime);
}
 
Example #6
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 #7
Source File: BuildTool.java    From thorntail with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private void expandArtifact(File artifactFile) throws IOException {
    try {
        ZipFile zipFile = new ZipFile(artifactFile);
        for (FileHeader each : (List<FileHeader>) zipFile.getFileHeaders()) {
            String fileName = each.getFileName();
            if (fileName.startsWith("META-INF") && !fileName.startsWith("META-INF/versions")) {
                continue;
            }
            if (each.isDirectory()) {
                continue;
            }
            this.archive.add(new ZipFileHeaderAsset(zipFile, each), fileName);
        }
    } catch (ZipException e) {
        throw new IOException(e);
    }
}
 
Example #8
Source File: BlamerTest.java    From apkfile with Apache License 2.0 6 votes vote down vote up
private static void old(String path) throws Exception {
    ApkFile apkFile = new ApkFileFactory()
            .skipParsingResources()
            .skipParsingAndroidManifest()
            .skipParsingResources()
            .skipParsingDexFiles()
            .build(path);

    FileHeader resourcesEntry = apkFile.getEntry("resources.arsc");
    InputStream resourcesStream = apkFile.getInputStream(resourcesEntry);

    ResourceFile arscRF = ResourceFile.fromInputStream(resourcesStream);
    ResourceTableChunk resourceTable = (ResourceTableChunk) arscRF.getChunks().get(0);

    FileHeader manifestEntry = apkFile.getEntry("AndroidManifest.xml");
    InputStream manifestStream = apkFile.getInputStream(manifestEntry);
    //        manifestRF = ResourceFile.fromInputStream(manifestStream);
    byte[] buf = ByteStreams.toByteArray(manifestStream);
    ByteBuffer buffer = ByteBuffer.wrap(buf).order(ByteOrder.LITTLE_ENDIAN);
    Chunk manifestChunk = Chunk.newInstance(buffer, resourceTable);

    System.out.println(manifestChunk);
}
 
Example #9
Source File: ZipFileUtil.java    From java-trader with Apache License 2.0 6 votes vote down vote up
public static void archiveAddAll(File zip, final List<String> pathInZips, final List<byte[]> datas)
        throws IOException
{
    net.lingala.zip4j.ZipFile zipFile = new net.lingala.zip4j.ZipFile(zip);

    List<FileHeader> items = new ArrayList<>( zipFile.getFileHeaders() );

    for(FileHeader zipItem : items) {
        if ( pathInZips.contains(zipItem.getFileName()) ) {
            zipFile.removeFile(zipItem);
        }
    }

    for(int i=0;i<pathInZips.size();i++) {
        net.lingala.zip4j.model.ZipParameters zipParams = new net.lingala.zip4j.model.ZipParameters();
        byte[] data = datas.get(i);
        zipParams.setCompressionLevel(CompressionLevel.MAXIMUM);
        zipParams.setFileNameInZip(pathInZips.get(i));
        zipFile.addStream(new ByteArrayInputStream(data), zipParams);
    }
}
 
Example #10
Source File: RenameFilesTask.java    From zip4j with Apache License 2.0 6 votes vote down vote up
private Map<String, String> filterNonExistingEntriesAndAddSeparatorIfNeeded(Map<String, String> inputFileNamesMap) throws ZipException {
  Map<String, String> fileNamesMapToBeChanged = new HashMap<>();
  for (Map.Entry<String, String> allNamesToBeChanged : inputFileNamesMap.entrySet()) {
    if (!Zip4jUtil.isStringNotNullAndNotEmpty(allNamesToBeChanged.getKey())) {
      continue;
    }

    FileHeader fileHeaderToBeChanged = HeaderUtil.getFileHeader(zipModel, allNamesToBeChanged.getKey());
    if (fileHeaderToBeChanged != null) {
      if (fileHeaderToBeChanged.isDirectory() && !allNamesToBeChanged.getValue().endsWith(InternalZipConstants.ZIP_FILE_SEPARATOR)) {
        fileNamesMapToBeChanged.put(allNamesToBeChanged.getKey(), allNamesToBeChanged.getValue() + InternalZipConstants.ZIP_FILE_SEPARATOR);
      } else {
        fileNamesMapToBeChanged.put(allNamesToBeChanged.getKey(), allNamesToBeChanged.getValue());
      }
    }
  }
  return fileNamesMapToBeChanged;
}
 
Example #11
Source File: ZipUtil.java    From MonitorClient with Apache License 2.0 6 votes vote down vote up
/**
 * 查看压缩包的文件列表
 * @param inPath
 * @param password
 * @return
 */
public static boolean getNameFromZip(String inPath,String password) {
	try {
		ZipFile zipFile = new ZipFile(inPath);
		if (zipFile.isEncrypted()) {  
			zipFile.setPassword(password);  
		}  
		List fileHeaderList = zipFile.getFileHeaders();  
		  
		for (int i = 0; i < fileHeaderList.size(); i++) {  
		    FileHeader fileHeader = (FileHeader)fileHeaderList.get(i); 
		    System.out.println("Name: " + fileHeader.getFileName());  
		    System.out.println("Compressed Size: " + fileHeader.getCompressedSize());  
		    System.out.println("Uncompressed Size: " + fileHeader.getUncompressedSize());  
		    System.out.println("CRC: " + fileHeader.getCrc32());  
		    System.out.println("************************************************************");  
		}  
		return true;
	} catch (ZipException e) {
		e.printStackTrace();
		return false;
	}
}
 
Example #12
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 #13
Source File: HeaderUtilTest.java    From zip4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetIndexOfFileHeaderGetsIndexSuccessfully() throws ZipException {
  String fileNamePrefix = "FILE_NAME_";
  int numberOfEntriesToAdd = 10;
  List<FileHeader> fileHeadersInZipModel = generateFileHeaderWithFileNamesWithEmptyAndNullFileNames(fileNamePrefix, numberOfEntriesToAdd);
  ZipModel zipModel = new ZipModel();
  zipModel.getCentralDirectory().setFileHeaders(fileHeadersInZipModel);

  FileHeader fileHeaderToFind = new FileHeader();
  for (int i = 0; i < numberOfEntriesToAdd; i++) {
    fileHeaderToFind.setFileName(fileNamePrefix + i);
    assertThat(HeaderUtil.getIndexOfFileHeader(zipModel, fileHeaderToFind)).isEqualTo(i);
  }

  fileHeaderToFind.setFileName(fileNamePrefix + numberOfEntriesToAdd);
  assertThat(HeaderUtil.getIndexOfFileHeader(zipModel, fileHeaderToFind)).isEqualTo(-1);
}
 
Example #14
Source File: Unzip.java    From AndroidZip with Apache License 2.0 6 votes vote down vote up
private long calculateTotalWork(ArrayList fileHeaders) throws ZipException {
	
	if (fileHeaders == null) {
		throw new ZipException("fileHeaders is null, cannot calculate total work");
	}
	
	long totalWork = 0;
	
	for (int i = 0; i < fileHeaders.size(); i++) {
		FileHeader fileHeader = (FileHeader)fileHeaders.get(i);
		if (fileHeader.getZip64ExtendedInfo() != null && 
				fileHeader.getZip64ExtendedInfo().getUnCompressedSize() > 0) {
			totalWork += fileHeader.getZip64ExtendedInfo().getCompressedSize();
		} else {
			totalWork += fileHeader.getCompressedSize();
		}
		
	}
	
	return totalWork;
}
 
Example #15
Source File: HeaderUtilTest.java    From zip4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetFileHeaderWithExactMatch() throws ZipException {
  ZipModel zipModel = new ZipModel();
  CentralDirectory centralDirectory = new CentralDirectory();
  centralDirectory.setFileHeaders(Arrays.asList(
      generateFileHeader(null),
      generateFileHeader(""),
      generateFileHeader("SOME_OTHER_NAME"),
      generateFileHeader(FILE_NAME)
  ));
  zipModel.setCentralDirectory(centralDirectory);

  FileHeader fileHeader = HeaderUtil.getFileHeader(zipModel, FILE_NAME);
  assertThat(fileHeader).isNotNull();
  assertThat(fileHeader.getFileName()).isEqualTo(FILE_NAME);
}
 
Example #16
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 extractFileFromZip(String inPath,String storagePath,String outPath ,String password) {
	try {
		ZipFile zipFile = new ZipFile(inPath);
		if (zipFile.isEncrypted()) {  
			zipFile.setPassword(password);  
		}  
		List fileHeaderList = zipFile.getFileHeaders();  
		storagePath = storagePath.replaceAll("\\\\", "/");
		for (int i =0;i<fileHeaderList.size() ;i++) {  
		    FileHeader fileHeader = (FileHeader)fileHeaderList.get(i); 
		    if(fileHeader.getFileName().indexOf(storagePath)==0){
		    	zipFile.extractFile(fileHeader, outPath);
		    	zipFile.removeFile(fileHeader.getFileName());	
		    }
		}  
		return true;
	} catch (ZipException e) {
		e.printStackTrace();
		return false;
	}
}
 
Example #17
Source File: HeaderWriterIT.java    From zip4j with Apache License 2.0 6 votes vote down vote up
private void testFinalizeZipFileWhenExtraDataRecordIsNullOrEmpty(byte[] extraDataRecord) throws IOException {
  ZipModel zipModel = createZipModel(10);
  File headersFile = temporaryFolder.newFile();
  addExtraDataRecordToFirstFileHeader(zipModel, extraDataRecord);

  try(OutputStream outputStream = new FileOutputStream(headersFile)) {
    headerWriter.finalizeZipFile(zipModel, outputStream, InternalZipConstants.CHARSET_UTF_8);
  }

  try(RandomAccessFile randomAccessFile = new RandomAccessFile(headersFile, RandomAccessFileMode.READ.getValue())) {
    ZipModel readZipModel = headerReader.readAllHeaders(randomAccessFile, null);
    verifyZipModel(readZipModel, 10);

    for (int i = 0; i < zipModel.getCentralDirectory().getFileHeaders().size(); i++) {
      FileHeader fileHeader = readZipModel.getCentralDirectory().getFileHeaders().get(i);
      assertThat(fileHeader.getZip64ExtendedInfo()).isNull();
      assertThat(fileHeader.getAesExtraDataRecord()).isNull();
      assertThat(fileHeader.getExtraFieldLength()).isEqualTo(i == 0 ? 4 : 0);
    }
  }
}
 
Example #18
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 #19
Source File: ZipUtil.java    From MonitorClient with Apache License 2.0 6 votes vote down vote up
/**
 * 从zip中删除文件
 * @param inPath
 * @param storagePath
 * @param password
 * @return
 */
public static boolean removeFileInZip(String inPath,String storagePath,String password) {
	try {
		ZipFile zipFile = new ZipFile(inPath);
		if (zipFile.isEncrypted()) {  
			zipFile.setPassword(password);  
		}  
		List fileHeaderList = zipFile.getFileHeaders();  
		storagePath = storagePath.replaceAll("\\\\", "/");
		for (int i =fileHeaderList.size() -1; i>0 ; i--) {  
		    FileHeader fileHeader = (FileHeader)fileHeaderList.get(i); 
		    if(fileHeader.getFileName().indexOf(storagePath)==0){
		    	System.out.println("Name: " + fileHeader.getFileName());  
		    	zipFile.removeFile(fileHeader.getFileName());	
		    }
		}  
		return true;
	} catch (ZipException e) {
		e.printStackTrace();
		return false;
	}
}
 
Example #20
Source File: HeaderWriterIT.java    From zip4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testFinalizeZipFileForZip64FormatForSplitFileWithCountingOutputStream() throws IOException {
  ZipModel zipModel = createZipModel(10, COMPRESSED_SIZE_ZIP64, UNCOMPRESSED_SIZE_ZIP64);
  File headersFile = temporaryFolder.newFile();

  try(CountingOutputStream outputStream = new CountingOutputStream(new SplitOutputStream(headersFile, 65536))) {
    headerWriter.finalizeZipFile(zipModel, outputStream, InternalZipConstants.CHARSET_UTF_8);
  }

  try(RandomAccessFile randomAccessFile = new RandomAccessFile(headersFile, RandomAccessFileMode.READ.getValue())) {
    ZipModel readZipModel = headerReader.readAllHeaders(randomAccessFile, null);
    verifyZipModel(readZipModel, 10, COMPRESSED_SIZE_ZIP64, UNCOMPRESSED_SIZE_ZIP64, true);

    List<FileHeader> fileHeaders = readZipModel.getCentralDirectory().getFileHeaders();
    for (FileHeader fileHeader : fileHeaders) {
      verifyZip64ExtendedInfo(fileHeader.getZip64ExtendedInfo(), COMPRESSED_SIZE_ZIP64, UNCOMPRESSED_SIZE_ZIP64, 0,
          0);
      assertThat(fileHeader.getAesExtraDataRecord()).isNull();
    }
  }
}
 
Example #21
Source File: HeaderVerifier.java    From zip4j with Apache License 2.0 6 votes vote down vote up
private static InputStream positionRandomAccessFileToLocalFileHeaderStart(File generatedZipFile, String fileNameInZip)
    throws IOException{

  ZipFile zipFile = new ZipFile(generatedZipFile);
  FileHeader fileHeader = zipFile.getFileHeader(fileNameInZip);

  if (fileHeader == null) {
    throw new RuntimeException("Cannot find an entry with name: " + fileNameInZip + " in zip file: "
        + generatedZipFile);
  }

  InputStream inputStream = new FileInputStream(generatedZipFile);
  if (inputStream.skip(fileHeader.getOffsetLocalHeader()) != fileHeader.getOffsetLocalHeader()) {
    throw new IOException("Cannot skip " + fileHeader.getOffsetLocalHeader() + " bytes for entry "
        + fileHeader.getFileName());
  }
  return inputStream;
}
 
Example #22
Source File: HeaderUtilTest.java    From zip4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetFileHeadersUnderDirectoryWhenNotDirectoryReturnsEmptyList() {
  List<FileHeader> allFileHeaders = generateFileHeaderWithFileNames("header", 5);
  FileHeader rootFileHeader = generateFileHeader("some_name");
  rootFileHeader.setDirectory(false);

  assertThat(HeaderUtil.getFileHeadersUnderDirectory(allFileHeaders, rootFileHeader)).isEmpty();
}
 
Example #23
Source File: ZipFile.java    From zip4j with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the list of file headers in the zip file. Returns an empty list if the zip file does not exist.
 *
 * @return list of file headers
 * @throws ZipException
 */
public List<FileHeader> getFileHeaders() throws ZipException {
  readZipInfo();
  if (zipModel == null || zipModel.getCentralDirectory() == null) {
    return Collections.emptyList();
  }
  return zipModel.getCentralDirectory().getFileHeaders();
}
 
Example #24
Source File: ZipFile.java    From AndroidZip with Apache License 2.0 5 votes vote down vote up
/**
 * Returns FileHeader if a file header with the given fileHeader 
 * string exists in the zip model: If not returns null
 * @param fileName
 * @return FileHeader
 * @throws ZipException
 */
public FileHeader getFileHeader(String fileName) throws ZipException {
	if (!Zip4jUtil.isStringNotNullAndNotEmpty(fileName)) {
		throw new ZipException("input file name is emtpy or null, cannot get FileHeader");
	}
	
	readZipInfo();
	if (zipModel == null || zipModel.getCentralDirectory() == null) {
		return null;
	}
	
	return Zip4jUtil.getFileHeader(zipModel, fileName);
}
 
Example #25
Source File: HeaderReader.java    From zip4j with Apache License 2.0 5 votes vote down vote up
private void readAesExtraDataRecord(FileHeader fileHeader, RawIO rawIO) throws ZipException {
  if (fileHeader.getExtraDataRecords() == null || fileHeader.getExtraDataRecords().size() <= 0) {
    return;
  }

  AESExtraDataRecord aesExtraDataRecord = readAesExtraDataRecord(fileHeader.getExtraDataRecords(), rawIO);
  if (aesExtraDataRecord != null) {
    fileHeader.setAesExtraDataRecord(aesExtraDataRecord);
    fileHeader.setEncryptionMethod(EncryptionMethod.AES);
  }
}
 
Example #26
Source File: HeaderReader.java    From zip4j with Apache License 2.0 5 votes vote down vote up
private void readZip64ExtendedInfo(FileHeader fileHeader, RawIO rawIO) throws ZipException {
  if (fileHeader.getExtraDataRecords() == null || fileHeader.getExtraDataRecords().size() <= 0) {
    return;
  }

  Zip64ExtendedInfo zip64ExtendedInfo = readZip64ExtendedInfo(fileHeader.getExtraDataRecords(), rawIO,
      fileHeader.getUncompressedSize(), fileHeader.getCompressedSize(), fileHeader.getOffsetLocalHeader(),
      fileHeader.getDiskNumberStart());

  if (zip64ExtendedInfo == null) {
    return;
  }

  fileHeader.setZip64ExtendedInfo(zip64ExtendedInfo);

  if (zip64ExtendedInfo.getUncompressedSize() != -1) {
    fileHeader.setUncompressedSize(zip64ExtendedInfo.getUncompressedSize());
  }

  if (zip64ExtendedInfo.getCompressedSize() != -1) {
    fileHeader.setCompressedSize(zip64ExtendedInfo.getCompressedSize());
  }

  if (zip64ExtendedInfo.getOffsetLocalHeader() != -1) {
    fileHeader.setOffsetLocalHeader(zip64ExtendedInfo.getOffsetLocalHeader());
  }

  if (zip64ExtendedInfo.getDiskNumberStart() != -1) {
    fileHeader.setDiskNumberStart(zip64ExtendedInfo.getDiskNumberStart());
  }
}
 
Example #27
Source File: HeaderUtilTest.java    From zip4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetFileHeaderWithUnixFileSeparator() throws ZipException {
  ZipModel zipModel = new ZipModel();
  CentralDirectory centralDirectory = new CentralDirectory();
  centralDirectory.setFileHeaders(Arrays.asList(
      generateFileHeader(FILE_NAME),
      generateFileHeader("SOME_OTHER_NAME/")
  ));
  zipModel.setCentralDirectory(centralDirectory);

  FileHeader fileHeader = HeaderUtil.getFileHeader(zipModel, "SOME_OTHER_NAME/");
  assertThat(fileHeader).isNotNull();
  assertThat(fileHeader.getFileName()).isEqualTo("SOME_OTHER_NAME/");
}
 
Example #28
Source File: MiscZipFileIT.java    From zip4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetFileHeadersReturnsAllHeaders() throws ZipException {
  ZipFile zipFile = new ZipFile(generatedZipFile);
  zipFile.addFiles(FILES_TO_ADD);

  List<FileHeader> fileHeaders = zipFile.getFileHeaders();

  assertThat(fileHeaders).isNotNull();
  assertThat(fileHeaders).hasSize(FILES_TO_ADD.size());
  List<String> fileNames = FILES_TO_ADD.stream().map(File::getName).collect(Collectors.toList());
  verifyFileHeadersContainsFiles(fileHeaders, fileNames);
}
 
Example #29
Source File: FileHeaderFactoryTest.java    From zip4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testGenerateFileHeaderWithAesEncryptionVersionV1() throws ZipException {
  ZipParameters zipParameters = generateZipParameters();
  zipParameters.setEncryptFiles(true);
  zipParameters.setEncryptionMethod(EncryptionMethod.AES);
  zipParameters.setAesKeyStrength(AesKeyStrength.KEY_STRENGTH_256);
  zipParameters.setAesVersion(AesVersion.ONE);

  FileHeader fileHeader = fileHeaderFactory.generateFileHeader(zipParameters, false, 0, InternalZipConstants.CHARSET_UTF_8, rawIO);
  verifyFileHeader(fileHeader, zipParameters, false, 0, 51, true);
  verifyAesExtraDataRecord(fileHeader.getAesExtraDataRecord(), AesKeyStrength.KEY_STRENGTH_256,
      CompressionMethod.DEFLATE, AesVersion.ONE);
}
 
Example #30
Source File: ZipUtil.java    From document-management-software with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Read the entry inside the file zip resource.
 * 
 * @param zip File to read inside it
 * @param entry The entry to be read
 * @return The stream of the entry
 */
public InputStream getEntryStream(File zip, String entry) {
	if (entry.startsWith("/"))
		entry = entry.substring(1);

	try {
		ZipFile zipFile = new ZipFile(zip);
		setCharset(zipFile);
		FileHeader header = zipFile.getFileHeader(entry);
		return zipFile.getInputStream(header);
	} catch (Throwable e) {
		logError(e.getMessage());
		return null;
	}
}