Example usage for java.util.zip ZipInputStream close

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

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes this input stream and releases any system resources associated with the stream.

Usage

From source file:org.etudes.jforum.view.admin.ImportExportAction.java

/**
 * unzip the file and write to disk/*w ww  . j  a  v a  2 s  .  c om*/
 * 
 * @param zipfile
 * @param dirpath
 * @throws FileNotFoundException
 * @throws IOException
 */
private void unZipFile(File zipfile, String dirpath) throws Exception {
    FileInputStream fis = new FileInputStream(zipfile);
    ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
    ZipEntry entry;
    while ((entry = zis.getNextEntry()) != null) {
        if (entry.isDirectory()) {

        } else if (entry.getName().lastIndexOf('\\') != -1) {
            String filenameincpath = entry.getName();

            String actFileNameIncPath = dirpath;

            while (filenameincpath.indexOf('\\') != -1) {
                String subFolName = filenameincpath.substring(0, filenameincpath.indexOf('\\'));

                File subfol = new File(actFileNameIncPath + File.separator + subFolName);
                if (!subfol.exists())
                    subfol.mkdirs();

                actFileNameIncPath = actFileNameIncPath + File.separator + subFolName;

                filenameincpath = filenameincpath.substring(filenameincpath.indexOf('\\') + 1);
            }

            String filename = entry.getName().substring(entry.getName().lastIndexOf('\\') + 1);
            unzip(zis, actFileNameIncPath + File.separator + filename);
        } else if (entry.getName().lastIndexOf('/') != -1) {
            String filenameincpath = entry.getName();

            String actFileNameIncPath = dirpath;

            while (filenameincpath.indexOf('/') != -1) {
                String subFolName = filenameincpath.substring(0, filenameincpath.indexOf('/'));
                File subfol = new File(actFileNameIncPath + File.separator + subFolName);
                if (!subfol.exists())
                    subfol.mkdirs();

                actFileNameIncPath = actFileNameIncPath + File.separator + subFolName;

                filenameincpath = filenameincpath.substring(filenameincpath.indexOf('/') + 1);
            }

            String filename = entry.getName().substring(entry.getName().lastIndexOf('/') + 1);
            unzip(zis, actFileNameIncPath + File.separator + filename);
        } else
            unzip(zis, dirpath + File.separator + entry.getName());
    }
    zis.close();
}

From source file:com.orange.mmp.midlet.MidletManager.java

/**
 * Get Midlet for download./*from   w ww  .  j  av  a2s. co  m*/
 * @param appId            The midlet main application ID
 * @param mobile          The mobile to use
 * @param isMidletSigned   Boolean indicating if the midlet is signed (true), unsigned (false), to sign (null)
 * @throws IOException
 */
@SuppressWarnings("unchecked")
public ByteArrayOutputStream getJar(String appId, Mobile mobile, Boolean isMidletSigned) throws MMPException {
    if (appId == null)
        appId = ServiceManager.getInstance().getDefaultService().getId();

    //Search in Cache first
    String jarKey = appId + isMidletSigned + mobile.getKey();

    if (this.midletCache.isKeyInCache(jarKey)) {
        return (ByteArrayOutputStream) this.midletCache.get(jarKey).getValue();
    }

    Object extraCSSJadAttr = null;

    //Not found, build the JAR
    ByteArrayOutputStream output = null;
    ZipOutputStream zipOut = null;
    ZipInputStream zipIn = null;
    InputStream resourceStream = null;
    try {
        Midlet midlet = new Midlet();
        midlet.setType(mobile.getMidletType());
        Midlet[] midlets = (Midlet[]) DaoManagerFactory.getInstance().getDaoManager().getDao("midlet")
                .find(midlet);
        if (midlets.length == 0)
            throw new MMPException("Midlet type not found : " + mobile.getMidletType());
        else
            midlet = midlets[0];

        //Get navigation widget
        Widget appWidget = WidgetManager.getInstance().getWidget(appId, mobile.getBranchId());
        if (appWidget == null) {
            // Use Default if not found
            appWidget = WidgetManager.getInstance().getWidget(appId);
        }
        List<URL> embeddedResources = WidgetManager.getInstance().findWidgetResources("/m4m/", "*", appId,
                mobile.getBranchId(), false);
        output = new ByteArrayOutputStream();
        zipOut = new ZipOutputStream(output);
        zipIn = new ZipInputStream(new FileInputStream(new File(new URI(midlet.getJarLocation()))));

        ZipEntry entry;
        while ((entry = zipIn.getNextEntry()) != null) {
            zipOut.putNextEntry(entry);

            // Manifest found, modify it before delivery
            if (entry.getName().equals(Constants.JAR_MANIFEST_ENTRY) && appWidget != null) {
                Manifest midletManifest = new Manifest(zipIn);

                // TODO ? Remove optional permissions if midlet is not signed
                if (isMidletSigned != null && !isMidletSigned)
                    midletManifest.getMainAttributes().remove(Constants.JAD_PARAMETER_OPT_PERMISSIONS);

                midletManifest.getMainAttributes().putValue(Constants.JAD_PARAMETER_APPNAME,
                        appWidget.getName());
                String launcherLine = midletManifest.getMainAttributes()
                        .getValue(Constants.JAD_PARAMETER_LAUNCHER);
                Matcher launcherLineMatcher = launcherPattern.matcher(launcherLine);
                if (launcherLineMatcher.matches()) {
                    midletManifest.getMainAttributes().putValue(Constants.JAD_PARAMETER_LAUNCHER,
                            appWidget.getName().concat(", ").concat(launcherLineMatcher.group(2)).concat(", ")
                                    .concat(launcherLineMatcher.group(3)));
                } else
                    midletManifest.getMainAttributes().putValue(Constants.JAD_PARAMETER_LAUNCHER,
                            appWidget.getName());

                // Add/Modify/Delete MANIFEST parameters according to mobile rules
                JadAttributeAction[] jadActions = mobile.getJadAttributeActions();
                for (JadAttributeAction jadAction : jadActions) {
                    if (jadAction.getInManifest().equals(ApplyCase.ALWAYS)
                            || (isMidletSigned != null && isMidletSigned
                                    && jadAction.getInManifest().equals(ApplyCase.SIGNED))
                            || (isMidletSigned != null && !isMidletSigned
                                    && jadAction.getInManifest().equals(ApplyCase.UNSIGNED))) {
                        Attributes.Name attrName = new Attributes.Name(jadAction.getAttribute());
                        boolean exists = midletManifest.getMainAttributes().get(attrName) != null;
                        if (jadAction.isAddAction() || jadAction.isModifyAction()) {
                            if (exists || !jadAction.isStrict())
                                midletManifest.getMainAttributes().putValue(jadAction.getAttribute(),
                                        jadAction.getValue());
                        } else if (jadAction.isDeleteAction() && exists)
                            midletManifest.getMainAttributes().remove(attrName);
                    }
                }

                //Retrieve MeMo CSS extra attribute
                extraCSSJadAttr = midletManifest.getMainAttributes()
                        .get(new Attributes.Name(Constants.JAD_PARAMETER_MEMO_EXTRA_CSS));

                midletManifest.write(zipOut);
            }
            //Other files of Midlet
            else {
                IOUtils.copy(zipIn, zipOut);
            }
            zipIn.closeEntry();
            zipOut.closeEntry();
        }

        if (embeddedResources != null) {
            for (URL resourceUrl : embeddedResources) {
                resourceStream = resourceUrl.openConnection().getInputStream();
                String resourcePath = resourceUrl.getPath();
                entry = new ZipEntry(resourcePath.substring(resourcePath.lastIndexOf("/") + 1));
                entry.setTime(MIDLET_LAST_MODIFICATION_DATE);
                zipOut.putNextEntry(entry);
                IOUtils.copy(resourceStream, zipOut);
                zipOut.closeEntry();
                resourceStream.close();
            }
        }

        //Put JAR in cache for next uses
        this.midletCache.set(new Element(jarKey, output));

        //If necessary, add special CSS file if specified in JAD attributes
        if (extraCSSJadAttr != null) {
            String extraCSSSheetName = (String) extraCSSJadAttr;
            //Get resource stream
            resourceStream = WidgetManager.getInstance().getWidgetResource(
                    extraCSSSheetName + "/" + this.cssSheetsBundleName, mobile.getBranchId());

            if (resourceStream == null)
                throw new DataAccessResourceFailureException("no CSS sheet named " + extraCSSSheetName + " in "
                        + this.cssSheetsBundleName + " special bundle");

            //Append CSS sheet file into JAR
            entry = new ZipEntry(new File(extraCSSSheetName).getName());
            entry.setTime(MidletManager.MIDLET_LAST_MODIFICATION_DATE);
            zipOut.putNextEntry(entry);
            IOUtils.copy(resourceStream, zipOut);
            zipOut.closeEntry();
            resourceStream.close();
        }

        return output;

    } catch (IOException ioe) {
        throw new MMPException(ioe);
    } catch (URISyntaxException use) {
        throw new MMPException(use);
    } catch (DataAccessException dae) {
        throw new MMPException(dae);
    } finally {
        try {
            if (output != null)
                output.close();
            if (zipIn != null)
                zipIn.close();
            if (zipOut != null)
                zipOut.close();
            if (resourceStream != null)
                resourceStream.close();
        } catch (IOException ioe) {
            //NOP
        }
    }
}

From source file:lu.fisch.unimozer.Diagram.java

/**
 * http://snippets.dzone.com/posts/show/3468
 * modified to create the zip file if it does not exist
 * /*from   w ww.j  a va  2 s.  c  o m*/
 * @param zipFile
 * @param files
 * @throws IOException
 */
public void addFilesToExistingZip(File zipFile, String baseDir, File directory) throws IOException {
    ZipOutputStream out;
    File tempFile = null;

    byte[] buf = new byte[1024];
    boolean delete = false;

    if (zipFile.exists()) {
        delete = true;
        // get a temp file
        tempFile = File.createTempFile(zipFile.getName(), null);
        // delete it, otherwise you cannot rename your existing zip to it.
        tempFile.delete();

        boolean renameOk = zipFile.renameTo(tempFile);
        if (!renameOk) {
            throw new RuntimeException("could not rename the file " + zipFile.getAbsolutePath() + " to "
                    + tempFile.getAbsolutePath());
        }

        ZipInputStream zin = new ZipInputStream(new FileInputStream(tempFile));
        out = new ZipOutputStream(new FileOutputStream(zipFile));

        ZipEntry entry = zin.getNextEntry();
        while (entry != null) {
            String name = entry.getName();
            boolean notInFiles = true;
            /*
            for (File f : files)
            {
            if (f.getName().equals(name))
            {
                notInFiles = false;
                break;
            }
            }*/
            if (notInFiles) {
                // Add ZIP entry to output stream.
                out.putNextEntry(new ZipEntry(name));
                // Transfer bytes from the ZIP file to the output file
                int len;
                while ((len = zin.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
            }
            entry = zin.getNextEntry();
        }
        // Close the streams
        zin.close();
    } else {
        out = new ZipOutputStream(new FileOutputStream(zipFile));
    }
    /*
    // Compress the files
    for (int i = 0; i < files.length; i++)
    {
    InputStream in = new FileInputStream(files[i]);
    // Add ZIP entry to output stream.
    out.putNextEntry(new ZipEntry(files[i].getName()));
    // Transfer bytes from the file to the ZIP file
    int len;
    while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
    }
    // Complete the entry
    out.closeEntry();
    in.close();
    }
    */

    addToZip(out, baseDir, directory);

    // Complete the ZIP file
    out.close();

    if (delete == true)
        tempFile.delete();
}

From source file:eu.esdihumboldt.hale.io.appschema.writer.AppSchemaFileWriterTest.java

private void checkArchive(File archive) throws IOException {
    final File tempFile = File.createTempFile(Long.toString(System.currentTimeMillis()), ".xml");
    ZipInputStream zis = null;
    Document doc = null;/*from  ww w . jav  a 2  s  . co m*/
    try {
        zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(archive)));

        ZipEntry lcvWsDir = zis.getNextEntry();
        checkDirEntry(lcvWsDir, "lcv/");
        zis.closeEntry();

        ZipEntry lcvWsFile = zis.getNextEntry();
        checkFileEntry(lcvWsFile, "lcv/" + AppSchemaIO.WORKSPACE_FILE);
        doc = readDocument(zis);
        checkWorkspaceDocument(doc, "lcv_workspace", "lcv");
        zis.closeEntry();

        ZipEntry lcvNsFile = zis.getNextEntry();
        checkFileEntry(lcvNsFile, "lcv/" + AppSchemaIO.NAMESPACE_FILE);
        doc = readDocument(zis);
        checkNamespaceDocument(doc, "lcv_namespace", "lcv", "http://inspire.ec.europa.eu/schemas/lcv/3.0");
        zis.closeEntry();

        ZipEntry lcvDataStoreDir = zis.getNextEntry();
        checkDirEntry(lcvDataStoreDir, "lcv/LandCoverVector/");
        zis.closeEntry();

        ZipEntry lcvDataStoreFile = zis.getNextEntry();
        checkFileEntry(lcvDataStoreFile, "lcv/LandCoverVector/" + AppSchemaIO.DATASTORE_FILE);
        doc = readDocument(zis);
        assertNotNull(doc);
        assertEquals("LandCoverVector_datastore",
                getFirstElementByTagName(doc.getDocumentElement(), "id").getTextContent());
        assertEquals("LandCoverVector",
                getFirstElementByTagName(doc.getDocumentElement(), "name").getTextContent());
        Element wsEl = getFirstElementByTagName(doc.getDocumentElement(), "workspace");
        assertNotNull(wsEl);
        assertEquals("lcv_workspace", getFirstElementByTagName(wsEl, "id").getTextContent());
        NodeList paramEntries = doc.getDocumentElement().getElementsByTagName("entry");
        assertNotNull(paramEntries);
        assertEquals(3, paramEntries.getLength());
        for (int i = 0; i < paramEntries.getLength(); i++) {
            Node param = paramEntries.item(i);
            Node key = param.getAttributes().getNamedItem("key");
            if ("dbtype".equals(key.getTextContent())) {
                assertEquals("app-schema", param.getTextContent());
            } else if ("namespace".equals(key.getTextContent())) {
                assertEquals("http://inspire.ec.europa.eu/schemas/lcv/3.0", param.getTextContent());
            } else if ("url".equals(key.getTextContent())) {
                assertEquals("file:./workspaces/lcv/LandCoverVector/LandCoverVector.xml",
                        param.getTextContent());
            } else {
                fail("Unknown connection parameter found: " + key.getTextContent());
            }
        }
        zis.closeEntry();

        ZipEntry mappingFile = zis.getNextEntry();
        checkFileEntry(mappingFile, "lcv/LandCoverVector/LandCoverVector.xml");
        ByteStreams.copy(zis, new FileOutputStream(tempFile));
        assertTrue(isMappingValid(tempFile));
        zis.closeEntry();

        ZipEntry unitFtDir = zis.getNextEntry();
        checkDirEntry(unitFtDir, "lcv/LandCoverVector/LandCoverUnit/");
        zis.closeEntry();

        ZipEntry unitFtFile = zis.getNextEntry();
        checkFileEntry(unitFtFile, "lcv/LandCoverVector/LandCoverUnit/" + AppSchemaIO.FEATURETYPE_FILE);
        doc = readDocument(zis);
        checkFeatureTypeDocument(doc, "LandCoverUnit");
        zis.closeEntry();

        ZipEntry unitLayerFile = zis.getNextEntry();
        checkFileEntry(unitLayerFile, "lcv/LandCoverVector/LandCoverUnit/" + AppSchemaIO.LAYER_FILE);
        doc = readDocument(zis);
        checkLayerDocument(doc, "LandCoverUnit");
        zis.closeEntry();

        ZipEntry datasetFtDir = zis.getNextEntry();
        checkDirEntry(datasetFtDir, "lcv/LandCoverVector/LandCoverDataset/");
        zis.closeEntry();

        ZipEntry datasetFtFile = zis.getNextEntry();
        checkFileEntry(datasetFtFile, "lcv/LandCoverVector/LandCoverDataset/" + AppSchemaIO.FEATURETYPE_FILE);
        doc = readDocument(zis);
        checkFeatureTypeDocument(doc, "LandCoverDataset");
        zis.closeEntry();

        ZipEntry datasetLayerFile = zis.getNextEntry();
        checkFileEntry(datasetLayerFile, "lcv/LandCoverVector/LandCoverDataset/" + AppSchemaIO.LAYER_FILE);
        doc = readDocument(zis);
        checkLayerDocument(doc, "LandCoverDataset");
        zis.closeEntry();

        ZipEntry baseWsDir = zis.getNextEntry();
        checkDirEntry(baseWsDir, "base/");
        zis.closeEntry();

        ZipEntry baseWsFile = zis.getNextEntry();
        checkFileEntry(baseWsFile, "base/" + AppSchemaIO.WORKSPACE_FILE);
        doc = readDocument(zis);
        checkWorkspaceDocument(doc, "base_workspace", "base");
        zis.closeEntry();

        ZipEntry baseNsFile = zis.getNextEntry();
        checkFileEntry(baseNsFile, "base/" + AppSchemaIO.NAMESPACE_FILE);
        doc = readDocument(zis);
        checkNamespaceDocument(doc, "base_namespace", "base", "http://inspire.ec.europa.eu/schemas/base/3.3");
        zis.closeEntry();

        ZipEntry gmlWsDir = zis.getNextEntry();
        checkDirEntry(gmlWsDir, "gml/");
        zis.closeEntry();

        ZipEntry gmlWsFile = zis.getNextEntry();
        checkFileEntry(gmlWsFile, "gml/" + AppSchemaIO.WORKSPACE_FILE);
        doc = readDocument(zis);
        checkWorkspaceDocument(doc, "gml_workspace", "gml");
        zis.closeEntry();

        ZipEntry gmlNsFile = zis.getNextEntry();
        checkFileEntry(gmlNsFile, "gml/" + AppSchemaIO.NAMESPACE_FILE);
        doc = readDocument(zis);
        checkNamespaceDocument(doc, "gml_namespace", "gml", "http://www.opengis.net/gml/3.2");
        zis.closeEntry();

        ZipEntry xlinkWsDir = zis.getNextEntry();
        checkDirEntry(xlinkWsDir, "xlink/");
        zis.closeEntry();

        ZipEntry xlinkWsFile = zis.getNextEntry();
        checkFileEntry(xlinkWsFile, "xlink/" + AppSchemaIO.WORKSPACE_FILE);
        doc = readDocument(zis);
        checkWorkspaceDocument(doc, "xlink_workspace", "xlink");
        zis.closeEntry();

        ZipEntry xlinkNsFile = zis.getNextEntry();
        checkFileEntry(xlinkNsFile, "xlink/" + AppSchemaIO.NAMESPACE_FILE);
        doc = readDocument(zis);
        checkNamespaceDocument(doc, "xlink_namespace", "xlink", "http://www.w3.org/1999/xlink");
        zis.closeEntry();

        ZipEntry xsiWsDir = zis.getNextEntry();
        checkDirEntry(xsiWsDir, "xsi/");
        zis.closeEntry();

        ZipEntry xsiWsFile = zis.getNextEntry();
        checkFileEntry(xsiWsFile, "xsi/" + AppSchemaIO.WORKSPACE_FILE);
        doc = readDocument(zis);
        checkWorkspaceDocument(doc, "xsi_workspace", "xsi");
        zis.closeEntry();

        ZipEntry xsiNsFile = zis.getNextEntry();
        checkFileEntry(xsiNsFile, "xsi/" + AppSchemaIO.NAMESPACE_FILE);
        doc = readDocument(zis);
        checkNamespaceDocument(doc, "xsi_namespace", "xsi", AppSchemaMappingUtils.XSI_URI);
        zis.closeEntry();

        assertNull(zis.getNextEntry());
    } catch (ZipException e) {
        fail("Exception reading generated ZIP archive: " + e.getMessage());
    } finally {
        if (tempFile != null)
            tempFile.delete();
        if (zis != null)
            zis.close();
    }
}

From source file:com.portfolio.data.provider.MysqlAdminProvider.java

public static String unzip(String zipFile, String destinationFolder) throws FileNotFoundException, IOException {
    String folder = "";
    File zipfile = new File(zipFile);
    ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(zipfile)));

    ZipEntry ze = null;//from  w ww.j a v a  2s .c  om
    try {
        while ((ze = zis.getNextEntry()) != null) {

            //folder = zipfile.getCanonicalPath().substring(0, zipfile.getCanonicalPath().length()-4)+"/";
            folder = destinationFolder;
            File f = new File(folder, ze.getName());

            if (ze.isDirectory()) {
                f.mkdirs();
                continue;
            }

            f.getParentFile().mkdirs();
            OutputStream fos = new BufferedOutputStream(new FileOutputStream(f));
            try {
                try {
                    final byte[] buf = new byte[8192];
                    int bytesRead;
                    while (-1 != (bytesRead = zis.read(buf)))
                        fos.write(buf, 0, bytesRead);
                } finally {
                    fos.close();
                }
            } catch (final IOException ioe) {
                f.delete();
                throw ioe;
            }
        }
    } finally {
        zis.close();
    }
    return folder;
}

From source file:edu.harvard.iq.dataverse.ingest.IngestServiceBean.java

public List<DataFile> createDataFiles(DatasetVersion version, InputStream inputStream, String fileName,
        String suppliedContentType) throws IOException {
    List<DataFile> datafiles = new ArrayList<DataFile>();

    String warningMessage = null;

    // save the file, in the temporary location for now: 
    Path tempFile = null;/*w w  w  . j a v a2 s  . com*/

    if (getFilesTempDirectory() != null) {
        tempFile = Files.createTempFile(Paths.get(getFilesTempDirectory()), "tmp", "upload");
        // "temporary" location is the key here; this is why we are not using 
        // the DataStore framework for this - the assumption is that 
        // temp files will always be stored on the local filesystem. 
        //          -- L.A. Jul. 2014
        logger.fine("Will attempt to save the file as: " + tempFile.toString());
        Files.copy(inputStream, tempFile, StandardCopyOption.REPLACE_EXISTING);
    } else {
        throw new IOException("Temp directory is not configured.");
    }
    logger.fine("mime type supplied: " + suppliedContentType);
    // Let's try our own utilities (Jhove, etc.) to determine the file type 
    // of the uploaded file. (We may already have a mime type supplied for this
    // file - maybe the type that the browser recognized on upload; or, if 
    // it's a harvest, maybe the remote server has already given us the type
    // for this file... with our own type utility we may or may not do better 
    // than the type supplied:
    //  -- L.A. 
    String recognizedType = null;
    String finalType = null;
    try {
        recognizedType = FileUtil.determineFileType(tempFile.toFile(), fileName);
        logger.fine("File utility recognized the file as " + recognizedType);
        if (recognizedType != null && !recognizedType.equals("")) {
            // is it any better than the type that was supplied to us,
            // if any?
            // This is not as trivial a task as one might expect... 
            // We may need a list of "good" mime types, that should always
            // be chosen over other choices available. Maybe it should 
            // even be a weighed list... as in, "application/foo" should 
            // be chosen over "application/foo-with-bells-and-whistles".

            // For now the logic will be as follows: 
            //
            // 1. If the contentType supplied (by the browser, most likely) 
            // is some form of "unknown", we always discard it in favor of 
            // whatever our own utilities have determined; 
            // 2. We should NEVER trust the browser when it comes to the 
            // following "ingestable" types: Stata, SPSS, R;
            // 2a. We are willing to TRUST the browser when it comes to
            //  the CSV and XSLX ingestable types.
            // 3. We should ALWAYS trust our utilities when it comes to 
            // ingestable types. 

            if (suppliedContentType == null || suppliedContentType.equals("")
                    || suppliedContentType.equalsIgnoreCase(MIME_TYPE_UNDETERMINED_DEFAULT)
                    || suppliedContentType.equalsIgnoreCase(MIME_TYPE_UNDETERMINED_BINARY)
                    || (ingestableAsTabular(suppliedContentType)
                            && !suppliedContentType.equalsIgnoreCase(MIME_TYPE_CSV)
                            && !suppliedContentType.equalsIgnoreCase(MIME_TYPE_CSV_ALT)
                            && !suppliedContentType.equalsIgnoreCase(MIME_TYPE_XLSX))
                    || ingestableAsTabular(recognizedType) || recognizedType.equals("application/fits-gzipped")
                    || recognizedType.equalsIgnoreCase(ShapefileHandler.SHAPEFILE_FILE_TYPE)
                    || recognizedType.equals(MIME_TYPE_ZIP)) {
                finalType = recognizedType;
            }
        }

    } catch (Exception ex) {
        logger.warning("Failed to run the file utility mime type check on file " + fileName);
    }

    if (finalType == null) {
        finalType = (suppliedContentType == null || suppliedContentType.equals(""))
                ? MIME_TYPE_UNDETERMINED_DEFAULT
                : suppliedContentType;
    }

    // A few special cases: 

    // if this is a gzipped FITS file, we'll uncompress it, and ingest it as
    // a regular FITS file:

    if (finalType.equals("application/fits-gzipped")) {

        InputStream uncompressedIn = null;
        String finalFileName = fileName;
        // if the file name had the ".gz" extension, remove it, 
        // since we are going to uncompress it:
        if (fileName != null && fileName.matches(".*\\.gz$")) {
            finalFileName = fileName.replaceAll("\\.gz$", "");
        }

        DataFile datafile = null;
        try {
            uncompressedIn = new GZIPInputStream(new FileInputStream(tempFile.toFile()));
            datafile = createSingleDataFile(version, uncompressedIn, finalFileName,
                    MIME_TYPE_UNDETERMINED_DEFAULT);
        } catch (IOException ioex) {
            datafile = null;
        } finally {
            if (uncompressedIn != null) {
                try {
                    uncompressedIn.close();
                } catch (IOException e) {
                }
            }
        }

        // If we were able to produce an uncompressed file, we'll use it 
        // to create and return a final DataFile; if not, we're not going
        // to do anything - and then a new DataFile will be created further 
        // down, from the original, uncompressed file.
        if (datafile != null) {
            // remove the compressed temp file: 
            try {
                tempFile.toFile().delete();
            } catch (SecurityException ex) {
                // (this is very non-fatal)
                logger.warning("Failed to delete temporary file " + tempFile.toString());
            }

            datafiles.add(datafile);
            return datafiles;
        }

        // If it's a ZIP file, we are going to unpack it and create multiple 
        // DataFile objects from its contents:
    } else if (finalType.equals("application/zip")) {

        ZipInputStream unZippedIn = null;
        ZipEntry zipEntry = null;

        int fileNumberLimit = systemConfig.getZipUploadFilesLimit();

        try {
            Charset charset = null;
            /*
            TODO: (?)
            We may want to investigate somehow letting the user specify 
            the charset for the filenames in the zip file...
            - otherwise, ZipInputStream bails out if it encounteres a file 
            name that's not valid in the current charest (i.e., UTF-8, in 
            our case). It would be a bit trickier than what we're doing for 
            SPSS tabular ingests - with the lang. encoding pulldown menu - 
            because this encoding needs to be specified *before* we upload and
            attempt to unzip the file. 
                -- L.A. 4.0 beta12
            logger.info("default charset is "+Charset.defaultCharset().name());
            if (Charset.isSupported("US-ASCII")) {
            logger.info("charset US-ASCII is supported.");
            charset = Charset.forName("US-ASCII");
            if (charset != null) {
                logger.info("was able to obtain charset for US-ASCII");
            }
                    
            }
            */

            if (charset != null) {
                unZippedIn = new ZipInputStream(new FileInputStream(tempFile.toFile()), charset);
            } else {
                unZippedIn = new ZipInputStream(new FileInputStream(tempFile.toFile()));
            }

            while (true) {
                try {
                    zipEntry = unZippedIn.getNextEntry();
                } catch (IllegalArgumentException iaex) {
                    // Note: 
                    // ZipInputStream documentation doesn't even mention that 
                    // getNextEntry() throws an IllegalArgumentException!
                    // but that's what happens if the file name of the next
                    // entry is not valid in the current CharSet. 
                    //      -- L.A.
                    warningMessage = "Failed to unpack Zip file. (Unknown Character Set used in a file name?) Saving the file as is.";
                    logger.warning(warningMessage);
                    throw new IOException();
                }

                if (zipEntry == null) {
                    break;
                }
                // Note that some zip entries may be directories - we 
                // simply skip them:

                if (!zipEntry.isDirectory()) {
                    if (datafiles.size() > fileNumberLimit) {
                        logger.warning("Zip upload - too many files.");
                        warningMessage = "The number of files in the zip archive is over the limit ("
                                + fileNumberLimit
                                + "); please upload a zip archive with fewer files, if you want them to be ingested "
                                + "as individual DataFiles.";
                        throw new IOException();
                    }

                    String fileEntryName = zipEntry.getName();
                    logger.fine("ZipEntry, file: " + fileEntryName);

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

                        String shortName = fileEntryName.replaceFirst("^.*[\\/]", "");

                        // Check if it's a "fake" file - a zip archive entry 
                        // created for a MacOS X filesystem element: (these 
                        // start with "._")
                        if (!shortName.startsWith("._") && !shortName.startsWith(".DS_Store")
                                && !"".equals(shortName)) {
                            // OK, this seems like an OK file entry - we'll try 
                            // to read it and create a DataFile with it:

                            DataFile datafile = createSingleDataFile(version, unZippedIn, shortName,
                                    MIME_TYPE_UNDETERMINED_DEFAULT, false);

                            if (!fileEntryName.equals(shortName)) {
                                String categoryName = fileEntryName.replaceFirst("[\\/][^\\/]*$", "");
                                if (!"".equals(categoryName)) {
                                    logger.fine("setting category to " + categoryName);
                                    //datafile.getFileMetadata().setCategory(categoryName.replaceAll("[\\/]", "-"));
                                    datafile.getFileMetadata()
                                            .addCategoryByName(categoryName.replaceAll("[\\/]", "-"));
                                }
                            }

                            if (datafile != null) {
                                // We have created this datafile with the mime type "unknown";
                                // Now that we have it saved in a temporary location, 
                                // let's try and determine its real type:

                                String tempFileName = getFilesTempDirectory() + "/"
                                        + datafile.getStorageIdentifier();

                                try {
                                    recognizedType = FileUtil.determineFileType(new File(tempFileName),
                                            shortName);
                                    logger.fine("File utility recognized unzipped file as " + recognizedType);
                                    if (recognizedType != null && !recognizedType.equals("")) {
                                        datafile.setContentType(recognizedType);
                                    }
                                } catch (Exception ex) {
                                    logger.warning("Failed to run the file utility mime type check on file "
                                            + fileName);
                                }

                                datafiles.add(datafile);
                            }
                        }
                    }
                }
                unZippedIn.closeEntry();

            }

        } catch (IOException ioex) {
            // just clear the datafiles list and let 
            // ingest default to creating a single DataFile out
            // of the unzipped file. 
            logger.warning("Unzipping failed; rolling back to saving the file as is.");
            if (warningMessage == null) {
                warningMessage = "Failed to unzip the file. Saving the file as is.";
            }

            datafiles.clear();
        } finally {
            if (unZippedIn != null) {
                try {
                    unZippedIn.close();
                } catch (Exception zEx) {
                }
            }
        }
        if (datafiles.size() > 0) {
            // link the data files to the dataset/version: 
            Iterator<DataFile> itf = datafiles.iterator();
            while (itf.hasNext()) {
                DataFile datafile = itf.next();
                datafile.setOwner(version.getDataset());
                if (version.getFileMetadatas() == null) {
                    version.setFileMetadatas(new ArrayList());
                }
                version.getFileMetadatas().add(datafile.getFileMetadata());
                datafile.getFileMetadata().setDatasetVersion(version);

                /* TODO!!
                // re-implement this in some way that does not use the 
                // deprecated .getCategory() on FileMeatadata:
                if (datafile.getFileMetadata().getCategory() != null) {
                datafile.getFileMetadata().addCategoryByName(datafile.getFileMetadata().getCategory());
                datafile.getFileMetadata().setCategory(null);
                -- done? see above?
                }
                */
                version.getDataset().getFiles().add(datafile);
            }
            // remove the uploaded zip file: 
            try {
                Files.delete(tempFile);
            } catch (IOException ioex) {
                // do nothing - it's just a temp file.
                logger.warning("Could not remove temp file " + tempFile.getFileName().toString());
            }
            // and return:
            return datafiles;
        }

    } else if (finalType.equalsIgnoreCase(ShapefileHandler.SHAPEFILE_FILE_TYPE)) {
        // Shape files may have to be split into multiple files, 
        // one zip archive per each complete set of shape files:

        //File rezipFolder = new File(this.getFilesTempDirectory());
        File rezipFolder = this.getShapefileUnzipTempDirectory();

        IngestServiceShapefileHelper shpIngestHelper;
        shpIngestHelper = new IngestServiceShapefileHelper(tempFile.toFile(), rezipFolder);

        boolean didProcessWork = shpIngestHelper.processFile();
        if (!(didProcessWork)) {
            logger.severe("Processing of zipped shapefile failed.");
            return null;
        }
        for (File finalFile : shpIngestHelper.getFinalRezippedFiles()) {
            FileInputStream finalFileInputStream = new FileInputStream(finalFile);
            finalType = this.getContentType(finalFile);
            if (finalType == null) {
                logger.warning("Content type is null; but should default to 'MIME_TYPE_UNDETERMINED_DEFAULT'");
                continue;
            }
            DataFile new_datafile = createSingleDataFile(version, finalFileInputStream, finalFile.getName(),
                    finalType);
            if (new_datafile != null) {
                datafiles.add(new_datafile);
            } else {
                logger.severe("Could not add part of rezipped shapefile. new_datafile was null: "
                        + finalFile.getName());
            }
            finalFileInputStream.close();

        }

        // Delete the temp directory used for unzipping
        /*
        logger.fine("Delete temp shapefile unzip directory: " + rezipFolder.getAbsolutePath());
        FileUtils.deleteDirectory(rezipFolder);
                
        // Delete rezipped files
        for (File finalFile : shpIngestHelper.getFinalRezippedFiles()){
        if (finalFile.isFile()){
            finalFile.delete();
        }
        }
        */

        if (datafiles.size() > 0) {
            return datafiles;
        } else {
            logger.severe("No files added from directory of rezipped shapefiles");
        }
        return null;

    }

    // Finally, if none of the special cases above were applicable (or 
    // if we were unable to unpack an uploaded file, etc.), we'll just 
    // create and return a single DataFile:
    // (Note that we are passing null for the InputStream; that's because
    // we already have the file saved; we'll just need to rename it, below)

    DataFile datafile = createSingleDataFile(version, null, fileName, finalType);

    if (datafile != null) {
        fileService.generateStorageIdentifier(datafile);
        if (!tempFile.toFile()
                .renameTo(new File(getFilesTempDirectory() + "/" + datafile.getStorageIdentifier()))) {
            return null;
        }

        // MD5:
        MD5Checksum md5Checksum = new MD5Checksum();
        try {
            datafile.setmd5(
                    md5Checksum.CalculateMD5(getFilesTempDirectory() + "/" + datafile.getStorageIdentifier()));
        } catch (Exception md5ex) {
            logger.warning("Could not calculate MD5 signature for new file " + fileName);
        }

        if (warningMessage != null) {
            createIngestFailureReport(datafile, warningMessage);
            datafile.SetIngestProblem();
        }
        datafiles.add(datafile);

        return datafiles;
    }

    return null;
}

From source file:com.panet.imeta.job.entries.zipfile.JobEntryZipFile.java

public boolean processRowFile(Job parentJob, Result result, String realZipfilename, String realWildcard,
        String realWildcardExclude, String realTargetdirectory, String realMovetodirectory,
        boolean createparentfolder) {
    LogWriter log = LogWriter.getInstance();
    boolean Fileexists = false;
    File tempFile = null;//from   w  w  w  . j av  a2 s.  c o  m
    File fileZip = null;
    boolean resultat = false;
    boolean renameOk = false;
    boolean orginexist = false;

    // Check if target file/folder exists!
    FileObject OriginFile = null;
    ZipInputStream zin = null;
    byte[] buffer = null;
    FileOutputStream dest = null;
    BufferedOutputStream buff = null;
    org.apache.tools.zip.ZipOutputStream out = null;
    org.apache.tools.zip.ZipEntry entry = null;

    try {
        OriginFile = KettleVFS.getFileObject(realTargetdirectory);
        orginexist = OriginFile.exists();
    } catch (Exception e) {
    } finally {
        if (OriginFile != null) {
            try {
                OriginFile.close();
            } catch (IOException ex) {
            }
            ;
        }
    }

    if (realZipfilename != null && orginexist) {

        FileObject fileObject = null;
        try {
            fileObject = KettleVFS.getFileObject(realZipfilename);

            // Check if Zip File exists
            if (fileObject.exists()) {
                Fileexists = true;
                if (log.isDebug())
                    log.logDebug(toString(), Messages.getString("JobZipFiles.Zip_FileExists1.Label")
                            + realZipfilename + Messages.getString("JobZipFiles.Zip_FileExists2.Label"));
            }
            // Let's see if we need to create parent folder of destination
            // zip filename
            if (createparentfolder) {
                createParentFolder(realZipfilename);
            }

            // Let's start the process now
            if (ifzipfileexists == 3 && Fileexists) {
                // the zip file exists and user want to Fail
                resultat = false;
            } else if (ifzipfileexists == 2 && Fileexists) {
                // the zip file exists and user want to do nothing
                if (addfiletoresult) {
                    // Add file to result files name
                    ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL,
                            KettleVFS.getFileObject(realZipfilename), parentJob.getJobname(), toString());
                    result.getResultFiles().put(resultFile.getFile().toString(), resultFile);
                }
                resultat = true;
            } else if (afterzip == 2 && realMovetodirectory == null) {
                // After Zip, Move files..User must give a destination
                // Folder
                resultat = false;
                log.logError(toString(),
                        Messages.getString("JobZipFiles.AfterZip_No_DestinationFolder_Defined.Label"));
            } else
            // After Zip, Move files..User must give a destination Folder
            {
                // Let's see if we deal with file or folder
                String[] filelist = null;

                File f = new File(realTargetdirectory);
                if (f.isDirectory()) {
                    // Target is a directory
                    // Get all the files in the directory...
                    filelist = f.list();
                } else {
                    // Target is a file
                    filelist = new String[1];
                    filelist[0] = f.getName();
                }
                if (filelist.length == 0) {
                    resultat = false;
                    log.logError(toString(),
                            Messages.getString("JobZipFiles.Log.FolderIsEmpty", realTargetdirectory));
                } else if (!checkContainsFile(realTargetdirectory, filelist)) {
                    resultat = false;
                    log.logError(toString(),
                            Messages.getString("JobZipFiles.Log.NoFilesInFolder", realTargetdirectory));
                } else {
                    if (ifzipfileexists == 0 && Fileexists) {
                        // the zip file exists and user want to create new
                        // one with unique name
                        // Format Date

                        // do we have already a .zip at the end?
                        if (realZipfilename.toLowerCase().endsWith(".zip")) {
                            // strip this off
                            realZipfilename = realZipfilename.substring(0, realZipfilename.length() - 4);
                        }

                        realZipfilename = realZipfilename + "_" + StringUtil.getFormattedDateTimeNow(true)
                                + ".zip";
                        if (log.isDebug())
                            log.logDebug(toString(),
                                    Messages.getString("JobZipFiles.Zip_FileNameChange1.Label")
                                            + realZipfilename
                                            + Messages.getString("JobZipFiles.Zip_FileNameChange1.Label"));
                    } else if (ifzipfileexists == 1 && Fileexists) {
                        // the zip file exists and user want to append
                        // get a temp file
                        fileZip = new File(realZipfilename);
                        tempFile = File.createTempFile(fileZip.getName(), null);

                        // delete it, otherwise we cannot rename existing
                        // zip to it.
                        tempFile.delete();

                        renameOk = fileZip.renameTo(tempFile);

                        if (!renameOk) {
                            log.logError(toString(),
                                    Messages.getString("JobZipFiles.Cant_Rename_Temp1.Label")
                                            + fileZip.getAbsolutePath()
                                            + Messages.getString("JobZipFiles.Cant_Rename_Temp2.Label")
                                            + tempFile.getAbsolutePath()
                                            + Messages.getString("JobZipFiles.Cant_Rename_Temp3.Label"));
                        }
                        if (log.isDebug())
                            log.logDebug(toString(),
                                    Messages.getString("JobZipFiles.Zip_FileAppend1.Label") + realZipfilename
                                            + Messages.getString("JobZipFiles.Zip_FileAppend2.Label"));
                    }

                    if (log.isDetailed())
                        log.logDetailed(toString(), Messages.getString("JobZipFiles.Files_Found1.Label")
                                + filelist.length + Messages.getString("JobZipFiles.Files_Found2.Label")
                                + realTargetdirectory + Messages.getString("JobZipFiles.Files_Found3.Label"));

                    Pattern pattern = null;
                    Pattern patternexclude = null;
                    // Let's prepare pattern..only if target is a folder !
                    if (f.isDirectory()) {
                        if (!Const.isEmpty(realWildcard)) {
                            pattern = Pattern.compile(realWildcard);
                        }

                        if (!Const.isEmpty(realWildcardExclude)) {
                            patternexclude = Pattern.compile(realWildcardExclude);
                        }
                    }

                    // Prepare Zip File
                    buffer = new byte[18024];
                    dest = new FileOutputStream(realZipfilename);
                    buff = new BufferedOutputStream(dest);
                    out = new org.apache.tools.zip.ZipOutputStream(buff);
                    HashSet<String> fileSet = new HashSet<String>();

                    if (renameOk) {
                        // User want to append files to existing Zip file
                        // The idea is to rename the existing zip file to a
                        // temporary file
                        // and then adds all entries in the existing zip
                        // along with the new files,
                        // excluding the zip entries that have the same name
                        // as one of the new files.

                        zin = new ZipInputStream(new FileInputStream(tempFile));
                        entry = (ZipEntry) zin.getNextEntry();

                        while (entry != null) {
                            String name = entry.getName();

                            if (!fileSet.contains(name)) {

                                // Add ZIP entry to output stream.
                                out.putNextEntry(new ZipEntry(name));
                                // Transfer bytes from the ZIP file to the
                                // output file
                                int len;
                                while ((len = zin.read(buffer)) > 0) {
                                    out.write(buffer, 0, len);
                                }

                                fileSet.add(name);
                            }
                            entry = (ZipEntry) zin.getNextEntry();
                        }
                        // Close the streams
                        zin.close();
                    }

                    // Set the method
                    out.setMethod(org.apache.tools.zip.ZipOutputStream.DEFLATED);
                    // Set the compression level
                    if (compressionrate == 0) {
                        out.setLevel(Deflater.NO_COMPRESSION);
                    } else if (compressionrate == 1) {
                        out.setLevel(Deflater.DEFAULT_COMPRESSION);
                    }
                    if (compressionrate == 2) {
                        out.setLevel(Deflater.BEST_COMPRESSION);
                    }
                    if (compressionrate == 3) {
                        out.setLevel(Deflater.BEST_SPEED);
                    }
                    // Specify Zipped files (After that we will move,delete
                    // them...)
                    String[] ZippedFiles = new String[filelist.length];
                    int FileNum = 0;

                    // Get the files in the list...
                    for (int i = 0; i < filelist.length && !parentJob.isStopped(); i++) {
                        boolean getIt = true;
                        boolean getItexclude = false;

                        // First see if the file matches the regular
                        // expression!
                        // ..only if target is a folder !
                        if (f.isDirectory()) {
                            if (pattern != null) {
                                Matcher matcher = pattern.matcher(filelist[i]);
                                getIt = matcher.matches();
                            }

                            if (patternexclude != null) {
                                Matcher matcherexclude = patternexclude.matcher(filelist[i]);
                                getItexclude = matcherexclude.matches();
                            }
                        }
                        // Get processing File
                        String targetFilename = realTargetdirectory + Const.FILE_SEPARATOR + filelist[i];
                        if (f.isFile())
                            targetFilename = realTargetdirectory;

                        File file = new File(targetFilename);

                        if (getIt && !getItexclude && !file.isDirectory() && !fileSet.contains(filelist[i])) {

                            // We can add the file to the Zip Archive
                            if (log.isDebug())
                                log.logDebug(toString(),
                                        Messages.getString("JobZipFiles.Add_FilesToZip1.Label") + filelist[i]
                                                + Messages.getString("JobZipFiles.Add_FilesToZip2.Label")
                                                + realTargetdirectory
                                                + Messages.getString("JobZipFiles.Add_FilesToZip3.Label"));

                            // Associate a file input stream for the current
                            // file
                            FileInputStream in = new FileInputStream(targetFilename);
                            // Add ZIP entry to output stream.
                            out.putNextEntry(new ZipEntry(filelist[i]));

                            int len;
                            while ((len = in.read(buffer)) > 0) {
                                out.write(buffer, 0, len);
                            }
                            out.flush();
                            out.closeEntry();

                            // Close the current file input stream
                            in.close();

                            // Get Zipped File
                            ZippedFiles[FileNum] = filelist[i];
                            FileNum = FileNum + 1;
                        }
                    }
                    // Close the ZipOutPutStream
                    out.close();
                    buff.close();
                    dest.close();

                    if (log.isBasic())
                        log.logBasic(toString(), Messages.getString("JobZipFiles.Log.TotalZippedFiles",
                                "" + ZippedFiles.length));
                    // Delete Temp File
                    if (tempFile != null) {
                        tempFile.delete();
                    }

                    // -----Get the list of Zipped Files and Move or Delete
                    // Them
                    if (afterzip == 1 || afterzip == 2) {
                        // iterate through the array of Zipped files
                        for (int i = 0; i < ZippedFiles.length; i++) {
                            if (ZippedFiles[i] != null) {
                                // Delete File
                                FileObject fileObjectd = KettleVFS.getFileObject(
                                        realTargetdirectory + Const.FILE_SEPARATOR + ZippedFiles[i]);
                                if (f.isFile())
                                    fileObjectd = KettleVFS.getFileObject(realTargetdirectory);

                                // Here gc() is explicitly called if e.g.
                                // createfile is used in the same
                                // job for the same file. The problem is
                                // that after creating the file the
                                // file object is not properly garbaged
                                // collected and thus the file cannot
                                // be deleted anymore. This is a known
                                // problem in the JVM.

                                System.gc();

                                // Here we can move, delete files
                                if (afterzip == 1) {

                                    // Delete File
                                    boolean deleted = fileObjectd.delete();
                                    if (!deleted) {
                                        resultat = false;
                                        log.logError(toString(), Messages
                                                .getString("JobZipFiles.Cant_Delete_File1.Label")
                                                + realTargetdirectory + Const.FILE_SEPARATOR + ZippedFiles[i]
                                                + Messages.getString("JobZipFiles.Cant_Delete_File2.Label"));

                                    }
                                    // File deleted
                                    if (log.isDebug())
                                        log.logDebug(toString(),
                                                Messages.getString("JobZipFiles.File_Deleted1.Label")
                                                        + realTargetdirectory + Const.FILE_SEPARATOR
                                                        + ZippedFiles[i] + Messages
                                                                .getString("JobZipFiles.File_Deleted2.Label"));
                                } else if (afterzip == 2) {
                                    // Move File
                                    try {
                                        FileObject fileObjectm = KettleVFS.getFileObject(
                                                realMovetodirectory + Const.FILE_SEPARATOR + ZippedFiles[i]);
                                        fileObjectd.moveTo(fileObjectm);
                                    } catch (IOException e) {
                                        log.logError(toString(),
                                                Messages.getString("JobZipFiles.Cant_Move_File1.Label")
                                                        + ZippedFiles[i]
                                                        + Messages
                                                                .getString("JobZipFiles.Cant_Move_File2.Label")
                                                        + e.getMessage());
                                        resultat = false;
                                    }
                                    // File moved
                                    if (log.isDebug())
                                        log.logDebug(toString(),
                                                Messages.getString("JobZipFiles.File_Moved1.Label")
                                                        + ZippedFiles[i]
                                                        + Messages.getString("JobZipFiles.File_Moved2.Label"));
                                }
                            }
                        }
                    }

                    if (addfiletoresult) {
                        // Add file to result files name
                        ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL,
                                KettleVFS.getFileObject(realZipfilename), parentJob.getJobname(), toString());
                        result.getResultFiles().put(resultFile.getFile().toString(), resultFile);
                    }

                    resultat = true;
                }
            }
        } catch (Exception e) {
            log.logError(toString(),
                    Messages.getString("JobZipFiles.Cant_CreateZipFile1.Label") + realZipfilename
                            + Messages.getString("JobZipFiles.Cant_CreateZipFile2.Label") + e.getMessage());
            // result.setResult( false );
            // result.setNrErrors(1);
            resultat = false;
        } finally {
            if (fileObject != null) {
                try {
                    fileObject.close();
                } catch (IOException ex) {
                }
                ;
            }
            // Close the ZipOutPutStream
            try {
                if (out != null)
                    out.close();
                if (buff != null)
                    buff.close();
                if (dest != null)
                    dest.close();
                if (zin != null)
                    zin.close();
                if (entry != null)
                    entry = null;

            } catch (IOException ex) {
            }
            ;
        }
    } else {
        resultat = true;
        if (realZipfilename == null)
            log.logError(toString(), Messages.getString("JobZipFiles.No_ZipFile_Defined.Label"));
        if (!orginexist)
            log.logError(toString(),
                    Messages.getString("JobZipFiles.No_FolderCible_Defined.Label", realTargetdirectory));
    }
    // return a verifier
    return resultat;
}

