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

br.com.objectos.way.upload.AndSaveTo 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 java.io.File;
import java.io.IOException;
import java.io.InputStream;

import br.com.objectos.comuns.web.upload.UploadRequestException;
import br.com.objectos.comuns.web.upload.UploadedFile;

import com.google.common.base.Preconditions;
import com.google.common.io.Files;

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

  final UploadCtx ctx;

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

  public abstract Unzip unzip();

  public abstract  Execute execute(UploadSingleAction action);

  public abstract  Execute executeAsync(UploadSingleAsync async);

  static AndSaveTo executeDir(UploadCtx ctx, UploadedFile uploadedFile, File dir) {
    Preconditions.checkArgument(dir.isDirectory(), "dir must be a directory");
    String name = uploadedFile.getName();
    File target = new File(dir, name);
    return executeFile(ctx, uploadedFile, target);
  }

  static AndSaveTo executeFile(UploadCtx ctx, UploadedFile uploadedFile, File target) {
    Preconditions.checkArgument(!target.isDirectory(), "file cannot be a directory");

    InputStream is = null;

    try {
      is = uploadedFile.openStream();
      Files.asByteSink(target).writeFrom(is);
      return new AndSaveToValid(ctx, target);

    } catch (UploadRequestException e) {
      return new AndSaveToInvalid(ctx, e);

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

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

  File getFile() {
    return null;
  }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy