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:org.jahia.services.content.rules.Service.java

private Map<Object, Object> prepareSiteImport(File i, String filename) throws IOException {
    Map<Object, Object> importInfos = new HashMap<Object, Object>();
    importInfos.put("importFile", i);
    importInfos.put("importFileName", filename);
    importInfos.put("selected", Boolean.TRUE);
    if (filename.endsWith(".xml")) {
        importInfos.put("type", "xml");
    } else {// w w w  .jav  a  2  s.  c  o  m
        ZipEntry z;
        ZipInputStream zis2 = new ZipInputStream(new BufferedInputStream(new FileInputStream(i)));
        boolean isSite = false;
        boolean isLegacySite = false;
        try {
            while ((z = zis2.getNextEntry()) != null) {
                if ("site.properties".equals(z.getName())) {
                    Properties p = new Properties();
                    p.load(zis2);
                    zis2.closeEntry();
                    importInfos.putAll(p);
                    importInfos.put("templates",
                            importInfos.containsKey("templatePackageName")
                                    ? importInfos.get("templatePackageName")
                                    : "");
                    importInfos.put("oldsitekey", importInfos.get("sitekey"));
                    isSite = true;
                } else if (z.getName().startsWith("export_")) {
                    isLegacySite = true;
                }
            }
        } finally {
            IOUtils.closeQuietly(zis2);
        }
        importInfos.put("isSite", Boolean.valueOf(isSite));
        // todo import ga parameters
        if (isSite || isLegacySite) {
            importInfos.put("type", "site");
            if (!importInfos.containsKey("sitekey")) {
                importInfos.put("sitekey", "");
                importInfos.put("siteservername", "");
                importInfos.put("sitetitle", "");
                importInfos.put("description", "");
                importInfos.put("mixLanguage", "false");
                importInfos.put("templates", "");
                importInfos.put("siteKeyExists", Boolean.TRUE);
                importInfos.put("siteServerNameExists", Boolean.TRUE);
            } else {
                try {
                    importInfos.put("siteKeyExists",
                            Boolean.valueOf(
                                    sitesService.getSiteByKey((String) importInfos.get("sitekey")) != null
                                            || "".equals(importInfos.get("sitekey"))));
                    importInfos.put("siteServerNameExists",
                            Boolean.valueOf(
                                    sitesService.getSite((String) importInfos.get("siteservername")) != null
                                            || "".equals(importInfos.get("siteservername"))));
                } catch (JahiaException e) {
                    logger.error(e.getMessage(), e);
                }
            }
        } else {
            importInfos.put("type", "files");
        }

    }
    return importInfos;
}

From source file:net.ymate.platform.core.beans.impl.DefaultBeanLoader.java

private List<Class<?>> __doFindClassByZip(URL zipUrl, IBeanFilter filter) throws Exception {
    List<Class<?>> _returnValue = new ArrayList<Class<?>>();
    ZipInputStream _zipStream = null;
    try {/*  w ww . j ava  2  s .c o m*/
        String _zipFilePath = zipUrl.toString();
        if (_zipFilePath.indexOf('!') > 0) {
            _zipFilePath = StringUtils.substringBetween(zipUrl.toString(), "zip:", "!");
        } else {
            _zipFilePath = StringUtils.substringAfter(zipUrl.toString(), "zip:");
        }
        File _zipFile = new File(_zipFilePath);
        if (!__doCheckExculedFile(_zipFile.getName())) {
            _zipStream = new ZipInputStream(new FileInputStream(_zipFile));
            ZipEntry _zipEntry = null;
            while (null != (_zipEntry = _zipStream.getNextEntry())) {
                if (!_zipEntry.isDirectory()) {
                    if (_zipEntry.getName().endsWith(".class") && _zipEntry.getName().indexOf('$') < 0) {
                        String _className = StringUtils.substringBefore(_zipEntry.getName().replace("/", "."),
                                ".class");
                        __doAddClass(_returnValue, __doLoadClass(_className), filter);
                    }
                }
                _zipStream.closeEntry();
            }
        }
    } finally {
        if (_zipStream != null) {
            try {
                _zipStream.close();
            } catch (IOException ignored) {
            }
        }
    }
    return _returnValue;
}

From source file:org.nuxeo.keynote.ZippedKeynoteToPDFUtils.java

public boolean isZippedKeynote() throws Exception {

    if (status != kSTATUS_UNKNOWN) {
        return status == kSTATUS_KEYNOTE;
    }//from  www .ja  v a  2s.  c o  m

    status = kSTATUS_NOT_KEYNOTE;
    if (blob != null && blob.getMimeType().equalsIgnoreCase("application/zip")) {
        ZipInputStream zis = new ZipInputStream(blob.getStream());
        ZipEntry zentry = null;
        String name;

        /* We are reading from a stream, not a file, so we can't make sure
         * it reads the "first" file, and can't rely on the fact that the
         * "zip contains a Keynote file if one of the 2 first elements
         * is a .key file (second can be a __MACOS folder).
         * The workaround is to find an item which:
         *      -> Is a directory (a Keynote presentation is a directory)
         *      -> The name ends with .key/
         *      -> And it contains one single "/" (just in case the Keynote
         *         format contains sub-.key files. Never seen that, but who
         *         knows and it is easy to test, not impacting performance)
         */
        do {
            zentry = zis.getNextEntry();
            if (zentry != null) {
                name = zentry.getName();
                if (zentry.isDirectory() && name.endsWith(".key/")
                        && name.indexOf('/') == (name.length() - 1)) {
                    status = kSTATUS_KEYNOTE;
                }
                zis.closeEntry();
            }
        } while (zentry != null && status == kSTATUS_NOT_KEYNOTE);
        zis.close();
    }

    return status == kSTATUS_KEYNOTE;
}

From source file:org.geoserver.wfs.response.ShapeZipTest.java

private void checkShapefileIntegrity(String[] typeNames, final InputStream in) throws IOException {
    ZipInputStream zis = new ZipInputStream(in);
    ZipEntry entry = null;//from w  ww.j  a  va2s .  c o m

    final String[] extensions = new String[] { ".shp", ".shx", ".dbf", ".prj", ".cst" };
    Set names = new HashSet();
    for (String name : typeNames) {
        for (String extension : extensions) {
            names.add(name + extension);
        }
    }
    while ((entry = zis.getNextEntry()) != null) {
        final String name = entry.getName();
        if (name.endsWith(".txt")) {
            // not part of the shapefile, it's the request dump
            continue;
        }
        assertTrue("Missing " + name, names.contains(name));
        names.remove(name);
        zis.closeEntry();
    }
    zis.close();
}

From source file:controller.servlet.Upload.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from   w w w. j a  v  a2s.co m
 * @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.pnnl.goss.gridappsd.app.AppManagerImpl.java

@Override
public void registerApp(AppInfo appInfo, byte[] appPackage) throws Exception {
    System.out.println("REGISTER REQUEST RECEIVED ");
    // appPackage should be received as a zip file. extract this to the apps
    // directory, and write appinfo to a json file under config/
    File appHomeDir = getAppConfigDirectory();
    if (!appHomeDir.exists()) {
        appHomeDir.mkdirs();//from  w  w w. j a  va 2 s  . com
        if (!appHomeDir.exists()) {
            // if it still doesn't exist throw an error
            throw new Exception(
                    "App home directory does not exist and cannot be created " + appHomeDir.getAbsolutePath());
        }
    }
    System.out.println("HOME DIR " + appHomeDir.getAbsolutePath());
    // create a directory for the app
    File newAppDir = new File(appHomeDir.getAbsolutePath() + File.separator + appInfo.getId());
    if (newAppDir.exists()) {
        throw new Exception("App " + appInfo.getId() + " already exists");
    }

    try {
        newAppDir.mkdirs();
        // Extract zip file into new app dir
        ZipInputStream zipIn = new ZipInputStream(new ByteArrayInputStream(appPackage));
        ZipEntry entry = zipIn.getNextEntry();
        // iterates over entries in the zip file and write to dir
        while (entry != null) {
            String filePath = newAppDir + File.separator + entry.getName();
            if (!entry.isDirectory()) {
                // if the entry is a file, extracts it
                extractFile(zipIn, filePath);
            } else {
                // if the entry is a directory, make the directory
                File dir = new File(filePath);
                dir.mkdir();
            }
            zipIn.closeEntry();
            entry = zipIn.getNextEntry();
        }
        zipIn.close();

        writeAppInfo(appInfo);

        // add to apps hashmap
        apps.put(appInfo.getId(), appInfo);
    } catch (Exception e) {
        // Clean up app dir if fails
        newAppDir.delete();
        throw e;
    }
}

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;
    }//from w  ww  . j  a  v a 2 s  .co  m

    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:hoot.services.controllers.ogr.OgrAttributesResource.java

/**
 * This rest endpoint uploads multipart data from UI and then generates attribute output
 * Example: http://localhost:8080//hoot-services/ogr/info/upload?INPUT_TYPE=DIR
 * Output: {"jobId":"e43feae4-0644-47fd-a23c-6249e6e7f7fb"}
 * /*ww w  . java 2s.  com*/
 * After getting the jobId, one can track the progress through job status rest end point
 * Example: http://localhost:8080/hoot-services/job/status/e43feae4-0644-47fd-a23c-6249e6e7f7fb
 * Output: {"jobId":"e43feae4-0644-47fd-a23c-6249e6e7f7fb","statusDetail":null,"status":"complete"}
 * 
 * Once status is "complete"
 * Result attribute can be obtained through
 * Example:http://localhost:8080/hoot-services/ogr/info/e43feae4-0644-47fd-a23c-6249e6e7f7fb
 * output: JSON of attributes
 * 
 * @param inputType : [FILE | DIR] where FILE type should represents zip,shp or OMS and DIR represents FGDB
 * @param request
 * @return
 */
@POST
@Path("/upload")
@Produces(MediaType.TEXT_PLAIN)
public Response processUpload(@QueryParam("INPUT_TYPE") final String inputType,
        @Context HttpServletRequest request) {
    JSONObject res = new JSONObject();
    String jobId = UUID.randomUUID().toString();

    try {
        log.debug("Starting file upload for ogr attribute Process");
        Map<String, String> uploadedFiles = new HashMap<String, String>();
        ;
        Map<String, String> uploadedFilesPaths = new HashMap<String, String>();

        MultipartSerializer ser = new MultipartSerializer();
        ser.serializeUpload(jobId, inputType, uploadedFiles, uploadedFilesPaths, request);

        List<String> filesList = new ArrayList<String>();
        List<String> zipList = new ArrayList<String>();

        Iterator it = uploadedFiles.entrySet().iterator();
        while (it.hasNext()) {

            Map.Entry pairs = (Map.Entry) it.next();
            String fName = pairs.getKey().toString();
            String ext = pairs.getValue().toString();

            String inputFileName = "";

            inputFileName = uploadedFilesPaths.get(fName);

            JSONObject param = new JSONObject();
            // If it is zip file then we crack open to see if it contains FGDB.
            // If so then we add the folder location and desired output name which is fgdb name in the zip
            if (ext.equalsIgnoreCase("ZIP")) {
                zipList.add(fName);
                String zipFilePath = homeFolder + "/upload/" + jobId + "/" + inputFileName;
                ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFilePath));
                ZipEntry ze = zis.getNextEntry();

                while (ze != null) {

                    String zipName = ze.getName();
                    if (ze.isDirectory()) {

                        if (zipName.toLowerCase().endsWith(".gdb/") || zipName.toLowerCase().endsWith(".gdb")) {
                            String fgdbZipName = zipName;
                            if (zipName.toLowerCase().endsWith(".gdb/")) {
                                fgdbZipName = zipName.substring(0, zipName.length() - 1);
                            }
                            filesList.add("\"" + fName + "/" + fgdbZipName + "\"");
                        }
                    } else {
                        if (zipName.toLowerCase().endsWith(".shp")) {
                            filesList.add("\"" + fName + "/" + zipName + "\"");
                        }

                    }
                    ze = zis.getNextEntry();
                }

                zis.closeEntry();
                zis.close();
            } else {
                filesList.add("\"" + inputFileName + "\"");
            }

        }

        String mergeFilesList = StringUtils.join(filesList.toArray(), ' ');
        String mergedZipList = StringUtils.join(zipList.toArray(), ';');
        JSONArray params = new JSONArray();
        JSONObject param = new JSONObject();
        param.put("INPUT_FILES", mergeFilesList);
        params.add(param);
        param = new JSONObject();
        param.put("INPUT_ZIPS", mergedZipList);
        params.add(param);

        String argStr = createPostBody(params);
        postJobRquest(jobId, argStr);

    } catch (Exception ex) {
        ResourceErrorHandler.handleError("Failed upload: " + ex.toString(), Status.INTERNAL_SERVER_ERROR, log);
    }
    res.put("jobId", jobId);
    return Response.ok(res.toJSONString(), MediaType.APPLICATION_JSON).build();
}

