Example usage for java.util.zip ZipFile getInputStream

List of usage examples for java.util.zip ZipFile getInputStream

Introduction

In this page you can find the example usage for java.util.zip ZipFile getInputStream.

Prototype

public InputStream getInputStream(ZipEntry entry) throws IOException 

Source Link

Document

Returns an input stream for reading the contents of the specified zip file entry.

Usage

From source file:mondrian.test.loader.MondrianFoodMartLoader.java

/**
 * Open the file of INSERT statements to load the data. Default
 * file name is ./demo/FoodMartCreateData.zip
 *
 * @return FileInputStream/*from   w  w  w  . jav a2 s  . com*/
 */
private InputStream openInputStream() throws Exception {
    String defaultZipFileName = getClass().getResource("FoodMartCreateData.zip").getPath();
    final String defaultDataFileName = "FoodMartCreateData.sql";
    final File file = (inputFile != null) ? new File(inputFile) : new File(defaultZipFileName);
    if (!file.exists()) {
        LOGGER.error("No input file: " + file);
        return null;
    }
    if (file.getName().toLowerCase().endsWith(".zip")) {
        ZipFile zippedData = new ZipFile(file);
        ZipEntry entry = zippedData.getEntry(defaultDataFileName);
        return zippedData.getInputStream(entry);
    } else {
        return new FileInputStream(file);
    }
}

From source file:org.dspace.installer_edm.InstallerEDMAskosi.java

/**
 * Descomprime el zip y copia los archivos a un directorio
 *
 * @param sourcePackageFile archivo zip//from ww w .j  a  v  a2 s .c  o  m
 * @param destDir directorio destino de la copia
 * @return   xito de la copia
 */
private boolean copyPackageZipFile(File sourcePackageFile, String destDir) {
    try {
        // lectura de los archivos que componen el zip
        ZipFile zf = new ZipFile(sourcePackageFile.getAbsolutePath());
        Enumeration entries = zf.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) entries.nextElement();
            if (entry.isDirectory()) {
                File dirAux = new File(destDir + entry.getName());
                if (!dirAux.exists() && !dirAux.mkdir()) {
                    installerEDMDisplay.showQuestion(currentStepGlobal, "copyPackageZipFile.failcreate",
                            new String[] { dirAux.getAbsolutePath() });
                }
            } else {
                if (verbose)
                    installerEDMDisplay.showQuestion(currentStepGlobal, "copyPackageZipFile.extract",
                            new String[] { entry.getName() });
                int index = entry.getName().lastIndexOf(47);
                if (index == -1) {
                    index = entry.getName().lastIndexOf(92);
                }
                if (index > 0) {
                    File dir = new File(destDir + entry.getName().substring(0, index));
                    if (!dir.exists() && !dir.mkdirs()) {
                        installerEDMDisplay.showQuestion(currentStepGlobal, "copyPackageZipFile.failcreate.dir",
                                new String[] { dir.getAbsolutePath() });
                    }
                }
                // lectura del archivo interno y posterior escritura al directorio final
                byte[] buffer = new byte[1024];

                InputStream in = zf.getInputStream(entry);
                BufferedOutputStream out = new BufferedOutputStream(
                        new FileOutputStream(destDir + entry.getName()));
                int len;
                while ((len = in.read(buffer)) >= 0) {
                    out.write(buffer, 0, len);
                }
                in.close();
                out.close();
            }
        }
        return true;
    } catch (IOException e) {
        showException(e);
    }
    return false;
}

From source file:de.uni_potsdam.hpi.bpt.promnicat.importer.bpmai.BpmaiImporter.java

/**
 * Scans the given root directory for sgx-archives and extracts them into the dummy folder.
 * The extracted models can be parsed like any other process models from the BPM AI.
 * @param rootDir container of archives to extract
 * @param dummyFolder folder to extract the models to
 * @throws ZipException if archive extraction went wrong
 * @throws IOException if one of the given paths can not be read or written
 *//*from w w  w.j  a v a2 s .  c o  m*/
private void extractAvailableSgxArchives(File rootDir, File dummyFolder) throws ZipException, IOException {
    for (File file : rootDir.listFiles()) {
        if ((!file.isDirectory()) && (file.getName().endsWith(".sgx"))) {
            ZipFile zipFile = new ZipFile(file);
            Enumeration<? extends ZipEntry> entries = zipFile.entries();
            //iterate through files of an zip archive
            while (entries.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                String entryName = entry.getName();
                if (entryName.contains("/")) {
                    //ignore meta data files
                    if (entryName.endsWith("_meta.json")) {
                        continue;
                    }
                    //remove directory folder to fit into expected structure
                    String[] pathParts = entryName.split("/");
                    if (entryName.contains("directory_")) {
                        entryName = "";
                        for (int i = 0; i < pathParts.length; i++) {
                            if (!(pathParts[i].startsWith("directory_"))) {
                                entryName = entryName.concat(pathParts[i] + "/");
                            }
                        }
                        entryName = entryName.substring(0, entryName.length() - 1);
                    }
                    //rename process model files
                    String oldModelName = pathParts[pathParts.length - 1];
                    String[] nameParts = oldModelName.split("_");
                    if (nameParts.length > 2) {
                        String modelName = pathParts[pathParts.length - 2].split("_")[1] + "_rev" + nameParts[1]
                                + nameParts[2];
                        entryName = entryName.replace(oldModelName, modelName);
                    }
                    //create directories
                    (new File(dummyFolder.getPath() + File.separatorChar
                            + entryName.substring(0, entryName.lastIndexOf("/")))).mkdirs();
                }
                //extract process model
                copyInputStream(zipFile.getInputStream(entry),
                        dummyFolder.getPath() + File.separatorChar + entryName);
            }
            zipFile.close();
        }
    }
}

From source file:com.web.server.WarDeployer.java

/**
 * This method deploys the war in exploded form and configures it. 
 * @param file/* w  ww. j a v a  2  s  . c  om*/
 * @param customClassLoader
 * @param warDirectoryPath
 */
