Example usage for java.util.zip Deflater NO_COMPRESSION

List of usage examples for java.util.zip Deflater NO_COMPRESSION

Introduction

In this page you can find the example usage for java.util.zip Deflater NO_COMPRESSION.

Prototype

int NO_COMPRESSION

To view the source code for java.util.zip Deflater NO_COMPRESSION.

Click Source Link

Document

Compression level for no compression.

Usage

From source file:org.dataconservancy.dcs.access.http.dataPackager.ZipPackageCreator.java

/**
 *
 * @param link// w w  w .j a  v a2s . c  o m
 * @return
 */

@Override
public void getPackage(String link, OutputStream stream) throws FileNotFoundException {
    zipOutputStream = new ZipOutputStream(stream);
    zipOutputStream.setLevel(Deflater.NO_COMPRESSION);

    String sipPath = cachePath + link.substring(link.lastIndexOf("/") + 1).replace(".zip", "");

    if (!new File(sipPath).exists())
        throw new FileNotFoundException("Sorry, there seems to be an error. Package does not exist.");

    ResearchObject dcp = null;
    try {
        dcp = (ResearchObject) builder.buildSip(new FileInputStream(new File(sipPath)));
    } catch (InvalidXmlException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    }

    allEntities = new HashMap<String, DcsEntity>();

    String rootId = "";
    String collectionTitle = "";

    for (DcsEntity entity : dcp.getDeliverableUnits()) {
        if (((DcsDeliverableUnit) entity).getParents().isEmpty())
            rootId = entity.getId();
        allEntities.put(entity.getId(), entity);
    }

    /************* This part of the code is used to get the tar file from SDA *****************************/
    DcsEntity tmp = allEntities.get(rootId);
    if (tmp instanceof DcsDeliverableUnit) {
        collectionTitle = ((DcsDeliverableUnit) tmp).getTitle();
    }

    String storageFormat = null;
    Collection<DcsDeliverableUnit> dus = dcp.getDeliverableUnits();

    for (DcsDeliverableUnit d : dus) {
        Collection<DcsResourceIdentifier> alternateIds = null;
        if (d.getParents() == null || d.getParents().isEmpty()) {
            alternateIds = d.getAlternateIds();
            if (alternateIds != null) {
                DcsResourceIdentifier id = null;
                Iterator<DcsResourceIdentifier> idIt = alternateIds.iterator();
                while (idIt.hasNext()) {
                    id = idIt.next();
                    if (id.getTypeId().equalsIgnoreCase("storage_format")) {
                        storageFormat = id.getIdValue();
                        System.out.println("Alternate Object ID for storage_format: " + storageFormat);
                        break;
                    }
                }

            }
        }
    }
    try {
        if (storageFormat.equalsIgnoreCase("tar")) {
            getTarFromSDA("", collectionTitle);
            try {
                zipOutputStream.putNextEntry(new ZipEntry(collectionTitle + ".tar"));
                IOUtils.copy(new FileInputStream(collectionTitle + ".tar"), zipOutputStream);
                zipOutputStream.closeEntry();

                //Close the whole Zip stream
                zipOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
            } catch (Exception e) {
                System.out.println("Something went wrong...");
            }

            return;
        }
    } catch (NullPointerException e) {
        e.printStackTrace();
    }
    /*************************************************************************************************/

    for (DcsEntity entity : dcp.getFiles())
        allEntities.put(entity.getId(), entity);

    parentChildMap = new HashMap<String, List<String>>();
    for (DcsManifestation manifestation : dcp.getManifestations()) {
        List<String> children;
        if (parentChildMap.containsKey(manifestation.getDeliverableUnit()))
            children = parentChildMap.get(manifestation.getDeliverableUnit());
        else
            children = new ArrayList<String>();
        for (DcsManifestationFile file : manifestation.getManifestationFiles())
            children.add(file.getRef().getRef());
        parentChildMap.put(manifestation.getDeliverableUnit(), children);
    }

    for (DcsDeliverableUnit du : dcp.getDeliverableUnits()) {
        for (DcsDeliverableUnitRef parent : du.getParents()) {
            List<String> children;
            if (parentChildMap.containsKey(parent.getRef()))
                children = parentChildMap.get(parent.getRef());
            else
                children = new ArrayList<String>();

            children.add(du.getId());
            parentChildMap.put(parent.getRef(), children);
        }
    }

    createZip("", rootId);
    try {
        //Add ORE file inside the folder
        String id = rootId.split("/")[rootId.split("/").length - 1];
        String oreFilePath = oreConversion(sipPath, id);
        String[] fileName = sipPath.split("/");
        zipOutputStream.putNextEntry(new ZipEntry(fileName[fileName.length - 1] + "_oaiore.xml"));
        IOUtils.copy(new FileInputStream(oreFilePath), zipOutputStream);
        zipOutputStream.closeEntry();

        zipOutputStream.putNextEntry(new ZipEntry("bagit.txt"));
        zipOutputStream.closeEntry();

        zipOutputStream.putNextEntry(new ZipEntry("manifest.txt"));
        zipOutputStream.closeEntry();

        //Close the whole Zip stream
        zipOutputStream.close();
    } catch (IOException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    }
    return;
}

From source file:com.thoughtworks.go.util.ZipUtilTest.java

@Test
void shouldZipFileContentsOnly() throws IOException {
    zipFile = zipUtil.zipFolderContents(srcDir, temporaryFolder.newFile(), Deflater.NO_COMPRESSION);
    assertThat(zipFile.isFile()).isTrue();

    zipUtil.unzip(zipFile, destDir);//  w w w.  j a v a 2 s  . c  om

    assertIsDirectory(new File(destDir, emptyDir.getName()));
    assertIsDirectory(new File(destDir, childDir1.getName()));

    File actual1 = new File(destDir, file1.getName());
    assertThat(actual1.isFile()).isTrue();
    assertThat(fileContent(actual1)).isEqualTo(fileContent(file1));

    File actual2 = new File(destDir, childDir1.getName() + File.separator + file2.getName());
    assertThat(actual2.isFile()).isTrue();
    assertThat(fileContent(actual2)).isEqualTo(fileContent(file2));
}

From source file:de.fu_berlin.inf.dpp.core.zip.FileZipper.java

private static void internalZipFiles(List<FileWrapper> files, File archive, boolean compress,
        boolean includeDirectories, long totalSize, ZipListener listener)
        throws IOException, OperationCanceledException {

    byte[] buffer = new byte[BUFFER_SIZE];

    OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(archive), BUFFER_SIZE);

    ZipOutputStream zipStream = new ZipOutputStream(outputStream);

    zipStream.setLevel(compress ? Deflater.DEFAULT_COMPRESSION : Deflater.NO_COMPRESSION);

    boolean cleanup = true;
    boolean isCanceled = false;

    StopWatch stopWatch = new StopWatch();
    stopWatch.start();/*from ww  w  .j a  v a 2  s  . c  om*/

    long totalRead = 0L;

    try {
        for (FileWrapper file : files) {
            String entryName = includeDirectories ? file.getPath() : file.getName();

            if (listener != null) {
                isCanceled = listener.update(file.getPath());
            }

            log.trace("compressing file: " + entryName);

            zipStream.putNextEntry(new ZipEntry(entryName));

            InputStream in = null;

            try {
                int read = 0;
                in = file.getInputStream();
                while (-1 != (read = in.read(buffer))) {

                    if (isCanceled) {
                        throw new OperationCanceledException(
                                "compressing of file '" + entryName + "' was canceled");
                    }

                    zipStream.write(buffer, 0, read);

                    totalRead += read;

                    if (listener != null) {
                        listener.update(totalRead, totalSize);
                    }

                }
            } finally {
                IOUtils.closeQuietly(in);
            }
            zipStream.closeEntry();
        }
        cleanup = false;
    } finally {
        IOUtils.closeQuietly(zipStream);
        if (cleanup && archive != null && archive.exists() && !archive.delete()) {
            log.warn("could not delete archive file: " + archive);
        }
    }

    stopWatch.stop();

    log.debug(String.format("created archive %s I/O: [%s]", archive.getAbsolutePath(),
            CoreUtils.throughput(archive.length(), stopWatch.getTime())));

}

From source file:org.eclipse.gemini.blueprint.test.internal.util.jar.JarUtils.java

/**
 * Creates a jar based on the given entries and manifest. This method will
 * always close the given output stream.
 * /*from   www  .ja  v a 2 s.com*/
 * @param manifest jar manifest
 * @param entries map of resources keyed by the jar entry named
 * @param outputStream output stream for writing the jar
 * @return number of byte written to the jar
 */
public static int createJar(Manifest manifest, Map entries, OutputStream outputStream) throws IOException {
    int writtenBytes = 0;

    // load manifest
    // add it to the jar
    JarOutputStream jarStream = null;

    try {
        // add a jar stream on top
        jarStream = (manifest != null ? new JarOutputStream(outputStream, manifest)
                : new JarOutputStream(outputStream));

        // select fastest level (no compression)
        jarStream.setLevel(Deflater.NO_COMPRESSION);

        // add deps
        for (Iterator iter = entries.entrySet().iterator(); iter.hasNext();) {
            Map.Entry element = (Map.Entry) iter.next();

            String entryName = (String) element.getKey();

            // safety check - all entries must start with /
            if (!entryName.startsWith(SLASH))
                entryName = SLASH + entryName;

            Resource entryValue = (Resource) element.getValue();

            // skip special/duplicate entries (like MANIFEST.MF)
            if (MANIFEST_JAR_LOCATION.equals(entryName)) {
                iter.remove();
            } else {
                // write jar entry
                writtenBytes += JarUtils.writeToJar(entryValue, entryName, jarStream);
            }
        }
    } finally {
        try {
            jarStream.flush();
        } catch (IOException ex) {
            // ignore
        }
        try {
            jarStream.finish();
        } catch (IOException ex) {
            // ignore
        }

    }

    return writtenBytes;
}

From source file:com.thoughtworks.go.util.ZipUtilTest.java

@Test
@EnabledOnOs(OS.LINUX)/*from   w ww. ja v a  2  s .c o  m*/
void shouldZipFileWhoseNameHasSpecialCharactersOnLinux() throws IOException {
    File specialFile = new File(srcDir, "$`#?@!()?-_{}^'~.+=[];,a.txt");
    FileUtils.writeStringToFile(specialFile, "specialFile", UTF_8);

    zipFile = zipUtil.zip(srcDir, temporaryFolder.newFile(), Deflater.NO_COMPRESSION);
    zipUtil.unzip(zipFile, destDir);
    File baseDir = new File(destDir, srcDir.getName());

    File actualSpecialFile = new File(baseDir, specialFile.getName());
    assertThat(actualSpecialFile.isFile()).isTrue();
    assertThat(fileContent(actualSpecialFile)).isEqualTo(fileContent(specialFile));
}

From source file:com.thoughtworks.go.util.ZipUtilTest.java

@Test
void shouldReadContentsOfAFileWhichIsInsideAZip() throws Exception {
    FileUtils.writeStringToFile(new File(srcDir, "some-file.txt"), "some-text-here", UTF_8);
    zipFile = zipUtil.zip(srcDir, temporaryFolder.newFile(), Deflater.NO_COMPRESSION);

    String someStuff = zipUtil.getFileContentInsideZip(new ZipInputStream(new FileInputStream(zipFile)),
            "some-file.txt");

    assertThat(someStuff).isEqualTo("some-text-here");
}

From source file:org.fao.geonet.services.resources.DownloadArchive.java

