use of net.lingala.zip4j.exception.ZipException in project codeforces-commons by Codeforces.
the class ZipUtil method formatZipArchiveContentForView.
/**
* Formats content of the ZIP-archive for view and returns result as UTF-8 bytes. The {@code truncated} flag
* indicates that the length of returned view was restricted by {@code maxLength} parameter.
*
* @param zipFile ZIP-archive to format
* @param maxLength maximal allowed length of result
* @param maxEntryLineCount maximal allowed number of content lines to display for a single ZIP-archive entry
* @param maxEntryLineLength maximal allowed length of ZIP-archive entry content line
* @param entryListHeaderPattern pattern of entry list header; parameters: {@code fileName}, {@code filePath}, {@code entryCount}
* @param entryListItemPattern pattern of entry list item; parameters: {@code entryName}, {@code entrySize}, {@code entryIndex} (1-based)
* @param entryListItemSeparatorPattern pattern of entry list separator
* @param entryListCloserPattern pattern of entry list closer; parameters: {@code fileName}, {@code filePath}
* @param entryContentHeaderPattern pattern of entry content header; parameters: {@code entryName}, {@code entrySize}
* @param entryContentLinePattern pattern of entry content line; parameters: {@code entryLine}
* @param entryContentLineSeparatorPattern pattern of entry content separator
* @param entryContentCloserPattern pattern of entry content closer; parameters: {@code entryName}
* @param binaryEntryContentPlaceholderPattern pattern of binary entry content placeholder; parameters: {@code entrySize}
* @param emptyZipFilePlaceholderPattern pattern of empty (no entries) ZIP-file placeholder; parameters: {@code fileName}, {@code filePath}
* @return formatted view of ZIP-archive
* @throws IOException if {@code zipFile} is not a correct ZIP-archive or any other I/O-error has been occured
* @see String#format(String, Object...)
*/
@SuppressWarnings("OverlyLongMethod")
@Nonnull
public static FileUtil.FirstBytes formatZipArchiveContentForView(File zipFile, int maxLength, int maxEntryLineCount, int maxEntryLineLength, @Nullable String entryListHeaderPattern, @Nullable String entryListItemPattern, @Nullable String entryListItemSeparatorPattern, @Nullable String entryListCloserPattern, @Nullable String entryContentHeaderPattern, @Nullable String entryContentLinePattern, @Nullable String entryContentLineSeparatorPattern, @Nullable String entryContentCloserPattern, @Nullable String binaryEntryContentPlaceholderPattern, @Nullable String emptyZipFilePlaceholderPattern) throws IOException {
entryListHeaderPattern = StringUtil.nullToDefault(entryListHeaderPattern, "ZIP-file entries {\n");
entryListItemPattern = StringUtil.nullToDefault(entryListItemPattern, " %3$03d. %1$s (%2$d B)");
entryListItemSeparatorPattern = StringUtil.nullToDefault(entryListItemSeparatorPattern, "\n");
entryListCloserPattern = StringUtil.nullToDefault(entryListCloserPattern, "\n}\n\n");
entryContentHeaderPattern = StringUtil.nullToDefault(entryContentHeaderPattern, "Entry %1$s (%2$d B) {\n");
entryContentLinePattern = StringUtil.nullToDefault(entryContentLinePattern, " %1$s");
entryContentLineSeparatorPattern = StringUtil.nullToDefault(entryContentLineSeparatorPattern, "\n");
entryContentCloserPattern = StringUtil.nullToDefault(entryContentCloserPattern, "\n} // %1$s\n\n");
binaryEntryContentPlaceholderPattern = StringUtil.nullToDefault(binaryEntryContentPlaceholderPattern, " *** BINARY DATA (%1$d B) ***");
emptyZipFilePlaceholderPattern = StringUtil.nullToDefault(emptyZipFilePlaceholderPattern, "Empty ZIP-file.");
try {
Charset charset = StandardCharsets.UTF_8;
ZipFile internalZipFile = new ZipFile(zipFile);
List<?> fileHeaders = internalZipFile.getFileHeaders();
int headerCount = fileHeaders.size();
if (headerCount <= 0) {
return formatEmptyZipFilePlaceholder(zipFile, maxLength, emptyZipFilePlaceholderPattern, charset);
}
MutableBoolean truncated = new MutableBoolean(Boolean.FALSE);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
CountingOutputStream countingOutputStream = new CountingOutputStream(byteArrayOutputStream);
byte[] entryListHeaderBytes = String.format(entryListHeaderPattern, zipFile.getName(), zipFile.getPath(), headerCount).getBytes(charset);
if (!writeBytesForView(countingOutputStream, entryListHeaderBytes, maxLength, truncated)) {
throw new IllegalArgumentException(String.format("Argument 'maxLength' (%d) is less than the length of entry list header '%s' (%d bytes).", maxLength, new String(entryListHeaderBytes, charset), entryListHeaderBytes.length));
}
fileHeaders.sort(Comparator.comparing(header -> ((FileHeader) header).getFileName()));
for (int headerIndex = 0; headerIndex < headerCount; ++headerIndex) {
FileHeader header = (FileHeader) fileHeaders.get(headerIndex);
String fileName = header.getFileName();
String entryListItemAppendix = headerIndex == headerCount - 1 ? String.format(entryListCloserPattern, zipFile.getName(), zipFile.getPath()) : entryListItemSeparatorPattern;
byte[] entryListItemBytes = (String.format(entryListItemPattern, fileName, header.getUncompressedSize(), headerIndex + 1) + entryListItemAppendix).getBytes(charset);
if (!writeBytesForView(countingOutputStream, entryListItemBytes, maxLength, truncated)) {
break;
}
}
for (int headerIndex = 0; headerIndex < headerCount; ++headerIndex) {
FileHeader header = (FileHeader) fileHeaders.get(headerIndex);
if (header.isDirectory()) {
continue;
}
formatAndAppendEntryContent(countingOutputStream, maxLength, truncated, charset, internalZipFile, header, maxEntryLineCount, maxEntryLineLength, entryContentHeaderPattern, entryContentLinePattern, entryContentLineSeparatorPattern, entryContentCloserPattern, binaryEntryContentPlaceholderPattern);
if (truncated.booleanValue()) {
break;
}
}
return new FileUtil.FirstBytes(truncated.booleanValue(), byteArrayOutputStream.toByteArray());
} catch (ZipException e) {
throw new IOException("Can't format ZIP-file for view.", e);
}
}
use of net.lingala.zip4j.exception.ZipException in project codeforces-commons by Codeforces.
the class ZipUtil method unzip.
public static void unzip(File zipArchive, File destinationDirectory, @Nullable FileFilter skipFilter) throws IOException {
try {
FileUtil.ensureDirectoryExists(destinationDirectory);
ZipFile zipFile = new ZipFile(zipArchive);
int count = 0;
for (Object fileHeader : zipFile.getFileHeaders()) {
if (count >= MAX_ZIP_ENTRY_COUNT) {
break;
}
FileHeader entry = (FileHeader) fileHeader;
File file = new File(destinationDirectory, entry.getFileName());
if (skipFilter != null && skipFilter.accept(file)) {
continue;
}
if (entry.isDirectory()) {
FileUtil.ensureDirectoryExists(file);
} else {
long maxSize = max(entry.getUncompressedSize(), entry.getCompressedSize());
if (maxSize <= MAX_ZIP_ENTRY_SIZE) {
FileUtil.ensureDirectoryExists(file.getParentFile());
zipFile.extractFile(entry, destinationDirectory.getAbsolutePath());
} else {
throw new IOException(String.format("Entry '%s' (%s) is larger than %s.", entry.getFileName(), FileUtil.formatSize(maxSize), FileUtil.formatSize(MAX_ZIP_ENTRY_SIZE)));
}
}
++count;
}
} catch (ZipException e) {
throw new IOException("Can't extract ZIP-file to directory.", e);
}
}
use of net.lingala.zip4j.exception.ZipException in project VoxelGamesLibv2 by VoxelGamesLib.
the class WorldHandler method finishWorldEditing.
public void finishWorldEditing(@Nonnull User editor, @Nonnull Map map) {
World world = Bukkit.getWorld(map.getLoadedName(editor.getUuid()));
world.setSpawnLocation((int) map.getCenter().getX(), (int) map.getCenter().getY(), (int) map.getCenter().getZ());
world.setAutoSave(true);
world.save();
NMSUtil.flushSaveQueue(world);
mapScanner.scan(map, editor.getUuid());
File worldFolder = new File(getWorldContainer(), map.getWorldName());
try {
FileWriter fileWriter = new FileWriter(new File(worldFolder, "config.json"));
gson.toJson(map, fileWriter);
fileWriter.close();
} catch (IOException e) {
Lang.msg(editor, LangKey.WORLD_CREATOR_SAVE_CONFIG_ERROR, e.getMessage(), e.getClass().getName());
log.log(Level.WARNING, "Error while saving the world config", e);
return;
}
ZipFile zip;
try {
zip = ZipUtil.createZip(worldFolder, map.getInfo().getName());
} catch (ZipException e) {
Lang.msg(editor, LangKey.WORLD_CREATOR_SAVE_ZIP_ERROR, e.getMessage(), e.getClass().getName());
log.log(Level.WARNING, "Error while creating the zip", e);
return;
}
try {
File to = new File(getWorldsFolder(), zip.getFile().getName());
if (to.exists()) {
if (!to.delete()) {
log.warning("Could not delete " + to.getName());
}
}
Files.move(zip.getFile(), to);
} catch (IOException e) {
e.printStackTrace();
}
if (!config.maps.contains(map.getInfo())) {
config.maps.add(map.getInfo());
saveConfig();
}
getWorldRepository().commitRepo();
Lang.msg(editor, LangKey.WORLD_CREATOR_DONE);
}
use of net.lingala.zip4j.exception.ZipException in project molgenis by molgenis.
the class AppRepositoryDecorator method validateResourceZip.
private void validateResourceZip(App app) {
FileMeta appZipMeta = app.getSourceFiles();
if (appZipMeta != null) {
File fileStoreFile = fileStore.getFile(appZipMeta.getId());
if (fileStoreFile == null) {
LOG.error("Resource zip '{}' for app '{}' missing in file store", appZipMeta.getId(), app.getName());
throw new RuntimeException("An error occurred trying to create or update app");
}
ZipFile zipFile;
try {
zipFile = new ZipFile(fileStoreFile);
} catch (ZipException e) {
LOG.error("Error creating zip file object", e);
throw new RuntimeException("An error occurred trying to create or update app");
}
if (!zipFile.isValidZipFile()) {
throw new MolgenisValidationException(new ConstraintViolation(String.format("'%s' is not a valid zip file.", appZipMeta.getFilename())));
}
}
}
use of net.lingala.zip4j.exception.ZipException in project molgenis by molgenis.
the class AppRepositoryDecorator method activateApp.
private void activateApp(App app) {
FileMeta appSourceArchive = app.getSourceFiles();
if (appSourceArchive != null) {
File fileStoreFile = fileStore.getFile(appSourceArchive.getId());
if (fileStoreFile == null) {
LOG.error("Source archive '{}' for app '{}' missing in file store", appSourceArchive.getId(), app.getName());
throw new RuntimeException("An error occurred trying to activate app");
}
try {
ZipFile zipFile = new ZipFile(fileStoreFile);
if (!app.getUseFreemarkerTemplate()) {
FileHeader fileHeader = zipFile.getFileHeader("index.html");
if (fileHeader == null) {
LOG.error("Missing index.html in {} while option Use freemarker template as index.html was set 'No'", app.getName());
throw new RuntimeException(format("Missing index.html in %s while option 'Use freemarker template as index.html' was set 'No'", app.getName()));
}
}
// noinspection StringConcatenationMissingWhitespace
zipFile.extractAll(fileStore.getStorageDir() + separatorChar + FILE_STORE_PLUGIN_APPS_PATH + separatorChar + app.getId() + separatorChar);
} catch (ZipException e) {
LOG.error("", e);
throw new RuntimeException(format("An error occurred activating app '%s'", app.getName()));
}
}
}
Aggregations