Example usage for java.util.zip ZipEntry isDirectory

List of usage examples for java.util.zip ZipEntry isDirectory

Introduction

In this page you can find the example usage for java.util.zip ZipEntry isDirectory.

Prototype

public boolean isDirectory() 

Source Link

Document

Returns true if this is a directory entry.

Usage

From source file:com.redhat.ceylon.compiler.java.test.cmr.CMRTests.java

@Test
public void testMdlByName() throws IOException {
    List<String> options = new LinkedList<String>();
    options.add("-src");
    options.add(getPackagePath() + "/modules/byName");
    options.addAll(defaultOptions);//from  ww  w .  j av  a2  s . c  o m
    CeyloncTaskImpl task = getCompilerTask(options, null, Arrays.asList("default", "mod"));
    Boolean ret = task.call();
    assertTrue(ret);

    File carFile = getModuleArchive("default", null);
    assertTrue(carFile.exists());

    JarFile car = new JarFile(carFile);

    ZipEntry moduleClass = car.getEntry("def/Foo.class");
    assertNotNull(moduleClass);
    ZipEntry moduleClassDir = car.getEntry("def/");
    assertNotNull(moduleClassDir);
    assertTrue(moduleClassDir.isDirectory());

    car.close();

    carFile = getModuleArchive("mod", "1");
    assertTrue(carFile.exists());

    car = new JarFile(carFile);

    moduleClass = car.getEntry("mod/$module_.class");
    assertNotNull(moduleClass);
    moduleClassDir = car.getEntry("mod/");
    assertNotNull(moduleClassDir);
    assertTrue(moduleClassDir.isDirectory());

    car.close();
}

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

/**
 * import command :  ( -fileFormat utilis si l'extension du fichier n'est pas reprsentative du format)
 * -c import -o line -format XXX -inputFile YYYY [-fileFormat TTT] -importId ZZZ ... 
 * @param manager//w w w .  ja v a 2 s  .c  om
 * @param parameters
 * @return
 */
