Search in sources :

Example 71 with ZipException

use of java.util.zip.ZipException in project ceylon-compiler by ceylon.

the class ZipFileIndex method getHeader.

// ----------------------------------------------------------------------------
// Zip utilities
// ----------------------------------------------------------------------------
private byte[] getHeader(Entry entry) throws IOException {
    zipRandomFile.seek(entry.offset);
    byte[] header = new byte[30];
    zipRandomFile.readFully(header);
    if (get4ByteLittleEndian(header, 0) != 0x04034b50)
        throw new ZipException("corrupted zip file");
    if ((get2ByteLittleEndian(header, 6) & 1) != 0)
        // offset 6 in the header of the ZipFileEntry
        throw new ZipException("encrypted zip file");
    return header;
}
Also used : ZipException(java.util.zip.ZipException)

Example 72 with ZipException

use of java.util.zip.ZipException in project ceylon-compiler by ceylon.

the class ZipFileIndex method readBytes.

private byte[] readBytes(Entry entry) throws IOException {
    byte[] header = getHeader(entry);
    int csize = entry.compressedSize;
    byte[] cbuf = new byte[csize];
    zipRandomFile.skipBytes(get2ByteLittleEndian(header, 26) + get2ByteLittleEndian(header, 28));
    zipRandomFile.readFully(cbuf, 0, csize);
    // is this compressed - offset 8 in the ZipEntry header
    if (get2ByteLittleEndian(header, 8) == 0)
        return cbuf;
    int size = entry.size;
    byte[] buf = new byte[size];
    if (inflate(cbuf, buf) != size)
        throw new ZipException("corrupted zip file");
    return buf;
}
Also used : ZipException(java.util.zip.ZipException)

Example 73 with ZipException

use of java.util.zip.ZipException in project gerrit by GerritCodeReview.

the class InstallPlugin method apply.

@Override
public Response<PluginInfo> apply(TopLevelResource resource, InstallPluginInput input) throws RestApiException, IOException {
    loader.checkRemoteAdminEnabled();
    try {
        try (InputStream in = openStream(input)) {
            String pluginName = loader.installPluginFromStream(name, in);
            PluginInfo info = ListPlugins.toPluginInfo(loader.get(pluginName));
            return created ? Response.created(info) : Response.ok(info);
        }
    } catch (PluginInstallException e) {
        StringWriter buf = new StringWriter();
        buf.write(String.format("cannot install %s", name));
        if (e.getCause() instanceof ZipException) {
            buf.write(": ");
            buf.write(e.getCause().getMessage());
        } else {
            buf.write(":\n");
            PrintWriter pw = new PrintWriter(buf);
            e.printStackTrace(pw);
            pw.flush();
        }
        throw new BadRequestException(buf.toString());
    }
}
Also used : StringWriter(java.io.StringWriter) InputStream(java.io.InputStream) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) PluginInfo(com.google.gerrit.extensions.common.PluginInfo) ZipException(java.util.zip.ZipException) IdString(com.google.gerrit.extensions.restapi.IdString) PrintWriter(java.io.PrintWriter)

Example 74 with ZipException

use of java.util.zip.ZipException in project Openfire by igniterealtime.

the class PluginManager method installPlugin.

/**
 * Installs or updates an existing plugin.
 *
 * @param in the input stream that contains the new plugin definition.
 * @param pluginFilename the filename of the plugin to create or update.
 * @return true if the plugin was successfully installed or updated.
 */
