package com.tamakloe.guestbook;
import java.io.InputStream;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.LineIterator;
public class MessageUploadForm extends Form {
private static final String FIELD_RESULT = "result";
private static final long MAX_FILE_SIZE = 50000;
private Greeting greeting;
private static final String CSV_PATTERN = "\"([^\"]+?)\",?|([^,]+),?|,";
private static Pattern csvRE;
public MessageUploadForm(Greeting greeting) {
this.greeting = greeting;
csvRE = Pattern.compile(CSV_PATTERN);
}
// Form actions -------------------------------------------------------------------------------
public void registerMessages(HttpServletRequest request){
int messageCount = 0;
try {
ServletFileUpload upload = new ServletFileUpload();
upload.setSizeMax(MAX_FILE_SIZE);
try {
FileItemIterator iterator = upload.getItemIterator(request);
while (iterator.hasNext()) {
FileItemStream item = iterator.next();
InputStream in = item.openStream();
if ((!item.isFormField()) && (item.getFieldName().equals("file1"))) {
String fileName = item.getName();
if (fileName.length()>0){
try {
LineIterator it = IOUtils.lineIterator(in, "UTF-8");
while (it.hasNext()) {
String line = it.nextLine();
PersistenceManager pm = PMF.get().getPersistenceManager();
try {
pm.makePersistent(processMessage(line));
messageCount ++;
}finally {
pm.close();
}
}
} finally {
IOUtils.closeQuietly(in);
setMessage(FIELD_RESULT, "Successfully uploaded " + messageCount + " messages");
}
} else {
setError(FIELD_RESULT, "No file selected for upload!");
}
}
}
} catch (SizeLimitExceededException e) {
setError(FIELD_RESULT, "You exceeded the maximum size ("
+ e.getPermittedSize() + ") of the file ("
+ e.getActualSize() + ")");
}
} catch (Exception ex) {
setError(FIELD_RESULT, "Message post failed due to incorrect file format or database error."
+ " Please try again later. Detail message: " + ex.getMessage());
ex.printStackTrace();
}
}
@SuppressWarnings("unchecked")
public List parse(String line) {
List list = new ArrayList();
Matcher m = csvRE.matcher(line);
// For each field
while (m.find()) {
String match = m.group();
if (match == null)
break;
if (match.endsWith(",")) { // trim trailing ,
match = match.substring(0, match.length() - 1);
}
if (match.startsWith("\"")) { // assume also ends with
match = match.substring(1, match.length() - 1);
}
if (match.length() == 0)
match = null;
list.add(match);
}
return list;
}
@SuppressWarnings("unchecked")
public Greeting processMessage(String line) throws ParseException{
String messageDate = "";
String name = "";
String content = "";
String email = "";
List l =parse(line);
int arraySize = l.size();
if (arraySize == 4){
if (l.get(2) != null){
email = l.get(2).toString();
}
}
if (l.get(1) != null){
name = l.get(1).toString();
}
if (l.get(0)!= null){
messageDate = l.get(0).toString();
}
if (l.get(3) != null){
content = l.get(3).toString();
}
greeting = new Greeting(name, email, content, DateUtils.getDateObect(messageDate));
return greeting;
}
}