Example usage for java.util.zip ZipEntry setTime

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

Introduction

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

Prototype

public void setTime(long time) 

Source Link

Document

Sets the last modification time of the entry.

Usage

From source file:org.fuin.utils4j.Utils4J.java

/**
 * Adds a file to a ZIP output stream./*from  ww w. j a v  a 2  s  . c om*/
 * 
 * @param srcFile
 *            File to add - Cannot be <code>null</code>.
 * @param destPath
 *            Path to use for the file - May be <code>null</code> or empty.
 * @param out
 *            Destination stream - Cannot be <code>null</code>.
 * 
 * @throws IOException
 *             Error writing to the output stream.
 */
private static void zipFile(final File srcFile, final String destPath, final ZipOutputStream out)
        throws IOException {

    final byte[] buf = new byte[1024];
    final InputStream in = new BufferedInputStream(new FileInputStream(srcFile));
    try {
        final ZipEntry zipEntry = new ZipEntry(
                concatPathAndFilename(destPath, srcFile.getName(), File.separator));
        zipEntry.setTime(srcFile.lastModified());
        out.putNextEntry(zipEntry);
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        out.closeEntry();
    } finally {
        in.close();
    }
}

From source file:edu.cmu.tetrad.util.TetradSerializableUtils.java

/**
 * Creates a zip archive of the currently serialized files in
 * getCurrentDirectory(), placing the archive in getArchiveDirectory().
 *
 * @throws RuntimeException if clazz cannot be serialized. This exception
 *                          has an informative message and wraps the
 *                          originally thrown exception as root cause.
 * @see #getCurrentDirectory()//w  ww . ja  v  a  2s. co  m
 * @see #getArchiveDirectory()
 */
public void archiveCurrentDirectory() throws RuntimeException {
    System.out.println("Making zip archive of files in " + getCurrentDirectory() + ", putting it in "
            + getArchiveDirectory() + ".");

    File current = new File(getCurrentDirectory());

    if (!current.exists() || !current.isDirectory()) {
        throw new IllegalArgumentException("There is no " + current.getAbsolutePath() + " directory. "
                + "\nThis is where the serialized classes should be. "
                + "Please run serializeCurrentDirectory() first.");
    }

    File archive = new File(getArchiveDirectory());
    if (archive.exists() && !archive.isDirectory()) {
        throw new IllegalArgumentException(
                "Output directory " + archive.getAbsolutePath() + " is not a directory.");
    }

    if (!archive.exists()) {
        boolean success = archive.mkdirs();
    }

    String[] filenames = current.list();

    // Create a buffer for reading the files
    byte[] buf = new byte[1024];

    try {
        String version = Version.currentRepositoryVersion().toString();

        // Create the ZIP file
        String outFilename = "serializedclasses-" + version + ".zip";
        File _file = new File(getArchiveDirectory(), outFilename);
        FileOutputStream fileOut = new FileOutputStream(_file);
        ZipOutputStream out = new ZipOutputStream(fileOut);

        // Compress the files
        for (String filename : filenames) {
            File file = new File(current, filename);

            FileInputStream in = new FileInputStream(file);

            // Add ZIP entry to output stream.
            ZipEntry entry = new ZipEntry(filename);
            entry.setSize(file.length());
            entry.setTime(file.lastModified());

            out.putNextEntry(entry);

            // 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();
        }

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

        System.out.println("Finished writing zip file " + outFilename + ".");
    } catch (IOException e) {
        throw new RuntimeException("There was an I/O error associated with "
                + "the process of zipping up files in " + getCurrentDirectory() + ".", e);
    }
}

From source file:edu.cmu.tetradapp.util.TetradSerializableUtils.java

/**
 * Creates a zip archive of the currently serialized files in
 * getCurrentDirectory(), placing the archive in getArchiveDirectory().
 *
 * @throws RuntimeException if clazz cannot be serialized. This exception
 *                          has an informative message and wraps the
 *                          originally thrown exception as root cause.
 * @see #getCurrentDirectory()/*  w  ww  .j a  v a 2 s  .  c o  m*/
 * @see #getArchiveDirectory()
 */
public void archiveCurrentDirectory() throws RuntimeException {
    System.out.println("Making zip archive of files in " + getCurrentDirectory() + ", putting it in "
            + getArchiveDirectory() + ".");

    File current = new File(getCurrentDirectory());

    if (!current.exists() || !current.isDirectory()) {
        throw new IllegalArgumentException("There is no " + current.getAbsolutePath() + " directory. "
                + "\nThis is where the serialized classes should be. "
                + "Please run serializeCurrentDirectory() first.");
    }

    File archive = new File(getArchiveDirectory());
    if (archive.exists() && !archive.isDirectory()) {
        throw new IllegalArgumentException(
                "Output directory " + archive.getAbsolutePath() + " is not a directory.");
    }

    if (!archive.exists()) {
        archive.mkdirs();
    }

    String[] filenames = current.list();

    // Create a buffer for reading the files
    byte[] buf = new byte[1024];

    try {
        String version = Version.currentRepositoryVersion().toString();

        // Create the ZIP file
        String outFilename = "serializedclasses-" + version + ".zip";
        File _file = new File(getArchiveDirectory(), outFilename);
        FileOutputStream fileOut = new FileOutputStream(_file);
        ZipOutputStream out = new ZipOutputStream(fileOut);

        // Compress the files
        for (String filename : filenames) {
            File file = new File(current, filename);

            FileInputStream in = new FileInputStream(file);

            // Add ZIP entry to output stream.
            ZipEntry entry = new ZipEntry(filename);
            entry.setSize(file.length());
            entry.setTime(file.lastModified());

            out.putNextEntry(entry);

            // 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();
        }

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

        System.out.println("Finished writing zip file " + outFilename + ".");
    } catch (IOException e) {
        throw new RuntimeException("There was an I/O error associated with "
                + "the process of zipping up files in " + getCurrentDirectory() + ".", e);
    }
}

From source file:com.liferay.ide.server.remote.AbstractRemoteServerPublisher.java

protected void addToZip(IPath path, IResource resource, ZipOutputStream zip, boolean adjustGMTOffset)
        throws IOException, CoreException {
    switch (resource.getType()) {
    case IResource.FILE:
        ZipEntry zipEntry = new ZipEntry(path.toString());

        zip.putNextEntry(zipEntry);/*from ww w  . j  ava  2s  . c o m*/

        InputStream contents = ((IFile) resource).getContents();

        if (adjustGMTOffset) {
            TimeZone currentTimeZone = TimeZone.getDefault();
            Calendar currentDt = new GregorianCalendar(currentTimeZone, Locale.getDefault());

            // Get the Offset from GMT taking current TZ into account
            int gmtOffset = currentTimeZone.getOffset(currentDt.get(Calendar.ERA), currentDt.get(Calendar.YEAR),
                    currentDt.get(Calendar.MONTH), currentDt.get(Calendar.DAY_OF_MONTH),
                    currentDt.get(Calendar.DAY_OF_WEEK), currentDt.get(Calendar.MILLISECOND));

            zipEntry.setTime(System.currentTimeMillis() + (gmtOffset * -1));
        }

        try {
            IOUtils.copy(contents, zip);
        } finally {
            contents.close();
        }

        break;

    case IResource.FOLDER:
    case IResource.PROJECT:
        IContainer container = (IContainer) resource;

        IResource[] members = container.members();

        for (IResource res : members) {
            addToZip(path.append(res.getName()), res, zip, adjustGMTOffset);
        }
    }
}

From source file:edu.umd.cs.eclipse.courseProjectManager.TurninProjectAction.java

public void run(IAction action) {
    // TODO Refactor: Should the places where we raise a dialog and return
    // could throw an exception instead?
    String timeOfSubmission = "t" + System.currentTimeMillis();

    // Make sure we can get the workbench...
    IWorkbench workbench = PlatformUI.getWorkbench();
    if (workbench == null) {
        Dialogs.errorDialog(null, "Warning: project submission failed", "Could not submit project",
                "Internal error: Can't get workbench", IStatus.ERROR);
        return;//from  w w  w  . j  a v a2 s. c  om
    }
    // ...and the workbenchWindow
    IWorkbenchWindow wwin = workbench.getActiveWorkbenchWindow();
    if (wwin == null) {
        Dialogs.errorDialog(null, "Error submitting project", "Could not submit project",
                "Internal error: Can't get workbench window", IStatus.ERROR);
        return;
    }

    // Shell to use as parent of dialogs.
    Shell parent = wwin.getShell();
    // Sanity check.
    if (!(selection instanceof IStructuredSelection)) {
        Dialogs.errorDialog(parent, "Warning: Selection is Invalid",
                "Invalid turnin action: You have selected an object that is not a Project. Please select a Project and try again.",
                "Object selected is not a Project", IStatus.WARNING);
        return;
    }
    IStructuredSelection structured = (IStructuredSelection) selection;
    Object obj = structured.getFirstElement();
    Debug.print("Selection object is a " + obj.getClass().getName() + " @" + System.identityHashCode(obj));
    IProject project;
    if (obj instanceof IProject) {
        project = (IProject) obj;
    } else if (obj instanceof IProjectNature) {
        project = ((IProjectNature) obj).getProject();
    } else {
        Dialogs.errorDialog(null, "Warning: Selection is Invalid",
                "Invalid turnin action: You have selected an object that is not a Project. Please select a Project and try again.",
                "Object selected is not a Project", IStatus.WARNING);
        return;
    }
    Debug.print("Got the IProject for the turnin action @" + System.identityHashCode(project));

    // ================================= save dirty editors
    // ========================================
    // save dirty editors
    try {
        if (!saveDirtyEditors(project, workbench)) {
            Dialogs.errorDialog(parent, "Submit not performed",
                    "Projects cannot be submitted unless all open files are saved",
                    "Unsaved files prevent submission", IStatus.WARNING);
            return;
        }
    } catch (CoreException e) {
        Dialogs.errorDialog(parent, "Submit not performed",
                "Could not turn on cvs management for all project files", e);
        return;
    }

    // ========================= Add all non-ignored files in the project
    // =========================
    IResource[] files;
    try {
        Set<IResource> resourceSet = getProjectResources(project);
        ArrayList<IFile> addedFiles = new ArrayList<IFile>();
        for (Iterator<IResource> iter = resourceSet.iterator(); iter.hasNext();) {
            IResource resource = iter.next();
            if (resource instanceof IFile) {
                IFile file = (IFile) resource;
                if (!AutoCVSPlugin.isCVSIgnored(file) && !AutoCVSPlugin.isCVSManaged(file)) {
                    addedFiles.add(file);
                }
            }
        }
        files = (IResource[]) addedFiles.toArray(new IResource[addedFiles.size()]);
    } catch (CoreException e) {
        Dialogs.errorDialog(parent, "Submit not performed",
                "Could not perform submit; unable to find non-ignored resources", e);
        return;
        // TODO what to do here?
    }

    // ================================= perform CVS commit
    // ========================================
    // TODO Somehow move this into the previous try block
    // This forces add/commit operations when AutoSync was shut off
    // Would it just be easier to enable autoSync and then trigger
    // a resource changed delta, since this method appears to enable
    // autoSync anyway?
    //
    String cvsStatus = "Not performed";
    try {
        cvsStatus = forceCommit(project, files);
    } catch (Exception e) {
        Dialogs.errorDialog(parent,
                "CVS commit not performed as part of submission due to unexpected exception",
                e.getClass().getName() + " " + e.getMessage(), e);
    }

    // ================================= perform CVS tag
    // ========================================
    try {
        CVSOperations.tagProject(project, timeOfSubmission, CVSOperations.SYNC);
    } catch (Exception e) {
        AutoCVSPlugin.getPlugin().getEventLog()
                .logError("Error tagging submission; submission via the web unlikely to work", e);
    }

    // ================================= find properties
    // ========================================
    // find the .submitProject file
    IResource submitProjectFile = project.findMember(AutoCVSPlugin.SUBMITPROJECT);
    if (submitProjectFile == null) {
        Dialogs.errorDialog(parent, "Warning: Project submission not enabled", "Submission is not enabled",
                "There is no " + AutoCVSPlugin.SUBMITPROJECT + " file for the project", IStatus.ERROR);
        return;
    }
    // Get the properties from the .submit file, and the .submitUser file,
    // if it exists
    // or can be fetched from the server
    Properties allSubmissionProps = null;
    try {
        allSubmissionProps = getAllProperties(timeOfSubmission, parent, project, submitProjectFile);
    } catch (IOException e) {
        String message = "IOException finding " + AutoCVSPlugin.SUBMITPROJECT + " and "
                + AutoCVSPlugin.SUBMITUSER + " files; " + cvsStatus;
        AutoCVSPlugin.getPlugin().getEventLog().logError(message, e);
        Dialogs.errorDialog(parent, "Submission failed", message, e.getMessage(), IStatus.ERROR);
        Debug.print("IOException: " + e);
        return;
    } catch (CoreException e) {
        String message = "IOException finding " + AutoCVSPlugin.SUBMITPROJECT + " and "
                + AutoCVSPlugin.SUBMITUSER + " files; " + cvsStatus;
        AutoCVSPlugin.getPlugin().getEventLog().logError(message, e);
        Dialogs.errorDialog(parent, "Submission failed", message, e.getMessage(), IStatus.ERROR);
        Debug.print("CoreException: " + e);
        return;
    }

    //
    // THE ACTUAL SUBMIT HAPPENS HERE
    //
    try {
        // ============================== find files to submit
        // ====================================
        Collection<IFile> cvsFiles = findFilesForSubmission(project);

        // ========================== assemble zip file in byte array
        // ==============================

        ByteArrayOutputStream bytes = new ByteArrayOutputStream(4096);
        ZipOutputStream zipfile = new ZipOutputStream(bytes);
        zipfile.setComment("zipfile for submission created by CourseProjectManager version "
                + AutoCVSPlugin.getPlugin().getVersion());

        try {
            byte[] buf = new byte[4096];
            for (IFile file : cvsFiles) {
                if (!file.exists()) {
                    Debug.print("Resource " + file.getName() + " being ignored because it doesn't exist");
                    continue;
                }

                ZipEntry entry = new ZipEntry(file.getProjectRelativePath().toString());
                entry.setTime(file.getModificationStamp());

                zipfile.putNextEntry(entry);
                // Copy file data to zip file
                InputStream in = file.getContents();

                try {
                    while (true) {
                        int n = in.read(buf);
                        if (n < 0)
                            break;
                        zipfile.write(buf, 0, n);
                    }
                } finally {
                    in.close();
                }
                zipfile.closeEntry();
            }
        } catch (IOException e1) {
            Dialogs.errorDialog(parent, "Warning: Project submission failed",
                    "Unable to zip files for submission\n" + cvsStatus, e1);
            return;
        } finally {
            if (zipfile != null)
                zipfile.close();
        }

        // ============================== Post to submit server
        // ====================================
        String version = System.getProperties().getProperty("java.runtime.version");
        boolean useEasyHttps = version.startsWith("1.3") || version.startsWith("1.2")
                || version.startsWith("1.4.0") || version.startsWith("1.4.1")
                || version.startsWith("1.4.2_0") && version.charAt(7) < '5';
        if (useEasyHttps) {
            String submitURL = allSubmissionProps.getProperty("submitURL");
            if (submitURL.startsWith("https"))
                submitURL = "easy" + submitURL;
            allSubmissionProps.setProperty("submitURL", submitURL);
        }
        // prepare multipart post method
        MultipartPostMethod filePost = new MultipartPostMethod(allSubmissionProps.getProperty("submitURL"));

        // add properties
        addAllPropertiesButSubmitURL(allSubmissionProps, filePost);

        // add filepart
        byte[] allInput = bytes.toByteArray();
        filePost.addPart(new FilePart("submittedFiles", new ByteArrayPartSource("submit.zip", allInput)));

        // prepare httpclient
        HttpClient client = new HttpClient();
        client.setConnectionTimeout(5000);
        int status = client.executeMethod(filePost);

        // Piggy-back uploading the launch events onto submitting.
        EclipseLaunchEventLog.postEventLogToServer(project);

        if (status == HttpStatus.SC_OK) {
            Dialogs.okDialog(parent, "Project submission successful",
                    "Project " + allSubmissionProps.getProperty("projectNumber")
                            + " was submitted successfully\n" + filePost.getResponseBodyAsString());

        } else {
            Dialogs.errorDialog(parent, "Warning: Project submission failed", "Project submission failed",
                    filePost.getStatusText() + "\n " + cvsStatus, IStatus.CANCEL);
            AutoCVSPlugin.getPlugin().getEventLog().logMessage(filePost.getResponseBodyAsString());
        }

    } catch (CoreException e) {
        Dialogs.errorDialog(parent, "Warning: Project submission failed",
                "Project submissions via https failed\n" + cvsStatus, e);
    } catch (HttpConnection.ConnectionTimeoutException e) {
        Dialogs.errorDialog(parent, "Warning: Project submission failed", "Project submissions failed",
                "Connection timeout while trying to connect to submit server\n " + cvsStatus, IStatus.ERROR);
    } catch (IOException e) {
        Dialogs.errorDialog(parent, "Warning: Project submission failed",
                "Project submissions failed\n " + cvsStatus, e);
    }
}

From source file:de.mpg.escidoc.services.dataacquisition.DataHandlerBean.java

/**
 * fetch data from a given url.//from  w w  w. j a v  a2  s  .  c  o  m
 * 
 * @param url
 * @return byte[]
 * @throws SourceNotAvailableException
 * @throws RuntimeException
 * @throws AccessException
 */
public byte[] fetchMetadatafromURL(URL url)
        throws SourceNotAvailableException, RuntimeException, AccessException {
    byte[] input = null;
    URLConnection conn = null;
    Date retryAfter = null;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);
    try {
        conn = ProxyHelper.openConnection(url);
        HttpURLConnection httpConn = (HttpURLConnection) conn;
        int responseCode = httpConn.getResponseCode();
        switch (responseCode) {
        case 503:
            String retryAfterHeader = conn.getHeaderField("Retry-After");
            if (retryAfterHeader != null) {
                SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
                retryAfter = dateFormat.parse(retryAfterHeader);
                this.logger.debug("Source responded with 503, retry after " + retryAfter + ".");
                throw new SourceNotAvailableException(retryAfter);
            }
            break;
        case 302:
            String alternativeLocation = conn.getHeaderField("Location");
            return fetchMetadatafromURL(new URL(alternativeLocation));
        case 200:
            this.logger.info("Source responded with 200.");
            // Fetch file
            GetMethod method = new GetMethod(url.toString());
            HttpClient client = new HttpClient();
            ProxyHelper.executeMethod(client, method);
            input = method.getResponseBody();
            httpConn.disconnect();
            // Create zip file with fetched file
            ZipEntry ze = new ZipEntry("unapi");
            ze.setSize(input.length);
            ze.setTime(this.currentDate());
            CRC32 crc321 = new CRC32();
            crc321.update(input);
            ze.setCrc(crc321.getValue());
            zos.putNextEntry(ze);
            zos.write(input);
            zos.flush();
            zos.closeEntry();
            zos.close();
            this.setContentType("application/zip");
            this.setFileEnding(".zip");
            break;
        case 403:
            throw new AccessException("Access to url " + url + " is restricted.");
        default:
            throw new RuntimeException("An error occurred during importing from external system: "
                    + responseCode + ": " + httpConn.getResponseMessage() + ".");
        }
    } catch (AccessException e) {
        this.logger.error("Access denied.", e);
        throw new AccessException(url.toString());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    return baos.toByteArray();
}

From source file:VASSAL.tools.io.ZipArchive.java

private void writeToDisk() throws IOException {
    // write all files to a temporary zip archive
    final File tmpFile = File.createTempFile("tmp", ".zip", archiveFile.getParentFile());

    ZipOutputStream out = null;/*www  .ja v a  2 s.co m*/
    try {
        out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(tmpFile)));
        out.setLevel(9);

        final byte[] buf = new byte[8192];

        if (zipFile != null) {
            zipFile.close();
            zipFile = null;

            // copy unmodified file into the temp archive
            ZipInputStream in = null;
            try {
                in = new ZipInputStream(new BufferedInputStream(new FileInputStream(archiveFile)));

                ZipEntry ze = null;
                while ((ze = in.getNextEntry()) != null) {
                    // skip modified or removed entries
                    final Entry e = entries.get(ze.getName());
                    if (e == null || e.file != null)
                        continue;

                    // We can't reuse entries for compressed files because there's
                    // no way to reset all fields to acceptable values.
                    if (ze.getMethod() == ZipEntry.DEFLATED) {
                        ze = new ZipEntry(ze.getName());
                        ze.setTime(ze.getTime());
                    }

                    out.putNextEntry(ze);
                    IOUtils.copy(in, out, buf);

                    entries.remove(ze.getName());
                }

                in.close();
            } finally {
                IOUtils.closeQuietly(in);
            }
        }

        for (String name : entries.keySet()) {
            final Entry e = entries.get(name);

            // write new or modified file into the temp archive
            FileInputStream in = null;
            try {
                in = new FileInputStream(e.file);
                out.putNextEntry(e.ze);
                IOUtils.copy(in, out, buf);
                in.close();
            } finally {
                IOUtils.closeQuietly(in);
            }
        }

        out.close();
    } finally {
        IOUtils.closeQuietly(out);
    }

    // Replace old archive with temp archive.
    if (!tmpFile.renameTo(archiveFile)) {
        try {
            FileUtils.forceDelete(archiveFile);
            FileUtils.moveFile(tmpFile, archiveFile);
        } catch (IOException e) {
            String err = "Unable to overwrite " + archiveFile.getAbsolutePath() + ": ";

            if (!archiveFile.exists()) {
                err += " file does not exist.";
            } else if (!archiveFile.canWrite()) {
                err += " file is not writable.";
            } else if (!archiveFile.isFile()) {
                err += " not a normal file.";
            }

            err += " Data written to " + tmpFile.getAbsolutePath() + " instead.";
            throw (IOException) new IOException(err).initCause(e);
        }
    }

    closed = true;
    modified = false;
    entries.clear();
}

From source file:de.mpg.escidoc.services.dataacquisition.DataHandlerBean.java

/**
 * Operation for fetching data of type FILE.
 * //  w  ww. j a  v  a 2 s  .c o m
 * @param importSource
 * @param identifier
 * @param listOfFormats
 * @return byte[] of the fetched file, zip file if more than one record was
 *         fetched
 * @throws RuntimeException
 * @throws SourceNotAvailableException
 */
private byte[] fetchData(String identifier, Format[] formats)
        throws SourceNotAvailableException, RuntimeException, FormatNotAvailableException {
    byte[] in = null;
    FullTextVO fulltext = new FullTextVO();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);

    try {
        // Call fetch file for every given format
        for (int i = 0; i < formats.length; i++) {
            Format format = formats[i];
            fulltext = this.util.getFtObjectToFetch(this.currentSource, format.getName(), format.getType(),
                    format.getEncoding());
            // Replace regex with identifier
            String decoded = java.net.URLDecoder.decode(fulltext.getFtUrl().toString(),
                    this.currentSource.getEncoding());
            fulltext.setFtUrl(new URL(decoded));
            fulltext.setFtUrl(
                    new URL(fulltext.getFtUrl().toString().replaceAll(this.regex, identifier.trim())));
            this.logger.debug("Fetch file from URL: " + fulltext.getFtUrl());

            // escidoc file
            if (this.currentSource.getHarvestProtocol().equalsIgnoreCase("ejb")) {
                in = this.fetchEjbFile(fulltext, identifier);
            }
            // other file
            else {
                in = this.fetchFile(fulltext);
            }

            this.setFileProperties(fulltext);
            // If only one file => return it in fetched format
            if (formats.length == 1) {
                return in;
            }
            // If more than one file => add it to zip
            else {
                // If cone service is not available (we do not get a
                // fileEnding) we have
                // to make sure that the zip entries differ in name.
                String fileName = identifier;
                if (this.getFileEnding().equals("")) {
                    fileName = fileName + "_" + i;
                }
                ZipEntry ze = new ZipEntry(fileName + this.getFileEnding());
                ze.setSize(in.length);
                ze.setTime(this.currentDate());
                CRC32 crc321 = new CRC32();
                crc321.update(in);
                ze.setCrc(crc321.getValue());
                zos.putNextEntry(ze);
                zos.write(in);
                zos.flush();
                zos.closeEntry();
            }
        }
        this.setContentType("application/zip");
        this.setFileEnding(".zip");
        zos.close();

    } catch (SourceNotAvailableException e) {
        this.logger.error("Import Source " + this.currentSource + " not available.", e);
        throw new SourceNotAvailableException(e);
    } catch (FormatNotAvailableException e) {
        throw new FormatNotAvailableException(e.getMessage());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    return baos.toByteArray();
}

From source file:org.rhq.bundle.ant.AntLauncherTest.java

private File createZip(String[] content, File destDir, String zipName, String[] entryName) throws Exception {
    FileOutputStream stream = null;
    ZipOutputStream out = null;// ww w  .j a  va 2s . co  m

    try {
        destDir.mkdirs();
        File zipFile = new File(destDir, zipName);
        stream = new FileOutputStream(zipFile);
        out = new ZipOutputStream(stream);

        assertEquals(content.length, entryName.length);
        for (int i = 0; i < content.length; i++) {
            ZipEntry zipAdd = new ZipEntry(entryName[i]);
            zipAdd.setTime(System.currentTimeMillis());
            out.putNextEntry(zipAdd);
            out.write(content[i].getBytes());
        }
        return zipFile;
    } finally {
        if (out != null) {
            out.close();
        }
        if (stream != null) {
            stream.close();
        }
    }
}

From source file:org.broad.igv.feature.genome.GenomeManager.java

/**
 * Rewrite the {@link Globals#GENOME_ARCHIVE_SEQUENCE_FILE_LOCATION_KEY} property to equal
 * the specified {@code newSequencePath}. Works by creating a temp file and renaming
 *
 * @param targetFile      A .genome file, in zip format
 * @param newSequencePath/*from www  .  j a  va2s. com*/
 * @return boolean indicating success or failure.
 * @throws IOException
 */
static boolean rewriteSequenceLocation(File targetFile, String newSequencePath) throws IOException {

    ZipFile targetZipFile = new ZipFile(targetFile);
    boolean success = false;

    File tmpZipFile = File.createTempFile("tmpGenome", ".zip");
    ZipEntry propEntry = targetZipFile.getEntry(Globals.GENOME_ARCHIVE_PROPERTY_FILE_NAME);

    InputStream propertyInputStream = null;
    ZipOutputStream zipOutputStream = null;
    Properties inputProperties = new Properties();

    try {
        propertyInputStream = targetZipFile.getInputStream(propEntry);
        BufferedReader reader = new BufferedReader(new InputStreamReader(propertyInputStream));

        //Copy over property.txt, only replacing a few properties
        inputProperties.load(reader);
        inputProperties.put(Globals.GENOME_ARCHIVE_SEQUENCE_FILE_LOCATION_KEY, newSequencePath);
        inputProperties.put(Globals.GENOME_ARCHIVE_CUSTOM_SEQUENCE_LOCATION_KEY, Boolean.TRUE.toString());

        ByteArrayOutputStream propertyBytes = new ByteArrayOutputStream();
        PrintWriter propertyFileWriter = new PrintWriter(new OutputStreamWriter(propertyBytes));

        inputProperties.store(propertyFileWriter, null);

        propertyFileWriter.flush();
        byte[] newPropertyBytes = propertyBytes.toByteArray();

        Enumeration<? extends ZipEntry> entries = targetZipFile.entries();
        zipOutputStream = new ZipOutputStream(new FileOutputStream(tmpZipFile));
        while (entries.hasMoreElements()) {
            ZipEntry curEntry = entries.nextElement();
            ZipEntry writeEntry = null;

            if (curEntry.getName().equals(Globals.GENOME_ARCHIVE_PROPERTY_FILE_NAME)) {
                writeEntry = new ZipEntry(Globals.GENOME_ARCHIVE_PROPERTY_FILE_NAME);
                writeEntry.setSize(newPropertyBytes.length);
                zipOutputStream.putNextEntry(writeEntry);
                zipOutputStream.write(newPropertyBytes);
                continue;
            } else {
                //Because the compressed size can vary,
                //we generate a new ZipEntry and copy some attributes
                writeEntry = new ZipEntry(curEntry.getName());
                writeEntry.setSize(curEntry.getSize());
                writeEntry.setComment(curEntry.getComment());
                writeEntry.setTime(curEntry.getTime());
            }

            zipOutputStream.putNextEntry(writeEntry);
            InputStream tmpIS = null;
            try {
                tmpIS = targetZipFile.getInputStream(writeEntry);
                int bytes = IOUtils.copy(tmpIS, zipOutputStream);
                log.debug(bytes + " bytes written to " + targetFile);
            } finally {
                if (tmpIS != null)
                    tmpIS.close();
            }

        }
    } catch (Exception e) {
        tmpZipFile.delete();
        throw new RuntimeException(e.getMessage(), e);
    } finally {
        if (propertyInputStream != null)
            propertyInputStream.close();
        if (zipOutputStream != null) {
            zipOutputStream.flush();
            zipOutputStream.finish();
            zipOutputStream.close();
        }
        zipOutputStream = null;
        System.gc();
        success = true;
    }

    //This is a hack. I don't know why it's necessary,
    //but for some reason the output zip file seems to be corrupt
    //at least when called from GenomeManager.refreshArchive
    try {
        Thread.sleep(1500);
    } catch (InterruptedException e) {
        //
    }

    //Rename tmp file
    if (success) {
        targetFile.delete();
        FileUtils.copyFile(tmpZipFile, targetFile);
        success = targetFile.exists();
        tmpZipFile.delete();
    }
    return success;
}