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.submit.CommandLineSubmit.java

/**
 * @param p//from ww w.ja v a2  s  .com
 * @param find
 * @param files
 * @param userProps
 * @return
 * @throws IOException
 * @throws FileNotFoundException
 */
public static MultipartPostMethod createFilePost(Properties p, FindAllFiles find, Collection<File> files,
        Properties userProps) throws IOException, FileNotFoundException {
    // ========================== assemble zip file in byte array
    // ==============================
    String loginName = userProps.getProperty("loginName");
    String classAccount = userProps.getProperty("classAccount");
    String from = classAccount;
    if (loginName != null && !loginName.equals(classAccount))
        from += "/" + loginName;
    System.out.println(" submitted by " + from);
    System.out.println();
    System.out.println("Submitting the following files");
    ByteArrayOutputStream bytes = new ByteArrayOutputStream(4096);
    byte[] buf = new byte[4096];
    ZipOutputStream zipfile = new ZipOutputStream(bytes);
    zipfile.setComment("zipfile for CommandLineTurnin, version " + VERSION);
    for (File resource : files) {
        if (resource.isDirectory())
            continue;
        String relativePath = resource.getCanonicalPath().substring(find.rootPathLength + 1);
        System.out.println(relativePath);
        ZipEntry entry = new ZipEntry(relativePath);
        entry.setTime(resource.lastModified());

        zipfile.putNextEntry(entry);
        InputStream in = new FileInputStream(resource);
        try {
            while (true) {
                int n = in.read(buf);
                if (n < 0)
                    break;
                zipfile.write(buf, 0, n);
            }
        } finally {
            in.close();
        }
        zipfile.closeEntry();

    } // for each file
    zipfile.close();

    MultipartPostMethod filePost = new MultipartPostMethod(p.getProperty("submitURL"));

    p.putAll(userProps);
    // add properties
    for (Map.Entry<?, ?> e : p.entrySet()) {
        String key = (String) e.getKey();
        String value = (String) e.getValue();
        if (!key.equals("submitURL"))
            filePost.addParameter(key, value);
    }
    filePost.addParameter("submitClientTool", "CommandLineTool");
    filePost.addParameter("submitClientVersion", VERSION);
    byte[] allInput = bytes.toByteArray();
    filePost.addPart(new FilePart("submittedFiles", new ByteArrayPartSource("submit.zip", allInput)));
    return filePost;
}

From source file:br.univali.celine.lms.utils.zip.Zip.java

public void zipDir(String zipFileName, String dir) throws Exception {
    File dirObj = new File(dir);
    if (!dirObj.isDirectory()) {
        throw new Exception(dir + " is not a directory");
    }/* ww  w  . j  a va 2 s  .  com*/

    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));

    addDir(dirObj, out, dir.length() + 1);

    out.close();

}

From source file:csns.web.controller.DownloadController.java

@RequestMapping(value = "/download", params = "submissionId")
public String downloadSubmissionFiles(@RequestParam Long submissionId, HttpServletResponse response,
        ModelMap models) throws IOException {
    Submission submission = submissionDao.getSubmission(submissionId);
    String name = submission.getAssignment().getAlias().replace(replaceRegex, "_");

    response.setContentType("application/zip");
    response.setHeader("Content-Disposition", "attachment; filename=" + name + ".zip");

    ZipOutputStream zip = new ZipOutputStream(response.getOutputStream());
    addToZip(zip, name, submission.getFiles());
    zip.close();
    return null;//from   www.j  a  va  2  s.co m
}

From source file:org.apache.brooklyn.rest.resources.BundleAndTypeResourcesTest.java

private static File createZip(Map<String, String> files) throws Exception {
    File f = Os.newTempFile("osgi", "zip");

    ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(f));

    for (Map.Entry<String, String> entry : files.entrySet()) {
        ZipEntry ze = new ZipEntry(entry.getKey());
        zip.putNextEntry(ze);/*from   w ww  . j  av a  2s  .co  m*/
        zip.write(entry.getValue().getBytes());
    }

    zip.closeEntry();
    zip.flush();
    zip.close();

    return f;
}

From source file:com.mycollab.vaadin.resources.StreamDownloadResourceSupportExtDrive.java

@Override
public InputStream getStream() {
    if (resources.size() == 1) {
        Resource res = resources.iterator().next();
        if (!(res instanceof Folder)) {
            if (res.isExternalResource()) {
                ExternalResourceService service = ResourceUtils
                        .getExternalResourceService(ResourceUtils.getType(res));
                return service.download(ResourceUtils.getExternalDrive(res), res.getPath());
            } else {
                return resourceService.getContentStream(res.getPath());
            }/*from w ww.j  a v a  2s .  c o  m*/
        }
    }

    final PipedInputStream inStream = new PipedInputStream();
    final PipedOutputStream outStream;

    try {
        outStream = new PipedOutputStream(inStream);
    } catch (IOException ex) {
        LOG.error("Can not create outstream file", ex);
        return null;
    }

    Thread threadExport = new MyCollabThread(new Runnable() {
        @Override
        public void run() {
            try {
                ZipOutputStream zipOutStream = new ZipOutputStream(outStream);
                zipResource(zipOutStream, resources);
                zipOutStream.close();
                outStream.close();
            } catch (Exception e) {
                LOG.error("Error while saving content stream", e);
            }
        }
    });

    threadExport.start();
    return inStream;
}

From source file:com.esofthead.mycollab.vaadin.resources.StreamDownloadResourceSupportExtDrive.java

@Override
public InputStream getStream() {
    if (resources.size() == 1) {
        Resource res = resources.iterator().next();
        if (res.isExternalResource()) {
            ExternalResourceService service = ResourceUtils
                    .getExternalResourceService(ResourceUtils.getType(res));
            return service.download(ResourceUtils.getExternalDrive(res), res.getPath());
        } else {//w w w. j a v  a 2  s  . c om
            return resourceService.getContentStream(res.getPath());
        }
    }

    final PipedInputStream inStream = new PipedInputStream();
    final PipedOutputStream outStream;

    try {
        outStream = new PipedOutputStream(inStream);
    } catch (IOException ex) {
        LOG.error("Can not create outstream file", ex);
        return null;
    }

    Thread threadExport = new MyCollabThread(new Runnable() {

        @Override
        public void run() {
            try {
                ZipOutputStream zipOutStream = new ZipOutputStream(outStream);
                zipResource(zipOutStream, resources);
                zipOutStream.close();
                outStream.close();
            } catch (Exception e) {
                LOG.error("Error while saving content stream", e);
            }
        }
    });

    threadExport.start();

    return inStream;
}

From source file:csns.web.controller.DownloadController.java

@RequestMapping(value = "/download", params = "folderId")
public String downloadFolderFiles(@RequestParam Long folderId, HttpServletResponse response, ModelMap models)
        throws IOException {
    File folder = fileDao.getFile(folderId);
    response.setContentType("application/zip");
    response.setHeader("Content-Disposition", "attachment; filename=" + folder.getName() + ".zip");
    ZipOutputStream zip = new ZipOutputStream(response.getOutputStream());
    addToZip(zip, folder.getName(), fileDao.listFiles(folder));
    zip.close();

    String username = SecurityUtils.isAnonymous() ? "guest" : SecurityUtils.getUser().getUsername();
    logger.info(username + " downloaded folder " + folderId);

    return null;//from  w w w  .j ava2  s  . co  m
}

From source file:com.asual.summer.bundle.BundleDescriptorMojo.java