public Element exec(Element params, ServiceContext context) throws Exception {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    GeonetContext gc = (GeonetContext) context.getHandlerContext(Geonet.CONTEXT_NAME);
    DataManager dm = gc.getBean(DataManager.class);
    Dbms dbms = (Dbms) context.getResourceManager().open(Geonet.Res.MAIN_DB);
    UserSession session = context.getUserSession();

    String id = Utils.getIdentifierFromParameters(params, context);
    String access = Util.getParam(params, Params.ACCESS, Params.Access.PUBLIC);

    //--- resource required is public (thumbnails)
    if (access.equals(Params.Access.PUBLIC)) {
        File dir = new File(Lib.resource.getDir(context, access, id));
        String fname = Util.getParam(params, Params.FNAME);

        if (fname.contains("..")) {
            throw new BadParameterEx("Invalid character found in resource name.", fname);
        }//  w w  w .  java2s .co m

        File file = new File(dir, fname);
        return BinaryFile.encode(200, file.getAbsolutePath(), false);
    }

    //--- from here on resource required is private datafile(s)

    //--- check if disclaimer for this metadata has been displayed
    Element elData = (Element) session.getProperty(Geonet.Session.FILE_DISCLAIMER);
    if (elData == null) {
        return new Element("response");
    } else {
        String idAllowed = elData.getChildText(Geonet.Elem.ID);
        if (idAllowed == null || !idAllowed.equals(id)) {
            return new Element("response");
        }
    }

    //--- check whether notify is required
    boolean doNotify = false;
    Lib.resource.checkPrivilege(context, id, AccessManager.OPER_DOWNLOAD);
    doNotify = true;

    //--- set username for emails and logs
    String username = session.getUsername();
    if (username == null)
        username = "internet";
    String userId = session.getUserId();

    //--- get feedback/reason for download info passed in & record in 'entered'
    //      String name     = Util.getParam(params, Params.NAME);
    //      String org      = Util.getParam(params, Params.ORG);
    //      String email    = Util.getParam(params, Params.EMAIL);
    //      String comments = Util.getParam(params, Params.COMMENTS);
    Element entered = new Element("entered").addContent(params.cloneContent());

    //--- get logged in user details & record in 'userdetails'
    Element userDetails = new Element("userdetails");
    if (!username.equals("internet")) {
        Element elUser = dbms.select(
                "SELECT username, surname, name, address, state, zip, country, email, organisation FROM Users WHERE id=?",
                Integer.valueOf(userId));
        if (elUser.getChild("record") != null) {
            userDetails.addContent(elUser.getChild("record").cloneContent());
        }
    }

    //--- get metadata info
    MdInfo info = dm.getMetadataInfo(dbms, id);

    // set up zip output stream
    File zFile = File.createTempFile(username + "_" + info.uuid, ".zip");
    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zFile));

    //--- because often content has already been compressed
    out.setLevel(Deflater.NO_COMPRESSION);

    //--- now add the files chosen from the interface and record in 'downloaded'
    Element downloaded = new Element("downloaded");
    File dir = new File(Lib.resource.getDir(context, access, id));

    @SuppressWarnings("unchecked")
    List<Element> files = params.getChildren(Params.FNAME);
    for (Element elem : files) {
        String fname = elem.getText();

        if (fname.contains("..")) {
            continue;
        }

        File file = new File(dir, fname);
        if (!file.exists())
            throw new ResourceNotFoundEx(file.getAbsolutePath());

        Element fileInfo = new Element("file");

        Element details = BinaryFile.encode(200, file.getAbsolutePath(), false);
        String remoteURL = details.getAttributeValue("remotepath");
        if (remoteURL != null) {
            if (context.isDebug())
                context.debug("Downloading " + remoteURL + " to archive " + zFile.getName());
            fileInfo.setAttribute("size", "unknown");
            fileInfo.setAttribute("datemodified", "unknown");
            fileInfo.setAttribute("name", remoteURL);
            notifyAndLog(doNotify, id, info.uuid, access, username,
                    remoteURL + " (local config: " + file.getAbsolutePath() + ")", context);
            fname = details.getAttributeValue("remotefile");
        } else {
            if (context.isDebug())
                context.debug("Writing " + fname + " to archive " + zFile.getName());
            fileInfo.setAttribute("size", file.length() + "");
            fileInfo.setAttribute("name", fname);
            Date date = new Date(file.lastModified());
            fileInfo.setAttribute("datemodified", sdf.format(date));
            notifyAndLog(doNotify, id, info.uuid, access, username, file.getAbsolutePath(), context);
        }
        addFile(out, file.getAbsolutePath(), details, fname);
        downloaded.addContent(fileInfo);
    }

    //--- get metadata
    boolean forEditing = false, withValidationErrors = false, keepXlinkAttributes = false;
    Element elMd = dm.getMetadata(context, id, forEditing, withValidationErrors, keepXlinkAttributes);

    if (elMd == null)
        throw new MetadataNotFoundEx("Metadata not found - deleted?");

    //--- transform record into brief version
    String briefXslt = stylePath + Geonet.File.METADATA_BRIEF;
    Element elBrief = Xml.transform(elMd, briefXslt);

    //--- create root element for passing all the info we've gathered 
    //--- to license annex xslt generator
    Element root = new Element("root");
    elBrief.setAttribute("changedate", info.changeDate);
    elBrief.setAttribute("currdate", now());
    root.addContent(elBrief);
    root.addContent(downloaded);
    root.addContent(entered);
    root.addContent(userDetails);
    if (context.isDebug())
        context.debug("Passed to metadata-license-annex.xsl:\n " + Xml.getString(root));

    //--- create the license annex html file using the info in root element and
    //--- add it to the zip stream
    String licenseAnnexXslt = stylePath + Geonet.File.LICENSE_ANNEX_XSL;
    File licenseAnnex = File.createTempFile(username + "_" + info.uuid, ".annex");
    FileOutputStream las = new FileOutputStream(licenseAnnex);
    Xml.transform(root, licenseAnnexXslt, las);
    las.close();
    InputStream in = null;
    try {
        in = new FileInputStream(licenseAnnex);
        addFile(out, Geonet.File.LICENSE_ANNEX, in);
    } finally {
        IOUtils.closeQuietly(in);
    }

    //--- if a license is specified include any license files mirrored locally 
    //--- for inclusion
    includeLicenseFiles(context, out, root);

    //--- export the metadata as a partial mef/zip file and add that to the zip
    //--- stream FIXME: some refactoring required here to avoid metadata 
    //--- being read yet again(!) from the database by the MEF exporter
    String outmef = MEFLib.doExport(context, info.uuid, MEFLib.Format.PARTIAL.toString(), false, true, true);
    FileInputStream in2 = null;
    try {
        in2 = new FileInputStream(outmef);
        addFile(out, "metadata.zip", in2);
    } finally {
        IOUtils.closeQuietly(in2);
    }

    //--- now close the zip file and send it out
    if (out != null)
        out.close();
    return BinaryFile.encode(200, zFile.getAbsolutePath(), true);

}

