All Downloads are FREE. Search and download functionalities are using the official Maven repository.

br.com.objectos.way.upload.Unzip Maven / Gradle / Ivy

/*
 * Copyright 2013 Objectos, Fábrica de Software LTDA.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package br.com.objectos.way.upload;

import static com.google.common.collect.Lists.newArrayList;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.io.ByteStreams;
import com.google.common.io.Files;

/**
 * @author [email protected] (Marcio Endo)
 */
public abstract class Unzip {

  final UploadCtx ctx;

  Unzip(UploadCtx ctx) {
    this.ctx = ctx;
  }

  public abstract  Execute execute(UploadUnzipAction action);

  public abstract  Execute executeAsync(UploadUnzipAsync async);

  static Unzip execute(UploadCtx ctx, File file) {
    try {
      List entries = extract(file);
      return new UnzipValid(ctx, file, entries);

    } catch (ZipException e) {
      return new UnzipInvalid(ctx, e);

    } catch (IOException e) {
      return new UnzipInvalid(ctx, e);

    }
  }

  @VisibleForTesting
  static List extract(File file) throws ZipException, IOException {
    ZipFile zip = null;

    try {

      File dir = Files.createTempDir();
      List entries = newArrayList();

      zip = new ZipFile(file);

      for (Enumeration e = zip.entries(); e.hasMoreElements();) {
        ZipEntry entry = e.nextElement();
        String name = entry.getName();
        File entryFile = new File(dir, name);

        if (!entry.isDirectory()) {
          Files.createParentDirs(entryFile);
          InputStream input = zip.getInputStream(entry);
          OutputStream output = new FileOutputStream(entryFile);
          ByteStreams.copy(input, output);
          entries.add(entryFile);
        }
      }

      return entries;

    } finally {
      if (zip != null) {
        try {
          zip.close();
        } catch (IOException e) {}
      }
    }
  }

  UploadedZip getUploadedZip() {
    return null;
  }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy