Example usage for java.util.zip ZipOutputStream STORED

List of usage examples for java.util.zip ZipOutputStream STORED

Introduction

In this page you can find the example usage for java.util.zip ZipOutputStream STORED.

Prototype

int STORED

To view the source code for java.util.zip ZipOutputStream STORED.

Click Source Link

Document

Compression method for uncompressed (STORED) entries.

Usage

From source file:JarUtil.java

/**
 * Writes all given files to the specified jar-file.
 * //w ww.j av a2  s  .c o m
 * @param files
 *            all files that should be added to the JAR file
 * @param sourceDir
 *            The parent directory containing the given files.
 * @param target
 *            The jar file which should be created
 * @param compress
 *            True when the jar file should be compressed
 * @throws FileNotFoundException
 *             when a file could not be found
 * @throws IOException
 *             when a file could not be read or the jar file could not be
 *             written to.
 */
public static void jar(File sourceDir, OutputStream target, boolean compress) throws IOException {
    File[] files = sourceDir.listFiles();
    // creates target-jar-file:
    JarOutputStream out = new JarOutputStream(target);
    if (compress) {
        out.setLevel(ZipOutputStream.DEFLATED);
    } else {
        out.setLevel(ZipOutputStream.STORED);
    }
    // create a CRC32 object:
    CRC32 crc = new CRC32();
    byte[] buffer = new byte[1024 * 1024];
    // add all files:
    int sourceDirLength = sourceDir.getAbsolutePath().length() + 1;
    for (File file : files) {
        addFile(file, out, crc, sourceDirLength, buffer);
    }
    out.close();
}

From source file:com.joliciel.talismane.machineLearning.linearsvm.LinearSVMOneVsRestModel.java

@Override
public void writeModelToStream(OutputStream outputStream) {
    try {// w w  w .j a  v  a  2 s.  c  om
        ZipOutputStream zos = new ZipOutputStream(outputStream);
        zos.setLevel(ZipOutputStream.STORED);
        int i = 0;
        for (Model model : models) {
            LOG.debug("Writing model " + i + " for outcome " + outcomes.get(i));
            ZipEntry zipEntry = new ZipEntry("model" + i);
            i++;
            zos.putNextEntry(zipEntry);
            Writer writer = new OutputStreamWriter(zos, "UTF-8");
            Writer unclosableWriter = new UnclosableWriter(writer);
            model.save(unclosableWriter);
            zos.closeEntry();
            zos.flush();
        }
    } catch (UnsupportedEncodingException e) {
        LogUtils.logError(LOG, e);
        throw new RuntimeException(e);
    } catch (IOException e) {
        LogUtils.logError(LOG, e);
        throw new RuntimeException(e);
    }
}

From source file:JarUtil.java

/**
 * Adds the given file to the specified JAR file.
 * //from   w  ww. j  ava2s  .  c o m
 * @param file
 *            the file that should be added
 * @param jarFile
 *            The JAR to which the file should be added
 * @param parentDir
 *            the parent directory of the file, this is used to calculate
 *            the path witin the JAR file. When null is given, the file will
 *            be added into the root of the JAR.
 * @param compress
 *            True when the jar file should be compressed
 * @throws FileNotFoundException
 *             when the jarFile does not exist
 * @throws IOException
 *             when a file could not be written or the jar-file could not
 *             read.
 */
public static void addToJar(File file, File jarFile, File parentDir, boolean compress)
        throws FileNotFoundException, IOException {
    File tmpJarFile = File.createTempFile("tmp", ".jar", jarFile.getParentFile());
    JarOutputStream out = new JarOutputStream(new FileOutputStream(tmpJarFile));
    if (compress) {
        out.setLevel(ZipOutputStream.DEFLATED);
    } else {
        out.setLevel(ZipOutputStream.STORED);
    }
    // copy contents of old jar to new jar:
    JarFile inputFile = new JarFile(jarFile);
    JarInputStream in = new JarInputStream(new FileInputStream(jarFile));
    CRC32 crc = new CRC32();
    byte[] buffer = new byte[512 * 1024];
    JarEntry entry = (JarEntry) in.getNextEntry();
    while (entry != null) {
        InputStream entryIn = inputFile.getInputStream(entry);
        add(entry, entryIn, out, crc, buffer);
        entryIn.close();
        entry = (JarEntry) in.getNextEntry();
    }
    in.close();
    inputFile.close();

    int sourceDirLength;
    if (parentDir == null) {
        sourceDirLength = file.getAbsolutePath().lastIndexOf(File.separatorChar) + 1;
    } else {
        sourceDirLength = file.getAbsolutePath().lastIndexOf(File.separatorChar) + 1
                - parentDir.getAbsolutePath().length();
    }
    addFile(file, out, crc, sourceDirLength, buffer);
    out.close();

    // remove old jar file and rename temp file to old one:
    if (jarFile.delete()) {
        if (!tmpJarFile.renameTo(jarFile)) {
            throw new IOException(
                    "Unable to rename temporary JAR file to [" + jarFile.getAbsolutePath() + "].");
        }
    } else {
        throw new IOException("Unable to delete old JAR file [" + jarFile.getAbsolutePath() + "].");
    }

}