From source file:ingest.utility.IngestUtilities.java

private void extractZipEntry(final String fileName, final ZipInputStream zipInputStream, final String zipPath,
        final String extractPath) throws IOException {
    byte[] buffer = new byte[1024];

    String extension = FilenameUtils.getExtension(fileName);
    String filePath = String.format("%s%s%s.%s", extractPath, File.separator, "ShapefileData", extension);

    // Sanitize - blacklist
    if (filePath.contains("..") || (fileName.contains("/")) || (fileName.contains("\\"))) {
        logger.log(String.format(
                "Cannot extract Zip entry %s because it contains a restricted path reference. Characters such as '..' or slashes are disallowed. The initial zip path was %s. This was blocked to prevent a vulnerability.",
                fileName, zipPath), Severity.WARNING,
                new AuditElement(INGEST, "restrictedPathDetected", zipPath));
        zipInputStream.closeEntry();
        return;//  ww  w . ja v a2s  .  c  o  m
    }
    // Sanitize - whitelist
    boolean filePathContainsExtension = false;
    for (final String ext : Arrays.asList(".shp", ".prj", ".shx", ".dbf", ".sbn")) {
        if (filePath.contains(ext)) {
            filePathContainsExtension = true;
            break;
        }
    }

    if (filePathContainsExtension) {
        File newFile = new File(filePath).getCanonicalFile();

        // Create all non existing folders
        new File(newFile.getParent()).mkdirs();

        try (FileOutputStream outputStream = new FileOutputStream(newFile)) {
            int length;
            while ((length = zipInputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, length);
            }
        }

        zipInputStream.closeEntry();
    } else {
        zipInputStream.closeEntry();
    }
}

From source file:org.dhatim.ect.formats.unedifact.UnEdifactSpecificationReader.java

private void readDefinitionEntries(ZipInputStream folderZip, ZipDirectoryEntry... entries) throws IOException {

    ZipEntry fileEntry = folderZip.getNextEntry();
    while (fileEntry != null) {
        String fName = new File(fileEntry.getName().toLowerCase()).getName().replaceFirst("tr", "ed");
        for (ZipDirectoryEntry entry : entries) {
            if (fName.startsWith(entry.getDirectory())) {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();

                byte[] bytes = new byte[BUFFER];
                int size;
                while ((size = folderZip.read(bytes, 0, bytes.length)) != -1) {
                    baos.write(bytes, 0, size);
                }//  ww w  .j  a  v  a 2s  . co m

                ZipInputStream zipInputStream = new ZipInputStream(
                        new ByteArrayInputStream(baos.toByteArray()));
                readZipEntry(entry.getEntries(), zipInputStream, entry.getFile());
                zipInputStream.close();
            }
        }
        folderZip.closeEntry();
        fileEntry = folderZip.getNextEntry();
    }
}