private int executeImport(INeptuneManager<NeptuneIdentifiedObject> manager,
        Map<String, List<String>> parameters) {
    parameters.put("reportforsave", Arrays.asList(new String[] { "true" }));
    // parameters.put("validate",Arrays.asList(new String[]{"true"})); // force validation if possible

    GuiReport saveReport = new GuiReport("SAVE", Report.STATE.OK);
    Report importReport = null;

    List<Report> reports = new ArrayList<Report>();
    // check if import exists and accept unzip before call
    String format = getSimpleString(parameters, "format");
    String inputFile = getSimpleString(parameters, "inputfile");
    // String fileFormat = getSimpleString(parameters,"fileformat","");
    Long importId = Long.valueOf(getSimpleString(parameters, "importid"));
    if (!importDao.exists(importId)) {
        // error import not found
        logger.error("import not found " + importId);
        return 1;
    }
    GuiImport guiImport = importDao.get(importId);
    logger.info("Export data for export id " + importId);
    logger.info("  type : " + guiImport.getType());
    logger.info("  options : " + guiImport.getOptions());

    Referential referential = referentialDao.get(guiImport.getReferentialId());
    logger.info("Referential " + guiImport.getReferentialId());
    logger.info("  name : " + referential.getName());
    logger.info("  slug : " + referential.getSlug());
    logger.info("  projection type : " + referential.getProjectionType());

    String projectionType = null;
    if (referential.getProjectionType() != null && !referential.getProjectionType().isEmpty()) {
        logger.info("  projection type for export: " + referential.getProjectionType());
        projectionType = referential.getProjectionType();
        parameters.put("srid", Arrays.asList(new String[] { projectionType }));
    }
    // set projection for import (inactive if not set)
    geographicService.switchProjection(projectionType);

    int beanCount = 0;

    boolean zipped = (inputFile.toLowerCase().endsWith(".zip"));

    try {
        List<FormatDescription> formats = manager.getImportFormats(null);
        FormatDescription description = null;

        for (FormatDescription formatDescription : formats) {
            if (formatDescription.getName().equalsIgnoreCase(format)) {
                description = formatDescription;
                break;
            }
        }
        if (description == null) {
            throw new IllegalArgumentException("format " + format + " unavailable");
        }
        List<String> suffixes = new ArrayList<String>();
        for (ParameterDescription desc : description.getParameterDescriptions()) {
            if (desc.getName().equalsIgnoreCase("inputfile")) {
                suffixes = desc.getAllowedExtensions();
                break;
            }
        }
        List<ParameterValue> values = populateParameters(description, parameters, "inputfile", "fileformat");
        if (zipped && description.isUnzipAllowed()) {
            SimpleParameterValue inputFileParam = new SimpleParameterValue("inputFile");
            values.add(inputFileParam);
            // unzip files , import and save contents 
            ZipFile zip = null;
            File temp = null;
            File tempRep = new File(FileUtils.getTempDirectory(), "massImport" + importId);
            if (!tempRep.exists())
                tempRep.mkdirs();
            try {

                zip = new ZipFile(inputFile);
                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)) {
                        logger.error("entry " + entry.getName() + " ignored, unknown extension");
                        continue;
                    }
                    InputStream stream = null;
                    try {
                        stream = zip.getInputStream(entry);
                    } catch (IOException e) {
                        logger.error("entry " + entry.getName() + " cannot read");
                        continue;
                    }
                    byte[] bytes = new byte[4096];
                    int len = stream.read(bytes);
                    temp = new File(tempRep, entry.getName());
                    FileOutputStream fos = new FileOutputStream(temp);
                    while (len > 0) {
                        fos.write(bytes, 0, len);
                        len = stream.read(bytes);
                    }
                    fos.close();

                    // import
                    if (verbose)
                        System.out.println("import file " + entry.getName());
                    logger.info("import file " + entry.getName());
                    inputFileParam.setFilepathValue(temp.getAbsolutePath());
                    ReportHolder holder = new ReportHolder();
                    List<NeptuneIdentifiedObject> beans = manager.doImport(null, format, values, holder);
                    if (holder.getReport() != null) {
                        if (importReport == null) {
                            importReport = holder.getReport();
                            reports.add(importReport);
                        } else {
                            importReport.addAll(holder.getReport().getItems());
                        }

                    }
                    // save
                    if (beans != null && !beans.isEmpty()) {

                        for (NeptuneIdentifiedObject bean : beans) {
                            if (verbose) {
                                System.out.println("save " + bean.getName() + " (" + bean.getObjectId() + ")");
                            }
                            logger.info("save " + bean.getName() + " (" + bean.getObjectId() + ")");
                            // check all stopareas
                            if (bean instanceof Line) {
                                Line line = (Line) bean;
                                checkProjection(line);
                            }
                        }
                        try {
                            manager.saveAll(null, beans, true, true);
                            for (NeptuneIdentifiedObject bean : beans) {
                                GuiReportItem item = new GuiReportItem("SAVE_OK", Report.STATE.OK,
                                        bean.getName());
                                importReport.addItem(item);
                                beanCount++;
                            }
                        } catch (Exception e) {
                            logger.error("fail to save data :" + e.getMessage(), e);
                            for (NeptuneIdentifiedObject bean : beans) {
                                GuiReportItem item = new GuiReportItem("SAVE_ERROR", Report.STATE.ERROR,
                                        bean.getName(), filter_chars(e.getMessage()));
                                importReport.addItem(item);
                            }
                        }
                    }
                    temp.delete();
                }
                try {
                    zip.close();
                } catch (IOException e) {
                    logger.info("cannot close zip file");
                }
            } catch (IOException e) {
                //reports.add(saveReport);
                System.out.println("import failed " + e.getMessage());
                logger.error("import failed " + e.getMessage(), e);
                saveImportReports(importId, format, reports);
                return 1;
            } finally {
                try {
                    FileUtils.deleteDirectory(tempRep);
                } catch (IOException e) {
                    logger.warn("temporary directory " + tempRep.getAbsolutePath() + " could not be deleted");
                }
            }

        } else {
            SimpleParameterValue inputFileParam = new SimpleParameterValue("inputFile");
            inputFileParam.setFilepathValue(inputFile);
            values.add(inputFileParam);
            //            if (!fileFormat.isEmpty())
            //            {
            //               SimpleParameterValue fileFormatParam = new SimpleParameterValue("fileFormat");
            //               fileFormatParam.setStringValue(fileFormat);
            //               values.add(fileFormatParam);
            //            }
            // surround with try catch 
            ReportHolder holder = new ReportHolder();
            List<NeptuneIdentifiedObject> beans = manager.doImport(null, format, values, holder);
            if (holder.getReport() != null) {
                importReport = holder.getReport();
                reports.add(holder.getReport());
            }
            logger.info("imported Lines " + beans.size());

            for (NeptuneIdentifiedObject bean : beans) {
                if (bean instanceof Line) {
                    Line line = (Line) bean;
                    checkProjection(line);
                }
                List<NeptuneIdentifiedObject> oneBean = new ArrayList<NeptuneIdentifiedObject>();
                oneBean.add(bean);
                try {
                    logger.info("save  Line " + bean.getName());
                    manager.saveAll(null, oneBean, true, true);
                    GuiReportItem item = new GuiReportItem("SAVE_OK", Report.STATE.OK, bean.getName());
                    saveReport.addItem(item);
                    beanCount++;
                } catch (Exception e) {
                    logger.error("save failed " + e.getMessage(), e);
                    GuiReportItem item = new GuiReportItem("SAVE_ERROR", Report.STATE.ERROR, bean.getName(),
                            e.getMessage());
                    saveReport.addItem(item);
                }
            }
        }
    } catch (Exception e) {
        // fill report with error
        if (saveReport.getItems() != null && !saveReport.getItems().isEmpty())
            reports.add(saveReport);
        String msg = e.getMessage();
        if (msg == null)
            msg = e.getClass().getName();
        System.out.println("import failed " + msg);
        logger.error("import failed " + msg, e);
        GuiReport errorReport = new GuiReport("IMPORT_ERROR", Report.STATE.ERROR);
        GuiReportItem item = new GuiReportItem("EXCEPTION", Report.STATE.ERROR, msg);
        errorReport.addItem(item);
        reports.add(errorReport);
        saveImportReports(importId, format, reports);

        return 1;
    }
    if (saveReport.getItems() != null && !saveReport.getItems().isEmpty())
        reports.add(saveReport);
    saveImportReports(importId, format, reports);
    return (beanCount == 0 ? 1 : 0);

}

