Skip to content

Instantly share code, notes, and snippets.

@alexgutjahr
Created June 8, 2012 18:53
Show Gist options
  • Save alexgutjahr/2897560 to your computer and use it in GitHub Desktop.
Save alexgutjahr/2897560 to your computer and use it in GitHub Desktop.
Using Amazon Web Services S3 in Play Framework Model class
package models;
import play.db.ebean.Model;
import java.io.File;
import java.util.UUID;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
import com.amazonaws.HttpMethod;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.GetObjectRequest;
/**
* @author <a href="mailto:dev@alexander-hanschke.de">Alexander Hanschke</a>
*/
@Entity
@Table(name = "s3_resource")
public class S3Resource extends Model {
public static AmazonS3 s3;
public static String s3Bucket;
@Id
public Long id;
public String key;
public String url;
public String name;
public String bucket;
@Transient
public File content;
public static Finder<Long, S3Resource> find = new Finder<Long, S3Resource>(Long.class, S3Resource.class);
public static S3Resource findByKey(String key) {
return
find.where()
.eq("key", key)
.findUnique();
}
@Override
public void save() {
store();
super.save();
}
@Override
public void save(String server) {
store();
super.save(server);
}
@Override
public void delete() {
remove();
super.delete();
}
@Override
public void delete(String server) {
remove();
super.delete(server);
}
private void store() {
this.key = UUID.randomUUID().toString();
this.bucket = s3Bucket;
if (this.content != null) {
s3.putObject(new PutObjectRequest(this.bucket, this.key, this.content));
this.url = s3.generatePresignedUrl(this.bucket, this.key, null, HttpMethod.GET).toString();
this.name = this.content.getName();
}
}
private void remove() {
s3.deleteObject(this.bucket, this.key);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment