Example usage for java.util.zip ZipOutputStream close

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

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes the ZIP output stream as well as the stream being filtered.

Usage

From source file:edu.umd.cs.marmoset.modelClasses.TestOutcome.java

/**
 * Zips the contents of a given file containing code coverage results in XML format.
 * @param file The file containing the code coverage XML results.
 * @throws IOException If there are any error reading the file.
 */// w  ww . ja v  a2 s  . co m
public void setCodeCoveralXMLResults(File file) throws IOException {
    if (!file.exists() || !file.canRead()) {
        return;
    }
    ByteArrayOutputStream actualData = new ByteArrayOutputStream();
    ZipOutputStream zipOut = new ZipOutputStream(actualData);

    ZipEntry entry = new ZipEntry("coverage");
    zipOut.putNextEntry(entry);

    BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
    try {
        int bytesRead = 0;
        byte[] bytes = new byte[2048];
        while (true) {
            int numBytes = in.read(bytes);
            if (numBytes == -1)
                break;
            zipOut.write(bytes, 0, numBytes);
            bytesRead += numBytes;
        }
        zipOut.closeEntry();
        zipOut.close();
        byte[] outbytes = actualData.toByteArray();
        //       System.out.println("outbytes.length: "+outbytes.length+
        //               " and we read: " +bytesRead+ " total bytes");
        setDetails(outbytes);
    } finally {
        in.close();
    }
}

From source file:com.esd.ps.WorkerController.java

/**
 * //from   w w  w .  j  ava2  s  . c o  m
 * 
 * @param zipFile
 * @param list
 * @return
 */
public String wrongPath(File zipFile, List<taskWithBLOBs> list) {
    logger.debug("list2:{}", list);
    try {
        FileOutputStream fos = new FileOutputStream(zipFile);
        ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(fos));
        byte[] bufs = new byte[1024 * 10];
        for (Iterator<taskWithBLOBs> iterator = list.iterator(); iterator.hasNext();) {
            taskWithBLOBs taskWithBLOBs = (taskWithBLOBs) iterator.next();
            String fileName = taskWithBLOBs.getTaskName() == null ? "Task.wav" : taskWithBLOBs.getTaskName();
            // ZIP,
            ZipEntry zipEntry = new ZipEntry(fileName);
            zos.putNextEntry(zipEntry);
            byte[] data = taskWithBLOBs.getTaskWav();
            InputStream is = new ByteArrayInputStream(data);
            // ?
            BufferedInputStream bis = new BufferedInputStream(is, 1024);
            int read;
            while ((read = bis.read(bufs)) > 0) {
                zos.write(bufs, 0, read);//
            }
            // zos.closeEntry();
            bis.close();
            is.close();
            // task
        }
        zos.close();// ,??0kb
        fos.flush();
        fos.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {

        e.printStackTrace();
    }
    return "";
}

From source file:com.funambol.framework.tools.FileArchiverTest.java

public void testAddFile() throws Throwable {

    String sourceFilename = MULTILEVELTREE + File.separator + "multilog.txt";
    String destFilename = BASE_TARGET_DIR + "addedFile.zip";

    File destFile = new File(destFilename);
    if (destFile.exists()) {
        assertTrue("Unable to delete destination file", destFile.delete());
    }//from www  . j a v a 2s. c  om

    // recursively = true, includeRoot = true
    FileArchiver instance = new FileArchiver(sourceFilename, destFilename, true, true);

    FileOutputStream outputStream = null;
    ZipOutputStream zipOutputStream = null;

    try {

        outputStream = new FileOutputStream(destFile, false);
        zipOutputStream = new ZipOutputStream(outputStream);

        PrivateAccessor.invoke(instance, "addFile",
                new Class[] { ZipOutputStream.class, String.class, File.class },
                new Object[] { zipOutputStream, "", new File(sourceFilename) });

        assertCounters(instance, 0, 1, 0, 0);
        assertDestFile(destFile, true);

    } finally {

        if (zipOutputStream != null) {
            zipOutputStream.flush();
        }
        if (outputStream != null) {
            outputStream.flush();
        }
    }

    try {
        sourceFilename = MULTILEVELTREE + File.separator + "first" + File.separator + "firstlog.zip";

        PrivateAccessor.setField(instance, "sourceFile", new File(sourceFilename));

        PrivateAccessor.invoke(instance, "addFile",
                new Class[] { ZipOutputStream.class, String.class, File.class },
                new Object[] { zipOutputStream, "", new File(sourceFilename) });

        assertCounters(instance, 0, 2, 0, 0);
        assertDestFile(destFile, true);

    } finally {
        if (zipOutputStream != null) {
            zipOutputStream.flush();
            zipOutputStream.close();
        }
        if (outputStream != null) {
            outputStream.flush();
            outputStream.close();
        }
    }

    List<String> expContent = new ArrayList<String>();
    expContent.add("multilog.txt");
    expContent.add("firstlog.zip");
    assertDestFileContent(destFile, expContent);
}

From source file:com.jayway.maven.plugins.android.phase09package.ApkMojo.java

private File removeDuplicatesFromJar(File in, List<String> duplicates) {
    String target = projectOutputDirectory.getAbsolutePath();
    File tmp = new File(target, "unpacked-embedded-jars");
    tmp.mkdirs();//  w  ww. ja  v  a2  s .  c o m
    File out = new File(tmp, in.getName());

    if (out.exists()) {
        return out;
    } else {
        try {
            out.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // Create a new Jar file
    final FileOutputStream fos;
    final ZipOutputStream jos;
    try {
        fos = new FileOutputStream(out);
        jos = new ZipOutputStream(fos);
    } catch (FileNotFoundException e1) {
        getLog().error(
                "Cannot remove duplicates : the output file " + out.getAbsolutePath() + " does not found");
        return null;
    }

    final ZipFile inZip;
    try {
        inZip = new ZipFile(in);
        Enumeration<? extends ZipEntry> entries = inZip.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            // If the entry is not a duplicate, copy.
            if (!duplicates.contains(entry.getName())) {
                // copy the entry header to jos
                jos.putNextEntry(entry);
                InputStream currIn = inZip.getInputStream(entry);
                copyStreamWithoutClosing(currIn, jos);
                currIn.close();
                jos.closeEntry();
            }
        }
    } catch (IOException e) {
        getLog().error("Cannot removing duplicates : " + e.getMessage());
        return null;
    }

    try {
        inZip.close();
        jos.close();
        fos.close();
    } catch (IOException e) {
        // ignore it.
    }
    getLog().info(in.getName() + " rewritten without duplicates : " + out.getAbsolutePath());
    return out;
}

From source file:com.funambol.framework.tools.FileArchiverTest.java

public void testAddFile_WithFilter() throws Throwable {

    String sourceFilename = MULTILEVELTREE + File.separator + "multilog.txt";
    String destFilename = BASE_TARGET_DIR + "addedFile.zip";

    File destFile = new File(destFilename);
    if (destFile.exists()) {
        assertTrue("Unable to delete destination file", destFile.delete());
    }//from  w  w w.j  av a  2 s . com

    // recursively = true, includeRoot = true
    FileArchiver instance = new FileArchiver(sourceFilename, destFilename, true, true);

    // applies a filter based on a suffix
    SuffixFileFilter fileFilter = new SuffixFileFilter("txt");
    instance.setFilter(fileFilter);

    FileOutputStream outputStream = null;
    ZipOutputStream zipOutputStream = null;

    try {

        outputStream = new FileOutputStream(destFile, false);
        zipOutputStream = new ZipOutputStream(outputStream);

        PrivateAccessor.invoke(instance, "addFile",
                new Class[] { ZipOutputStream.class, String.class, File.class },
                new Object[] { zipOutputStream, "", new File(sourceFilename) });

        assertCounters(instance, 0, 1, 0, 0);
        assertDestFile(destFile, true);

    } finally {

        if (zipOutputStream != null) {
            zipOutputStream.flush();
        }
        if (outputStream != null) {
            outputStream.flush();
        }
    }

    try {
        sourceFilename = MULTILEVELTREE + File.separator + "first" + File.separator + "firstlog.zip";

        PrivateAccessor.setField(instance, "sourceFile", new File(sourceFilename));

        PrivateAccessor.invoke(instance, "addFile",
                new Class[] { ZipOutputStream.class, String.class, File.class },
                new Object[] { zipOutputStream, "", new File(sourceFilename) });

        assertCounters(instance, 0, 1, 0, 1);
        assertDestFile(destFile, true);
    } finally {
        if (zipOutputStream != null) {
            zipOutputStream.flush();
            zipOutputStream.close();
        }
        if (outputStream != null) {
            outputStream.flush();
            outputStream.close();
        }
    }

    List<String> expContent = new ArrayList<String>();
    expContent.add("multilog.txt");
    assertDestFileContent(destFile, expContent);
}

From source file:edu.harvard.iq.dvn.core.study.StudyFileServiceBean.java

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void addIngestedFiles(Long studyId, String versionNote, List fileBeans, Long userId) {
    // if no files, then just return
    if (fileBeans.isEmpty()) {
        return;/*ww w . jav a 2 s  .  co m*/
    }

    // first some initialization
    StudyVersion studyVersion = null;
    Study study = null;
    MD5Checksum md5Checksum = new MD5Checksum();

    study = em.find(Study.class, studyId);
    studyVersion = study.getEditVersion();
    if (studyVersion.getId() == null) {
        em.persist(studyVersion);
        em.flush();
    }

    studyVersion.setVersionNote(versionNote);

    VDCUser user = userService.find(userId);

    File newDir = new File(FileUtil.getStudyFileDir(),
            study.getAuthority() + File.separator + study.getStudyId());
    if (!newDir.exists()) {
        newDir.mkdirs();
    }

    // now iterate through fileBeans
    Iterator iter = fileBeans.iterator();
    while (iter.hasNext()) {
        StudyFileEditBean fileBean = (StudyFileEditBean) iter.next();

        // for now the logic is if the DSB does not return a file, don't copy
        // over anything; this is to cover the situation with the Ingest servlet
        // that uses takes a control card file to add a dataTable to a prexisting
        // file; this will have to change if we do this two files method at the
        // time of the original upload
        // (TODO: figure out what this comment means - ? - L.A.)
        // (is this some legacy thing? - it's talking about "ingest servlet"...)
        // (did we ever have a mechanism for adding a data table to an existing
        //  tab file?? - that's actually kinda cool)

        StudyFile f = fileBean.getStudyFile();

        // So, if there is a file: let's move it to its final destination
        // in the study directory. 
        //
        // First, if it's a subsettable or network, or any other
        // kind potentially, that gets transformed on ingest: 

        File newIngestedLocationFile = null;

        if (fileBean.getIngestedSystemFileLocation() != null) {

            String originalFileType = f.getFileType();

            // 1. move ingest-created file:

            File tempIngestedFile = new File(fileBean.getIngestedSystemFileLocation());
            newIngestedLocationFile = new File(newDir, f.getFileSystemName());
            try {
                FileUtil.copyFile(tempIngestedFile, newIngestedLocationFile);
                tempIngestedFile.delete();
                if (f instanceof TabularDataFile) {
                    f.setFileType("text/tab-separated-values");
                }
                f.setFileSystemLocation(newIngestedLocationFile.getAbsolutePath());

            } catch (IOException ex) {
                throw new EJBException(ex);
            }
            // 1b. If this is a NetworkDataFile,  move the SQLite file from the temp Ingested location to the system location
            if (f instanceof NetworkDataFile) {
                File tempSQLDataFile = new File(tempIngestedFile.getParent(), FileUtil
                        .replaceExtension(tempIngestedFile.getName(), NetworkDataServiceBean.SQLITE_EXTENSION));
                File newSQLDataFile = new File(newDir,
                        f.getFileSystemName() + "." + NetworkDataServiceBean.SQLITE_EXTENSION);

                File tempNeo4jDir = new File(tempIngestedFile.getParent(), FileUtil
                        .replaceExtension(tempIngestedFile.getName(), NetworkDataServiceBean.NEO4J_EXTENSION));
                File newNeo4jDir = new File(newDir,
                        f.getFileSystemName() + "." + NetworkDataServiceBean.NEO4J_EXTENSION);

                try {
                    FileUtil.copyFile(tempSQLDataFile, newSQLDataFile);
                    FileUtils.copyDirectory(tempNeo4jDir, newNeo4jDir);
                    tempSQLDataFile.delete();
                    FileUtils.deleteDirectory(tempNeo4jDir);
                    f.setOriginalFileType(originalFileType);

                } catch (IOException ex) {
                    throw new EJBException(ex);
                }
            }

            // 2. also move original file for archiving
            File tempOriginalFile = new File(fileBean.getTempSystemFileLocation());
            File newOriginalLocationFile = new File(newDir, "_" + f.getFileSystemName());
            try {
                if (fileBean.getControlCardSystemFileLocation() != null
                        && fileBean.getControlCardType() != null) {
                    // 2a. For the control card-based ingests (SPSS and DDI), we save
                    // a zipped bundle of both the card and the raw data file
                    // (TAB-delimited or CSV):

                    FileInputStream instream = null;
                    byte[] dataBuffer = new byte[8192];

                    ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(newOriginalLocationFile));

                    // First, the control card:

                    File controlCardFile = new File(fileBean.getControlCardSystemFileLocation());

                    ZipEntry ze = new ZipEntry(controlCardFile.getName());
                    instream = new FileInputStream(controlCardFile);
                    zout.putNextEntry(ze);

                    int k = 0;
                    while ((k = instream.read(dataBuffer)) > 0) {
                        zout.write(dataBuffer, 0, k);
                        zout.flush();
                    }

                    instream.close();

                    // And then, the data file:

                    ze = new ZipEntry(tempOriginalFile.getName());
                    instream = new FileInputStream(tempOriginalFile);
                    zout.putNextEntry(ze);

                    while ((k = instream.read(dataBuffer)) > 0) {
                        zout.write(dataBuffer, 0, k);
                        zout.flush();
                    }

                    instream.close();

                    zout.close();

                    // and control card file can be deleted now:
                    controlCardFile.delete();

                    // Mime types: 
                    // These are custom, made-up types, used to identify the 
                    // type of the source data:

                    if (fileBean.getControlCardType().equals("spss")) {
                        f.setOriginalFileType("application/x-dvn-csvspss-zip");
                    } else if (fileBean.getControlCardType().equals("ddi")) {
                        f.setOriginalFileType("application/x-dvn-tabddi-zip");
                    } else {
                        logger.info("WARNING: unknown control card-based Ingest type? -- "
                                + fileBean.getControlCardType());
                        f.setOriginalFileType(originalFileType);
                    }
                    f.setMd5(md5Checksum.CalculateMD5(tempOriginalFile.getAbsolutePath()));

                } else {
                    // 2b. Otherwise, simply store the data that was used for
                    // ingest as the original:

                    FileUtil.copyFile(tempOriginalFile, newOriginalLocationFile);
                    f.setOriginalFileType(originalFileType);
                    f.setMd5(md5Checksum.CalculateMD5(newOriginalLocationFile.getAbsolutePath()));
                }
                tempOriginalFile.delete();
            } catch (IOException ex) {
                throw new EJBException(ex);
            }
        } else if (f instanceof SpecialOtherFile) {
            // "Special" OtherFiles are still OtherFiles; we just add the file
            // uploaded by the user to the study as is:

            File tempIngestedFile = new File(fileBean.getTempSystemFileLocation());
            newIngestedLocationFile = new File(newDir, f.getFileSystemName());
            try {
                FileUtil.copyFile(tempIngestedFile, newIngestedLocationFile);
                tempIngestedFile.delete();
                f.setFileSystemLocation(newIngestedLocationFile.getAbsolutePath());
                f.setMd5(md5Checksum.CalculateMD5(newIngestedLocationFile.getAbsolutePath()));
            } catch (IOException ex) {
                throw new EJBException(ex);
            }
        }

        // Finally, if the file was copied sucessfully, 
        // attach file to study version and study

        if (newIngestedLocationFile != null && newIngestedLocationFile.exists()) {

            fileBean.getFileMetadata().setStudyVersion(studyVersion);
            studyVersion.getFileMetadatas().add(fileBean.getFileMetadata());
            fileBean.getStudyFile().setStudy(study);
            // don't need to set study side, since we're no longer using persistence cache
            //study.getStudyFiles().add(fileBean.getStudyFile());
            //fileBean.addFiletoStudy(study);

            em.persist(fileBean.getStudyFile());
            em.persist(fileBean.getFileMetadata());

        } else {
            //fileBean.getStudyFile().setSubsettable(true);
            em.merge(fileBean.getStudyFile());
        }
    }
    // calcualte UNF for study version
    try {
        studyVersion.getMetadata().setUNF(new DSBWrapper().calculateUNF(studyVersion));
    } catch (IOException e) {
        throw new EJBException("Could not calculate new study UNF");
    }

    studyService.saveStudyVersion(studyVersion, user.getId());
}

From source file:org.messic.server.api.APIPlayLists.java

@Transactional
public void getPlaylistZip(User user, Long playlistSid, OutputStream os)
        throws IOException, SidNotFoundMessicException {
    MDOPlaylist mdoplaylist = daoPlaylist.get(user.getLogin(), playlistSid);
    if (mdoplaylist == null) {
        throw new SidNotFoundMessicException();
    }/*from   ww  w  .j  a  v  a2s  .c  o  m*/
    List<MDOSong> desiredSongs = mdoplaylist.getSongs();

    ZipOutputStream zos = new ZipOutputStream(os);
    // level - the compression level (0-9)
    zos.setLevel(9);

    HashMap<String, String> songs = new HashMap<String, String>();

    M3U m3u = new M3U();
    m3u.setExtensionM3U(true);
    List<Resource> resources = m3u.getResources();

    for (MDOSong song : desiredSongs) {
        if (song != null) {

            // add file
            // extract the relative name for entry purpose
            String entryName = song.getLocation();
            if (songs.get(entryName) == null) {
                Resource r = new Resource();
                r.setLocation(song.getLocation());
                r.setName(song.getName());
                resources.add(r);

                songs.put(entryName, "ok");
                // song not repeated
                ZipEntry ze = new ZipEntry(entryName);
                zos.putNextEntry(ze);
                FileInputStream in = new FileInputStream(song.calculateAbsolutePath(daoSettings.getSettings()));
                int len;
                byte buffer[] = new byte[1024];
                while ((len = in.read(buffer)) > 0) {
                    zos.write(buffer, 0, len);
                }
                in.close();
                zos.closeEntry();
            }
        }
    }

    // the last is the playlist m3u
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        m3u.writeTo(baos, "UTF8");
        // song not repeated
        ZipEntry ze = new ZipEntry(mdoplaylist.getName() + ".m3u");
        zos.putNextEntry(ze);
        byte[] bytes = baos.toByteArray();
        zos.write(bytes, 0, bytes.length);
        zos.closeEntry();
    } catch (Exception e) {
        e.printStackTrace();
    }

    zos.close();
}

From source file:com.hichinaschool.flashcards.libanki.Media.java

/**
 * Add files to a zip until over SYNC_ZIP_SIZE. Return zip data.
 * /*from  ww w  .  j a  v  a2  s  .  c o m*/
 * @return Returns a tuple with two objects. The first one is the zip file contents, the second a list with the
 *         filenames of the files inside the zip.
 */
public Pair<File, List<String>> zipAdded() {
    File f = new File(mCol.getPath().replaceFirst("collection\\.anki2$", "tmpSyncToServer.zip"));

    String sql = "select fname from log where type = " + Integer.toString(MEDIA_ADD);
    List<String> filenames = mMediaDb.queryColumn(String.class, sql, 0);
    List<String> fnames = new ArrayList<String>();

    try {
        ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(f)));
        zos.setLevel(8);

        JSONObject files = new JSONObject();
        int cnt = 0;
        long sz = 0;
        byte buffer[] = new byte[2048];
        boolean finished = true;
        for (String fname : filenames) {
            fnames.add(fname);
            File file = new File(getDir(), fname);
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file), 2048);
            ZipEntry entry = new ZipEntry(Integer.toString(cnt));
            zos.putNextEntry(entry);
            int count = 0;
            while ((count = bis.read(buffer, 0, 2048)) != -1) {
                zos.write(buffer, 0, count);
            }
            zos.closeEntry();
            bis.close();
            files.put(Integer.toString(cnt), fname);
            sz += file.length();
            if (sz > SYNC_ZIP_SIZE) {
                finished = false;
                break;
            }
            cnt += 1;
        }
        if (finished) {
            zos.putNextEntry(new ZipEntry("_finished"));
            zos.closeEntry();
        }
        zos.putNextEntry(new ZipEntry("_meta"));
        zos.write(Utils.jsonToString(files).getBytes());
        zos.close();
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }

    return new Pair<File, List<String>>(f, fnames);
}

From source file:br.org.indt.ndg.client.Service.java

/**
 *
 * @param surveyIds/*from   w  w w.j av a 2s . co m*/
 * @return
 * @throws NDGServerException
 */
public String downloadSurvey(String username, ArrayList<String> surveyIds) throws NDGServerException {

    final String SURVEY = "survey";
    String strFileContent = null;
    byte[] fileContent = null;
    ArrayList<String> arrayStrFileContent;

    try {
        arrayStrFileContent = new ArrayList<String>();

        for (int i = 0; i < surveyIds.size(); i++) {
            arrayStrFileContent.add(i, msmBD.loadSurveyFromServerToEditor(username, surveyIds.get(i)));
        }
    } catch (MSMApplicationException e) {
        e.printStackTrace();
        throw new NDGServerException(e.getErrorCode());
    } catch (Exception e) {
        e.printStackTrace();
        throw new NDGServerException(UNEXPECTED_SERVER_EXCEPTION);
    }

    File f = new File(SURVEY + ZIP);

    ZipOutputStream out = null;
    try {
        out = new ZipOutputStream(new FileOutputStream(f));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    for (int i = 0; i < surveyIds.size(); i++) {
        StringBuilder sb = new StringBuilder();
        sb.append(arrayStrFileContent.get(i));

        File zipDir = new File(SURVEY + surveyIds.get(i));

        ZipEntry e = new ZipEntry(zipDir + File.separator + "survey.xml");

        try {
            out.putNextEntry(e);
            byte[] data = sb.toString().getBytes();
            out.write(data, 0, data.length);
            out.closeEntry();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }

    try {
        out.close();
        fileContent = getBytesFromFile(f);
        strFileContent = Base64Encode.base64Encode(fileContent);

    } catch (IOException e1) {
        e1.printStackTrace();
    }

    f.delete();

    return strFileContent;
}