From source file:com.htmlhifive.tools.wizard.download.DownloadModule.java

/**
 * ZIP?.//from  w ww .  j  a  v  a  2  s .  c o m
 * 
 * @param libraryNode 
 * @param perLibWork libWork
 * @param folder 
 * @param monitor 
 * @param logger .
 * @return ???????.
 * @throws IOException IO
 * @throws CoreException 
 */
private boolean downloadZip(LibraryNode libraryNode, int perLibWork, IContainer folder,
        IProgressMonitor monitor, ResultStatus logger) throws IOException, CoreException {

    boolean result = true;
    boolean addStatus = false;
    ZipFile cachedZipFile = null;
    String cachedSite = null;
    Library library = libraryNode.getValue();

    if (!library.getSite().isEmpty()) {
        int perSiteWork = Math.max(1, perLibWork / library.getSite().size());

        for (Site site : library.getSite()) {
            String siteUrl = site.getUrl();
            String path = H5IOUtils.getURLPath(siteUrl);
            if (path == null) {
                logger.log(Messages.SE0082, siteUrl);
                continue;
            }

            boolean setWorked = false;

            IContainer savedFolder = folder;
            if (site.getExtractPath() != null) {
                savedFolder = savedFolder.getFolder(Path.fromOSString(site.getExtractPath()));
            }

            // ?.
            IFile iFile = null;
            if (path.endsWith(".zip") || path.endsWith(".jar") || site.getFilePattern() != null) {

                // Zip

                // ?????????.
                if (!siteUrl.equals(cachedSite)) {
                    cachedZipFile = download(monitor, perSiteWork, logger, null, siteUrl);
                    setWorked = true;
                    if (!lastDownloadStatus || cachedZipFile == null) {
                        libraryNode.setInError(true);
                        result = false;
                        break;
                    }
                    cachedSite = siteUrl;
                }

                final ZipFile zipFile = cachedZipFile;

                // int perZipWork = Math.max(1, perSiteWork / zipFile.size());

                // Zip.
                for (Enumeration<? extends ZipEntry> e = zipFile.entries(); e.hasMoreElements();) {
                    final ZipEntry zipEntry = e.nextElement();

                    if (site.getFilePattern() != null
                            && !FilenameUtils.wildcardMatch(zipEntry.getName(), site.getFilePattern())) {
                        // ???.
                        continue;
                    }

                    IContainer savedFolder2 = savedFolder;
                    String wildCardStr = StringUtils.defaultString(site.getFilePattern());
                    if (wildCardStr.contains("*") && wildCardStr.contains("/")) {
                        // ??????.
                        wildCardStr = StringUtils.substringBeforeLast(site.getFilePattern(), "/");
                    }

                    String entryName = zipEntry.getName();
                    if (entryName.startsWith(wildCardStr + "/")) {
                        entryName = entryName.substring(wildCardStr.length() + 1);
                    }

                    if (zipEntry.isDirectory()) {
                        // zip?????.
                        if (StringUtils.isNotEmpty(entryName)) {
                            // ?.
                            savedFolder2 = savedFolder2.getFolder(Path.fromOSString(entryName));
                            if (libraryNode.isAddable() && !savedFolder2.exists()) {
                                logger.log(Messages.SE0091, savedFolder2.getFullPath());
                                H5IOUtils.createParentFolder(savedFolder2, null);
                                logger.log(Messages.SE0092, savedFolder2.getFullPath());
                            } else if (libraryNode.getState() == LibraryState.REMOVE && savedFolder2.exists()) {
                                // .
                                logger.log(Messages.SE0095, savedFolder2.getFullPath());
                                H5IOUtils.createParentFolder(savedFolder2, null);
                                logger.log(Messages.SE0096, savedFolder2.getFullPath());
                            }
                        }
                    } else {
                        // zip.

                        // ???.
                        if (site.getReplaceFileName() != null) {
                            iFile = savedFolder2.getFile(Path.fromOSString(site.getReplaceFileName()));
                        } else {
                            iFile = savedFolder2.getFile(Path.fromOSString(entryName));
                        }

                        // ?.
                        updateFile(monitor, 0, logger, iFile, new ZipFileContentsHandler(zipFile, zipEntry));
                        addStatus = true;
                    }
                }
                if (savedFolder.exists() && savedFolder.members().length == 0) {
                    // ????.
                    savedFolder.delete(true, monitor);
                }
            } else {
                // ???.
                if (site.getReplaceFileName() != null) {
                    iFile = savedFolder.getFile(Path.fromOSString(site.getReplaceFileName()));
                } else {
                    // .
                    iFile = savedFolder.getFile(Path.fromOSString(StringUtils.substringAfterLast(path, "/")));
                }

                // .
                download(monitor, perSiteWork, logger, iFile, siteUrl);
                setWorked = true;
                if (!lastDownloadStatus) {

                    // SE0101=ERROR,({0})??????URL={1}, File={2}
                    logger.log(Messages.SE0101,
                            iFile != null ? iFile.getFullPath().toString()
                                    : StringUtils.defaultString(site.getFilePattern()),
                            site.getUrl(), site.getFilePattern());
                    libraryNode.setInError(true);
                } else {
                    addStatus = true;
                }
            }

            // ?????.

            // .
            if (!addStatus) {
                // SE0099=ERROR,???????URL={1}, File={2}
                logger.log(Messages.SE0099, site.getUrl(), iFile != null ? iFile.getFullPath().toString()
                        : StringUtils.defaultString(site.getFilePattern()));
                libraryNode.setInError(true);
                result = false;
            }

            // folder.refreshLocal(IResource.DEPTH_ZERO, null);
            // // SE0102=INFO,????
            // logger.log(Messages.SE0102);
            // logger.log(Messages.SE0068, iFile.getFullPath());

            if (!setWorked) {
                monitor.worked(perSiteWork);
            }
        }
    } else {
        monitor.worked(perLibWork);
    }

    return result;
}

From source file:com.adobe.communities.ugc.migration.importer.ImportFileUploadServlet.java

private void saveExplodedFiles(final ResourceResolver resolver, final Resource folder, final JSONWriter writer,
        final ZipInputStream zipInputStream, final String basePath) throws ServletException {

    // we need the closeShieldInputStream to prevent the zipInputStream from being closed during resolver.create()
    final CloseShieldInputStream closeShieldInputStream = new CloseShieldInputStream(zipInputStream);

    // fileResourceProperties and folderProperties will be reused inside the while loop
    final Map<String, Object> fileResourceProperties = new HashMap<String, Object>();
    fileResourceProperties.put(JcrConstants.JCR_PRIMARYTYPE, JcrConstants.NT_FILE);

    final Map<String, Object> folderProperties = new HashMap<String, Object>();
    folderProperties.put(JcrConstants.JCR_PRIMARYTYPE, "sling:Folder");

    ZipEntry zipEntry;//from   w  ww  . j a v a 2  s.  co m
    try {
        zipEntry = zipInputStream.getNextEntry();
    } catch (final IOException e) {
        throw new ServletException("Unable to read entries from uploaded zip archive", e);
    }
    final List<Resource> toDelete = new ArrayList<Resource>();
    while (zipEntry != null) {
        // store files under the provided folder
        try {
            final String name = ResourceUtil.normalize("/" + zipEntry.getName());
            if (null == name) {
                // normalize filename and if they aren't inside upload path, don't store them
                continue;
            }
            Resource parent = folder;
            Resource subFolder = null;
            for (final String subFolderName : name.split("/")) {
                // check if the sub-folder already exists
                subFolder = resolver.getResource(parent, subFolderName);
                if (null == subFolder || subFolder instanceof NonExistingResource) {
                    // create the sub-folder
                    subFolder = resolver.create(parent, subFolderName, folderProperties);
                }
                parent = subFolder;
            }
            if (!zipEntry.isDirectory()) {
                // first represent the file as a resource
                final Resource file = resolver.create(subFolder, "file", fileResourceProperties);
                // now store its data as a jcr:content node
                final Map<String, Object> fileProperties = new HashMap<String, Object>();
                byte[] bytes = IOUtils.toByteArray(closeShieldInputStream);
                fileProperties.put(JcrConstants.JCR_DATA, new String(bytes, "UTF8"));
                fileProperties.put(JcrConstants.JCR_PRIMARYTYPE, "nt:resource");
                resolver.create(file, JcrConstants.JCR_CONTENT, fileProperties);

                // if provided a basePath, import immediately
                if (StringUtils.isNotBlank(basePath) && null != file
                        && !(file instanceof NonExistingResource)) {
                    Resource fileContent = file.getChild(JcrConstants.JCR_CONTENT);
                    if (null != fileContent && !(fileContent instanceof NonExistingResource)) {
                        final ValueMap contentVM = fileContent.getValueMap();
                        InputStream inputStream = (InputStream) contentVM.get(JcrConstants.JCR_DATA);
                        if (inputStream != null) {
                            final JsonParser jsonParser = new JsonFactory().createParser(inputStream);
                            jsonParser.nextToken(); // get the first token
                            String resName = basePath + name.substring(0, name.lastIndexOf(".json"));
                            Resource resource = resolver.getResource(resName);
                            if (resource == null) {
                                // voting does not have a node under articles
                                resource = resolver.getResource(resName.substring(0, resName.lastIndexOf("/")));
                            }
                            try {
                                importFile(jsonParser, resource, resolver);
                                toDelete.add(file);
                            } catch (final Exception e) {
                                // add the file name to our response ONLY if we failed to import it
                                writer.value(name);
                                // we want to log the reason we weren't able to import, but don't stop importing
                                LOG.error(e.getMessage());
                            }
                        }
                    }
                } else if (StringUtils.isBlank(basePath) && null != file
                        && !(file instanceof NonExistingResource)) {
                    // add the file name to our response
                    writer.value(name);
                }
            }
            resolver.commit();
            zipEntry = zipInputStream.getNextEntry();
        } catch (final IOException e) {
            // convert any IOExceptions into ServletExceptions
            throw new ServletException(e.getMessage(), e);
        } catch (final JSONException e) {
            // convert any JSONExceptions into ServletExceptions
            throw new ServletException(e.getMessage(), e);
        }
    }
    closeShieldInputStream.close();
    // delete any files that were successfully imported
    if (!toDelete.isEmpty()) {
        for (final Resource deleteResource : toDelete) {
            deleteResource(deleteResource);
        }
    }
}

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

/**
 * This method deploys the war in exploded form and configures it. 
 * @param file//from w  ww.j  av a 2  s.  co  m
 * @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.mirth.connect.server.controllers.DefaultExtensionController.java

@Override
public InstallationResult extractExtension(InputStream inputStream) {
    Throwable cause = null;//from www .  j  a  va  2s.  co m
    Set<MetaData> metaDataSet = new HashSet<MetaData>();

    File installTempDir = new File(ExtensionController.getExtensionsPath(), "install_temp");

    if (!installTempDir.exists()) {
        installTempDir.mkdir();
    }

    File tempFile = null;
    FileOutputStream tempFileOutputStream = null;
    ZipFile zipFile = null;

    try {
        /*
         * create a new temp file (in the install temp dir) to store the zip file contents
         */
        tempFile = File.createTempFile(ServerUUIDGenerator.getUUID(), ".zip", installTempDir);
        // write the contents of the multipart fileitem to the temp file
        try {
            tempFileOutputStream = new FileOutputStream(tempFile);
            IOUtils.copy(inputStream, tempFileOutputStream);
        } finally {
            IOUtils.closeQuietly(tempFileOutputStream);
        }

        // create a new zip file from the temp file
        zipFile = new ZipFile(tempFile);
        // get a list of all of the entries in the zip file
        Enumeration<? extends ZipEntry> entries = zipFile.entries();

        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            String entryName = entry.getName();

            if (entryName.endsWith("plugin.xml") || entryName.endsWith("destination.xml")
                    || entryName.endsWith("source.xml")) {
                // parse the extension metadata xml file
                MetaData extensionMetaData = serializer
                        .deserialize(IOUtils.toString(zipFile.getInputStream(entry)), MetaData.class);
                metaDataSet.add(extensionMetaData);

                if (!extensionLoader.isExtensionCompatible(extensionMetaData)) {
                    if (cause == null) {
                        cause = new VersionMismatchException("Extension \"" + entry.getName()
                                + "\" is not compatible with this version of Mirth Connect.");
                    }
                }
            }
        }

        if (cause == null) {
            // reset the entries and extract
            entries = zipFile.entries();

            while (entries.hasMoreElements()) {
                ZipEntry entry = entries.nextElement();

                if (entry.isDirectory()) {
                    /*
                     * assume directories are stored parents first then children.
                     * 
                     * TODO: this is not robust, just for demonstration purposes.
                     */
                    File directory = new File(installTempDir, entry.getName());
                    directory.mkdir();
                } else {
                    // otherwise, write the file out to the install temp dir
                    InputStream zipInputStream = zipFile.getInputStream(entry);
                    OutputStream outputStream = new BufferedOutputStream(
                            new FileOutputStream(new File(installTempDir, entry.getName())));
                    IOUtils.copy(zipInputStream, outputStream);
                    IOUtils.closeQuietly(zipInputStream);
                    IOUtils.closeQuietly(outputStream);
                }
            }
        }
    } catch (Throwable t) {
        cause = new ControllerException("Error extracting extension. " + t.toString(), t);
    } finally {
        if (zipFile != null) {
            try {
                zipFile.close();
            } catch (Exception e) {
                cause = new ControllerException(e);
            }
        }

        // delete the temp file since it is no longer needed
        FileUtils.deleteQuietly(tempFile);
    }

    return new InstallationResult(cause, metaDataSet);
}

From source file:edu.harvard.iq.dvn.core.web.study.AddFilesPage.java

private List<StudyFileEditBean> createStudyFilesFromZip(File uploadedInputFile) {
    List<StudyFileEditBean> fbList = new ArrayList<StudyFileEditBean>();

    // This is a Zip archive that we want to unpack, then upload/ingest individual
    // files separately

    ZipInputStream ziStream = null;
    ZipEntry zEntry = null;
    FileOutputStream tempOutStream = null;

    try {//from  w  ww  .j  av  a2s  .  co  m
        // Create ingest directory for the study: 
        File dir = new File(uploadedInputFile.getParentFile(), study.getId().toString());
        if (!dir.exists()) {
            dir.mkdir();
        }

        // Open Zip stream: 

        ziStream = new ZipInputStream(new FileInputStream(uploadedInputFile));

        if (ziStream == null) {
            return null;
        }
        while ((zEntry = ziStream.getNextEntry()) != null) {
            // Note that some zip entries may be directories - we 
            // simply skip them:
            if (!zEntry.isDirectory()) {

                String fileEntryName = zEntry.getName();

                if (fileEntryName != null && !fileEntryName.equals("")) {

                    String dirName = null;
                    String finalFileName = null;

                    int ind = fileEntryName.lastIndexOf('/');

                    if (ind > -1) {
                        finalFileName = fileEntryName.substring(ind + 1);
                        if (ind > 0) {
                            dirName = fileEntryName.substring(0, ind);
                            dirName = dirName.replace('/', '-');
                        }
                    } else {
                        finalFileName = fileEntryName;
                    }

                    // http://superuser.com/questions/212896/is-there-any-way-to-prevent-a-mac-from-creating-dot-underscore-files
                    if (!finalFileName.startsWith("._")) {
                        File tempUploadedFile = FileUtil.createTempFile(dir, finalFileName);

                        tempOutStream = new FileOutputStream(tempUploadedFile);

                        byte[] dataBuffer = new byte[8192];
                        int i = 0;

                        while ((i = ziStream.read(dataBuffer)) > 0) {
                            tempOutStream.write(dataBuffer, 0, i);
                            tempOutStream.flush();
                        }

                        tempOutStream.close();

                        // We now have the unzipped file saved in the upload directory;

                        StudyFileEditBean tempFileBean = new StudyFileEditBean(tempUploadedFile,
                                studyService.generateFileSystemNameSequence(), study);
                        tempFileBean.setSizeFormatted(tempUploadedFile.length());

                        // And, if this file was in a legit (non-null) directory, 
                        // we'll use its name as the file category: 

                        if (dirName != null) {
                            tempFileBean.getFileMetadata().setCategory(dirName);
                        }

                        fbList.add(tempFileBean);
                    }
                }
            }
            ziStream.closeEntry();

        }

    } catch (Exception ex) {
        String msg = "Failed ot unpack Zip file/create individual study files";

        dbgLog.warning(msg);
        dbgLog.warning(ex.getMessage());

        //return null; 
    } finally {
        if (ziStream != null) {
            try {
                ziStream.close();
            } catch (Exception zEx) {
            }
        }
        if (tempOutStream != null) {
            try {
                tempOutStream.close();
            } catch (Exception ioEx) {
            }
        }
    }

    // should we delete uploadedInputFile before return?
    return fbList;
}

From source file:UnZip.java

/**
 * Process one file from the zip, given its name. Either print the name, or
 * create the file on disk./*w  w w  . j  a  v  a2  s . c  o  m*/
 */
protected void getFile(ZipEntry e) throws IOException {
    String zipName = e.getName();
    switch (mode) {
    case EXTRACT:
        if (zipName.startsWith("/")) {
            if (!warnedMkDir)
                System.out.println("Ignoring absolute paths");
            warnedMkDir = true;
            zipName = zipName.substring(1);
        }
        // if a directory, just return. We mkdir for every file,
        // since some widely-used Zip creators don't put out
        // any directory entries, or put them in the wrong place.
        if (zipName.endsWith("/")) {
            return;
        }
        // Else must be a file; open the file for output
        // Get the directory part.
        int ix = zipName.lastIndexOf('/');
        if (ix > 0) {
            String dirName = zipName.substring(0, ix);
            if (!dirsMade.contains(dirName)) {
                File d = new File(dirName);
                // If it already exists as a dir, don't do anything
                if (!(d.exists() && d.isDirectory())) {
                    // Try to create the directory, warn if it fails
                    System.out.println("Creating Directory: " + dirName);
                    if (!d.mkdirs()) {
                        System.err.println("Warning: unable to mkdir " + dirName);
                    }
                    dirsMade.add(dirName);
                }
            }
        }
        System.err.println("Creating " + zipName);
        FileOutputStream os = new FileOutputStream(zipName);
        InputStream is = zippy.getInputStream(e);
        int n = 0;
        while ((n = is.read(b)) > 0)
            os.write(b, 0, n);
        is.close();
        os.close();
        break;
    case LIST:
        // Not extracting, just list
        if (e.isDirectory()) {
            System.out.println("Directory " + zipName);
        } else {
            System.out.println("File " + zipName);
        }
        break;
    default:
        throw new IllegalStateException("mode value (" + mode + ") bad");
    }
}

From source file:com.idega.slide.business.IWSlideServiceBean.java

/**
 * Uploads zip file's contents to slide. Note: only *.zip file allowed!
 *
 * @param zipInputStream:/*w  w  w  .  ja v a  2  s.co m*/
 *            a stream to read the file and its content from
 * @param uploadPath:
 *            a path in slide where to store files (for example:
 *            "/files/public/")
 * @return result: success (true) or failure (false) while uploading file
 */