From source file:com.portfolio.data.provider.MysqlDataProvider.java

public static String unzip(String zipFile, String destinationFolder) throws FileNotFoundException, IOException {
    String folder = "";
    File zipfile = new File(zipFile);
    ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(zipfile)));

    ZipEntry ze = null;//  w w w  .j  ava  2s.c o m
    try {
        while ((ze = zis.getNextEntry()) != null) {
            //folder = zipfile.getCanonicalPath().substring(0, zipfile.getCanonicalPath().length()-4)+"/";
            folder = destinationFolder;
            File f = new File(folder, ze.getName());

            if (ze.isDirectory()) {
                f.mkdirs();
                continue;
            }

            f.getParentFile().mkdirs();
            OutputStream fos = new BufferedOutputStream(new FileOutputStream(f));
            try {
                try {
                    final byte[] buf = new byte[8192];
                    int bytesRead;
                    while (-1 != (bytesRead = zis.read(buf)))
                        fos.write(buf, 0, bytesRead);
                } finally {
                    fos.close();
                }
            } catch (final IOException ioe) {
                f.delete();
                throw ioe;
            }
        }
    } finally {
        zis.close();
    }
    return folder;
}

From source file:jp.co.opentone.bsol.linkbinder.service.correspon.impl.CorresponSearchServiceImplTest.java

/**
 * ZIP?./*  w ww .ja v a 2  s . c o m*/
 */
@Test
public void testGenerateZip() throws Exception {
    MockAbstractService.RET_CURRENT_PROJECT_ID = "PJ1";

    //  ?????
    //  ???????????
    //  ????
    Correspon noNotAssigned = new Correspon();
    PropertyUtils.copyProperties(noNotAssigned, list.get(list.size() - 1));
    noNotAssigned.setCorresponNo(null);
    noNotAssigned.setId(Long.valueOf(list.size() + 1));

    list.add(noNotAssigned);

    Correspon c = new Correspon();
    c.setId(7L);
    c.setCorresponNo("YOC:OT:BUILDING-00007");
    CorresponGroup from = new CorresponGroup();
    from.setId(new Long(6L));
    from.setName("YOC:BUILDING");
    c.setFromCorresponGroup(from);
    c.setSubject("Mock");
    List<AddressCorresponGroup> addressGroups = new ArrayList<AddressCorresponGroup>();
    AddressCorresponGroup addressGroup = new AddressCorresponGroup();
    CorresponGroup group = new CorresponGroup();
    group.setId(2L);
    group.setName("YOC:IT");
    addressGroup.setCorresponGroup(group);
    addressGroup.setAddressType(AddressType.TO);
    addressGroups.add(addressGroup);
    addressGroup = new AddressCorresponGroup();
    group = new CorresponGroup();
    group.setId(2L);
    group.setName("TOK:BUILDING");
    addressGroup.setCorresponGroup(group);
    addressGroup.setAddressType(AddressType.CC);
    addressGroups.add(addressGroup);
    c.setAddressCorresponGroups(addressGroups);
    CorresponType ct = new CorresponType();
    ct.setId(new Long(1L));
    ct.setCorresponType("Request");
    c.setCorresponType(ct);
    c.setWorkflowStatus(WorkflowStatus.ISSUED);
    c.setIssuedAt(new GregorianCalendar(2009, 3, 5, 1, 1, 1).getTime());
    c.setCreatedAt(new GregorianCalendar(2009, 3, 1, 1, 1, 1).getTime());
    c.setUpdatedAt(new GregorianCalendar(2009, 3, 10, 10, 10, 10).getTime());
    User u = new User();
    u.setEmpNo("00001");
    u.setNameE("Test User");
    c.setIssuedBy(u);
    c.setCreatedBy(u);
    c.setUpdatedBy(u);
    c.setCorresponStatus(CorresponStatus.OPEN);
    c.setCustomField1Label("FIELD1");
    c.setCustomField1Value("VALUE1");
    c.setCustomField2Label("FIELD2");
    c.setCustomField2Value("VALUE2");
    c.setCustomField3Label("FIELD3");
    c.setCustomField3Value("VALUE3");
    c.setCustomField4Label("FIELD4");
    c.setCustomField4Value("VALUE4");
    c.setCustomField5Label("FIELD5");
    c.setCustomField5Value("VALUE5");
    c.setCustomField6Label("FIELD6");
    c.setCustomField6Value("VALUE6");
    c.setCustomField7Label("FIELD7");
    c.setCustomField7Value("VALUE7");
    c.setCustomField8Label("FIELD8");
    c.setCustomField8Value("VALUE8");
    c.setCustomField9Label("FIELD9");
    c.setCustomField9Value("VALUE9");
    c.setCustomField10Label("FIELD10");
    c.setCustomField10Value("VALUE10");
    c.setWorkflows(new ArrayList<Workflow>());
    c.setPreviousRevCorresponId(null);
    group = new CorresponGroup();
    group.setName("YOC:IT");
    c.setToCorresponGroup(group);
    c.setToCorresponGroupCount(2L);
    c.setIssuedAt(null);
    c.setIssuedBy(null);
    c.setReplyRequired(null);
    c.setDeadlineForReply(null);
    list.add(c);

    MockCorresponService.RET_FIND = list;
    MockAbstractService.CORRESPONS = list;
    byte[] actual = service.generateZip(list);

    ByteArrayInputStream bi = new ByteArrayInputStream(actual);
    ZipInputStream zis = new ZipInputStream(bi);
    byte[] b = new byte[1024];
    StringBuilder sb = new StringBuilder();
    String[] expFileNames = { "PJ1_YOC-OT-BUILDING-00001(0000000001).html",
            "PJ1_YOC-OT-BUILDING-00002(0000000002).html", "PJ1_YOC-OT-BUILDING-00003(0000000003).html",
            "PJ1_YOC-OT-BUILDING-00001-001(0000000004).html", "PJ1_YOC-OT-BUILDING-00001-002(0000000005).html",
            "PJ1_(0000000006).html", "PJ1_YOC-OT-BUILDING-00007(0000000007).html" };
    int index = 0;
    SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat f2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    try {
        for (ZipEntry ze = zis.getNextEntry(); ze != null; ze = zis.getNextEntry()) {
            String expFileName = expFileNames[index];
            assertEquals(expFileName, ze.getName());
            if (ze.isDirectory()) {
                continue;
            }

            c = list.get(index);
            int i;
            while ((i = zis.read(b, 0, b.length)) != -1) {
                sb.append(new String(b, 0, i));
            }
            String html = sb.toString();

            // ??script????????
            assertTrue(html.contains("<body>"));
            assertFalse(html.contains(">Print</a>"));
            assertFalse(html.contains(">Close</a>"));

            // ???
            assertTrue(c.getId().toString(), html.contains(getExpectedString(c.getId().toString())));
            assertTrue(c.getCorresponStatus().getLabel(),
                    html.contains(getExpectedHTMLString(c.getCorresponStatus().getLabel())));

            //  ?????
            //  ?????????
            if (c.getCorresponNo() == null) {
                assertTrue(c.getCorresponNo(),
                        html.contains(getExpectedHTMLString(CorresponPageFormatter.DEFAULT_CORRESPON_NO)));
            } else {
                assertTrue(c.getCorresponNo(), html.contains(getExpectedHTMLString(c.getCorresponNo())));
            }

            assertTrue(c.getWorkflowStatus().getLabel(),
                    html.contains(getExpectedHTMLString(c.getWorkflowStatus().getLabel())));
            if (c.getParentCorresponId() != null) {
                assertTrue(c.getParentCorresponNo(),
                        html.contains(getExpectedHTMLString(c.getParentCorresponNo())));
            }
            if (c.getPreviousRevCorresponId() != null) {
                assertTrue(c.getPreviousRevCorresponNo(),
                        html.contains(getExpectedHTMLString(c.getPreviousRevCorresponNo())));
            }
            assertTrue(c.getFromCorresponGroup().getName() + " " + index,
                    html.contains(getExpectedString(c.getFromCorresponGroup().getName())));
            if (c.getAddressCorresponGroups() != null) {
                for (AddressCorresponGroup addressCorresponGroup : c.getAddressCorresponGroups()) {
                    assertTrue(addressCorresponGroup.getCorresponGroup().getName(),
                            html.contains(addressCorresponGroup.getCorresponGroup().getName()));
                    if (addressCorresponGroup.getUsers() == null) {
                        continue;
                    }
                    for (AddressUser aUser : addressCorresponGroup.getUsers()) {
                        if (addressCorresponGroup.isTo() && aUser.isAttention()) {
                            assertTrue(aUser.getUser().getLabel(), html.contains(aUser.getUser().getLabel()));
                            if (aUser.getPersonInCharges() != null) {
                                assertTrue(aUser.getPersonInCharges().get(0).getUser().getLabel(),
                                        html.contains(aUser.getPersonInCharges().get(0).getUser().getLabel()));
                            }
                        } else if (addressCorresponGroup.isTo() && !aUser.isAttention()) {
                            assertFalse(aUser.getUser().getLabel(), html.contains(aUser.getUser().getLabel()));
                        } else if (addressCorresponGroup.isCc() && aUser.isCc()) {
                            assertTrue(aUser.getUser().getLabel(), html.contains(aUser.getUser().getLabel()));
                        }
                    }
                }
            }
            assertTrue(c.getCorresponType().getName(),
                    html.contains(getExpectedHTMLString(c.getCorresponType().getName())));
            assertTrue(c.getSubject(), html.contains(getExpectedHTMLString(c.getSubject())));
            assertTrue(c.getBody(), html.contains(getExpectedHTMLString(c.getBody())));
            if (ReplyRequired.YES.equals(c.getReplyRequired())) {
                assertTrue(c.getDeadlineForReply().toString(),
                        html.contains(f.format(c.getDeadlineForReply())));
            }
            if (c.getFile1FileName() != null) {
                assertTrue(c.getFile1FileName(), html.contains(c.getFile1FileName()));
            }
            if (c.getFile2FileName() != null) {
                assertTrue(c.getFile2FileName(), html.contains(c.getFile2FileName()));
            }
            if (c.getFile3FileName() != null) {
                assertTrue(c.getFile3FileName(), html.contains(c.getFile3FileName()));
            }
            if (c.getFile4FileName() != null) {
                assertTrue(c.getFile4FileName(), html.contains(c.getFile4FileName()));
            }
            if (c.getFile5FileName() != null) {
                assertTrue(c.getFile5FileName(), html.contains(c.getFile5FileName()));
            }
            if (c.getCustomField1Label() != null) {
                assertTrue(c.getCustomField1Label(),
                        html.contains(getExpectedHTMLString(c.getCustomField1Label())));
                assertTrue(c.getCustomField1Value(), html.contains(c.getCustomField1Value()));
            }
            if (c.getCustomField2Label() != null) {
                assertTrue(c.getCustomField2Label(),
                        html.contains(getExpectedHTMLString(c.getCustomField2Label())));
                assertTrue(c.getCustomField2Value(), html.contains(c.getCustomField2Value()));
            }
            if (c.getCustomField3Label() != null) {
                assertTrue(c.getCustomField3Label(),
                        html.contains(getExpectedHTMLString(c.getCustomField3Label())));
                assertTrue(c.getCustomField3Value(), html.contains(c.getCustomField3Value()));
            }
            if (c.getCustomField4Label() != null) {
                assertTrue(c.getCustomField4Label(),
                        html.contains(getExpectedHTMLString(c.getCustomField4Label())));
                assertTrue(c.getCustomField4Value(), html.contains(c.getCustomField4Value()));
            }
            if (c.getCustomField5Label() != null) {
                assertTrue(c.getCustomField5Label(),
                        html.contains(getExpectedHTMLString(c.getCustomField5Label())));
                assertTrue(c.getCustomField5Value(), html.contains(c.getCustomField5Value()));
            }
            if (c.getCustomField6Label() != null) {
                assertTrue(c.getCustomField6Label(),
                        html.contains(getExpectedHTMLString(c.getCustomField6Label())));
                assertTrue(c.getCustomField6Value(), html.contains(c.getCustomField6Value()));
            }
            if (c.getCustomField7Label() != null) {
                //  ???HTML??????????...
                //  ????????????????
                //  ?
                //                    assertTrue("" + index + "*"+c.getCustomField7Label()+"*",
                //                        html.contains(getExpectedHTMLString(c.getCustomField7Label())));
                //                    assertTrue(c.getCustomField7Value(),
                //                        html.contains(c.getCustomField7Value()));
            }
            if (c.getCustomField8Label() != null) {
                assertTrue(c.getCustomField8Label(),
                        html.contains(getExpectedHTMLString(c.getCustomField8Label())));
                assertTrue(c.getCustomField8Value(), html.contains(c.getCustomField8Value()));
            }
            if (c.getCustomField9Label() != null) {
                assertTrue(c.getCustomField9Label(),
                        html.contains(getExpectedHTMLString(c.getCustomField9Label())));
                assertTrue(c.getCustomField9Value(), html.contains(c.getCustomField9Value()));
            }
            if (c.getCustomField10Label() != null) {
                assertTrue(c.getCustomField10Label(),
                        html.contains(getExpectedHTMLString(c.getCustomField10Label())));
                assertTrue(c.getCustomField10Value(), html.contains(c.getCustomField10Value()));
            }
            //Created??????????
            //                assertTrue(c.getCreatedAt().toString(),
            //                   html.contains(getExpectedHTMLString(f2.format(c.getCreatedAt()))));
            if (c.getIssuedAt() != null) {
                assertTrue(c.getIssuedAt().toString(),
                        html.contains(getExpectedHTMLString(f2.format(c.getIssuedAt()))));
            }
            assertTrue(c.getUpdatedAt().toString(),
                    html.contains(getExpectedHTMLString(f2.format(c.getUpdatedAt()))));
            //Created??????????
            //                assertTrue(c.getCreatedBy().getNameE() + "/" + c.getCreatedBy().getEmpNo(),
            //                    html.contains(
            //                        c.getCreatedBy().getNameE() + "/" + c.getCreatedBy().getEmpNo()));
            if ((c.getIssuedBy() != null) && (c.getIssuedBy().getNameE() != null)
                    && (c.getIssuedBy().getEmpNo() != null)) {
                assertTrue(c.getIssuedBy().getNameE() + "/" + c.getIssuedBy().getEmpNo(),
                        html.contains(c.getIssuedBy().getNameE() + "/" + c.getIssuedBy().getEmpNo()));
            }
            assertTrue(c.getUpdatedBy().getNameE() + "/" + c.getUpdatedBy().getEmpNo(),
                    html.contains(c.getUpdatedBy().getNameE() + "/" + c.getUpdatedBy().getEmpNo()));
            if (c.getWorkflows() != null) {
                for (Workflow flow : c.getWorkflows()) {
                    assertTrue(flow.getWorkflowNo().toString(),
                            html.contains(getExpectedHTMLString(flow.getWorkflowNo().toString())));
                    assertTrue(flow.getWorkflowType().getLabel(),
                            html.contains(getExpectedHTMLString(flow.getWorkflowType().getLabel())));
                    assertTrue(flow.getUser().getNameE() + "/" + flow.getUser().getEmpNo(), html.contains(
                            getExpectedString(flow.getUser().getNameE() + "/" + flow.getUser().getEmpNo())));
                    assertTrue(flow.getWorkflowProcessStatus().getLabel(),
                            html.contains(getExpectedString(flow.getWorkflowProcessStatus().getLabel())));
                    if (flow.getUpdatedBy() != null) {
                        assertTrue(flow.getUpdatedBy().getNameE() + "/" + flow.getUpdatedBy().getEmpNo(),
                                html.contains(getExpectedString(flow.getUpdatedBy().getNameE() + "/"
                                        + flow.getUpdatedBy().getEmpNo())));
                        assertTrue(flow.getUpdatedAt().toString(),
                                html.contains(f2.format(flow.getUpdatedAt())));
                    }
                    assertTrue(flow.getCommentOn(), html.contains(getExpectedString(flow.getCommentOn())));
                }
            }

            index++;
        }
    } finally {
        zis.close();
        bi.close();
    }
}