Example usage for java.util.zip ZipInputStream close

List of usage examples for java.util.zip ZipInputStream close

Introduction

In this page you can find the example usage for java.util.zip ZipInputStream close.

Prototype

public void close() throws IOException 

Source Link

Document

Closes this input stream and releases any system resources associated with the stream.

Usage

From source file:org.geoserver.wps.ExecuteTest.java

private void checkShapefileIntegrity(String[] typeNames, final InputStream in) throws IOException {
    ZipInputStream zis = new ZipInputStream(in);
    ZipEntry entry = null;/*from w  ww .  j a  v a2s .  c  o  m*/

    final String[] extensions = new String[] { ".shp", ".shx", ".dbf", ".prj", ".cst" };
    Set names = new HashSet();
    for (String name : typeNames) {
        for (String extension : extensions) {
            names.add(name + extension);
        }
    }
    while ((entry = zis.getNextEntry()) != null) {
        final String name = entry.getName();
        Assert.assertTrue("Missing " + name, names.contains(name));
        names.remove(name);
        zis.closeEntry();
    }
    zis.close();
}

From source file:org.eclipse.koneki.ldt.core.internal.buildpath.LuaExecutionEnvironmentManager.java

/**
 * Will deploy files from a valid Execution Environment file in installation directory. File will be considered as installed when its name will be
 * appended in {@link LuaExecutionEnvironmentConstants#PREF_EXECUTION_ENVIRONMENTS_LIST}
 * //from  w w w .j  av a  2  s .  co  m
 * @param zipPath
 *            Path to file to deploy
 * @return {@link LuaExecutionEnvironmentException} when deployment succeeded.
 * @throws CoreException
 */
public static LuaExecutionEnvironment installLuaExecutionEnvironment(final String zipPath)
        throws CoreException {
    /*
     * Ensure there are no folder named like the one we are about to create
     */
    LuaExecutionEnvironment ee = null;
    ee = getExecutionEnvironmentFromCompressedFile(zipPath);

    if (ee == null)
        throwException(
                MessageFormat.format("Unable to extract execution environment information from {0}.", zipPath), //$NON-NLS-1$
                null, IStatus.ERROR);

    // check if it is already installed
    if (getInstalledExecutionEnvironments().contains(ee)) {
        throwException("Execution environment is already installed.", null, IStatus.ERROR); //$NON-NLS-1$
    }

    // prepare/clean the directory where the Execution environment will be installed
    final IPath eePath = getInstallDirectory().append(ee.getEEIdentifier());
    final File installDirectory = eePath.toFile();
    // clean install directory if it exists
    if (installDirectory.exists()) {
        if (installDirectory.isFile()) {
            if (!installDirectory.delete())
                throwException(MessageFormat.format("Unable to clean installation directory : {0}", //$NON-NLS-1$
                        eePath.toOSString()), null, IStatus.ERROR);
        } else {
            try {
                FileUtils.deleteDirectory(installDirectory);
            } catch (IOException e) {
                throwException(MessageFormat.format("Unable to clean installation directory : {0}", //$NON-NLS-1$
                        eePath.toOSString()), e, IStatus.ERROR);
            }
        }
    }

    // in all case create the install directory
    if (!installDirectory.mkdirs()) {
        throwException(
                MessageFormat.format("Unable to create installation directory : {0}", eePath.toOSString()), //$NON-NLS-1$
                null, IStatus.ERROR);
    }

    // Extract Execution environment from zip
    // Loop over content
    ZipInputStream zipStream = null;
    FileInputStream input = null;
    try {
        // Open given file
        input = new FileInputStream(zipPath);
        zipStream = new ZipInputStream(new BufferedInputStream(input));

        for (ZipEntry entry = zipStream.getNextEntry(); entry != null; entry = zipStream.getNextEntry()) {
            /*
             * Flush current file on disk
             */
            final File outputFile = new File(installDirectory, entry.getName());
            // Define output file
            if (entry.isDirectory()) {
                // Create sub directory if needed
                if (!outputFile.mkdir()) {
                    throwException(MessageFormat.format("Unable to create install directory {0}", //$NON-NLS-1$
                            outputFile.toString()), null, IStatus.ERROR);
                }
            } else {
                // copy file
                FileOutputStream fileOutputStream = null;
                try {
                    fileOutputStream = new FileOutputStream(outputFile);
                    // Inflate file
                    IOUtils.copy(zipStream, fileOutputStream);

                    // Flush on disk
                    fileOutputStream.flush();
                } finally {
                    if (fileOutputStream != null) {
                        try {
                            fileOutputStream.close();
                        } catch (IOException e) {
                            Activator.logWarning(MessageFormat.format("Unable to close file {0}", outputFile), //$NON-NLS-1$
                                    e);
                        }

                    }
                }
            }
        }
    } catch (IOException e) {
        throwException(MessageFormat.format("Unable to extract zip file : {0}", zipPath), e, IStatus.ERROR); //$NON-NLS-1$
    } finally {
        /*
         * Make sure all streams are closed
         */
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
                Activator.logWarning(MessageFormat.format("Unable to close file {0}", zipPath), e); //$NON-NLS-1$
            }
        }
        if (zipStream != null) {
            try {
                zipStream.close();
            } catch (IOException e) {
                Activator.logWarning(MessageFormat.format("Unable to close file {0}", zipPath), e); //$NON-NLS-1$
            }
        }
    }

    // try to get installed Execution Environment to be sure, it is well installed
    getInstalledExecutionEnvironment(ee.getID(), ee.getVersion());

    refreshDLTKModel(ee);
    return ee;
}

From source file:io.lightlink.excel.StreamingExcelTransformer.java

public void doExport(InputStream template, OutputStream out, ExcelStreamVisitor visitor) throws IOException {
    try {/*from   w ww.  j av a  2 s .  co m*/
        ZipInputStream zipIn = new ZipInputStream(template);
        ZipOutputStream zipOut = new ZipOutputStream(out);

        ZipEntry entry;

        Map<String, byte[]> sheets = new HashMap<String, byte[]>();

        while ((entry = zipIn.getNextEntry()) != null) {

            String name = entry.getName();

            if (name.startsWith("xl/sharedStrings.xml")) {

                byte[] bytes = IOUtils.toByteArray(zipIn);
                zipOut.putNextEntry(new ZipEntry(name));
                zipOut.write(bytes);

                sharedStrings = processSharedStrings(bytes);

            } else if (name.startsWith("xl/worksheets/sheet")) {
                byte[] bytes = IOUtils.toByteArray(zipIn);
                sheets.put(name, bytes);
            } else if (name.equals("xl/calcChain.xml")) {
                // skip this file, let excel recreate it
            } else if (name.equals("xl/workbook.xml")) {
                zipOut.putNextEntry(new ZipEntry(name));

                SAXParserFactory factory = SAXParserFactory.newInstance();
                SAXParser saxParser = factory.newSAXParser();
                Writer writer = new OutputStreamWriter(zipOut, "UTF-8");

                byte[] bytes = IOUtils.toByteArray(zipIn);
                saxParser.parse(new ByteArrayInputStream(bytes), new WorkbookTemplateHandler(writer));

                writer.flush();
            } else {
                zipOut.putNextEntry(new ZipEntry(name));
                IOUtils.copy(zipIn, zipOut);
            }

        }

        for (Map.Entry<String, byte[]> sheetEntry : sheets.entrySet()) {
            String name = sheetEntry.getKey();

            byte[] bytes = sheetEntry.getValue();
            zipOut.putNextEntry(new ZipEntry(name));
            processSheet(bytes, zipOut, visitor);
        }

        zipIn.close();
        template.close();

        zipOut.close();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e.toString(), e);
    }
}

From source file:org.jboss.dashboard.factory.Factory.java

protected synchronized void init(ZipInputStream zis) throws IOException {
    ArrayList entriesOrder = new ArrayList();
    HashMap entries = new HashMap();
    ZipEntry entry;//from  ww w .j  av  a 2s  .  co  m
    while ((entry = zis.getNextEntry()) != null) {
        if (entry.isDirectory())
            continue;

        String entryName = entry.getName().replace('\\', '/');
        if (entryName.equals(FACTORY_FILENAME)) {
            log.debug("Using config file: zip:/" + entryName);
            BufferedReader input = new BufferedReader(new InputStreamReader(zis));
            String line;
            while ((line = input.readLine()) != null) {
                if (!checkModuleName(line))
                    continue;
                entriesOrder.add(line);
            }
        } else if (entryName.indexOf('/') == -1) {
            log.warn("Ignoring entry inside ZIP " + entryName);
        } else {
            int index = entryName.indexOf('/');
            Properties prop = new Properties();
            try {
                prop.load(zis);
            } catch (IOException e) {
                log.error("Error processing entry zip:/" + entryName + ". It will be ignored.", e);
                continue;
            }
            String product = entryName.substring(0, index);
            String component = entryName
                    .substring(index + 1, entryName.length() - 1 - FACTORY_EXTENSION.length()).replace('/', '.')
                    .replace('\\', '.');
            Map m = (Map) entries.get(product);
            if (m == null) {
                m = new HashMap();
                entries.put(product, m);
            }
            m.put(component, prop);
        }
    }
    zis.close();
    List descriptorFiles = new ArrayList();
    for (int i = 0; i < entriesOrder.size(); i++) {
        String product = (String) entriesOrder.get(i);
        Map components = (Map) entries.get(product);
        if (components == null || components.isEmpty())
            continue;
        for (Iterator it = components.keySet().iterator(); it.hasNext();) {
            String componentName = (String) it.next();
            Properties componentProperties = (Properties) components.get(componentName);
            descriptorFiles.add(new DescriptorFile(componentName, componentProperties,
                    "zip:/" + product + "/" + componentName.replace('.', '/') + "." + FACTORY_EXTENSION));
        }
    }
    addDescriptorFiles(descriptorFiles);
}

From source file:nl.nn.adapterframework.webcontrol.api.ShowConfiguration.java

private String processZipFile(InputStream inputStream, String fileEncoding, String jmsRealm,
        boolean automatic_reload, boolean activate_config, String user) throws Exception {
    String result = "";
    if (inputStream.available() > 0) {
        ZipInputStream archive = new ZipInputStream(inputStream);
        int counter = 1;
        for (ZipEntry entry = archive.getNextEntry(); entry != null; entry = archive.getNextEntry()) {
            String entryName = entry.getName();
            int size = (int) entry.getSize();
            if (size > 0) {
                byte[] b = new byte[size];
                int rb = 0;
                int chunk = 0;
                while (((int) size - rb) > 0) {
                    chunk = archive.read(b, rb, (int) size - rb);
                    if (chunk == -1) {
                        break;
                    }/* www  .  j av a  2s  .co  m*/
                    rb += chunk;
                }
                ByteArrayInputStream bais = new ByteArrayInputStream(b, 0, rb);
                String fileName = "file_zipentry" + counter;
                if (StringUtils.isNotEmpty(result)) {
                    result += "\n";
                }
                String name = "";
                String version = "";
                String[] fnArray = splitFilename(entryName);
                if (fnArray[0] != null) {
                    name = fnArray[0];
                }
                if (fnArray[1] != null) {
                    version = fnArray[1];
                }
                result += entryName + ":" + ConfigurationUtils.addConfigToDatabase(ibisContext, jmsRealm,
                        activate_config, automatic_reload, name, version, fileName, bais, user);
            }
            archive.closeEntry();
            counter++;
        }
        archive.close();
    }
    return result;
}

From source file:com.twemyeez.picklr.InstallManager.java

public static void unzip() {

    // Firstly get the working directory
    String workingDirectory = Minecraft.getMinecraft().mcDataDir.getAbsolutePath();

    // If it ends with a . then remove it
    if (workingDirectory.endsWith(".")) {
        workingDirectory = workingDirectory.substring(0, workingDirectory.length() - 1);
    }/* www. j av  a  2 s .c  om*/

    // If it doesn't end with a / then add it
    if (!workingDirectory.endsWith("/") && !workingDirectory.endsWith("\\")) {
        workingDirectory = workingDirectory + "/";
    }

    // Use a test file to see if libraries installed
    File file = new File(workingDirectory + "mods/mp3spi1.9.5.jar");

    // If the libraries are installed, return
    if (file.exists()) {
        System.out.println("Checking " + file.getAbsolutePath());
        System.out.println("Target file exists, so not downloading API");
        return;
    }

    // Now try to download the libraries
    try {

        String location = "http://www.javazoom.net/mp3spi/sources/mp3spi1.9.5.zip";

        // Define the URL
        URL url = new URL(location);

        // Get the ZipInputStream
        ZipInputStream zipInput = new ZipInputStream(new BufferedInputStream((url).openStream()));

        // Use a temporary ZipEntry as a buffer
        ZipEntry zipFile;

        // While there are more file entries
        while ((zipFile = zipInput.getNextEntry()) != null) {
            // Check if it is one of the file names that we want to copy
            Boolean required = false;
            if (zipFile.getName().indexOf("mp3spi1.9.5.jar") != -1) {
                required = true;
            }
            if (zipFile.getName().indexOf("jl1.0.1.jar") != -1) {
                required = true;
            }
            if (zipFile.getName().indexOf("tritonus_share.jar") != -1) {
                required = true;
            }
            if (zipFile.getName().indexOf("LICENSE.txt") != -1) {
                required = true;
            }

            // If it is, then we shall now copy it
            if (!zipFile.getName().replace("MpegAudioSPI1.9.5/", "").equals("") && required) {

                // Get the file location
                String tempFile = new File(zipFile.getName()).getName();

                tempFile = tempFile.replace("LICENSE.txt", "MpegAudioLicence.txt");

                // Initialise the target file
                File targetFile = (new File(
                        workingDirectory + "mods/" + tempFile.replace("MpegAudioSPI1.9.5/", "")));

                // Print a debug/alert message
                System.out.println("Picklr is extracting to " + workingDirectory + "mods/"
                        + tempFile.replace("MpegAudioSPI1.9.5/", ""));

                // Make parent directories if required
                targetFile.getParentFile().mkdirs();

                // If the file does not exist, create it
                if (!targetFile.exists()) {
                    targetFile.createNewFile();
                }

                // Create a buffered output stream to the destination
                BufferedOutputStream destinationOutput = new BufferedOutputStream(
                        new FileOutputStream(targetFile, false), 2048);

                // Store the data read
                int bytesRead;

                // Data buffer
                byte dataBuffer[] = new byte[2048];

                // While there is still data to write
                while ((bytesRead = zipInput.read(dataBuffer, 0, 2048)) != -1) {
                    // Write it to the output stream
                    destinationOutput.write(dataBuffer, 0, bytesRead);
                }

                // Flush the output
                destinationOutput.flush();

                // Close the output stream
                destinationOutput.close();
            }

        }
        // Close the zip input
        zipInput.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:org.jboss.tools.tycho.sitegenerator.FetchSourcesFromManifests.java

public void execute() throws MojoExecutionException, MojoFailureException {
    if (!skip) {//from ww w  .j ava 2s  .c o m
        if (this.zipCacheFolder == null) {
            this.zipCacheFolder = new File(project.getBasedir() + File.separator + "cache" + File.separator);
        }
        if (this.zipCacheFolder != null && !this.zipCacheFolder.isDirectory()) {
            try {
                if (!this.zipCacheFolder.exists()) {
                    this.zipCacheFolder.mkdirs();
                }
            } catch (Exception ex) {
                throw new MojoExecutionException("'zipCacheFolder' must be a directory", ex);
            }
        }
        if (this.outputFolder == null) {
            this.outputFolder = new File(project.getBasedir() + File.separator + "zips" + File.separator);
        }
        if (this.outputFolder.equals(this.zipCacheFolder)) {
            throw new MojoExecutionException("zipCacheFolder and outputFolder can not be the same folder");
        }

        zipsDirectory = new File(this.outputFolder, "all");
        if (!zipsDirectory.exists()) {
            zipsDirectory.mkdirs();
        }

        File digestFile = new File(this.outputFolder, "ALL_REVISIONS.txt");
        FileWriter dfw;
        StringBuffer sb = new StringBuffer();
        String branch = project.getProperties().getProperty("mvngit.branch");
        sb.append("-=> " + project.getGroupId() + ":" + project.getArtifactId() + ":" + project.getVersion()
                + columnSeparator + branch + " <=-\n");

        String pluginPath = project.getBasedir() + File.separator + "target" + File.separator + "repository"
                + File.separator + "plugins";
        String sep = " " + columnSeparator + " ";

        if (sourceFetchMap == null) {
            getLog().warn(
                    "No <sourceFetchMap> defined in pom. Can't fetch sources without a list of plugins. Did you forget to enable fetch-source-zips profile?");
        } else {
            for (String projectName : this.sourceFetchMap.keySet()) {
                String pluginNameOrBuildInfoJsonUrl = this.sourceFetchMap.get(projectName);
                // jbosstools-base = org.jboss.tools.common
                getLog().debug("For project " + projectName + ": plugin name or buildinfo.json = "
                        + pluginNameOrBuildInfoJsonUrl);

                String SHA = null;
                String qualifier = null;
                String SHASource = null;

                // if the value is a buildinfo.json URL, not a plugin name
                if ((pluginNameOrBuildInfoJsonUrl.startsWith("http")
                        || pluginNameOrBuildInfoJsonUrl.startsWith("ftp"))
                        && pluginNameOrBuildInfoJsonUrl.matches(".+buildinfo.*json")) {
                    getLog().debug("Read JSON from: " + pluginNameOrBuildInfoJsonUrl);
                    ModelNode obj;
                    try {
                        obj = ModelNode.fromJSONStream((new URL(pluginNameOrBuildInfoJsonUrl)).openStream());
                    } catch (IOException e) {
                        throw new MojoExecutionException(
                                "Problem occurred reading " + pluginNameOrBuildInfoJsonUrl, e);
                    }
                    SHA = getSHA(obj);
                    getLog().debug("Found SHA = " + SHA);
                    // create qualifier from buildinfo.json BUILD_ALIAS and ZIPSUFFIX
                    qualifier = getProperty(obj, "BUILD_ALIAS") + "-" + getProperty(obj, "ZIPSUFFIX");
                    getLog().debug("Found qualifier = " + qualifier);
                    SHASource = pluginNameOrBuildInfoJsonUrl;
                } else {
                    // find the first matching plugin jar, eg., target/repository/plugins/org.jboss.tools.common_3.6.0.Alpha2-v20140304-0055-B440.jar
                    File[] matchingFiles = listFilesMatching(new File(pluginPath),
                            pluginNameOrBuildInfoJsonUrl + "_.+\\.jar");
                    // for (File file : matchingFiles) getLog().debug(file.toString());
                    if (matchingFiles.length < 1) {
                        throw new MojoExecutionException("No matching plugin found in " + pluginPath + " for "
                                + pluginNameOrBuildInfoJsonUrl
                                + "_.+\\.jar.\nCheck your pom.xml for this line: <" + projectName + ">"
                                + pluginNameOrBuildInfoJsonUrl + "</" + projectName + ">");
                    }
                    File jarFile = matchingFiles[0];
                    File manifestFile = null;

                    try {
                        FileInputStream fin = new FileInputStream(jarFile);
                        manifestFile = File.createTempFile(MANIFEST, "");
                        OutputStream out = new FileOutputStream(manifestFile);
                        BufferedInputStream bin = new BufferedInputStream(fin);
                        ZipInputStream zin = new ZipInputStream(bin);
                        ZipEntry ze = null;
                        while ((ze = zin.getNextEntry()) != null) {
                            // getLog().debug(ze.getName());
                            if (ze.getName().equals("META-INF/" + MANIFEST)) {
                                // getLog().debug("Found " + ze.getName() + " in " +
                                // jarFile);
                                byte[] buffer = new byte[8192];
                                int len;
                                while ((len = zin.read(buffer)) != -1) {
                                    out.write(buffer, 0, len);
                                }
                                out.close();
                                break;
                            }
                        }
                        zin.close();
                        // getLog().debug("Saved " + jarFile + "!/META-INF/" + MANIFEST);
                    } catch (Exception ex) {
                        throw new MojoExecutionException("Error extracting " + MANIFEST + " from " + jarFile,
                                ex);
                    }

                    // retrieve the MANIFEST.MF file, eg., org.jboss.tools.usage_1.2.100.Alpha2-v20140221-1555-B437.jar!/META-INF/MANIFEST.MF
                    Manifest manifest;
                    try {
                        manifest = new Manifest(new FileInputStream(manifestFile));
                    } catch (Exception ex) {
                        throw new MojoExecutionException("Error while reading manifest file " + MANIFEST, ex);
                    }

                    // parse out the commitId from Eclipse-SourceReferences:
                    // scm:git:https://github.com/jbosstools/jbosstools-base.git;path="usage/plugins/org.jboss.tools.usage";commitId=184e18cc3ac7c339ce406974b6a4917f73909cc4
                    Attributes attr = manifest.getMainAttributes();
                    String ESR = null;
                    SHA = null;
                    ESR = attr.getValue("Eclipse-SourceReferences");
                    // getLog().debug(ESR);
                    if (ESR != null) {
                        SHA = ESR.substring(ESR.lastIndexOf(";commitId=") + 10);
                        // getLog().debug(SHA);
                    } else {
                        SHA = "UNKNOWN";
                    }
                    // cleanup
                    manifestFile.delete();

                    qualifier = getQualifier(pluginNameOrBuildInfoJsonUrl, jarFile.toString(), true);
                    SHASource = removePrefix(jarFile.toString(), pluginPath) + " " + MANIFEST;
                }
                // fetch github source archive for that SHA, eg., https://github.com/jbosstools/jbosstools-base/archive/184e18cc3ac7c339ce406974b6a4917f73909cc4.zip
                // to jbosstools-base_184e18cc3ac7c339ce406974b6a4917f73909cc4_sources.zip
                String URL = "";
                String outputZipName = "";
                try {
                    if (SHA == null || SHA.equals("UNKNOWN")) {
                        getLog().warn("Cannot fetch " + projectName
                                + " sources: no Eclipse-SourceReferences in " + SHASource);
                    } else {
                        URL = "https://github.com/jbosstools/" + projectName + "/archive/" + SHA + ".zip";
                        outputZipName = projectName + "_" + SHA + "_sources.zip";
                        fetchUpstreamSourcesZip(projectName, SHA);
                    }
                } catch (Exception ex) {
                    throw new MojoExecutionException("Error while downloading github source archive", ex);
                }

                // github project, plugin, version, SHA, origin/branch@SHA, remote zipfile, local zipfile
                String revisionLine = projectName + sep + pluginNameOrBuildInfoJsonUrl + sep + qualifier + sep
                        + SHA + sep + "origin/" + branch + "@" + SHA + sep + URL + sep + outputZipName + "\n";
                // getLog().debug(revisionLine);
                sb.append(revisionLine);
            }
        }

        /*
        JBIDE-19467 check if SHA in buildinfo_projectName.json matches projectName_65cb06bb81773714b9e3fc1c312e33aaa068dc33_sources.zip.
        Note: this may fail if you've built stuff locally because those plugins will use different SHAs (eg., from a pull-request topic branch)
                
        To test this is working via commandline shell equivalent
                
        cd jbosstools-build-sites/aggregate/site
        for j in target/buildinfo/buildinfo_jbosstools-*; do
           echo -n $j; k=${j##*_}; k=${k/.json}; echo " :: $k";
           cat $j | grep HEAD | head -1 | sed "s#[\t\w\ ]\+\"HEAD\" : \"\(.\+\)\",#0: \1#";
           ls cache/${k}_*_sources.zip  | sed -e "s#cache/${k}_\(.\+\)_sources.zip#1: \1#";
           echo "";
        done
        */
        if (skipCheckSHAs) {
            getLog().warn(
                    "skipCheckSHAs=true :: Skip check that buildinfo_*.json HEAD SHA matches MANIFEST.MF Eclipse-SourceReferences commitId SHA.");
        } else {
            File buildinfoFolder = new File(this.project.getBuild().getDirectory(), "buildinfo");
            if (buildinfoFolder.isDirectory()) {
                try {
                    File[] buildInfoFiles = listFilesMatching(buildinfoFolder, "buildinfo_.+.json");
                    for (int i = 0; i < buildInfoFiles.length; i++) {
                        InputStream in = null;
                        ModelNode obj = null;
                        String upstreamSHA = null;
                        String upstreamProjectName = buildInfoFiles[i].toString()
                                .replaceAll(".+buildinfo_(.+).json", "$1");
                        getLog().debug(i + ": " + buildInfoFiles[i].toString() + " :: " + upstreamProjectName);
                        try {
                            getLog().debug("Read JSON from: " + buildInfoFiles[i].toString());
                            in = new FileInputStream(buildInfoFiles[i]);
                            obj = ModelNode.fromJSONStream(in);
                            upstreamSHA = getSHA(obj);
                            getLog().debug("Found SHA = " + upstreamSHA);
                            // check if there's a file called upstreamProjectName_upstreamSHA_sources.zip
                            String outputZipName = upstreamProjectName + "_" + upstreamSHA + "_sources.zip";
                            File outputZipFile = new File(zipsDirectory, outputZipName);
                            if (!outputZipFile.isFile()) {
                                getLog().debug("Check " + outputFolder.toString() + " for "
                                        + upstreamProjectName + "_.+_sources.zip");
                                // find the sources we DID download, eg., jbosstools-browsersim_9255a5b7c04fb10768c14942e60092e860881d6b_sources.zip
                                File[] wrongZipFiles = listFilesMatching(zipsDirectory,
                                        upstreamProjectName + "_.+_sources.zip");
                                String wrongZips = "";
                                for (int j = 0; j < wrongZipFiles.length; j++) {
                                    getLog().debug(wrongZipFiles[j].toString());
                                    wrongZips += (wrongZips.isEmpty() ? "" : ", ") + wrongZipFiles[j].toString()
                                            .replaceAll(".+" + upstreamProjectName + "_(.+)_sources.zip", "$1");
                                }
                                if (!wrongZips.isEmpty()) {
                                    throw new MojoFailureException("\n\n" + buildInfoFiles[i].toString()
                                            + "\ncontains " + upstreamSHA + ", but upstream "
                                            + upstreamProjectName
                                            + " project's MANIFEST.MF has Eclipse-SourceReferences \n"
                                            + "commitId " + wrongZips + ". \n\n"
                                            + "If you have locally built projects which are being aggregated here, ensure \n"
                                            + "they are built from the latest SHA from HEAD, not a local topic branch. \n\n"
                                            + "It's also possible that some recent changes have not yet been built upstream. \n"
                                            + "If that's the case, trigger a build for the "
                                            + upstreamProjectName + " project \n"
                                            + "to ensure that the latest commits have been built and can be aggregated here. \n\n"
                                            + "Or, use -DskipCheckSHAs=true to bypass this check.\n\n"); // JBIDE-22808
                                } else {
                                    getLog().warn("\n" + buildInfoFiles[i].toString() + "\ncontains "
                                            + upstreamSHA + ", but upstream " + upstreamProjectName
                                            + " project's MANIFEST.MF has no Eclipse-SourceReferences commitId.\n"
                                            + "Using sources from " + upstreamSHA + ".");
                                    // fetch sources from upstreamProjectName's upstreamSHA (but do not log in the digestFile)
                                    fetchUpstreamSourcesZip(upstreamProjectName, upstreamSHA);
                                }
                            }
                        } finally {
                            IOUtils.closeQuietly(in);
                        }
                    }
                } catch (Exception ex) {
                    throw new MojoExecutionException("Problem occurred checking upstream buildinfo.json files!",
                            ex);
                }
            }
        }

        /*
        JBIDE-19467 check if SHA in buildinfo_projectName.json matches projectName_65cb06bb81773714b9e3fc1c312e33aaa068dc33_sources.zip.
        Note: this may fail if you've built stuff locally because those plugins will use different SHAs (eg., from a pull-request topic branch)
                
        To test this is working via commandline shell equivalent
                
        cd jbosstools-build-sites/aggregate/site
        for j in target/buildinfo/buildinfo_jbosstools-*; do
           echo -n $j; k=${j##*_}; k=${k/.json}; echo " :: $k";
           cat $j | grep HEAD | head -1 | sed "s#[\t\w\ ]\+\"HEAD\" : \"\(.\+\)\",#0: \1#";
           ls cache/${k}_*_sources.zip  | sed -e "s#cache/${k}_\(.\+\)_sources.zip#1: \1#";
           echo "";
        done
        */
        if (skipCheckSHAs) {
            getLog().warn(
                    "skipCheckSHAs=true :: Skip check that buildinfo_*.json HEAD SHA matches MANIFEST.MF Eclipse-SourceReferences commitId SHA.");
        } else {
            File buildinfoFolder = new File(this.project.getBuild().getDirectory(), "buildinfo");
            if (buildinfoFolder.isDirectory()) {
                try {
                    File[] buildInfoFiles = listFilesMatching(buildinfoFolder, "buildinfo_.+.json");
                    for (int i = 0; i < buildInfoFiles.length; i++) {
                        InputStream in = null;
                        ModelNode obj = null;
                        String upstreamSHA = null;
                        String upstreamProjectName = buildInfoFiles[i].toString()
                                .replaceAll(".+buildinfo_(.+).json", "$1");
                        getLog().debug(i + ": " + buildInfoFiles[i].toString() + " :: " + upstreamProjectName);
                        try {
                            getLog().debug("Read JSON from: " + buildInfoFiles[i].toString());
                            in = new FileInputStream(buildInfoFiles[i]);
                            obj = ModelNode.fromJSONStream(in);
                            upstreamSHA = getSHA(obj);
                            getLog().debug("Found SHA = " + upstreamSHA);
                            // check if there's a file called upstreamProjectName_upstreamSHA_sources.zip
                            String outputZipName = upstreamProjectName + "_" + upstreamSHA + "_sources.zip";
                            File outputZipFile = new File(zipsDirectory, outputZipName);
                            if (!outputZipFile.isFile()) {
                                getLog().debug("Check " + outputFolder.toString() + " for "
                                        + upstreamProjectName + "_.+_sources.zip");
                                // find the sources we DID download, eg., jbosstools-browsersim_9255a5b7c04fb10768c14942e60092e860881d6b_sources.zip
                                File[] wrongZipFiles = listFilesMatching(zipsDirectory,
                                        upstreamProjectName + "_.+_sources.zip");
                                String wrongZips = "";
                                for (int j = 0; j < wrongZipFiles.length; j++) {
                                    getLog().debug(wrongZipFiles[j].toString());
                                    wrongZips += (wrongZips.isEmpty() ? "" : ", ") + wrongZipFiles[j].toString()
                                            .replaceAll(".+" + upstreamProjectName + "_(.+)_sources.zip", "$1");
                                }
                                if (!wrongZips.isEmpty()) {
                                    throw new MojoFailureException("\n" + buildInfoFiles[i].toString()
                                            + "\ncontains " + upstreamSHA + ", but upstream "
                                            + upstreamProjectName
                                            + " project's MANIFEST.MF has Eclipse-SourceReferences\ncommitId "
                                            + wrongZips
                                            + ". \nIf you have locally built projects which are aggregated here, \nensure they are built from the latest SHA from HEAD, not a local topic branch.\n"
                                            + "Or, use -DskipCheckSHAs=true to bypass this check.");
                                } else {
                                    getLog().warn("\n" + buildInfoFiles[i].toString() + "\ncontains "
                                            + upstreamSHA + ", but upstream " + upstreamProjectName
                                            + " project's MANIFEST.MF has no Eclipse-SourceReferences commitId.\n"
                                            + "Using sources from " + upstreamSHA + ".");
                                    // fetch sources from upstreamProjectName's upstreamSHA (but do not log in the digestFile)
                                    fetchUpstreamSourcesZip(upstreamProjectName, upstreamSHA);
                                }
                            }
                        } finally {
                            IOUtils.closeQuietly(in);
                        }
                    }
                } catch (Exception ex) {
                    throw new MojoExecutionException("Problem occurred checking upstream buildinfo.json files!",
                            ex);
                }
            }
        }

        // JBDS-3364 JBDS-3208 JBIDE-19467 when not using publish.sh, unpack downloaded source zips and combine them into a single zip
        createCombinedZipFile(zipsDirectory, zipFiles, CACHE_ZIPS);

        // getLog().debug("Generating aggregate site metadata");
        try {
            {
                File buildPropertiesAllXml = new File(this.outputFolder, "build.properties.all.xml");
                if (!buildPropertiesAllXml.exists()) {
                    buildPropertiesAllXml.createNewFile();
                }
                FileOutputStream xmlOut = new FileOutputStream(buildPropertiesAllXml);
                allBuildProperties.storeToXML(xmlOut, null);
                xmlOut.close();
            }

            {
                File buildPropertiesFileTxt = new File(this.outputFolder, "build.properties.file.txt");
                if (!buildPropertiesFileTxt.exists()) {
                    buildPropertiesFileTxt.createNewFile();
                }
                FileOutputStream textOut = new FileOutputStream(buildPropertiesFileTxt);
                allBuildProperties.store(textOut, null);
                textOut.close();
            }
        } catch (Exception ex) {
            throw new MojoExecutionException("Error while creating 'metadata' files", ex);
        }

        try {
            dfw = new FileWriter(digestFile);
            dfw.write(sb.toString());
            dfw.close();
        } catch (Exception ex) {
            throw new MojoExecutionException("Error writing to " + digestFile.toString(), ex);
        }
        // getLog().debug("Written to " + digestFile.toString() + ":\n\n" + sb.toString());
    } else {
        getLog().info("fetch-sources-from-manifests (fetch-sources) :: skipped.");
    }
}

From source file:org.jlgranda.fede.controller.FacturaElectronicaHome.java

public void procesarUploadFile(UploadedFile file) {

    if (file == null) {
        this.addErrorMessage(I18nUtil.getMessages("action.fail"), I18nUtil.getMessages("fede.file.null"));
        return;/*from w  w  w  .  ja v a2 s  . c  o  m*/
    }

    if (subject == null) {
        this.addErrorMessage(I18nUtil.getMessages("action.fail"), I18nUtil.getMessages("fede.subject.null"));
        return;
    }
    String xml = null;
    try {
        if (file.getFileName().endsWith(".xml")) {
            byte[] content = IOUtils.toByteArray(file.getInputstream());
            xml = new String(content);
            procesarFactura(FacturaUtil.read(xml), xml, file.getFileName(), SourceType.FILE);
            this.addSuccessMessage(I18nUtil.getMessages("action.sucessfully"), "Su factura electrnica "
                    + file.getFileName() + " ahora empieza a generar valor para ud!");
            IOUtils.closeQuietly(file.getInputstream());
        } else if (file.getFileName().endsWith(".zip")) {
            ZipInputStream zis = new ZipInputStream(file.getInputstream());
            try {
                ZipEntry entry = null;
                ByteArrayOutputStream fout = null;
                while ((entry = zis.getNextEntry()) != null) {
                    if (entry.getName().endsWith(".xml")) {
                        //logger.debug("Unzipping {}", entry.getFilename());
                        fout = new ByteArrayOutputStream();
                        for (int c = zis.read(); c != -1; c = zis.read()) {
                            fout.write(c);
                        }

                        xml = new String(fout.toByteArray(), Charset.defaultCharset());
                        procesarFactura(FacturaUtil.read(xml), xml, file.getFileName(), SourceType.FILE);
                        this.addSuccessMessage(I18nUtil.getMessages("action.sucessfully"),
                                "Su factura electrnica " + entry.getName()
                                        + " ahora empieza a generar valor para ud!");
                        fout.close();
                    }
                    zis.closeEntry();
                }
                zis.close();

            } finally {
                IOUtils.closeQuietly(file.getInputstream());
                IOUtils.closeQuietly(zis);
            }
        }

    } catch (IOException | FacturaXMLReadException e) {
        this.addErrorMessage(I18nUtil.getMessages("action.fail"), e.getMessage());
    }
}