@Override
public boolean uploadZipFileContents(ZipInputStream zipInputStream, String uploadPath) {
    boolean result = (uploadPath == null || CoreConstants.EMPTY.equals(uploadPath)) ? false : true; // Checking if
    // parameters are valid
    if (!result) {
        LOGGER.warning("Invalid upload path!");
        return result;
    }
    result = zipInputStream == null ? false : true;
    if (!result) {
        LOGGER.warning("ZipInputStream is closed!");
        return result;
    }

    ZipEntry entry = null;
    ZipInstaller zip = new ZipInstaller();
    ByteArrayOutputStream memory = null;
    InputStream is = null;
    String pathToFile = null;
    String fileName = null;
    try {
        while ((entry = zipInputStream.getNextEntry()) != null && result) {
            if (!entry.isDirectory()) {
                pathToFile = CoreConstants.EMPTY;
                fileName = StringHandler.removeCharacters(entry.getName(), CoreConstants.SPACE,
                        CoreConstants.UNDER);
                fileName = StringHandler.removeCharacters(fileName, CoreConstants.BRACKET_LEFT,
                        CoreConstants.EMPTY);
                fileName = StringHandler.removeCharacters(fileName, CoreConstants.BRACKET_RIGHT,
                        CoreConstants.EMPTY);
                int lastSlash = fileName.lastIndexOf(CoreConstants.SLASH);
                if (lastSlash != -1) {
                    pathToFile = fileName.substring(0, lastSlash + 1);
                    fileName = fileName.substring(lastSlash + 1, fileName.length());
                }
                if (!fileName.startsWith(CoreConstants.DOT)) { // If not a system file
                    memory = new ByteArrayOutputStream();
                    zip.writeFromStreamToStream(zipInputStream, memory);
                    is = new ByteArrayInputStream(memory.toByteArray());
                    result = uploadFile(uploadPath + pathToFile, fileName, null, is);
                    memory.close();
                    is.close();
                }
            }
            zip.closeEntry(zipInputStream);
        }
    } catch (IOException e) {
        LOGGER.log(Level.WARNING, "Error uploading zip file to: " + uploadPath, e);
        return false;
    } finally {
        zip.closeEntry(zipInputStream);
    }
    return result;
}

From source file:com.mobicage.rogerthat.plugins.messaging.BrandingMgr.java

private void extractJSEmbedding(final JSEmbeddingItemTO packet)
        throws BrandingFailureException, NoSuchAlgorithmException, FileNotFoundException, IOException {
    File brandingCache = getJSEmbeddingPacketFile(packet.name);
    if (!brandingCache.exists())
        throw new BrandingFailureException("Javascript package not found!");

    File jsRootDir = getJSEmbeddingRootDirectory();
    if (!(jsRootDir.exists() || jsRootDir.mkdir()))
        throw new BrandingFailureException("Could not create private javascript dir!");

    File jsPacketDir = getJSEmbeddingPacketDirectory(packet.name);
    if (jsPacketDir.exists() && !SystemUtils.deleteDir(jsPacketDir))
        throw new BrandingFailureException("Could not delete existing javascript dir");
    if (!jsPacketDir.mkdir())
        throw new BrandingFailureException("Could not create javascript dir");

    MessageDigest digester = MessageDigest.getInstance("SHA256");
    DigestInputStream dis = new DigestInputStream(new BufferedInputStream(new FileInputStream(brandingCache)),
            digester);//from w ww.  j a v  a 2s .  co m
    try {
        ZipInputStream zis = new ZipInputStream(dis);
        try {
            byte data[] = new byte[BUFFER_SIZE];
            ZipEntry entry;
            while ((entry = zis.getNextEntry()) != null) {
                L.d("Extracting: " + entry);
                int count = 0;
                if (entry.isDirectory()) {
                    L.d("Skipping javascript dir " + entry.getName());
                    continue;
                }
                File destination = new File(jsPacketDir, entry.getName());
                destination.getParentFile().mkdirs();
                final OutputStream fos = new BufferedOutputStream(new FileOutputStream(destination),
                        BUFFER_SIZE);
                try {
                    while ((count = zis.read(data, 0, BUFFER_SIZE)) != -1) {
                        fos.write(data, 0, count);
                    }
                } finally {
                    fos.close();
                }
            }
            while (dis.read(data) >= 0)
                ;
        } finally {
            zis.close();
        }
    } finally {
        dis.close();
    }
}