From source file:org.mule.module.launcher.log4j2.LoggerContextConfigurer.java

private RollingFileAppender createRollingFileAppender(String logFilePath, String filePattern,
        String appenderName, Configuration configuration) {
    TriggeringPolicy triggeringPolicy = TimeBasedTriggeringPolicy.createPolicy("1", "true");
    RolloverStrategy rolloverStrategy = DefaultRolloverStrategy.createStrategy("30", "1", null,
            String.valueOf(Deflater.NO_COMPRESSION), configuration);

    return RollingFileAppender.createAppender(logFilePath, logFilePath + filePattern, "true", appenderName,
            "true", null, null, triggeringPolicy, rolloverStrategy, createLayout(configuration), null, null,
            null, null, configuration);/*w w  w. j a v a 2s.  c  o  m*/
}

From source file:cz.cuni.mff.ufal.AllBitstreamZipArchiveReader.java

@Override
public void generate() throws IOException, SAXException, ProcessingException {

    if (redirect != NO_REDIRECTION) {
        return;/*from w  ww. j av a 2 s. c  om*/
    }

    String name = item.getName() + ".zip";

    try {

        // first write everything to a temp file
        String tempDir = ConfigurationManager.getProperty("upload.temp.dir");
        String fn = tempDir + File.separator + "SWORD." + item.getID() + "." + UUID.randomUUID().toString()
                + ".zip";
        OutputStream outStream = new FileOutputStream(new File(fn));
        ZipArchiveOutputStream zip = new ZipArchiveOutputStream(outStream);
        zip.setCreateUnicodeExtraFields(UnicodeExtraFieldPolicy.ALWAYS);
        zip.setLevel(Deflater.NO_COMPRESSION);
        ConcurrentMap<String, AtomicInteger> usedFilenames = new ConcurrentHashMap<String, AtomicInteger>();

        Bundle[] originals = item.getBundles("ORIGINAL");
        if (needsZip64) {
            zip.setUseZip64(Zip64Mode.Always);
        }
        for (Bundle original : originals) {
            Bitstream[] bss = original.getBitstreams();
            for (Bitstream bitstream : bss) {
                String filename = bitstream.getName();
                String uniqueName = createUniqueFilename(filename, usedFilenames);
                ZipArchiveEntry ze = new ZipArchiveEntry(uniqueName);
                zip.putArchiveEntry(ze);
                InputStream is = bitstream.retrieve();
                Utils.copy(is, zip);
                zip.closeArchiveEntry();
                is.close();
            }
        }
        zip.close();

        File file = new File(fn);
        zipFileSize = file.length();

        zipInputStream = new TempFileInputStream(file);
    } catch (AuthorizeException e) {
        log.error(e.getMessage(), e);
        throw new ProcessingException("You do not have permissions to access one or more files.");
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new ProcessingException("Could not create ZIP, please download the files one by one. "
                + "The error has been stored and will be solved by our technical team.");
    }

    // Log download statistics
    for (int bitstreamID : bitstreamIDs) {
        DSpaceApi.updateFileDownloadStatistics(userID, bitstreamID);
    }

    response.setDateHeader("Last-Modified", item.getLastModified().getTime());

    // Try and make the download file name formated for each browser.
    try {
        String agent = request.getHeader("USER-AGENT");
        if (agent != null && agent.contains("MSIE")) {
            name = URLEncoder.encode(name, "UTF8");
        } else if (agent != null && agent.contains("Mozilla")) {
            name = MimeUtility.encodeText(name, "UTF8", "B");
        }
    } catch (UnsupportedEncodingException see) {
        name = "item_" + item.getID() + ".zip";
    }
    response.setHeader("Content-Disposition", "attachment;filename=" + name);

    byte[] buffer = new byte[BUFFER_SIZE];
    int length = -1;

    try {
        response.setHeader("Content-Length", String.valueOf(this.zipFileSize));

        while ((length = this.zipInputStream.read(buffer)) > -1) {
            out.write(buffer, 0, length);
        }
        out.flush();
    } finally {
        try {
            if (this.zipInputStream != null) {
                this.zipInputStream.close();
            }
            if (out != null) {
                out.close();
            }
        } catch (IOException ioe) {
            // Closing the stream threw an IOException but do we want this to propagate up to Cocoon?
            // No point since the user has already got the file contents.
            log.warn("Caught IO exception when closing a stream: " + ioe.getMessage());
        }
    }

}

From source file:org.apache.sling.tooling.support.install.impl.InstallServlet.java

private static void createJar(final File sourceDir, final File jarFile, final Manifest mf) throws IOException {
    final JarOutputStream zos = new JarOutputStream(new FileOutputStream(jarFile));
    try {//from ww w.  j  a va2s  .c o m
        zos.setLevel(Deflater.NO_COMPRESSION);
        // manifest first
        final ZipEntry anEntry = new ZipEntry(JarFile.MANIFEST_NAME);
        zos.putNextEntry(anEntry);
        mf.write(zos);
        zos.closeEntry();
        zipDir(sourceDir, zos, "");
    } finally {
        try {
            zos.close();
        } catch (final IOException ignore) {
            // ignore
        }
    }
}