public boolean installPlugin(InputStream in, String pluginFilename) {
    if (pluginFilename == null || pluginFilename.isEmpty()) {
        Log.error("Error installing plugin: pluginFilename was null or empty.");
        return false;
    }
    if (in == null) {
        Log.error("Error installing plugin '{}': Input stream was null.", pluginFilename);
        return false;
    }
    try (final BufferedInputStream bin = new BufferedInputStream(in)) {
        // Check magic bytes to ensure this is a JAR file.
        final boolean magicNumberCheckEnabled = JiveGlobals.getBooleanProperty("plugins.upload.magic-number-check.enabled", true);
        if (magicNumberCheckEnabled && !validMagicNumbers(bin)) {
            Log.error("Error installing plugin '{}': This does not appear to be a JAR file (unable to find a magic byte match).", pluginFilename);
            return false;
        }
        // If pluginFilename is a path instead of a simple file name, we only want the file name
        pluginFilename = Paths.get(pluginFilename).getFileName().toString();
        // Absolute path to the plugin file
        Path absolutePath = pluginDirectory.resolve(pluginFilename);
        Path partFile = pluginDirectory.resolve(pluginFilename + ".part");
        // Save input stream contents to a temp file
        Files.copy(bin, partFile, StandardCopyOption.REPLACE_EXISTING);
        // Check if zip file, else ZipException caught below.
        try (JarFile pluginJar = new JarFile(partFile.toFile())) {
            final boolean pluginXMLCheckEnabled = JiveGlobals.getBooleanProperty("plugins.upload.pluginxml-check.enabled", true);
            // Check if the zip file contains a plugin.xml file.
            if (pluginXMLCheckEnabled && pluginJar.getEntry("plugin.xml") == null) {
                Log.error("Error installing plugin '{}': Unable to find 'plugin.xml' in archive.", pluginFilename);
                Files.deleteIfExists(partFile);
                return false;
            }
        } catch (ZipException e) {
            Log.error("Error installing plugin '{}': Cannot parse file into a JAR format.", pluginFilename, e);
            Files.deleteIfExists(partFile);
            return false;
        }
        // Rename temp file to .jar
        Files.move(partFile, absolutePath, StandardCopyOption.REPLACE_EXISTING);
        // Ask the plugin monitor to update the plugin immediately.
        pluginMonitor.runNow(true);
    } catch (IOException e) {
        Log.error("An exception occurred while installing new version of plugin '{}':", pluginFilename, e);
        return false;
    }
    return true;
}
Also used : BufferedInputStream(java.io.BufferedInputStream) ZipException(java.util.zip.ZipException) IOException(java.io.IOException) JarFile(java.util.jar.JarFile)

Example 75 with ZipException

use of java.util.zip.ZipException in project CzechIdMng by bcvsolutions.

the class ProjectManager method build.

/**
 * Build project.
 *
 * @param rootPath
 * @return true - project artifacts are available in dist directory
 */
public boolean build(String rootPath, boolean clean) {
    try {
        Assert.notNull(mavenManager, "Maven manager is not inited. Init manager before usage.");
        Assert.notNull(rootPath, "Path to folder with product and modules is required.");
        // 
        File rootFolder = new File(rootPath);
        Assert.isTrue(rootFolder.exists(), String.format("Root folder [%s] not found.", rootPath));
        File productFolder = new File(rootFolder, "product");
        Assert.isTrue(productFolder.exists(), String.format("Product folder [%s] not found.", productFolder));
        File modulesFolder = new File(rootFolder, "modules");
        File frontendFolder = new File(rootFolder, "frontend");
        File targetFolder = new File(rootFolder, "target");
        File distFolder = new File(rootFolder, "dist");
        // 
        LOG.info("Clean previous target and distribution ...");
        if (clean) {
            LOG.info("Previously installed / used frontend nodejs, npm and node_modules will be deleted ...");
        }
        // clean previous target and dist
        if (targetFolder.exists()) {
            // cleanup content, which can be copied
            for (File file : targetFolder.listFiles()) {
                // prevent to delete node_modules, if clean is not used
                if (clean) {
                    FileUtils.forceDelete(file);
                } else if ("npm".equals(file.getName())) {
                // nothing - leave installed npm
                } else if ("frontend".equals(file.getName())) {
                    for (File frontendFile : file.listFiles()) {
                        if ("node_modules".equals(frontendFile.getName())) {
                        // nothing
                        } else {
                            FileUtils.forceDelete(frontendFile);
                        }
                    }
                } else {
                    FileUtils.forceDelete(file);
                }
            }
        } else {
            targetFolder.mkdirs();
        }
        if (distFolder.exists()) {
            // cleanup all content from dist folder
            for (File file : distFolder.listFiles()) {
                FileUtils.forceDelete(file);
            }
        } else {
            distFolder.mkdirs();
        }
        // 
        // resolve product artefact
        File extractedProductFolder = new File(targetFolder, "war");
        // 
        // check product version in product folder
        String productVersion = getVersion(productFolder);
        if (StringUtils.isNotEmpty(productVersion)) {
            // extracted product
            FileUtils.copyDirectory(productFolder, extractedProductFolder);
            LOG.info("Extracted product [{}] found directly in product folder.", productFolder.getPath());
        } else {
            for (File file : productFolder.listFiles()) {
                // TODO: extracted product higher priority?
                if (file.isDirectory()) {
                    productVersion = getVersion(file);
                    if (StringUtils.isNotEmpty(productVersion)) {
                        // extracted product => just copy in this case
                        FileUtils.copyDirectory(file, extractedProductFolder);
                        LOG.info("Extracted product folder [{}] found.", file.getPath());
                        // 
                        break;
                    }
                }
                if (file.getName().endsWith(".war")) {
                    // .war artefact
                    File productWar = file;
                    LOG.info("Product artefact [{}] found.", productWar.getName());
                    // 
                    // extract war file
                    LOG.info("Product artefact [{}] will be extracted ...", productWar.getName());
                    ZipUtils.extract(productWar, extractedProductFolder.getPath());
                    LOG.info("Product [{}] extracted into target folder [{}].", productWar, targetFolder);
                    // 
                    productVersion = getVersion(extractedProductFolder);
                    break;
                }
            }
        }
        Assert.isTrue(StringUtils.isNotEmpty(productVersion), String.format("Product artefact not found in product folder [%s].", productFolder.getPath()));
        // 
        LOG.info("Product version [{}] resolved.", productVersion);
        // 
        // add modules into BE libs
        // extract FE sources - prepare for build
        // has to be lower - modules are linked automatically from parent folder
        File extractedFrontendFolder = new File(new File(targetFolder, "frontend"), "fe-sources");
        File productFrontendFolder = new File(String.format("%s/fe-sources", extractedProductFolder.getPath()));
        FileUtils.copyDirectory(productFrontendFolder, extractedFrontendFolder);
        // 
        File productFrontendModulesFolder = new File(String.format("%s/czechidm-modules", productFrontendFolder.getPath()));
        File extractedFrontendModulesFolder = new File(String.format("%s/czechidm-modules", extractedFrontendFolder.getPath()));
        List<String> installedModules = new ArrayList<>();
        List<File> installedJarModules = new ArrayList<>();
        Map<String, String> distinctModuleNames = Maps.newHashMap();
        // 
        if (!modulesFolder.exists()) {
            LOG.info("Folder with modules not found, modules will not be installed.");
        } else {
            ObjectMapper mapper = new ObjectMapper();
            // ensure files are sorted alphabetically
            File[] files = modulesFolder.listFiles();
            Arrays.sort(files);
            // 
            for (File module : files) {
                String moduleName = module.getName();
                // 
                FileUtils.copyFile(module, new File(String.format("%s/WEB-INF/lib", extractedProductFolder.getPath()), moduleName));
                // 
                // extract module jar into target
                File extractedModuleFolder = new File(targetFolder, FilenameUtils.removeExtension(moduleName));
                try {
                    ZipUtils.extract(module, extractedModuleFolder.getPath());
                    // 
                    // module name without version suffix
                    String simpleModuleName = null;
                    String backendModuleVersion = getVersion(extractedModuleFolder);
                    if (StringUtils.isNotEmpty(backendModuleVersion)) {
                        simpleModuleName = moduleName.replace(String.format("-%s", backendModuleVersion), "");
                        if (distinctModuleNames.containsKey(simpleModuleName)) {
                            throw new BuildException(String.format("Module [%s] cannot be installed twice. Remove one version from modules folder. Found versions [%s, %s].", simpleModuleName, distinctModuleNames.get(simpleModuleName), backendModuleVersion));
                        } else {
                            distinctModuleNames.put(simpleModuleName, backendModuleVersion);
                        }
                        // 
                        LOG.info("Backend module [{}] instaled in version [{}].", moduleName, // third party libraries without version in manifest ...
                        backendModuleVersion == null ? "n/a" : backendModuleVersion);
                    } else {
                        // third party libraries without version in manifest ...
                        LOG.info("Backend module [{}] instaled.", moduleName);
                    }
                    // 
                    // copy FE sources info product frontend
                    File moduleFrontendFolder = new File(String.format("%s/fe-sources/czechidm-modules", extractedModuleFolder.getPath()));
                    // 
                    if (moduleFrontendFolder.exists()) {
                        if (skipFrontendBuild) {
                            LOG.info("Frontend build is skipped. Module [{}] frontend will not be included.", moduleName);
                        } else {
                            // check BE vs. FE version -> throw exception otherwise
                            for (File moduleFolder : moduleFrontendFolder.listFiles()) {
                                File modulePackage = new File(moduleFolder.getPath(), "package.json");
                                try (InputStream is = new FileInputStream(modulePackage)) {
                                    // FIXME: refactor super class from product / project manager (DRY - #getCurrentFrontendModuleVersion).
                                    JsonNode json = mapper.readTree(IOUtils.toString(is, AttachableEntity.DEFAULT_CHARSET));
                                    String frontendModuleVersion = json.get("version").textValue();
                                    if (!StringUtils.equalsIgnoreCase(backendModuleVersion, frontendModuleVersion)) {
                                        throw new BuildException(String.format("Module [%s] versions differs [BE: %s] vs [FE: %s]. " + "Module is wrongly released or built. Build module properly and install him again.", moduleName, backendModuleVersion, frontendModuleVersion));
                                    }
                                    // 
                                    LOG.info("Frontend module [{}] instaled in version [{}].", moduleName, frontendModuleVersion);
                                }
                            }
                            // 
                            FileUtils.copyDirectory(moduleFrontendFolder, extractedFrontendModulesFolder);
                            // we need to know, what was installed in target war
                            FileUtils.copyDirectory(moduleFrontendFolder, productFrontendModulesFolder);
                        }
                    } else {
                        LOG.info("Module [{}] not contain frontend.", moduleName);
                    }
                    installedJarModules.add(module);
                } catch (ZipException ex) {
                    LOG.warn("Module [{}] cannot be extracted, is not .jar library. Library will be installed without frontend resolving.", module.getName());
                }
                // 
                installedModules.add(moduleName);
            }
        }
        // build FE - create new maven task and build
        if (!skipFrontendBuild) {
            // copy / override project frontends
            if (frontendFolder.exists() && frontendFolder.listFiles().length > 0) {
                FileUtils.copyDirectory(frontendFolder, extractedFrontendFolder);
                // we need to know, what was installed in target war
                FileUtils.copyDirectory(frontendFolder, productFrontendFolder);
                // 
                LOG.info("Custom or overriden frontend artifacts installed {}.", Arrays.stream(frontendFolder.listFiles()).map(f -> f.getName()).collect(Collectors.toList()));
            }
            // 
            LOG.info("Compile frontend application, this can take several minutes ...");
            prepareFrontendMavenProject(extractedFrontendFolder, targetFolder);
            mavenManager.command(targetFolder, "clean", "package", String.format("-Dnode.home=%s", nodeHome));
            LOG.info("Frontend successfully compiled.");
        } else {
            LOG.info("Frontend build is skipped. Product provided frontend will be used.");
        }
        // 
        // create new idm.war
        LOG.info("Build backend application with frontend included ...");
        prepareBackendMavenProject(extractedProductFolder, productVersion, installedJarModules, targetFolder);
        mavenManager.command(targetFolder, "clean", "package", String.format("-Dtool.version=%s", this.getClass().getPackage().getImplementationVersion()), String.format("-Dczechidm.version=%s", productVersion), String.format("-Dinstalled.modules=%s", installedModules));
        LOG.info("Application successfully built.");
        // 
        // move war to dist folder
        File projectWar = new File(distFolder, "idm.war");
        FileUtils.moveFile(new File(String.format("%s/target", targetFolder.getPath()), "idm.war"), projectWar);
        // 
        LOG.info("Deployable project artefact [idm.war] is available in dist directory,");
        LOG.info("with installed modules {}.", installedModules);
        // 
        return true;
    } catch (Exception ex) {
        throw new BuildException(ex.getLocalizedMessage(), ex);
    }
}
Also used : FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) JsonNode(com.fasterxml.jackson.databind.JsonNode) ZipException(java.util.zip.ZipException) FileInputStream(java.io.FileInputStream) ZipException(java.util.zip.ZipException) IOException(java.io.IOException) BuildException(eu.bcvsolutions.idm.tool.exception.BuildException) BuildException(eu.bcvsolutions.idm.tool.exception.BuildException) File(java.io.File) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Aggregations

ZipException (java.util.zip.ZipException)197 IOException (java.io.IOException)96 File (java.io.File)74 ZipEntry (java.util.zip.ZipEntry)67 ZipFile (java.util.zip.ZipFile)63 InputStream (java.io.InputStream)50 FileInputStream (java.io.FileInputStream)39 ZipInputStream (java.util.zip.ZipInputStream)26 FileOutputStream (java.io.FileOutputStream)23 BufferedInputStream (java.io.BufferedInputStream)22 JarFile (java.util.jar.JarFile)21 FileNotFoundException (java.io.FileNotFoundException)19 JarEntry (java.util.jar.JarEntry)19 ArrayList (java.util.ArrayList)18 ByteArrayInputStream (java.io.ByteArrayInputStream)15 ZipOutputStream (java.util.zip.ZipOutputStream)15 URL (java.net.URL)14 GZIPInputStream (java.util.zip.GZIPInputStream)12 BufferedOutputStream (java.io.BufferedOutputStream)8 RandomAccessFile (java.io.RandomAccessFile)8