public void execute() throws MojoExecutionException {

    try {//  w  w  w  .jav a2 s  .  c  om

        String webXml = "WEB-INF/web.xml";
        File warDir = new File(buildDirectory, finalName);
        File warFile = new File(buildDirectory, finalName + ".war");
        File webXmlFile = new File(warDir, webXml);
        FileUtils.copyFile(new File(basedir, "src/main/webapp/" + webXml), webXmlFile);

        Configuration[] configurations = new Configuration[] { new WebXmlConfiguration(),
                new FragmentConfiguration() };
        WebAppContext context = new WebAppContext();
        context.setDefaultsDescriptor(null);
        context.setDescriptor(webXmlFile.getAbsolutePath());
        context.setConfigurations(configurations);

        for (Artifact artifact : artifacts) {
            JarInputStream in = new JarInputStream(new FileInputStream(artifact.getFile()));
            while (true) {
                ZipEntry entry = in.getNextEntry();
                if (entry != null) {
                    if ("META-INF/web-fragment.xml".equals(entry.getName())) {
                        Resource fragment = Resource
                                .newResource("file:" + artifact.getFile().getAbsolutePath());
                        context.getMetaData().addFragment(fragment, Resource
                                .newResource("jar:" + fragment.getURL() + "!/META-INF/web-fragment.xml"));
                        context.getMetaData().addWebInfJar(fragment);
                    }
                } else {
                    break;
                }
            }
            in.close();
        }

        for (int i = 0; i < configurations.length; i++) {
            configurations[i].preConfigure(context);
        }

        for (int i = 0; i < configurations.length; i++) {
            configurations[i].configure(context);
        }

        for (int i = 0; i < configurations.length; i++) {
            configurations[i].postConfigure(context);
        }

        Descriptor descriptor = context.getMetaData().getWebXml();
        Node root = descriptor.getRoot();

        List<Object> nodes = new ArrayList<Object>();
        List<FragmentDescriptor> fragmentDescriptors = context.getMetaData().getOrderedFragments();
        for (FragmentDescriptor fd : fragmentDescriptors) {
            for (int i = 0; i < fd.getRoot().size(); i++) {
                Object el = fd.getRoot().get(i);
                if (el instanceof Node && ((Node) el).getTag().matches("^name|ordering$")) {
                    continue;
                }
                nodes.add(el);
            }
        }
        root.addAll(nodes);

        BufferedWriter writer = new BufferedWriter(new FileWriter(new File(warDir, webXml)));
        writer.write(root.toString());
        writer.close();

        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(warFile));
        zip(warDir, warDir, zos);
        zos.close();

    } catch (Exception e) {
        getLog().error(e.getMessage(), e);
        throw new MojoExecutionException(e.getMessage(), e);
    }
}

From source file:Main.java

public void doZip(String filename, String zipfilename) throws Exception {
    byte[] buf = new byte[1024];
    FileInputStream fis = new FileInputStream(filename);
    fis.read(buf, 0, buf.length);//from w  ww  .ja v a2 s . c  o m

    CRC32 crc = new CRC32();
    ZipOutputStream s = new ZipOutputStream((OutputStream) new FileOutputStream(zipfilename));
    s.setLevel(6);

    ZipEntry entry = new ZipEntry(filename);
    entry.setSize((long) buf.length);
    crc.reset();
    crc.update(buf);
    entry.setCrc(crc.getValue());
    s.putNextEntry(entry);
    s.write(buf, 0, buf.length);
    s.finish();
    s.close();
}

From source file:S3DataManager.java

public UploadToS3Output uploadSourceToS3(Run<?, ?> build, Launcher launcher, TaskListener listener)
        throws Exception {
    Validation.checkS3SourceUploaderConfig(projectName, workspace);

    String localfileName = this.projectName + "-" + "source.zip";
    String sourceFilePath = workspace.getRemote();
    String zipFilePath = sourceFilePath.substring(0, sourceFilePath.lastIndexOf(File.separator))
            + File.separator + localfileName;
    File zipFile = new File(zipFilePath);

    if (!zipFile.getParentFile().exists()) {
        boolean dirMade = zipFile.getParentFile().mkdirs();
        if (!dirMade) {
            throw new Exception("Unable to create directory: " + zipFile.getParentFile().getAbsolutePath());
        }//from  w  w  w .j  a v a 2s .c o m
    }

    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFilePath));
    try {
        zipSource(sourceFilePath, out, sourceFilePath);
    } finally {
        out.close();
    }

    File sourceZipFile = new File(zipFilePath);
    PutObjectRequest putObjectRequest = new PutObjectRequest(s3InputBucket, s3InputKey, sourceZipFile);

    // Add MD5 checksum as S3 Object metadata
    String zipFileMD5;
    try (FileInputStream fis = new FileInputStream(zipFilePath)) {
        zipFileMD5 = new String(org.apache.commons.codec.binary.Base64.encodeBase64(DigestUtils.md5(fis)),
                "UTF-8");
    }
    ObjectMetadata objectMetadata = new ObjectMetadata();
    objectMetadata.setContentMD5(zipFileMD5);
    objectMetadata.setContentLength(sourceZipFile.length());
    putObjectRequest.setMetadata(objectMetadata);

    LoggingHelper.log(listener, "Uploading code to S3 at location " + putObjectRequest.getBucketName() + "/"
            + putObjectRequest.getKey() + ". MD5 checksum is " + zipFileMD5);
    PutObjectResult putObjectResult = s3Client.putObject(putObjectRequest);

    return new UploadToS3Output(putObjectRequest.getBucketName() + "/" + putObjectRequest.getKey(),
            putObjectResult.getVersionId());
}