Skip to content

Instantly share code, notes, and snippets.

@ceosilvajr
Last active March 23, 2016 18:28
Show Gist options
  • Save ceosilvajr/6ddd18d178ea68a21139 to your computer and use it in GitHub Desktop.
Save ceosilvajr/6ddd18d178ea68a21139 to your computer and use it in GitHub Desktop.
/*
* Copyright (c) 2015 WiseTime Pty Ltd. All rights reserved.
*/
package com.pi.account.server.utils.s3;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* @author ceosilvajr
*/
public class ImageUploader {
private static final Logger log = LoggerFactory.getLogger(ImageUploader.class);
private static final String IMAGE_BASE_URL = "http://192.168.99.100:32780/s3/" + S3Buckets.PI_ACCOUNTS + "/";
private String userId;
private String userImageUrl;
public ImageUploader(String userId) {
this.userId = userId;
}
public void uploadPhoto(HttpServletRequest req, ImageUploaderListener listener) throws IOException {
try {
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload();
upload.setHeaderEncoding("UTF-8");
// Parse the request
FileItemIterator iterator = upload.getItemIterator(req);
while (iterator.hasNext()) {
FileItemStream item = iterator.next();
final boolean handled = handleFileItemStream(item);
if (handled) {
break;
}
}
if (!StringUtils.isEmpty(userImageUrl)) {
listener.onSuccess(IMAGE_BASE_URL + userImageUrl);
} else {
listener.onError("Image url not found!");
}
} catch (Exception e) {
log.error(e.getMessage(), e);
listener.onError(e.getMessage());
} finally {
listener.onFinish();
}
}
private synchronized boolean handleFileItemStream(FileItemStream item) throws Exception {
String fieldName = item.getFieldName();
InputStream stream = item.openStream();
if (item.isFormField()) {
// Please note the stream can only be read once
String fieldValue = Streams.asString(stream, "UTF-8");
log.debug("Form field '{}' with value {} detected.", fieldName, fieldValue);
return false;
} else {
String fileName = item.getName();
log.debug("File field '{}' with file name {} detected.", fieldName, fileName);
File tempFile = createTempFile(stream, fileName);
final String s3Key = userId + "." + FilenameUtils.getExtension(fileName);
S3Client.get().upload(tempFile, S3Buckets.PI_ACCOUNTS, s3Key, new S3Client.UploadCompleteHandler() {
@Override
public void onUploadComplete() {
userImageUrl = s3Key;
}
});
return true;
}
}
private File createTempFile(InputStream stream, String fileName) throws IOException {
File tmpDir = UploadUtils.getTempDir();
File tempFile = new File(tmpDir, fileName);
IOUtils.copy(stream, new FileOutputStream(tempFile));
log.debug("Created temporary file: {}", tempFile.getAbsolutePath());
return tempFile;
}
public interface ImageUploaderListener {
void onSuccess(String imageUrl) throws IOException;
void onError(String message) throws IOException;
void onFinish();
}
}
package com.pi.account.server.utils;
import com.pi.account.common.type.TestType;
import com.pi.account.server.utils.s3.ImageUploader;
import mockit.Mocked;
import mockit.integration.junit4.JMockit;
import org.apache.commons.lang.StringUtils;
import org.junit.runner.RunWith;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import static org.testng.Assert.assertTrue;
/**
* Created by ceosilvajr on 23/03/2016.
*/
@RunWith(JMockit.class)
public class ImageUploaderTest {
ImageUploader imageUploader;
String sampleUserId = "test123";
@Mocked
private HttpServletRequest mockHttpServletRequest;
@BeforeClass(groups = TestType.UNIT)
public void setup() throws IOException {
imageUploader = new ImageUploader(sampleUserId);
}
@Test(groups = TestType.UNIT)
public void testUploadImage() throws IOException {
imageUploader.uploadPhoto(mockHttpServletRequest, new ImageUploader.ImageUploaderListener() {
@Override
public void onSuccess(String imageUrl) throws IOException {
assertTrue(!StringUtils.isEmpty(imageUrl));
}
@Override
public void onError(String message) throws IOException {
}
@Override
public void onFinish() {
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment