Example usage for java.util.zip ZipInputStream closeEntry

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

Introduction

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

Prototype

public void closeEntry() throws IOException 

Source Link

Document

Closes the current ZIP entry and positions the stream for reading the next entry.

Usage

From source file:ZipTest.java

/**
 * Loads a file from the ZIP archive into the text area
 * @param name the name of the file in the archive
 *//*from ww w .j a v  a 2 s . c o  m*/
public void loadZipFile(final String name) {
    fileCombo.setEnabled(false);
    fileText.setText("");
    new SwingWorker<Void, Void>() {
        protected Void doInBackground() throws Exception {
            try {
                ZipInputStream zin = new ZipInputStream(new FileInputStream(zipname));
                ZipEntry entry;

                // find entry with matching name in archive
                while ((entry = zin.getNextEntry()) != null) {
                    if (entry.getName().equals(name)) {
                        // read entry into text area
                        Scanner in = new Scanner(zin);
                        while (in.hasNextLine()) {
                            fileText.append(in.nextLine());
                            fileText.append("\n");
                        }
                    }
                    zin.closeEntry();
                }
                zin.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        protected void done() {
            fileCombo.setEnabled(true);
        }
    }.execute();
}

From source file:io.sledge.core.impl.installer.SledgePackageConfigurer.java

private void createNewZipfileWithReplacedPlaceholders(InputStream packageStream, Path configurationPackagePath,
        Properties envProps) throws IOException {

    // For reading the original configuration package
    ZipInputStream configPackageZipStream = new ZipInputStream(new BufferedInputStream(packageStream),
            Charset.forName("UTF-8"));

    // For outputting the configured (placeholders replaced) version of the package as zip file
    File outZipFile = configurationPackagePath.toFile();
    ZipOutputStream outConfiguredZipStream = new ZipOutputStream(new FileOutputStream(outZipFile));

    ZipEntry zipEntry;/*from w  w  w  .ja va2 s  . c o  m*/
    while ((zipEntry = configPackageZipStream.getNextEntry()) != null) {

        if (zipEntry.isDirectory()) {
            configPackageZipStream.closeEntry();
            continue;
        } else {
            ByteArrayOutputStream output = new ByteArrayOutputStream();

            int length;
            byte[] buffer = new byte[2048];
            while ((length = configPackageZipStream.read(buffer, 0, buffer.length)) >= 0) {
                output.write(buffer, 0, length);
            }

            InputStream zipEntryInputStream = new BufferedInputStream(
                    new ByteArrayInputStream(output.toByteArray()));

            if (zipEntry.getName().endsWith("instance.properties")) {
                ByteArrayOutputStream envPropsOut = new ByteArrayOutputStream();
                envProps.store(envPropsOut, "Environment configurations");
                zipEntryInputStream = new BufferedInputStream(
                        new ByteArrayInputStream(envPropsOut.toByteArray()));

            } else if (isTextFile(zipEntry.getName(), zipEntryInputStream)) {
                String configuredContent = StrSubstitutor.replace(output, envProps);
                zipEntryInputStream = new BufferedInputStream(
                        new ByteArrayInputStream(configuredContent.getBytes()));
            }

            // Add to output zip file
            addToZipFile(zipEntry.getName(), zipEntryInputStream, outConfiguredZipStream);

            zipEntryInputStream.close();
            configPackageZipStream.closeEntry();
        }
    }

    outConfiguredZipStream.close();
    configPackageZipStream.close();
}

From source file:org.junitee.testngee.ant.AntTask.java

public void execute() throws BuildException {
    validateOptions();//from w  w  w.  j a v a2 s. c o m

    HttpClient client = new HttpClient();

    MultipartPostMethod method = new MultipartPostMethod(runnerUrl);

    if (null != m_isJUnit) {
        if (m_isJUnit.booleanValue()) {
            method.addParameter("isJunit", "true");
        }
    }

    //    if (null != m_verbose) {
    //      cmd.createArgument().setValue(TestNGCommandLineArgs.LOG);
    //      cmd.createArgument().setValue(m_verbose.toString());
    //    }

    if ((null != m_outputDir)) {
        if (!m_outputDir.exists()) {
            m_outputDir.mkdirs();
        }
        if (!m_outputDir.isDirectory()) {
            throw new BuildException("Output directory is not a directory: " + m_outputDir);
        }
    }

    if ((null != m_testjar)) {
        method.addParameter("testjar", m_testjar.getName());
    }

    if (null != m_groups) {
        method.addParameter("groups", m_groups);
    }

    if (m_classFilesets.size() > 0) {
        for (String file : fileset(m_classFilesets)) {
            method.addParameter("classfile", file);
        }
    }

    if (m_xmlFilesets.size() > 0) {
        for (String file : fileset(m_xmlFilesets)) {
            try {
                method.addParameter("file", new File(file));
            } catch (FileNotFoundException e) {
                throw new BuildException(e);
            }
        }
    }

    int exitValue = -1;

    try {
        client.executeMethod(method);
        InputStream in = method.getResponseBodyAsStream();
        ZipInputStream zipIn = new ZipInputStream(in);
        ZipEntry zipEntry;

        while ((zipEntry = zipIn.getNextEntry()) != null) {
            byte[] buffer = new byte[4096];
            File file = new File(m_outputDir, zipEntry.getName());
            file.getParentFile().mkdirs();
            FileOutputStream out = new FileOutputStream(file);
            int r;

            while ((r = zipIn.read(buffer)) != -1) {
                out.write(buffer, 0, r);
            }
            out.close();
            zipIn.closeEntry();
        }

        zipIn.close();
        exitValue = 0;
    } catch (IOException e) {
        throw new BuildException(e);
    }
    actOnResult(exitValue);
}

From source file:br.com.ingenieux.mojo.jbake.SeedMojo.java

private void unpackZip(File tmpZipFile) throws IOException {
    ZipInputStream zis = new ZipInputStream(new FileInputStream(tmpZipFile));
    //get the zipped file list entry
    ZipEntry ze = zis.getNextEntry();

    while (ze != null) {
        if (ze.isDirectory()) {
            ze = zis.getNextEntry();/*from   w  w  w  .ja  v a2 s  . com*/
            continue;
        }

        String fileName = stripLeadingPath(ze.getName());
        File newFile = new File(outputDirectory + File.separator + fileName);

        new File(newFile.getParent()).mkdirs();

        FileOutputStream fos = new FileOutputStream(newFile);

        IOUtils.copy(zis, fos);

        fos.close();
        ze = zis.getNextEntry();
    }

    zis.closeEntry();
    zis.close();
}

From source file:com.cloudera.recordservice.tests.ClusterConfiguration.java

/**
 * This method unzips a conf dir return through the CM api and returns the
 * path of the unzipped directory as a string
 *///from  ww w  .j  a  v a2s  .c  o  m
private String unzipConf(String zipFileName) throws IOException {
    int num = rand_.nextInt(10000000);
    String outDir = "/tmp/" + "confDir" + "_" + num + "/";
    byte[] buffer = new byte[4096];
    FileInputStream fis;
    String filename = "";
    fis = new FileInputStream(zipFileName);
    ZipInputStream zis = new ZipInputStream(fis);
    ZipEntry ze = zis.getNextEntry();
    while (ze != null) {
        filename = ze.getName();
        File unzippedFile = new File(outDir + filename);
        // Ensure that parent directories exist
        new File(unzippedFile.getParent()).mkdirs();
        FileOutputStream fos = new FileOutputStream(unzippedFile);
        int len;
        while ((len = zis.read(buffer)) > 0) {
            fos.write(buffer, 0, len);
        }
        fos.close();
        zis.closeEntry();
        ze = zis.getNextEntry();
    }
    zis.closeEntry();
    zis.close();
    fis.close();
    return outDir + "recordservice-conf/";
}

From source file:org.tonguetied.datatransfer.ExportServiceTest.java

public final void testCreateArchiveWithFiles() throws Exception {
    archiveTestDirectory = new File(USER_DIR, "testCreateArchiveWithFiles");
    FileUtils.forceMkdir(archiveTestDirectory);
    FileUtils.writeStringToFile(new File(archiveTestDirectory, "temp"), "test.value=value");
    FileUtils.writeStringToFile(new File(archiveTestDirectory, "temp_en"), "test.value=valyoo");
    assertEquals(2, archiveTestDirectory.listFiles().length);
    assertTrue(archiveTestDirectory.isDirectory());
    dataService.createArchive(archiveTestDirectory);
    assertEquals(3, archiveTestDirectory.listFiles().length);
    // examine zip file
    File[] files = archiveTestDirectory.listFiles(new FileExtensionFilter(".zip"));
    assertEquals(1, files.length);/*from   w  ww  .java  2  s.c o  m*/
    ZipInputStream zis = null;
    final String[] fileNames = { "temp", "temp_en" };
    try {
        zis = new ZipInputStream(new FileInputStream(files[0]));
        ZipEntry zipEntry = zis.getNextEntry();
        Arrays.binarySearch(fileNames, zipEntry.getName());
        zis.closeEntry();
        zipEntry = zis.getNextEntry();
        Arrays.binarySearch(fileNames, zipEntry.getName());
        zis.closeEntry();

        // confirm that there are no more files in the archive
        assertEquals(0, zis.available());
    } finally {
        IOUtils.closeQuietly(zis);
    }
}

From source file:com.silverpeas.wiki.WikiInstanciator.java

protected void createPages(File directory, String componentId) throws IOException, WikiException {
    ZipInputStream zipFile = new ZipInputStream(loader.getResourceAsStream("pages.zip"));
    ZipEntry page = zipFile.getNextEntry();
    while (page != null) {
        String pageName = page.getName();
        File newPage = new File(directory, pageName);
        if (page.isDirectory()) {
            newPage.mkdirs();/* www  . j a  v  a2 s. com*/
        } else {
            FileUtil.writeFile(newPage, new InputStreamReader(zipFile, "UTF-8"));
            PageDetail newPageDetail = new PageDetail();
            newPageDetail.setInstanceId(componentId);
            newPageDetail.setPageName(pageName.substring(0, pageName.lastIndexOf('.')));
            wikiDAO.createPage(newPageDetail);
            zipFile.closeEntry();
            page = zipFile.getNextEntry();
        }
    }
}

From source file:com.seer.datacruncher.spring.ValidateFilePopupController.java

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String idSchema = request.getParameter("idSchema");
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    MultipartFile multipartFile = multipartRequest.getFile("file");
    String resMsg = "";

    if (multipartFile.getOriginalFilename().endsWith(FileExtensionType.ZIP.getAbbreviation())) {
        // Case 1: When user upload a Zip file - All ZIP entries should be validate one by one      
        ZipInputStream inStream = null;
        try {/*from w w w .  ja va 2  s.  com*/
            inStream = new ZipInputStream(multipartFile.getInputStream());
            ZipEntry entry;
            while (!(isStreamClose(inStream)) && (entry = inStream.getNextEntry()) != null) {
                if (!entry.isDirectory()) {
                    DatastreamsInput datastreamsInput = new DatastreamsInput();
                    datastreamsInput.setUploadedFileName(entry.getName());
                    byte[] byteInput = IOUtils.toByteArray(inStream);
                    resMsg += datastreamsInput.datastreamsInput(new String(byteInput), Long.parseLong(idSchema),
                            byteInput);
                }
                inStream.closeEntry();
            }
        } catch (IOException ex) {
            resMsg = "Error occured during fetch records from ZIP file.";
        } finally {
            if (inStream != null)
                inStream.close();
        }
    } else {
        // Case 1: When user upload a single file. In this cae just validate a single stream 
        String datastream = new String(multipartFile.getBytes());
        DatastreamsInput datastreamsInput = new DatastreamsInput();
        datastreamsInput.setUploadedFileName(multipartFile.getOriginalFilename());

        resMsg = datastreamsInput.datastreamsInput(datastream, Long.parseLong(idSchema),
                multipartFile.getBytes());

    }
    String msg = resMsg.replaceAll("'", "\"").replaceAll("\\n", " ");
    msg = msg.trim();
    response.setContentType("text/html");
    ServletOutputStream out = null;
    out = response.getOutputStream();
    out.write(("{success: " + true + " , message:'" + msg + "',   " + "}").getBytes());
    out.flush();
    out.close();
    return null;
}

From source file:org.pdfgal.pdfgalweb.utils.impl.ZipUtilsImpl.java

@Override
public List<String> saveFilesFromZip(final InputStream inputStream) throws IOException {

    final List<String> result = new ArrayList<String>();

    if (inputStream != null) {
        final ZipInputStream zis = new ZipInputStream(inputStream);

        ZipEntry entry = zis.getNextEntry();

        while (entry != null) {
            final byte[] buffer = new byte[1024];
            final String fileName = this.fileUtils.getAutogeneratedName(entry.getName());
            final File file = new File(fileName);

            final FileOutputStream fos = new FileOutputStream(file);

            int len;
            while ((len = zis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }//  w  w w  . java  2  s.  c om

            fos.close();
            result.add(fileName);
            entry = zis.getNextEntry();
        }

        zis.closeEntry();
        zis.close();
    }

    return result;
}

From source file:com.seer.datacruncher.streams.ZipStreamTest.java

@Test
public void testZipStream() {
    String fileName = properties.getProperty("zip_test_stream_file_name");
    InputStream in = this.getClass().getClassLoader().getResourceAsStream(stream_file_path + fileName);
    byte[] arr = null;
    try {//from w  w w.j a v a 2 s.  c  o m
        arr = IOUtils.toByteArray(in);
    } catch (IOException e) {
        assertTrue("IOException while Zip test file reading", false);
    }

    ZipInputStream inStream = null;
    try {
        inStream = new ZipInputStream(new ByteArrayInputStream(arr));
        ZipEntry entry;
        while (!(isStreamClose(inStream)) && (entry = inStream.getNextEntry()) != null) {
            if (!entry.isDirectory()) {
                DatastreamsInput datastreamsInput = new DatastreamsInput();
                datastreamsInput.setUploadedFileName(entry.getName());
                byte[] byteInput = IOUtils.toByteArray(inStream);
                String res = datastreamsInput.datastreamsInput(null, (Long) schemaEntity.getIdSchema(),
                        byteInput, true);
                assertTrue("Zip file validation failed", Boolean.parseBoolean(res));
            }
            inStream.closeEntry();
        }
    } catch (IOException ex) {
        assertTrue("Error occured during fetch records from ZIP file.", false);
    } finally {
        if (in != null)
            try {
                in.close();
            } catch (IOException e) {
            }
    }
}