Search in sources :

Example 6 with ZipException

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);
    }
}
Also used : ZipArchiveEntry(org.apache.commons.compress.archivers.zip.ZipArchiveEntry) java.util(java.util) IOCase(org.apache.commons.io.IOCase) java.util.zip(java.util.zip) ByteArrayOutputStream(com.codeforces.commons.io.ByteArrayOutputStream) Charset(java.nio.charset.Charset) StringUtil(com.codeforces.commons.text.StringUtil) NameFileFilter(org.apache.commons.io.filefilter.NameFileFilter) Math.max(com.codeforces.commons.math.Math.max) Nonnull(javax.annotation.Nonnull) FileHeader(net.lingala.zip4j.model.FileHeader) Nullable(javax.annotation.Nullable) ZipFile(net.lingala.zip4j.core.ZipFile) ZipParameters(net.lingala.zip4j.model.ZipParameters) ZipArchiveInputStream(org.apache.commons.compress.archivers.zip.ZipArchiveInputStream) com.codeforces.commons.io(com.codeforces.commons.io) StandardCharsets(java.nio.charset.StandardCharsets) ZipException(net.lingala.zip4j.exception.ZipException) IOUtils(org.apache.commons.io.IOUtils) Contract(org.jetbrains.annotations.Contract) FsSyncException(de.schlichtherle.truezip.fs.FsSyncException) java.io(java.io) de.schlichtherle.truezip.file(de.schlichtherle.truezip.file) MutableBoolean(org.apache.commons.lang3.mutable.MutableBoolean) Patterns(com.codeforces.commons.text.Patterns) MutableBoolean(org.apache.commons.lang3.mutable.MutableBoolean) Charset(java.nio.charset.Charset) ZipException(net.lingala.zip4j.exception.ZipException) ByteArrayOutputStream(com.codeforces.commons.io.ByteArrayOutputStream) ZipFile(net.lingala.zip4j.core.ZipFile) FileHeader(net.lingala.zip4j.model.FileHeader) Nonnull(javax.annotation.Nonnull)

Example 7 with ZipException

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);
    }
}
Also used : ZipFile(net.lingala.zip4j.core.ZipFile) ZipException(net.lingala.zip4j.exception.ZipException) FileHeader(net.lingala.zip4j.model.FileHeader) ZipFile(net.lingala.zip4j.core.ZipFile)

Example 8 with ZipException

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);
}
Also used : ZipFile(net.lingala.zip4j.core.ZipFile) FileWriter(java.io.FileWriter) ZipException(net.lingala.zip4j.exception.ZipException) IOException(java.io.IOException) World(org.bukkit.World) ZipFile(net.lingala.zip4j.core.ZipFile) File(java.io.File)

Example 9 with ZipException

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())));
        }
    }
}
Also used : ZipFile(net.lingala.zip4j.core.ZipFile) ConstraintViolation(org.molgenis.data.validation.ConstraintViolation) ZipException(net.lingala.zip4j.exception.ZipException) ZipFile(net.lingala.zip4j.core.ZipFile) File(java.io.File) MolgenisValidationException(org.molgenis.data.validation.MolgenisValidationException) FileMeta(org.molgenis.data.file.model.FileMeta)

Example 10 with ZipException

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()));
        }
    }
}
Also used : ZipFile(net.lingala.zip4j.core.ZipFile) ZipException(net.lingala.zip4j.exception.ZipException) ZipFile(net.lingala.zip4j.core.ZipFile) File(java.io.File) FileHeader(net.lingala.zip4j.model.FileHeader) FileMeta(org.molgenis.data.file.model.FileMeta)

Aggregations

ZipException (net.lingala.zip4j.exception.ZipException)23 ZipFile (net.lingala.zip4j.core.ZipFile)15 File (java.io.File)13 ZipParameters (net.lingala.zip4j.model.ZipParameters)9 FileHeader (net.lingala.zip4j.model.FileHeader)8 IOException (java.io.IOException)5 ArrayList (java.util.ArrayList)5 ZipFile (net.lingala.zip4j.ZipFile)3 WorldException (com.voxelgameslib.voxelgameslib.exception.WorldException)2 BinaryContent (ddf.catalog.data.BinaryContent)2 FileOutputStream (java.io.FileOutputStream)2 OutputStream (java.io.OutputStream)2 RandomAccessFile (java.io.RandomAccessFile)2 ZipFile (java.util.zip.ZipFile)2 HeaderReader (net.lingala.zip4j.core.HeaderReader)2 LocalFileHeader (net.lingala.zip4j.model.LocalFileHeader)2 ZipModel (net.lingala.zip4j.model.ZipModel)2 UnzipEngine (net.lingala.zip4j.unzip.UnzipEngine)2 FileMeta (org.molgenis.data.file.model.FileMeta)2 Content (v7db.files.spi.Content)2