Example usage for java.util.zip ZipInputStream getNextEntry

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

Introduction

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

Prototype

public ZipEntry getNextEntry() throws IOException 

Source Link

Document

Reads the next ZIP file entry and positions the stream at the beginning of the entry data.

Usage

From source file:gov.nih.nci.caarray.web.action.project.ProjectExtractsActionTest.java

@Test
public void testDownload() throws Exception {
    final CaArrayFile rawFile = this.fasStub.add(MageTabDataFiles.MISSING_TERMSOURCE_IDF);
    final CaArrayFile derivedFile = this.fasStub.add(MageTabDataFiles.MISSING_TERMSOURCE_SDRF);

    final Project p = new Project();
    p.getExperiment().setPublicIdentifier("test");
    final Extract e1 = new Extract();
    final Extract e2 = new Extract();
    final LabeledExtract le1 = new LabeledExtract();
    e1.getLabeledExtracts().add(le1);//from   w  w  w.ja v  a  2  s  . c  o  m
    final LabeledExtract le2 = new LabeledExtract();
    e2.getLabeledExtracts().add(le2);
    final Hybridization h = new Hybridization();
    le2.getHybridizations().add(h);
    final RawArrayData raw = new RawArrayData();
    h.addArrayData(raw);
    final DerivedArrayData derived = new DerivedArrayData();
    h.getDerivedDataCollection().add(derived);
    raw.setDataFile(rawFile);
    derived.setDataFile(derivedFile);

    this.action.setCurrentExtract(e1);
    this.action.setProject(p);
    assertEquals("noExtractData", this.action.download());
    this.action.setCurrentExtract(e2);

    final List<CaArrayFile> files = new ArrayList<CaArrayFile>(e2.getAllDataFiles());
    Collections.sort(files, DownloadHelper.CAARRAYFILE_NAME_COMPARATOR_INSTANCE);
    assertEquals(2, files.size());
    assertEquals("missing_term_source.idf", files.get(0).getName());
    assertEquals("missing_term_source.sdrf", files.get(1).getName());

    this.action.download();
    assertEquals("application/zip", this.mockResponse.getContentType());
    assertEquals("filename=\"caArray_test_files.zip\"", this.mockResponse.getHeader("Content-disposition"));

    final ZipInputStream zis = new ZipInputStream(
            new ByteArrayInputStream(this.mockResponse.getContentAsByteArray()));
    ZipEntry ze = zis.getNextEntry();
    assertNotNull(ze);
    assertEquals("missing_term_source.idf", ze.getName());
    ze = zis.getNextEntry();
    assertNotNull(ze);
    assertEquals("missing_term_source.sdrf", ze.getName());
    assertNull(zis.getNextEntry());
    IOUtils.closeQuietly(zis);
}

From source file:com.fdt.sdl.admin.ui.action.UploadAction.java

public void extractZip(InputStream is) throws IOException {
    ZipInputStream zis = new ZipInputStream(new BufferedInputStream(is));
    int BUFFER = 4096;
    BufferedOutputStream dest = null;
    ZipEntry entry;/*w  ww.  j  av  a  2 s .  c o m*/
    while ((entry = zis.getNextEntry()) != null) {
        // System.out.println("Extracting: " +entry);
        // out.println(entry.getName());
        String entryPath = entry.getName();
        if (entryPath.indexOf('\\') >= 0) {
            entryPath = entryPath.replace('\\', File.separatorChar);
        }
        String destFilePath = WebserverStatic.getRootDirectory() + entryPath;
        int count;
        byte data[] = new byte[BUFFER];
        // write the files to the disk
        File f = new File(destFilePath);

        if (!f.getParentFile().exists()) {
            f.getParentFile().mkdirs();
        }
        if (!f.exists()) {
            FileUtil.createNewFile(f);
            logger.info("creating file: " + f);
        } else {
            logger.info("already existing file: " + f);
            if (f.isDirectory()) {
                continue;
            }
        }

        FileOutputStream fos = new FileOutputStream(f);
        dest = new BufferedOutputStream(fos, BUFFER);
        while ((count = zis.read(data, 0, BUFFER)) != -1) {
            dest.write(data, 0, count);
        }
        dest.flush();
        dest.close();
    }
    zis.close();
}

From source file:msearch.filmlisten.MSFilmlisteLesen.java

private InputStream selectDecompressor(String source, InputStream in) throws Exception {
    if (source.endsWith(MSConst.FORMAT_XZ)) {
        in = new XZInputStream(in);
    } else if (source.endsWith(MSConst.FORMAT_BZ2)) {
        in = new BZip2CompressorInputStream(in);
    } else if (source.endsWith(MSConst.FORMAT_ZIP)) {
        ZipInputStream zipInputStream = new ZipInputStream(in);
        zipInputStream.getNextEntry();
        in = zipInputStream;/*  w  w  w  .j  av  a 2  s .c o  m*/
    }
    return in;
}