From source file:fr.cirad.mgdb.exporting.markeroriented.EigenstratExportHandler.java

@Override
public void exportData(OutputStream outputStream, String sModule, List<SampleId> sampleIDs,
        ProgressIndicator progress, DBCursor markerCursor, Map<Comparable, Comparable> markerSynonyms,
        int nMinimumGenotypeQuality, int nMinimumReadDepth, Map<String, InputStream> readyToExportFiles)
        throws Exception {
    // long before = System.currentTimeMillis();

    File warningFile = File.createTempFile("export_warnings_", "");
    FileWriter warningFileWriter = new FileWriter(warningFile);
    File snpFile = null;/*from  www.j  a  v a  2s.com*/

    try {
        snpFile = File.createTempFile("snpFile", "");
        FileWriter snpFileWriter = new FileWriter(snpFile);

        ZipOutputStream zos = new ZipOutputStream(outputStream);
        if (ByteArrayOutputStream.class.isAssignableFrom(outputStream.getClass()))
            zos.setLevel(ZipOutputStream.STORED);

        if (readyToExportFiles != null)
            for (String readyToExportFile : readyToExportFiles.keySet()) {
                zos.putNextEntry(new ZipEntry(readyToExportFile));
                InputStream inputStream = readyToExportFiles.get(readyToExportFile);
                byte[] dataBlock = new byte[1024];
                int count = inputStream.read(dataBlock, 0, 1024);
                while (count != -1) {
                    zos.write(dataBlock, 0, count);
                    count = inputStream.read(dataBlock, 0, 1024);
                }
            }

        MongoTemplate mongoTemplate = MongoTemplateManager.get(sModule);
        int markerCount = markerCursor.count();

        List<Individual> individuals = getIndividualsFromSamples(sModule, sampleIDs);

        ArrayList<String> individualList = new ArrayList<String>();
        StringBuffer indFileContents = new StringBuffer();

        for (int i = 0; i < sampleIDs.size(); i++) {
            Individual individual = individuals.get(i);
            if (!individualList.contains(individual.getId())) {
                individualList.add(individual.getId());
                indFileContents
                        .append(individual.getId() + "\t" + getIndividualGenderCode(sModule, individual.getId())
                                + "\t" + (individual.getPopulation() == null ? "." : individual.getPopulation())
                                + LINE_SEPARATOR);
            }
        }

        String exportName = sModule + "_" + markerCount + "variants_" + individualList.size() + "individuals";
        zos.putNextEntry(new ZipEntry(exportName + ".ind"));
        zos.write(indFileContents.toString().getBytes());

        zos.putNextEntry(new ZipEntry(exportName + ".eigenstratgeno"));

        int avgObjSize = (Integer) mongoTemplate
                .getCollection(mongoTemplate.getCollectionName(VariantRunData.class)).getStats()
                .get("avgObjSize");
        int nChunkSize = nMaxChunkSizeInMb * 1024 * 1024 / avgObjSize;
        short nProgress = 0, nPreviousProgress = 0;
        long nLoadedMarkerCount = 0;

        while (markerCursor.hasNext()) {
            int nLoadedMarkerCountInLoop = 0;
            Map<Comparable, String> markerChromosomalPositions = new LinkedHashMap<Comparable, String>();
            boolean fStartingNewChunk = true;
            markerCursor.batchSize(nChunkSize);
            while (markerCursor.hasNext()
                    && (fStartingNewChunk || nLoadedMarkerCountInLoop % nChunkSize != 0)) {
                DBObject exportVariant = markerCursor.next();
                DBObject refPos = (DBObject) exportVariant.get(VariantData.FIELDNAME_REFERENCE_POSITION);
                markerChromosomalPositions.put((Comparable) exportVariant.get("_id"),
                        refPos.get(ReferencePosition.FIELDNAME_SEQUENCE) + ":"
                                + refPos.get(ReferencePosition.FIELDNAME_START_SITE));
                nLoadedMarkerCountInLoop++;
                fStartingNewChunk = false;
            }

            List<Comparable> currentMarkers = new ArrayList<Comparable>(markerChromosomalPositions.keySet());
            LinkedHashMap<VariantData, Collection<VariantRunData>> variantsAndRuns = MgdbDao.getSampleGenotypes(
                    mongoTemplate, sampleIDs, currentMarkers, true,
                    null /*new Sort(VariantData.FIELDNAME_REFERENCE_POSITION + "." + ChromosomalPosition.FIELDNAME_SEQUENCE).and(new Sort(VariantData.FIELDNAME_REFERENCE_POSITION + "." + ChromosomalPosition.FIELDNAME_START_SITE))*/); // query mongo db for matching genotypes
            for (VariantData variant : variantsAndRuns.keySet()) // read data and write results into temporary files (one per sample)
            {
                Comparable variantId = variant.getId();

                List<String> chromAndPos = Helper.split(markerChromosomalPositions.get(variantId), ":");
                if (chromAndPos.size() == 0)
                    LOG.warn("Chromosomal position not found for marker " + variantId);
                // LOG.debug(marker + "\t" + (chromAndPos.length == 0 ? "0" : chromAndPos[0]) + "\t" + 0 + "\t" + (chromAndPos.length == 0 ? 0l : Long.parseLong(chromAndPos[1])) + LINE_SEPARATOR);
                if (markerSynonyms != null) {
                    Comparable syn = markerSynonyms.get(variantId);
                    if (syn != null)
                        variantId = syn;
                }
                snpFileWriter.write(variantId + "\t" + (chromAndPos.size() == 0 ? "0" : chromAndPos.get(0))
                        + "\t" + 0 + "\t" + (chromAndPos.size() == 0 ? 0l : Long.parseLong(chromAndPos.get(1)))
                        + LINE_SEPARATOR);

                Map<String, List<String>> individualGenotypes = new LinkedHashMap<String, List<String>>();
                Collection<VariantRunData> runs = variantsAndRuns.get(variant);
                if (runs != null)
                    for (VariantRunData run : runs)
                        for (Integer sampleIndex : run.getSampleGenotypes().keySet()) {
                            SampleGenotype sampleGenotype = run.getSampleGenotypes().get(sampleIndex);
                            String individualId = individuals
                                    .get(sampleIDs
                                            .indexOf(new SampleId(run.getId().getProjectId(), sampleIndex)))
                                    .getId();

                            Integer gq = null;
                            try {
                                gq = (Integer) sampleGenotype.getAdditionalInfo().get(VariantData.GT_FIELD_GQ);
                            } catch (Exception ignored) {
                            }
                            if (gq != null && gq < nMinimumGenotypeQuality)
                                continue;

                            Integer dp = null;
                            try {
                                dp = (Integer) sampleGenotype.getAdditionalInfo().get(VariantData.GT_FIELD_DP);
                            } catch (Exception ignored) {
                            }
                            if (dp != null && dp < nMinimumReadDepth)
                                continue;

                            String gtCode = sampleGenotype.getCode();
                            List<String> storedIndividualGenotypes = individualGenotypes.get(individualId);
                            if (storedIndividualGenotypes == null) {
                                storedIndividualGenotypes = new ArrayList<String>();
                                individualGenotypes.put(individualId, storedIndividualGenotypes);
                            }
                            storedIndividualGenotypes.add(gtCode);
                        }

                for (int j = 0; j < individualList
                        .size(); j++ /* we use this list because it has the proper ordering*/) {
                    String individualId = individualList.get(j);
                    List<String> genotypes = individualGenotypes.get(individualId);
                    HashMap<Object, Integer> genotypeCounts = new HashMap<Object, Integer>(); // will help us to keep track of missing genotypes
                    int highestGenotypeCount = 0;
                    String mostFrequentGenotype = null;
                    if (genotypes != null)
                        for (String genotype : genotypes) {
                            if (genotype.length() == 0)
                                continue; /* skip missing genotypes */

                            int gtCount = 1 + MgdbDao.getCountForKey(genotypeCounts, genotype);
                            if (gtCount > highestGenotypeCount) {
                                highestGenotypeCount = gtCount;
                                mostFrequentGenotype = genotype;
                            }
                            genotypeCounts.put(genotype, gtCount);
                        }

                    List<String> alleles = mostFrequentGenotype == null ? new ArrayList<String>()
                            : variant.getAllelesFromGenotypeCode(mostFrequentGenotype);

                    int nOutputCode = 0;
                    if (mostFrequentGenotype == null)
                        nOutputCode = 9;
                    else
                        for (String all : Helper.split(mostFrequentGenotype, "/"))
                            if ("0".equals(all))
                                nOutputCode++;
                    if (j == 0 && variant.getKnownAlleleList().size() > 2)
                        warningFileWriter.write("- Variant " + variant.getId()
                                + " is multi-allelic. Make sure Eigenstrat genotype encoding specifications are suitable for you.\n");
                    zos.write(("" + nOutputCode).getBytes());

                    if (genotypeCounts.size() > 1 || alleles.size() > 2) {
                        if (genotypeCounts.size() > 1)
                            warningFileWriter.write("- Dissimilar genotypes found for variant "
                                    + (variantId == null ? variant.getId() : variantId) + ", individual "
                                    + individualId + ". Exporting most frequent: " + nOutputCode + "\n");
                        if (alleles.size() > 2)
                            warningFileWriter.write("- More than 2 alleles found for variant "
                                    + (variantId == null ? variant.getId() : variantId) + ", individual "
                                    + individualId + ". Exporting only the first 2 alleles.\n");
                    }
                }
                zos.write((LINE_SEPARATOR).getBytes());
            }

            if (progress.hasAborted())
                return;

            nLoadedMarkerCount += nLoadedMarkerCountInLoop;
            nProgress = (short) (nLoadedMarkerCount * 100 / markerCount);
            if (nProgress > nPreviousProgress) {
                // if (nProgress%5 == 0)
                //    LOG.info("============= exportData: " + nProgress + "% =============" + (System.currentTimeMillis() - before)/1000 + "s");
                progress.setCurrentStepProgress(nProgress);
                nPreviousProgress = nProgress;
            }
        }

        snpFileWriter.close();
        zos.putNextEntry(new ZipEntry(exportName + ".snp"));
        BufferedReader in = new BufferedReader(new FileReader(snpFile));
        String sLine;
        while ((sLine = in.readLine()) != null)
            zos.write((sLine + "\n").getBytes());
        in.close();

        warningFileWriter.close();
        if (warningFile.length() > 0) {
            zos.putNextEntry(new ZipEntry(exportName + "-REMARKS.txt"));
            int nWarningCount = 0;
            in = new BufferedReader(new FileReader(warningFile));
            while ((sLine = in.readLine()) != null) {
                zos.write((sLine + "\n").getBytes());
                nWarningCount++;
            }
            LOG.info("Number of Warnings for export (" + exportName + "): " + nWarningCount);
            in.close();
        }
        warningFile.delete();

        zos.close();
        progress.setCurrentStepProgress((short) 100);
    } finally {
        if (snpFile != null && snpFile.exists())
            snpFile.delete();
    }
}

From source file:com.jhash.oimadmin.Utils.java

public static void createJarFileFromContent(Map<String, byte[]> content, String[] fileSequence,
        String jarFileName) {//from  ww  w .  ja v  a2 s  . c  o m
    logger.trace("createJarFileFromContent({},{})", content, jarFileName);
    logger.trace("Trying to create a new jar file");
    try (ZipOutputStream jarFileOutputStream = new ZipOutputStream(new FileOutputStream(jarFileName))) {
        jarFileOutputStream.setMethod(ZipOutputStream.STORED);
        for (String jarItem : fileSequence) {
            logger.trace("Processing item {}", jarItem);
            byte[] fileContent = content.get(jarItem);
            if (fileContent == null)
                throw new NullPointerException("Failed to locate content for file " + jarItem);
            JarEntry pluginXMLFileEntry = new JarEntry(jarItem);
            pluginXMLFileEntry.setTime(System.currentTimeMillis());
            pluginXMLFileEntry.setSize(fileContent.length);
            pluginXMLFileEntry.setCompressedSize(fileContent.length);
            CRC32 crc = new CRC32();
            crc.update(fileContent);
            pluginXMLFileEntry.setCrc(crc.getValue());
            jarFileOutputStream.putNextEntry(pluginXMLFileEntry);
            jarFileOutputStream.write(fileContent);
            jarFileOutputStream.closeEntry();
        }
    } catch (Exception exception) {
        throw new OIMAdminException("Failed to create the Jar file " + jarFileName, exception);
    }
}

From source file:it.cnr.icar.eric.common.Utility.java

public static ZipOutputStream createZipOutputStream(String baseDir, String[] relativeFilePaths, OutputStream os)
        throws FileNotFoundException, IOException {
    if (baseDir.startsWith("file:/")) {
        baseDir = baseDir.substring(5);/*from  www.j a  v a 2  s.co  m*/
    }
    ZipOutputStream zipoutputstream = new ZipOutputStream(os);

    zipoutputstream.setMethod(ZipOutputStream.STORED);

    for (int i = 0; i < relativeFilePaths.length; i++) {
        File file = new File(baseDir + FILE_SEPARATOR + relativeFilePaths[i]);

        byte[] buffer = new byte[1000];

        int n;

        FileInputStream fis;

        // Calculate the CRC-32 value.  This isn't strictly necessary
        //   for deflated entries, but it doesn't hurt.

        CRC32 crc32 = new CRC32();

        fis = new FileInputStream(file);

        while ((n = fis.read(buffer)) > -1) {
            crc32.update(buffer, 0, n);
        }

        fis.close();

        // Create a zip entry.

        ZipEntry zipEntry = new ZipEntry(relativeFilePaths[i]);

        zipEntry.setSize(file.length());
        zipEntry.setTime(file.lastModified());
        zipEntry.setCrc(crc32.getValue());

        // Add the zip entry and associated data.

        zipoutputstream.putNextEntry(zipEntry);

        fis = new FileInputStream(file);

        while ((n = fis.read(buffer)) > -1) {
            zipoutputstream.write(buffer, 0, n);
        }

        fis.close();

        zipoutputstream.closeEntry();
    }

    return zipoutputstream;
}

From source file:brut.androlib.res.AndrolibResources.java

public void installFramework(File frameFile, String tag) throws AndrolibException {
    InputStream in = null;/* w ww .ja  va2  s.  c om*/
    ZipOutputStream out = null;
    try {
        ZipFile zip = new ZipFile(frameFile);
        ZipEntry entry = zip.getEntry("resources.arsc");

        if (entry == null) {
            throw new AndrolibException("Can't find resources.arsc file");
        }

        in = zip.getInputStream(entry);
        byte[] data = IOUtils.toByteArray(in);

        ARSCData arsc = ARSCDecoder.decode(new ByteArrayInputStream(data), true, true);
        publicizeResources(data, arsc.getFlagsOffsets());

        File outFile = new File(getFrameworkDir(),
                String.valueOf(arsc.getOnePackage().getId()) + (tag == null ? "" : '-' + tag) + ".apk");

        out = new ZipOutputStream(new FileOutputStream(outFile));
        out.setMethod(ZipOutputStream.STORED);
        CRC32 crc = new CRC32();
        crc.update(data);
        entry = new ZipEntry("resources.arsc");
        entry.setSize(data.length);
        entry.setCrc(crc.getValue());
        out.putNextEntry(entry);
        out.write(data);
        zip.close();
        LOGGER.info("Framework installed to: " + outFile);
    } catch (IOException ex) {
        throw new AndrolibException(ex);
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
    }
}

From source file:nl.mpi.tg.eg.frinex.rest.CsvController.java

@RequestMapping(value = "/audio_{yearString}-{monthString}-{dayString}.zip", method = RequestMethod.GET)
@ResponseBody//from  w  w  w.  j  av  a 2 s  .c om
public void getAudioZip(HttpServletResponse response,
        @PathVariable(value = "yearString", required = true) int selectedYear,
        @PathVariable(value = "monthString", required = true) int selectedMonth,
        @PathVariable(value = "dayString", required = true) int selectedDay) throws IOException {
    response.setContentType("application/zip");
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.YEAR, selectedYear);
    calendar.set(Calendar.MONTH, selectedMonth - 1);
    calendar.set(Calendar.DAY_OF_MONTH, selectedDay);
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    Date selectedDate = calendar.getTime();
    calendar.set(Calendar.DAY_OF_MONTH, selectedDay + 1);
    Date selectedEndDate = calendar.getTime();
    String selectedDateString = new SimpleDateFormat("yyyy-MM-dd").format(selectedDate);
    response.addHeader("Content-Disposition", "attachment; filename=\"audio_" + selectedDateString + ".zip\"");
    response.addHeader("Content-Transfer-Encoding", "binary");
    try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
        try (ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream)) {
            zipOutputStream.setLevel(ZipOutputStream.STORED);
            for (AudioData audioData : audioDataRepository.findAllBySubmitDateBetween(selectedDate,
                    selectedEndDate)) {
                addToZipArchive(zipOutputStream,
                        audioData.getUserId() + "_" + audioData.getScreenName() + "_"
                                + audioData.getStimulusId() + "_" + audioData.getId() + ".ogg",
                        audioData.getDataBlob());
            }
        }
        response.getOutputStream().write(outputStream.toByteArray());
        response.getOutputStream().flush();
    }
}