public void extractWar(File file, WebClassLoader customClassLoader) {

    StringBuffer classPath = new StringBuffer();
    int numBytes;
    try {
        ConcurrentHashMap jspMap = new ConcurrentHashMap();
        ZipFile zip = new ZipFile(file);
        ZipEntry ze = null;
        //String fileName=file.getName();
        String directoryName = file.getName();
        directoryName = directoryName.substring(0, directoryName.indexOf('.'));
        try {
            ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
            //logger.info("file://"+warDirectoryPath+"/WEB-INF/classes/");
            new WebServer().addURL(new URL("file:" + scanDirectory + "/" + directoryName + "/WEB-INF/classes/"),
                    customClassLoader);
            //new WebServer().addURL(new URL("file://"+warDirectoryPath+"/"),customClassLoader);
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        String fileDirectory;
        Enumeration<? extends ZipEntry> entries = zip.entries();
        while (entries.hasMoreElements()) {
            ze = entries.nextElement();
            // //System.out.println("Unzipping " + ze.getName());
            String filePath = scanDirectory + "/" + directoryName + "/" + ze.getName();
            if (!ze.isDirectory()) {
                fileDirectory = filePath.substring(0, filePath.lastIndexOf('/'));
            } else {
                fileDirectory = filePath;
            }
            // //System.out.println(fileDirectory);
            createDirectory(fileDirectory);
            if (!ze.isDirectory()) {
                FileOutputStream fout = new FileOutputStream(filePath);
                byte[] inputbyt = new byte[8192];
                InputStream istream = zip.getInputStream(ze);
                while ((numBytes = istream.read(inputbyt, 0, inputbyt.length)) >= 0) {
                    fout.write(inputbyt, 0, numBytes);
                }
                fout.close();
                istream.close();
                if (ze.getName().endsWith(".jsp")) {
                    jspMap.put(ze.getName(), filePath);
                } else if (ze.getName().endsWith(".jar")) {
                    new WebServer().addURL(
                            new URL("file:///" + scanDirectory + "/" + directoryName + "/" + ze.getName()),
                            customClassLoader);
                    classPath.append(filePath);
                    classPath.append(";");
                }
            }
        }
        zip.close();
        Set jsps = jspMap.keySet();
        Iterator jspIterator = jsps.iterator();
        classPath.append(scanDirectory + "/" + directoryName + "/WEB-INF/classes/;");
        ArrayList<String> jspFiles = new ArrayList();
        //System.out.println(classPath.toString());
        if (jspIterator.hasNext())
            new WebServer().addURL(new URL("file:" + scanDirectory + "/temp/" + directoryName + "/"),
                    customClassLoader);
        while (jspIterator.hasNext()) {
            String filepackageInternal = (String) jspIterator.next();
            String filepackageInternalTmp = filepackageInternal;
            if (filepackageInternal.lastIndexOf('/') == -1) {
                filepackageInternal = "";
            } else {
                filepackageInternal = filepackageInternal.substring(0, filepackageInternal.lastIndexOf('/'))
                        .replace("/", ".");
                filepackageInternal = "." + filepackageInternal;
            }
            createDirectory(scanDirectory + "/temp/" + directoryName);
            File jspFile = new File((String) jspMap.get(filepackageInternalTmp));
            String fName = jspFile.getName();
            String fileNameWithoutExtension = fName.substring(0, fName.lastIndexOf(".jsp")) + "_jsp";
            //String fileCreated=new JspCompiler().compileJsp((String) jspMap.get(filepackageInternalTmp), scanDirectory+"/temp/"+fileName, "com.web.server"+filepackageInternal,classPath.toString());
            synchronized (customClassLoader) {
                String fileNameInWar = filepackageInternalTmp;
                jspFiles.add(fileNameInWar.replace("/", "\\"));
                if (fileNameInWar.contains("/") || fileNameInWar.contains("\\")) {
                    customClassLoader.addURL("/" + fileNameInWar.replace("\\", "/"),
                            "com.web.server" + filepackageInternal + "." + fileNameWithoutExtension);
                } else {
                    customClassLoader.addURL("/" + fileNameInWar,
                            "com.web.server" + filepackageInternal + "." + fileNameWithoutExtension);
                }
            }
        }
        if (jspFiles.size() > 0) {
            ClassLoader oldCL = Thread.currentThread().getContextClassLoader();
            Thread.currentThread().setContextClassLoader(customClassLoader);
            try {
                JspC jspc = new JspC();
                jspc.setUriroot(scanDirectory + "/" + directoryName + "/");
                jspc.setAddWebXmlMappings(false);
                jspc.setCompile(true);
                jspc.setOutputDir(scanDirectory + "/temp/" + directoryName + "/");
                jspc.setPackage("com.web.server");
                StringBuffer buffer = new StringBuffer();
                for (String jspFile : jspFiles) {
                    buffer.append(",");
                    buffer.append(jspFile);
                }
                String jsp = buffer.toString();
                jsp = jsp.substring(1, jsp.length());
                System.out.println(jsp);
                jspc.setJspFiles(jsp);
                jspc.execute();
            } catch (Throwable je) {
                je.printStackTrace();
            } finally {
                Thread.currentThread().setContextClassLoader(oldCL);
            }
            Thread.currentThread().setContextClassLoader(customClassLoader);
        }
        try {
            new ExecutorServicesConstruct().getExecutorServices(serverdigester, executorServiceMap,
                    new File(scanDirectory + "/" + directoryName + "/WEB-INF/" + "executorservices.xml"),
                    customClassLoader);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            //e.printStackTrace();
        }
        try {
            new MessagingClassConstruct().getMessagingClass(messagedigester,
                    new File(scanDirectory + "/" + directoryName + "/WEB-INF/" + "messagingclass.xml"),
                    customClassLoader, messagingClassMap);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            //e.printStackTrace();
        }
        webxmldigester.setNamespaceAware(true);
        webxmldigester.setValidating(true);
        //digester.setRules(null);
        FileInputStream webxml = new FileInputStream(
                scanDirectory + "/" + directoryName + "/WEB-INF/" + "web.xml");
        InputSource is = new InputSource(webxml);
        try {
            System.out.println("SCHEMA");
            synchronized (webxmldigester) {
                //webxmldigester.set("config/web-app_2_4.xsd");
                WebAppConfig webappConfig = (WebAppConfig) webxmldigester.parse(is);
                servletMapping.put(scanDirectory + "/" + directoryName.replace("\\", "/"), webappConfig);
            }
            webxml.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //ClassLoaderUtil.closeClassLoader(customClassLoader);

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        //e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        //e.printStackTrace();
    } catch (Exception ex) {

    }
}

From source file:com.esd.ps.EmployerController.java

/**
 * ? zip//from   w  ww. j a  v  a2 s .  c  om
 * 
 * @param packName
 * @param taskLvl
 */
public void storeDataZIP(String packName, int taskLvl, String url, int userId, Date date) {
    InputStream in = null;
    String zipEntryName = null;
    int packId = 0;
    try {
        ZipFile zip = new ZipFile(url + Constants.SLASH + packName);
        for (Enumeration<?> entries = zip.entries(); entries.hasMoreElements();) {
            ZipEntry entry = (ZipEntry) entries.nextElement();
            String taskDir = Constants.EMPTY;
            if (entry.isDirectory()) {// ?
                continue;
            }
            zipEntryName = entry.getName();
            if (zipEntryName.indexOf(Constants.SLASH) < zipEntryName.lastIndexOf(Constants.SLASH)) {
                String str[] = zipEntryName.split(Constants.SLASH);
                // (zipEntryName.indexOf("/") + 1)
                taskDir = zipEntryName.substring((zipEntryName.indexOf(Constants.SLASH) + 1),
                        zipEntryName.lastIndexOf(Constants.SLASH));
                zipEntryName = str[(str.length - 1)];
            }
            zipEntryName = zipEntryName.substring(zipEntryName.indexOf(Constants.SLASH) + 1,
                    zipEntryName.length());
            // ?
            if (zipEntryName.substring((zipEntryName.length() - 3), zipEntryName.length())
                    .equals(Constants.WAV) == false) {
                // String noMatch = zipEntryName;
                continue;
            }
            in = zip.getInputStream(entry);
            // inputstrem?byte[]
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            byte[] data = new byte[4096];
            int count = -1;
            while ((count = in.read(data, 0, 4096)) != -1)
                outStream.write(data, 0, count);
            data = null;
            byte[] wav = outStream.toByteArray();

            taskWithBLOBs taskWithBLOBs = new taskWithBLOBs();
            packId = packService.getPackIdByPackName(packName);
            // wav?0kb
            if (outStream.size() == 0) {
                taskWithBLOBs.setWorkerId(0);
            }
            taskWithBLOBs.setTaskWav(wav);
            taskWithBLOBs.setTaskLvl(taskLvl);
            // ?
            taskWithBLOBs.setPackId(packId);
            taskWithBLOBs.setTaskName(zipEntryName);
            // 
            if (taskDir.trim().length() > 0) {
                taskDir = packName.substring(0, (packName.length() - 4)) + Constants.SLASH + taskDir;
            } else {
                taskDir = packName.substring(0, (packName.length() - 4));
            }
            taskWithBLOBs.setTaskDir(taskDir);
            taskWithBLOBs.setCreateId(userId);
            taskWithBLOBs.setCreateTime(date);
            // ?
            taskWithBLOBs.setTaskUpload(false);
            StackTraceElement[] items = Thread.currentThread().getStackTrace();
            taskWithBLOBs.setCreateMethod(items[1].toString());
            taskWithBLOBs.setVersion(1);
            taskService.insert(taskWithBLOBs);
        }
        zip.close();
        in.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    File fd = new File(packName);
    fd.delete();
    packWithBLOBs pack = new packWithBLOBs();
    pack.setPackId(packId);
    pack.setUnzip(2);// ??
    StackTraceElement[] items = Thread.currentThread().getStackTrace();
    pack.setUpdateMethod(items[1].toString());
    packService.updateByPrimaryKeySelective(pack);
}

From source file:com.serotonin.m2m2.Main.java

private static void openZipFiles() throws Exception {
    ProcessEPoll pep = new ProcessEPoll();
    try {//w w  w .j  av  a  2 s. c  o  m
        new Thread(pep).start();

        File[] zipFiles = new File(new StringBuilder().append(Common.MA_HOME).append("/web/modules").toString())
                .listFiles(new FilenameFilter() {
                    public boolean accept(File dir, String name) {
                        return name.endsWith(".zip");
                    }
                });
        if ((zipFiles == null) || (zipFiles.length == 0))
            return;
        for (File file : zipFiles) {
            if (!file.isFile()) {
                continue;
            }
            ZipFile zip = new ZipFile(file);
            try {
                Properties props = getProperties(zip);

                String moduleName = props.getProperty("name");
                if (moduleName == null) {
                    throw new RuntimeException("name not defined in module properties");
                }
                if (!ModuleUtils.validateName(moduleName)) {
                    throw new RuntimeException(new StringBuilder().append("Module name '").append(moduleName)
                            .append("' is invalid").toString());
                }
                File moduleDir = new File(
                        new StringBuilder().append(Common.MA_HOME).append("/web/modules").toString(),
                        moduleName);

                if (moduleDir.exists())
                    LOG.info(new StringBuilder().append("Upgrading module ").append(moduleName).toString());
                else {
                    LOG.info(new StringBuilder().append("Installing module ").append(moduleName).toString());
                }
                String persistDirs = props.getProperty("persistPaths");
                File moduleSaveDir = new File(new StringBuilder().append(moduleDir).append(".save").toString());

                if (!org.apache.commons.lang3.StringUtils.isBlank(persistDirs)) {
                    String[] paths = persistDirs.split(",");
                    for (String path : paths) {
                        path = path.trim();
                        if (!org.apache.commons.lang3.StringUtils.isBlank(path)) {
                            File from = new File(moduleDir, path);
                            File to = new File(moduleSaveDir, path);
                            if (from.exists()) {
                                if (from.isDirectory())
                                    moveDir(from, to);
                                else {
                                    FileUtils.moveFile(from, to);
                                }
                            }
                        }
                    }
                }

                deleteDir(moduleDir);

                if (moduleSaveDir.exists())
                    moveDir(moduleSaveDir, moduleDir);
                else {
                    moduleDir.mkdirs();
                }
                Enumeration entries = zip.entries();
                while (entries.hasMoreElements()) {
                    ZipEntry entry = (ZipEntry) entries.nextElement();
                    String name = entry.getName();
                    File entryFile = new File(moduleDir, name);

                    if (entry.isDirectory())
                        entryFile.mkdirs();
                    else {
                        writeFile(entryFile, zip.getInputStream(entry));
                    }
                }

                File moduleWorkDir = new File(moduleDir, "work");
                if (moduleWorkDir.exists()) {
                    moveDir(moduleWorkDir, new File(Common.MA_HOME, "work"));
                }

                if (HostUtils.isLinux()) {
                    String permissions = props.getProperty("permissions");
                    if (!org.apache.commons.lang3.StringUtils.isBlank(permissions)) {
                        String[] s = permissions.split(",");
                        for (String permission : s) {
                            setPermission(pep, moduleName, moduleDir, permission);
                        }

                    }

                }

                zip.close();
            } catch (Exception e) {
                LOG.warn(new StringBuilder().append("Error while opening zip file ").append(file.getName())
                        .append(". Is this module built for the core version that you are using? Module ignored.")
                        .toString(), e);
            } finally {
                zip.close();
            }

            file.delete();
        }

    } finally {
        pep.waitForAll();
        pep.terminate();
    }
}

From source file:fr.certu.chouette.gui.command.ImportCommand.java

/**
 * @param session//w w w. j a v a 2 s  . c  om
 * @param save
 * @param savedIds
 * @param manager
 * @param importTask
 * @param format
 * @param inputFile
 * @param suffixes
 * @param values
 * @param importHolder
 * @param validationHolder
 * @throws ChouetteException
 */
private int importZipEntries(EntityManager session, boolean save, List<Long> savedIds,
        INeptuneManager<NeptuneIdentifiedObject> manager, ImportTask importTask, String format,
        String inputFile, List<String> suffixes, List<ParameterValue> values, ReportHolder importHolder,
        ReportHolder validationHolder) throws ChouetteException {
    SimpleParameterValue inputFileParam = new SimpleParameterValue("inputFile");
    values.add(inputFileParam);

    ReportHolder zipHolder = new ReportHolder();
    if (format.equalsIgnoreCase("neptune")) {
        SharedImportedData sharedData = new SharedImportedData();
        UnsharedImportedData unsharedData = new UnsharedImportedData();
        SimpleParameterValue sharedDataParam = new SimpleParameterValue("sharedImportedData");
        sharedDataParam.setObjectValue(sharedData);
        values.add(sharedDataParam);
        SimpleParameterValue unsharedDataParam = new SimpleParameterValue("unsharedImportedData");
        unsharedDataParam.setObjectValue(unsharedData);
        values.add(unsharedDataParam);
    }

    // unzip files , import and save contents
    ZipFile zip = null;
    File temp = null;
    File tempRep = new File(FileUtils.getTempDirectory(), "massImport" + importTask.getId());
    if (!tempRep.exists())
        tempRep.mkdirs();
    File zipFile = new File(inputFile);
    ReportItem zipReportItem = new ExchangeReportItem(ExchangeReportItem.KEY.ZIP_FILE, Report.STATE.OK,
            zipFile.getName());
    try {
        Charset encoding = FileTool.getZipCharset(inputFile);
        if (encoding == null) {
            ReportItem fileErrorItem = new ExchangeReportItem(ExchangeReportItem.KEY.ZIP_ERROR,
                    Report.STATE.ERROR, "unknown encoding");
            zipReportItem.addItem(fileErrorItem);
            importHolder.getReport().addItem(zipReportItem);
            saveImportReports(session, importTask, importHolder.getReport(), validationHolder.getReport());
            return 1;
        }
        zip = new ZipFile(inputFile, encoding);
        zipHolder.setReport(zipReportItem);
        for (Enumeration<? extends ZipEntry> entries = zip.entries(); entries.hasMoreElements();) {
            ZipEntry entry = entries.nextElement();

            if (entry.isDirectory()) {
                File dir = new File(tempRep, entry.getName());
                dir.mkdirs();
                continue;
            }
            if (!FilenameUtils.isExtension(entry.getName().toLowerCase(), suffixes)) {
                ReportItem fileReportItem = new ExchangeReportItem(ExchangeReportItem.KEY.FILE_IGNORED,
                        Report.STATE.OK, FilenameUtils.getName(entry.getName()));
                zipReportItem.addItem(fileReportItem);
                log.info("entry " + entry.getName() + " ignored, unknown extension");
                continue;
            }
            InputStream stream = null;
            try {
                stream = zip.getInputStream(entry);
            } catch (IOException e) {
                ReportItem fileReportItem = new ExchangeReportItem(ExchangeReportItem.KEY.FILE_ERROR,
                        Report.STATE.WARNING, FilenameUtils.getName(entry.getName()));
                zipReportItem.addItem(fileReportItem);
                log.error("entry " + entry.getName() + " cannot read", e);
                continue;
            }
            byte[] bytes = new byte[4096];
            int len = stream.read(bytes);
            temp = new File(tempRep.getAbsolutePath() + "/" + entry.getName());
            FileOutputStream fos = new FileOutputStream(temp);
            while (len > 0) {
                fos.write(bytes, 0, len);
                len = stream.read(bytes);
            }
            fos.close();

            // import
            log.info("import file " + entry.getName());
            inputFileParam.setFilepathValue(temp.getAbsolutePath());
            List<NeptuneIdentifiedObject> beans = manager.doImport(null, format, values, zipHolder,
                    validationHolder);
            if (beans != null && !beans.isEmpty()) {
                // save
                if (save) {
                    saveBeans(manager, beans, savedIds, importHolder.getReport());
                } else {
                    for (NeptuneIdentifiedObject bean : beans) {
                        GuiReportItem item = new GuiReportItem(GuiReportItem.KEY.NO_SAVE, Report.STATE.OK,
                                bean.getName());
                        importHolder.getReport().addItem(item);
                    }

                }
            }
            temp.delete();
        }
        try {
            zip.close();
        } catch (IOException e) {
            log.info("cannot close zip file");
        }
        importHolder.getReport().addItem(zipReportItem);
    } catch (IOException e) {
        log.error("IO error", e);
        ReportItem fileErrorItem = new ExchangeReportItem(ExchangeReportItem.KEY.ZIP_ERROR, Report.STATE.ERROR,
                e.getLocalizedMessage());
        zipReportItem.addItem(fileErrorItem);
        importHolder.getReport().addItem(zipReportItem);
        saveImportReports(session, importTask, importHolder.getReport(), validationHolder.getReport());
        return 1;
    } catch (IllegalArgumentException e) {
        log.error("Format error", e);
        ReportItem fileErrorItem = new ExchangeReportItem(ExchangeReportItem.KEY.ZIP_ERROR, Report.STATE.ERROR,
                e.getLocalizedMessage());
        zipReportItem.addItem(fileErrorItem);
        importHolder.getReport().addItem(zipReportItem);
        saveImportReports(session, importTask, importHolder.getReport(), validationHolder.getReport());
        return 1;
    } finally {
        try {
            FileUtils.deleteDirectory(tempRep);
        } catch (IOException e) {
            log.warn("temporary directory " + tempRep.getAbsolutePath() + " could not be deleted");
        }
    }
    return 0;
}

From source file:fr.paris.lutece.plugins.upload.web.UploadJspBean.java

/**
 * Process file upload/*from  w ww  . j  av  a2  s .c o  m*/
 *
 * @param request Http request
 * @return Html form
 */
public String doCreateFile(HttpServletRequest request) {
    String strDirectoryIndex = null;

    try {
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        FileItem item = multiRequest.getFile(PARAMETER_FILE_NAME);

        // The index and value of the directory combo in the form
        strDirectoryIndex = multiRequest.getParameter(PARAMETER_DIRECTORY);

        String strRelativeDirectory = getDirectory(strDirectoryIndex);

        // The absolute path of the target directory
        String strDestDirectory = AppPathService.getWebAppPath() + strRelativeDirectory;

        // List the files in the target directory
        File[] existingFiles = (new File(strDestDirectory)).listFiles();

        // Is the 'unzip' checkbox checked?
        boolean bUnzip = (multiRequest.getParameter(PARAMETER_UNZIP) != null);

        if (item != null && !item.getName().equals(StringUtils.EMPTY)) {
            if (!bUnzip) // copy the file
            {
                AppLogService.debug("copying the file");

                // Getting downloadFile's name
                String strNameFile = FileUploadService.getFileNameOnly(item);

                // Clean name
                String strClearName = UploadUtil.cleanFileName(strNameFile);

                // Checking duplicate
                if (duplicate(strClearName, existingFiles)) {
                    return AdminMessageService.getMessageUrl(request, MESSAGE_FILE_EXISTS,
                            AdminMessage.TYPE_STOP);
                }

                // Move the file to the target directory
                File destFile = new File(strDestDirectory, strClearName);

                FileOutputStream fos = new FileOutputStream(destFile);
                fos.flush();
                fos.write(item.get());
                fos.close();
            } else // unzip the file
            {
                AppLogService.debug("unzipping the file");

                ZipFile zipFile;

                try {
                    // Create a temporary file with result of getTime() as unique file name
                    File tempFile = File.createTempFile(Long.toString((new Date()).getTime()), ".zip");
                    // Delete temp file when program exits.
                    tempFile.deleteOnExit();

                    FileOutputStream fos = new FileOutputStream(tempFile);
                    fos.flush();
                    fos.write(item.get());
                    fos.close();
                    zipFile = new ZipFile(tempFile);
                } catch (ZipException ze) {
                    AppLogService.error("Error opening zip file", ze);

                    return AdminMessageService.getMessageUrl(request, MESSAGE_ZIP_ERROR,
                            AdminMessage.TYPE_STOP);
                }

                // Each zipped file is indentified by a zip entry :
                Enumeration zipEntries = zipFile.entries();

                while (zipEntries.hasMoreElements()) {
                    ZipEntry zipEntry = (ZipEntry) zipEntries.nextElement();

                    // Clean the name :
                    String strZippedName = zipEntry.getName();
                    String strClearName = UploadUtil.cleanFilePath(strZippedName);

                    if (strZippedName.equals(strClearName)) {
                        // The unzipped file :
                        File destFile = new File(strDestDirectory, strClearName);

                        // Create the parent directory structure if needed :
                        destFile.getParentFile().mkdirs();

                        if (!zipEntry.isDirectory()) // don't unzip directories
                        {
                            AppLogService.debug("unzipping " + strZippedName + " to " + destFile.getName());

                            // InputStream from zipped data
                            InputStream inZipStream = zipFile.getInputStream(zipEntry);

                            // OutputStream to the destination file
                            OutputStream outDestStream = new FileOutputStream(destFile);

                            // Helper method to copy data
                            copyStream(inZipStream, outDestStream);

                            inZipStream.close();
                            outDestStream.close();
                        } else {
                            AppLogService.debug("skipping directory " + strZippedName);
                        }
                    } else {
                        AppLogService.debug("skipping accented file " + strZippedName);
                    }
                }
            }
        } else {
            return AdminMessageService.getMessageUrl(request, Messages.MANDATORY_FIELDS,
                    AdminMessage.TYPE_STOP);
        }
    } catch (IOException e) {
        AppLogService.error(e.getMessage(), e);
    }

    // Returns upload management page
    UrlItem url = new UrlItem(getHomeUrl(request));

    if (strDirectoryIndex != null) {
        url.addParameter(PARAMETER_DIRECTORY, strDirectoryIndex);
    }

    return url.getUrl();
}

From source file:fr.certu.chouette.exchange.xml.neptune.importer.XMLNeptuneImportLinePlugin.java

/**
 * import ZipFile/*w ww .j a v  a 2 s .  co  m*/
 * 
 * @param filePath
 *           path to zip File
 * @param validate
 *           process XML and XSD format validation
 * @param importReport
 *           report to fill
 * @param optimizeMemory
 * @param unsharedData
 * @param sharedData
 * @return list of loaded lines
 */
private List<Line> processZipImport(String filePath, boolean validate, Report importReport,
        Report validationReport, boolean optimizeMemory, SharedImportedData sharedData,
        UnsharedImportedData unsharedData) {
    ZipFile zip = null;
    try {
        Charset encoding = FileTool.getZipCharset(filePath);
        if (encoding == null) {
            ReportItem item = new ExchangeReportItem(ExchangeReportItem.KEY.FILE_ERROR, Report.STATE.ERROR,
                    filePath, "unknown encoding");
            importReport.addItem(item);
            importReport.updateStatus(Report.STATE.ERROR);
            logger.error("zip import failed (unknown encoding)");
            return null;
        }
        zip = new ZipFile(filePath);
    } catch (IOException e) {
        // report for save
        ReportItem fileErrorItem = new ExchangeReportItem(ExchangeReportItem.KEY.ZIP_ERROR, Report.STATE.ERROR,
                e.getLocalizedMessage());
        importReport.addItem(fileErrorItem);
        // log
        logger.error("zip import failed (cannot open zip)" + e.getLocalizedMessage());
        return null;
    }
    List<Line> lines = new ArrayList<Line>();
    for (Enumeration<? extends ZipEntry> entries = zip.entries(); entries.hasMoreElements();) {
        ZipEntry entry = entries.nextElement();

        // ignore directory without warning
        if (entry.isDirectory())
            continue;

        String entryName = entry.getName();
        if (!FilenameUtils.getExtension(entryName).toLowerCase().equals("xml")) {
            // report for save
            ReportItem fileReportItem = new ExchangeReportItem(ExchangeReportItem.KEY.FILE_IGNORED,
                    Report.STATE.OK, entryName);
            importReport.addItem(fileReportItem);
            // log
            logger.info("zip entry " + entryName + " bypassed ; not a XML file");
            continue;
        }
        logger.info("start import zip entry " + entryName);
        ReportItem fileReportItem = new ExchangeReportItem(ExchangeReportItem.KEY.FILE, Report.STATE.OK,
                entryName);
        importReport.addItem(fileReportItem);
        try {
            InputStream stream = zip.getInputStream(entry);
            stream.close();
        } catch (IOException e) {
            // report for save
            ReportItem errorItem = new ExchangeReportItem(ExchangeReportItem.KEY.FILE_ERROR, Report.STATE.ERROR,
                    e.getLocalizedMessage());
            fileReportItem.addItem(errorItem);
            // log
            logger.error("zip entry " + entryName + " import failed (get entry)" + e.getLocalizedMessage());
            continue;
        }
        ChouettePTNetworkHolder holder = null;
        try {
            holder = reader.read(zip, entry, validate);
            validationReport.addItem(holder.getReport());
        } catch (ExchangeRuntimeException e) {
            // report for save
            ReportItem errorItem = new ExchangeReportItem(ExchangeReportItem.KEY.FILE_ERROR, Report.STATE.ERROR,
                    e.getLocalizedMessage());
            fileReportItem.addItem(errorItem);
            // log
            logger.error("zip entry " + entryName + " import failed (read XML)" + e.getLocalizedMessage());
            continue;
        } catch (Exception e) {
            // report for save
            ReportItem errorItem = new ExchangeReportItem(ExchangeReportItem.KEY.FILE_ERROR, Report.STATE.ERROR,
                    e.getLocalizedMessage());
            fileReportItem.addItem(errorItem);
            // log
            logger.error(e.getLocalizedMessage());
            continue;
        }
        try {
            Line line = processImport(holder, validate, fileReportItem, validationReport, entryName, sharedData,
                    unsharedData, optimizeMemory);

            if (line != null) {
                lines.add(line);
            } else {
                logger.error("zip entry " + entryName + " import failed (build model)");
            }

        } catch (ExchangeException e) {
            // report for save
            ReportItem errorItem = new ExchangeReportItem(ExchangeReportItem.KEY.FILE_ERROR, Report.STATE.ERROR,
                    e.getLocalizedMessage());
            fileReportItem.addItem(errorItem);
            // log
            logger.error(
                    "zip entry " + entryName + " import failed (convert to model)" + e.getLocalizedMessage());
            continue;
        }
        logger.info("zip entry imported");
    }
    try {
        zip.close();
    } catch (IOException e) {
        logger.info("cannot close zip file");
    }
    if (lines.size() == 0) {
        logger.error("zip import failed (no valid entry)");
        return null;
    }
    return lines;
}