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:controller.servlet.Upload.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from   w  w w.j av  a  2s . com
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // Subida de los ficheros al sistema.

    UploadedFile uF;
    UploadedFileDaoImpl uFD = new UploadedFileDaoImpl();

    int numberOfCsvFiles = 0;
    int numberOfNotCsvFiles = 0;

    for (Part part : request.getParts()) {
        if (part.getName().equals("file")) {
            try (InputStream is = request.getPart(part.getName()).getInputStream()) {
                int i = is.available();
                byte[] b = new byte[i];

                if (b.length == 0) {
                    break;
                }

                is.read(b);
                String fileName = obtenerNombreFichero(part);
                String extension = FilenameUtils.getExtension(fileName);
                String path = this.getServletContext().getRealPath("");
                String ruta = path + File.separator + Path.UPLOADEDFILES_FOLDER + File.separator + fileName;
                File directorio = new File(path + File.separator + Path.UPLOADEDFILES_FOLDER);
                if (!directorio.exists()) {
                    directorio.mkdirs();
                }

                // Se sube el fichero en caso de ser zip o csv.
                if (extension.equals(Path.CSV_EXTENSION) || extension.equals(Path.ZIP_EXTENSION)) {
                    try (FileOutputStream os = new FileOutputStream(ruta)) {
                        os.write(b);
                    }
                    if (extension.equals(Path.CSV_EXTENSION)) {
                        numberOfCsvFiles++;
                    }
                } else {
                    numberOfNotCsvFiles++;
                }

                // Extraccin de los ficheros incluidos en el zip.
                if (extension.equals(Path.ZIP_EXTENSION)) {
                    ZipInputStream zis = new ZipInputStream(
                            new FileInputStream(directorio + File.separator + fileName));
                    ZipEntry eachFile;
                    while (null != (eachFile = zis.getNextEntry())) {
                        File newFile = new File(directorio + File.separator + eachFile.getName());
                        // Se guardan los csv.
                        if (FilenameUtils.getExtension(directorio + File.separator + eachFile.getName())
                                .equals(Path.CSV_EXTENSION)) {
                            numberOfCsvFiles++;
                            try (FileOutputStream fos = new FileOutputStream(newFile)) {
                                int len;
                                byte[] buffer = new byte[1024];
                                while ((len = zis.read(buffer)) > 0) {
                                    fos.write(buffer, 0, len);
                                }
                            }
                            zis.closeEntry();
                            // Insertar en BD
                            uF = new UploadedFile(0, eachFile.getName(),
                                    new java.sql.Date(new Date().getTime()), false, null);
                            uFD.createFile(uF);
                        } else {
                            numberOfNotCsvFiles++;
                        }
                    }
                    File fileToDelete = new File(
                            path + File.separator + Path.UPLOADEDFILES_FOLDER + File.separator + fileName);
                    fileToDelete.delete();
                } else {
                    // Insertar en BD
                    uF = new UploadedFile(0, fileName, new java.sql.Date(new Date().getTime()), false, null);
                    uFD.createFile(uF);
                }
            }
        }
    }

    // Asignacin de valores.
    HttpSession session = request.getSession(true);
    session.setAttribute("numberOfCsvFiles", numberOfCsvFiles);
    session.setAttribute("numberOfNotCsvFiles", numberOfNotCsvFiles);

    if (numberOfCsvFiles == 0 && numberOfNotCsvFiles == 0) {
        session.setAttribute("error", true);
    } else {
        session.setAttribute("error", false);
    }

    processRequest(request, response);
}

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

License:asdf

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

    final CaArrayFile rawFile = this.fasStub.add(AffymetrixArrayDesignFiles.TEST3_CDF);

    final ArrayDesign arrayDesign = new ArrayDesign();
    arrayDesign.setName("Test3");

    final CaArrayFileSet designFileSet = new CaArrayFileSet();
    designFileSet.add(rawFile);//from   w w  w. j  a v  a  2 s .  co m
    arrayDesign.setDesignFileSet(designFileSet);

    this.arrayDesignAction.setArrayDesign(arrayDesign);

    this.arrayDesignAction.download();

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

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

From source file:org.cloudfoundry.tools.io.zip.ZipArchiveTest.java

private List<String> getEntryNames(InputStream inputStream) throws IOException {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    FileCopyUtils.copy(inputStream, outputStream);
    ZipInputStream readInputStream = new ZipInputStream(new ByteArrayInputStream(outputStream.toByteArray()));
    List<String> entryNames = new ArrayList<String>();
    ZipEntry entry = readInputStream.getNextEntry();
    while (entry != null) {
        entryNames.add(entry.getName());
        readInputStream.closeEntry();//from w  w  w.j av a  2 s.com
        entry = readInputStream.getNextEntry();
    }
    return entryNames;
}

From source file:com.arcusys.liferay.vaadinplugin.VaadinUpdater.java

private String exctractZipFile(File vaadinZipFile, String tmpPath) throws IOException {
    byte[] buf = new byte[1024];
    String zipDestinationPath = tmpPath + fileSeparator + "unzip" + fileSeparator;
    File unzipDirectory = new File(zipDestinationPath);
    if (!unzipDirectory.mkdir()) {
        log.warn("Zip extract failed.");
        upgradeListener.updateFailed("Zip extract failed: Can not create directory " + zipDestinationPath);
        return null;
    }//w w  w.j a  va 2s . c  om

    ZipInputStream zinstream = new ZipInputStream(new FileInputStream(vaadinZipFile.getAbsolutePath()));
    ZipEntry zentry = zinstream.getNextEntry();

    while (zentry != null) {
        String entryName = zentry.getName();
        if (zentry.isDirectory()) {
            File newFile = new File(zipDestinationPath + entryName);
            if (!newFile.mkdir()) {
                break;
            }
            zentry = zinstream.getNextEntry();
            continue;
        }
        outputLog.log("Extracting " + entryName);
        FileOutputStream outstream = new FileOutputStream(
                zipDestinationPath + getFileNameWithoutVersion(entryName));
        int n;

        while ((n = zinstream.read(buf, 0, 1024)) > -1) {
            outstream.write(buf, 0, n);
        }

        outputLog.log("Successfully Extracted File Name : " + entryName);
        outstream.close();

        zinstream.closeEntry();
        zentry = zinstream.getNextEntry();
    }
    zinstream.close();

    return zipDestinationPath;
}

From source file:net.solarnetwork.node.backup.DefaultBackupManager.java

@Override
public void importBackupArchive(InputStream archive) throws IOException {
    final ZipInputStream zin = new ZipInputStream(archive);
    while (true) {
        final ZipEntry entry = zin.getNextEntry();
        if (entry == null) {
            break;
        }/*w  w  w  .  j  ava  2s  .c  o m*/
        final String path = entry.getName();
        log.debug("Restoring backup resource {}", path);
        final int providerIndex = path.indexOf('/');
        if (providerIndex != -1) {
            final String providerKey = path.substring(0, providerIndex);
            for (BackupResourceProvider provider : resourceProviders) {
                if (providerKey.equals(provider.getKey())) {
                    provider.restoreBackupResource(new BackupResource() {

                        @Override
                        public String getBackupPath() {
                            return path.substring(providerIndex + 1);
                        }

                        @Override
                        public InputStream getInputStream() throws IOException {
                            return new FilterInputStream(zin) {

                                @Override
                                public void close() throws IOException {
                                    // don't close me
                                }

                            };
                        }

                        @Override
                        public long getModificationDate() {
                            return entry.getTime();
                        }

                    });
                    break;
                }
            }
        }
    }
}

From source file:com.seer.datacruncher.services.ftp.FTPPollJobProcessor.java

@Override
public void process(Exchange exchange) throws Exception {
    String result = "";
    GenericFile file = (GenericFile) exchange.getIn().getBody();
    Message message = exchange.getOut();
    String inputFileName = file.getFileName();
    Map<String, byte[]> resultMap = new HashMap<String, byte[]>();
    if (isValidFileName(inputFileName)) {
        long schemaId = getSchemaIdUsingFileName(inputFileName);
        long userId = getUserIdFromFileName(inputFileName);
        if (!usersDao.isUserAssoicatedWithSchema(userId, schemaId)) {
            result = "User not authorized";
        } else {//w ww .j  a v a2 s  .  c o  m
            resultMap.put(inputFileName, file.getBody().toString().getBytes());
            SchemaEntity schemaEntity = schemasDao.find(schemaId);
            if (schemaEntity == null) {
                result = "No schema found in database with Id [" + schemaId + "]";
            } else {
                if (inputFileName.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 {
                        inStream = new ZipInputStream(new ByteArrayInputStream(resultMap.get(inputFileName)));
                        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);
                                result += datastreamsInput.datastreamsInput(new String(byteInput), schemaId,
                                        byteInput);
                            }
                            inStream.closeEntry();
                        }
                    } catch (IOException ex) {
                        result = "Error occured during fetch records from ZIP file.";
                    } finally {
                        if (inStream != null)
                            inStream.close();
                    }
                } else {
                    DatastreamsInput datastreamsInput = new DatastreamsInput();
                    datastreamsInput.setUploadedFileName(inputFileName);
                    result = datastreamsInput.datastreamsInput(new String(resultMap.get(inputFileName)),
                            schemaId, resultMap.get(inputFileName));
                }
            }
        }
    } else {
        result = "File Name not in specified format.";
    }

    // Store in Ftp location
    CamelContext context = exchange.getContext();
    FtpComponent component = context.getComponent("ftp", FtpComponent.class);
    FtpEndpoint<?> endpoint = (FtpEndpoint<?>) component.createEndpoint(getFTPEndPoint());

    Exchange outExchange = endpoint.createExchange();
    outExchange.getIn().setBody(result);
    outExchange.getIn().setHeader("CamelFileName", getFileNameWithoutExtensions(inputFileName) + ".txt");
    Producer producer = endpoint.createProducer();
    producer.start();
    producer.process(outExchange);
    producer.stop();
}

From source file:com.alcatel_lucent.nz.wnmsextract.reader.FileSelector.java

protected File unzip3(File zf) throws FileNotFoundException {
    //File f = null;
    String rename = zf.getAbsolutePath().replaceFirst("\\.zip", identifier + ".xml");//.replaceFirst("\\.gz", ".xml");
    File f = new File(rename);
    try {/*from   w w w  .j a v  a2 s  .c om*/
        FileInputStream fis = new FileInputStream(zf);

        ZipInputStream zin = new ZipInputStream(fis);
        ZipEntry ze;

        final byte[] content = new byte[BUFFER];

        while ((ze = zin.getNextEntry()) != null) {
            f = new File(getCalTempPath() + File.separator + ze.getName());
            FileOutputStream fos = new FileOutputStream(f);
            BufferedOutputStream bos = new BufferedOutputStream(fos, content.length);

            int n = 0;
            while (-1 != (n = zin.read(content))) {
                bos.write(content, 0, n);
            }
            bos.flush();
            bos.close();
        }

        fis.close();
        zin.close();
    } catch (IOException ioe) {
        jlog.error("Error processing Zip " + zf + " Excluding! :: " + ioe);
        return null;
    }
    //try again... what could go wrong
    /*
    if (checkMinFileSize(f) && retry_counter<MAX_UNGZIP_RETRIES){
       retry_counter++;
       f.delete();
       f = unzip2(zf);
    }
    */
    return f;
}

From source file:io.sledge.core.impl.extractor.SledgeApplicationPackageExtractor.java

@Override
public String getEnvironmentFile(String environmentName, ApplicationPackage appPackage) {
    ZipInputStream zipStream = getNewUtf8ZipInputStream(appPackage);
    ByteArrayOutputStream output = new ByteArrayOutputStream();

    try {//from  w  w  w  .  j a va2s  . c o  m
        byte[] buffer = new byte[2048];
        ZipEntry zipEntry = null;

        while ((zipEntry = zipStream.getNextEntry()) != null) {

            if (zipEntry.isDirectory()) {
                zipStream.closeEntry();
                continue;
            }

            if (getBaseName(zipEntry.getName()).equals(environmentName)) {

                int length;
                while ((length = zipStream.read(buffer, 0, buffer.length)) >= 0) {
                    output.write(buffer, 0, length);
                }

                zipStream.closeEntry();

                // Stop here because the file has been already read
                break;
            }
        }
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    } finally {
        try {
            zipStream.close();
            appPackage.getPackageFile().reset();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    return output.toString();
}

From source file:fr.fastconnect.factory.tibco.bw.fcunit.PrepareTestMojo.java

private void removeFileInZipContaining(List<String> contentFilter, File zipFile)
        throws ZipException, IOException {
    ZipScanner zs = new ZipScanner();
    zs.setSrc(zipFile);//from  w ww  .  j  ava 2  s . c om
    String[] includes = { "**/*.process" };
    zs.setIncludes(includes);
    //zs.setCaseSensitive(true);
    zs.init();
    zs.scan();

    File originalProjlib = zipFile; // to be overwritten
    File tmpProjlib = new File(zipFile.getAbsolutePath() + ".tmp"); // to read
    FileUtils.copyFile(originalProjlib, tmpProjlib);

    ZipFile listZipFile = new ZipFile(tmpProjlib);
    ZipInputStream readZipFile = new ZipInputStream(new FileInputStream(tmpProjlib));
    ZipOutputStream writeZipFile = new ZipOutputStream(new FileOutputStream(originalProjlib));

    ZipEntry zipEntry;
    boolean keep;
    while ((zipEntry = readZipFile.getNextEntry()) != null) {
        keep = true;
        for (String filter : contentFilter) {
            keep = keep && !containsString(filter, listZipFile.getInputStream(zipEntry));
        }
        //         if (!containsString("<pd:type>com.tibco.pe.core.OnStartupEventSource</pd:type>", listZipFile.getInputStream(zipEntry))
        //          && !containsString("<pd:type>com.tibco.plugin.jms.JMSTopicEventSource</pd:type>", listZipFile.getInputStream(zipEntry))) {
        if (keep) {
            writeZipFile.putNextEntry(zipEntry);
            int len = 0;
            byte[] buf = new byte[1024];
            while ((len = readZipFile.read(buf)) >= 0) {
                writeZipFile.write(buf, 0, len);
            }
            writeZipFile.closeEntry();
            //getLog().info("written");
        } else {
            getLog().info("removed " + zipEntry.getName());
        }

    }

    writeZipFile.close();
    readZipFile.close();
    listZipFile.close();

    originalProjlib.setLastModified(originalProjlib.lastModified() - 100000);
}

From source file:msearch.io.MSFilmlisteLesen.java

private boolean filmlisteJsonEinlesen(File vonDatei, ListeFilme listeFilme) {
    boolean ret = false;
    BZip2CompressorInputStream bZip2CompressorInputStream;
    JsonFactory jsonF = new JsonFactory();
    JsonParser jp = null;/*from  w  ww. ja va 2s  . c o m*/
    JsonToken jsonToken;
    String sender = "", thema = "";
    try {
        // ##########################################################
        // und jetzt die Liste einlesen, URL kann es jetzt schon nicht mehr sein!
        if (!vonDatei.exists()) {
            MSLog.fehlerMeldung(702030698, MSLog.FEHLER_ART_PROG, "MSearchIoXmlFilmlisteLesen.filmlisteLesen",
                    "Datei existiert nicht: " + vonDatei.getName());
            return false;
        }
        if (vonDatei.getName().endsWith(MSConst.FORMAT_XZ)) {
            XZInputStream xZInputStream = new XZInputStream(new FileInputStream(vonDatei));
            jp = jsonF.createParser(new InputStreamReader(xZInputStream, MSConst.KODIERUNG_UTF));
        } else if (vonDatei.getName().endsWith(MSConst.FORMAT_BZ2)) {
            bZip2CompressorInputStream = new BZip2CompressorInputStream(new FileInputStream(vonDatei));
            jp = jsonF.createParser(new InputStreamReader(bZip2CompressorInputStream, MSConst.KODIERUNG_UTF));
        } else if (vonDatei.getName().endsWith(MSConst.FORMAT_ZIP)) {
            ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(vonDatei));
            zipInputStream.getNextEntry();
            jp = jsonF.createParser(new InputStreamReader(zipInputStream, MSConst.KODIERUNG_UTF));
        } else {
            jp = jsonF.createParser(vonDatei); // geht so am schnellsten
        }
        if (jp.nextToken() != JsonToken.START_OBJECT) {
            throw new IOException("Expected data to start with an Object");
        }
        while ((jsonToken = jp.nextToken()) != null) {
            if (jsonToken == JsonToken.END_OBJECT) {
                break;
            }
            if (jp.isExpectedStartArrayToken()) {
                for (int k = 0; k < ListeFilme.MAX_ELEM; ++k) {
                    listeFilme.metaDaten[k] = jp.nextTextValue();
                }
                break;
            }
        }
        while ((jsonToken = jp.nextToken()) != null) {
            if (jsonToken == JsonToken.END_OBJECT) {
                break;
            }
            if (jp.isExpectedStartArrayToken()) {
                // sind nur die Feldbeschreibungen, brauch mer nicht
                jp.nextToken();
                break;
            }
        }
        while ((jsonToken = jp.nextToken()) != null) {
            if (jsonToken == JsonToken.END_OBJECT) {
                break;
            }
            if (jp.isExpectedStartArrayToken()) {
                DatenFilm datenFilm = new DatenFilm();
                for (int i = 0; i < DatenFilm.COLUMN_NAMES_JSON.length; ++i) {
                    datenFilm.arr[DatenFilm.COLUMN_NAMES_JSON[i]] = jp.nextTextValue();
                    /// fr die Entwicklungszeit
                    if (datenFilm.arr[DatenFilm.COLUMN_NAMES_JSON[i]] == null) {
                        datenFilm.arr[DatenFilm.COLUMN_NAMES_JSON[i]] = "";
                    }
                }
                if (datenFilm.arr[DatenFilm.FILM_SENDER_NR].equals("")) {
                    datenFilm.arr[DatenFilm.FILM_SENDER_NR] = sender;
                } else {
                    sender = datenFilm.arr[DatenFilm.FILM_SENDER_NR];
                }
                if (datenFilm.arr[DatenFilm.FILM_THEMA_NR].equals("")) {
                    datenFilm.arr[DatenFilm.FILM_THEMA_NR] = thema;
                } else {
                    thema = datenFilm.arr[DatenFilm.FILM_THEMA_NR];
                }
                listeFilme.importFilmliste(datenFilm);
            }
        }
        jp.close();
        ret = true;
    } catch (Exception ex) {
        MSLog.fehlerMeldung(468956200, MSLog.FEHLER_ART_PROG, "MSearchIoXmlFilmlisteLesen.filmlisteLesen", ex,
                "von: " + vonDatei.getName());
    }
    return ret;
}