From source file:gov.nih.nci.caarray.web.action.project.ProjectSourcesActionTest.java

@Test
public void testDownload() throws Exception {
    assertEquals("noSourceData", this.action.download());

    final CaArrayFile rawFile = this.fasStub.add(MageTabDataFiles.MISSING_TERMSOURCE_IDF);
    final CaArrayFile derivedFile = this.fasStub.add(MageTabDataFiles.MISSING_TERMSOURCE_SDRF);

    final Project p = new Project();
    p.getExperiment().setPublicIdentifier("test");
    final Source so = new Source();
    final Sample s1 = new Sample();
    so.getSamples().add(s1);/*from   w w w . j  a  va 2 s  .  c  o m*/
    final Sample s2 = new Sample();
    so.getSamples().add(s2);
    final Extract e = new Extract();
    s1.getExtracts().add(e);
    s2.getExtracts().add(e);
    final LabeledExtract le = new LabeledExtract();
    e.getLabeledExtracts().add(le);
    final Hybridization h = new Hybridization();
    le.getHybridizations().add(h);
    final RawArrayData raw = new RawArrayData();
    h.addArrayData(raw);
    final DerivedArrayData derived = new DerivedArrayData();
    h.getDerivedDataCollection().add(derived);
    raw.setDataFile(rawFile);
    derived.setDataFile(derivedFile);

    this.action.setCurrentSource(so);
    this.action.setProject(p);
    final List<CaArrayFile> files = new ArrayList<CaArrayFile>(so.getAllDataFiles());
    Collections.sort(files, DownloadHelper.CAARRAYFILE_NAME_COMPARATOR_INSTANCE);
    assertEquals(2, files.size());
    assertEquals("missing_term_source.idf", files.get(0).getName());
    assertEquals("missing_term_source.sdrf", files.get(1).getName());

    this.action.download();
    assertEquals("application/zip", this.mockResponse.getContentType());
    assertEquals("filename=\"caArray_test_files.zip\"", this.mockResponse.getHeader("Content-disposition"));

    final ZipInputStream zis = new ZipInputStream(
            new ByteArrayInputStream(this.mockResponse.getContentAsByteArray()));
    ZipEntry ze = zis.getNextEntry();
    assertNotNull(ze);
    assertEquals("missing_term_source.idf", ze.getName());
    ze = zis.getNextEntry();
    assertNotNull(ze);
    assertEquals("missing_term_source.sdrf", ze.getName());
    assertNull(zis.getNextEntry());
    IOUtils.closeQuietly(zis);
}

From source file:com.ibm.liberty.starter.ProjectConstructor.java

public void initializeMap() throws IOException {
    log.log(Level.INFO, "Entering method ProjectConstructor.initializeMap()");
    InputStream skeletonIS = this.getClass().getClassLoader().getResourceAsStream(SKELETON_FILENAME);
    ZipInputStream zis = new ZipInputStream(skeletonIS);
    ZipEntry ze;//from  ww w  .j  a  v a2 s.co  m
    while ((ze = zis.getNextEntry()) != null) {
        String path = ze.getName();
        int length = 0;
        byte[] bytes = new byte[1024];
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        while ((length = zis.read(bytes)) != -1) {
            baos.write(bytes, 0, length);
        }
        putFileInMap(path, baos.toByteArray());
    }
    zis.close();
}

From source file:cz.zcu.kiv.eegdatabase.logic.controller.experiment.AddDataFileController.java

/**
 * Processing of the valid form//www  . j a  va 2s.  co m
 */
@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
        BindException bindException) throws Exception {
    log.debug("Processing form data.");
    AddDataFileCommand addDataCommand = (AddDataFileCommand) command;
    MultipartHttpServletRequest mpRequest = (MultipartHttpServletRequest) request;
    // the map containing file names mapped to files
    Map m = mpRequest.getFileMap();
    Set set = m.keySet();
    for (Object key : set) {
        MultipartFile file = (MultipartFile) m.get(key);

        if (file == null) {
            log.error("No file was uploaded!");
        } else {
            log.debug("Creating measuration with ID " + addDataCommand.getMeasurationId());
            Experiment experiment = new Experiment();
            experiment.setExperimentId(addDataCommand.getMeasurationId());
            if (file.getOriginalFilename().endsWith(".zip")) {
                ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(file.getBytes()));
                ZipEntry en = zis.getNextEntry();
                while (en != null) {
                    if (en.isDirectory()) {
                        en = zis.getNextEntry();
                        continue;
                    }
                    DataFile data = new DataFile();
                    data.setExperiment(experiment);
                    String name[] = en.getName().split("/");
                    data.setFilename(name[name.length - 1]);
                    data.setDescription(addDataCommand.getDescription());
                    data.setFileContent(Hibernate.createBlob(zis));
                    String[] partOfName = en.getName().split("[.]");
                    data.setMimetype(partOfName[partOfName.length - 1]);
                    dataFileDao.create(data);
                    en = zis.getNextEntry();
                }
            } else {
                log.debug("Creating new Data object.");
                DataFile data = new DataFile();
                data.setExperiment(experiment);

                log.debug("Original name of uploaded file: " + file.getOriginalFilename());
                String filename = file.getOriginalFilename().replace(" ", "_");
                data.setFilename(filename);

                log.debug("MIME type of the uploaded file: " + file.getContentType());
                if (file.getContentType().length() > MAX_MIMETYPE_LENGTH) {
                    int index = filename.lastIndexOf(".");
                    data.setMimetype(filename.substring(index));
                } else {
                    data.setMimetype(file.getContentType());
                }

                log.debug("Parsing the sapmling rate.");
                data.setDescription(addDataCommand.getDescription());

                log.debug("Setting the binary data to object.");
                data.setFileContent(Hibernate.createBlob(file.getBytes()));

                dataFileDao.create(data);
                log.debug("Data stored into database.");
            }
        }
    }

    log.debug("Returning MAV");
    ModelAndView mav = new ModelAndView(
            "redirect:/experiments/detail.html?experimentId=" + addDataCommand.getMeasurationId());
    return mav;
}

From source file:edu.sabanciuniv.sentilab.sare.controllers.base.documentStore.NonDerivedStoreFactory.java

protected NonDerivedStoreFactory<T> addZipPacket(T store, InputStream input) throws IOException {

    Validate.notNull(store, CannedMessages.NULL_ARGUMENT, "store");
    Validate.notNull(input, CannedMessages.NULL_ARGUMENT, "input");

    ZipInputStream zipStream = new ZipInputStream(input);
    ZipEntry zipEntry;/*  ww w . j a  va  2  s.  co  m*/
    while ((zipEntry = zipStream.getNextEntry()) != null) {
        if (!zipEntry.isDirectory()) {
            // we create a byte stream so that the input stream is not closed by the underlying methods.
            this.createSpecific(store, new ByteArrayInputStream(IOUtils.toByteArray(zipStream)),
                    FilenameUtils.getExtension(zipEntry.getName()));
        }
    }

    return this;
}

From source file:gov.nih.nci.caarray.web.action.project.ProjectHybridizationsActionTest.java

@Test
public void testDownload() throws Exception {
    assertEquals("noHybData", this.action.download());

    final CaArrayFile rawFile = this.fasStub.add(MageTabDataFiles.MISSING_TERMSOURCE_IDF);
    final CaArrayFile derivedFile = this.fasStub.add(MageTabDataFiles.MISSING_TERMSOURCE_SDRF);

    final Project p = new Project();
    p.getExperiment().setPublicIdentifier("test");
    final Hybridization h1 = new Hybridization();
    final Hybridization h2 = new Hybridization();
    final RawArrayData raw = new RawArrayData();
    h1.addArrayData(raw);//from   ww w . j  av  a2s. co  m
    final DerivedArrayData derived = new DerivedArrayData();
    h2.getDerivedDataCollection().add(derived);
    raw.setDataFile(rawFile);
    derived.setDataFile(derivedFile);

    this.action.setCurrentHybridization(h1);
    this.action.setProject(p);
    List<CaArrayFile> files = new ArrayList<CaArrayFile>(h1.getAllDataFiles());
    Collections.sort(files, DownloadHelper.CAARRAYFILE_NAME_COMPARATOR_INSTANCE);
    assertEquals(1, files.size());
    assertEquals("missing_term_source.idf", files.get(0).getName());
    files = new ArrayList<CaArrayFile>(h2.getAllDataFiles());
    Collections.sort(files, DownloadHelper.CAARRAYFILE_NAME_COMPARATOR_INSTANCE);
    assertEquals(1, files.size());
    assertEquals("missing_term_source.sdrf", files.get(0).getName());

    assertEquals(null, this.action.download());
    assertEquals("application/zip", this.mockResponse.getContentType());
    assertEquals("filename=\"caArray_test_files.zip\"", this.mockResponse.getHeader("Content-disposition"));

    final ZipInputStream zis = new ZipInputStream(
            new ByteArrayInputStream(this.mockResponse.getContentAsByteArray()));
    ZipEntry ze = zis.getNextEntry();
    assertNotNull(ze);
    assertEquals("missing_term_source.idf", ze.getName());
    ze = zis.getNextEntry();
    assertNull(zis.getNextEntry());
    IOUtils.closeQuietly(zis);
}

From source file:com.joliciel.talismane.lexicon.LexiconDeserializer.java

public PosTaggerLexicon deserializeLexiconFile(ZipInputStream zis) {
    MONITOR.startTask("deserializeLexiconFile(ZipInputStream)");
    try {//from   ww  w  . j av  a2  s .co m
        PosTaggerLexicon lexicon = null;
        try {
            ZipEntry zipEntry;
            if ((zipEntry = zis.getNextEntry()) != null) {
                LOG.debug("Scanning zip entry " + zipEntry.getName());

                ObjectInputStream in = new ObjectInputStream(zis);
                lexicon = (PosTaggerLexicon) in.readObject();
                zis.closeEntry();
                in.close();
            } else {
                throw new RuntimeException("No zip entry in input stream");
            }
        } catch (IOException ioe) {
            throw new RuntimeException(ioe);
        } catch (ClassNotFoundException cnfe) {
            throw new RuntimeException(cnfe);
        }

        return lexicon;
    } finally {
        MONITOR.endTask("deserializeLexiconFile(ZipInputStream)");
    }
}

From source file:net.sf.mzmine.modules.rawdatamethods.rawdataimport.fileformats.ZipReadTask.java

/**
 * @see java.lang.Runnable#run()//from w  ww  .  j a  v  a  2  s.c  o m
 */
public void run() {

    // Update task status
    setStatus(TaskStatus.PROCESSING);
    logger.info("Started opening compressed file " + file);

    try {

        // Name of the uncompressed file
        String newName = file.getName();
        if (newName.toLowerCase().endsWith(".zip") || newName.toLowerCase().endsWith(".gz")) {
            newName = FilenameUtils.removeExtension(newName);
        }

        // Create decompressing stream
        FileInputStream fis = new FileInputStream(file);
        InputStream is;
        long decompressedSize = 0;
        switch (fileType) {
        case ZIP:
            ZipInputStream zis = new ZipInputStream(fis);
            ZipEntry entry = zis.getNextEntry();
            newName = entry.getName();
            decompressedSize = entry.getSize();
            if (decompressedSize < 0)
                decompressedSize = 0;
            is = zis;
            break;
        case GZIP:
            is = new GZIPInputStream(fis);
            decompressedSize = (long) (file.length() * 1.5); // Ballpark a
                                                             // decompressedFile
                                                             // size so the
                                                             // GUI can show
                                                             // progress
            if (decompressedSize < 0)
                decompressedSize = 0;
            break;
        default:
            setErrorMessage("Cannot decompress file type: " + fileType);
            setStatus(TaskStatus.ERROR);
            return;
        }

        tmpDir = Files.createTempDir();
        tmpFile = new File(tmpDir, newName);
        logger.finest("Decompressing to file " + tmpFile);
        tmpFile.deleteOnExit();
        tmpDir.deleteOnExit();
        FileOutputStream ous = new FileOutputStream(tmpFile);

        // Decompress the contents
        copy = new StreamCopy();
        copy.copy(is, ous, decompressedSize);

        // Close the streams
        is.close();
        ous.close();

        if (isCanceled())
            return;

        // Find the type of the decompressed file
        RawDataFileType fileType = RawDataFileTypeDetector.detectDataFileType(tmpFile);
        logger.finest("File " + tmpFile + " type detected as " + fileType);

        if (fileType == null) {
            setErrorMessage("Could not determine the file type of file " + newName);
            setStatus(TaskStatus.ERROR);
            return;
        }

        // Run the import module on the decompressed file
        RawDataFileWriter newMZmineFile = MZmineCore.createNewFile(newName);
        decompressedOpeningTask = RawDataImportModule.createOpeningTask(fileType, project, tmpFile,
                newMZmineFile);

        if (decompressedOpeningTask == null) {
            setErrorMessage("File type " + fileType + " of file " + newName + " is not supported.");
            setStatus(TaskStatus.ERROR);
            return;
        }

        // Run the underlying task
        decompressedOpeningTask.run();

        // Delete the temporary folder
        tmpFile.delete();
        tmpDir.delete();

        if (isCanceled())
            return;

    } catch (Throwable e) {
        logger.log(Level.SEVERE, "Could not open file " + file.getPath(), e);
        setErrorMessage(ExceptionUtils.exceptionToString(e));
        setStatus(TaskStatus.ERROR);
        return;
    }

    logger.info("Finished opening compressed file " + file);

    // Update task status
    setStatus(TaskStatus.FINISHED);

}