package com.pt.controller;
import static org.apache.commons.lang.StringUtils.isEmpty;
import java.io.InputStream;
import java.util.Calendar;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.codec.binary.Base64;
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.IOUtils;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.google.appengine.api.datastore.Text;
import com.pt.domain.Person;
import com.pt.domain.Thought;
import com.pt.service.DataService;
@Controller()
@RequestMapping(value="/thought")
public class ThoughtController {
private DataService dataService;
public void setDataService(DataService dataService) {
this.dataService = dataService;
}
private static final String PAGE_DIRECTORY = "thought";
private String show(String page) {
return String.format("%s/%s", PAGE_DIRECTORY, page);
}
@RequestMapping(value="/home", method = RequestMethod.GET)
public String homePage(ModelMap model) {
List<Thought> thoughtList = dataService.getAllThought();
model.addAttribute("thoughs", thoughtList);
return "home";
}
@RequestMapping(value="/write", method = RequestMethod.GET)
public String addThoughtPage(ModelMap model) {
return show("write");
}
@RequestMapping(value="/write", method = RequestMethod.POST)
public String addThought(ModelMap model, HttpServletRequest request, HttpServletResponse response) {
String userThought = null, name = null;
try {
ServletFileUpload upload = new ServletFileUpload();
FileItemIterator iterator = upload.getItemIterator(request);
byte[] image = null;
String contentType = null;
while (iterator.hasNext()) {
FileItemStream fileItem = iterator.next();
InputStream stream = fileItem.openStream();
if (fileItem.isFormField()) {
switch (fileItem.getFieldName()) {
case "thought":
userThought = Streams.asString(stream);
break;
case "name":
name = Streams.asString(stream);
break;
default: break;
}
} else {
if ("image".equals(fileItem.getFieldName())) {
contentType = fileItem.getContentType();
ByteArrayOutputStream out = new ByteArrayOutputStream();
IOUtils.copy(stream, out);
IOUtils.closeQuietly(stream);
IOUtils.closeQuietly(out);
image = out.toByteArray();
}
}
}
if (isEmpty(contentType) || isEmpty(name) || isEmpty(userThought) || image == null ) {
model.addAttribute("errorMessage", "Name, your thoughts and a picture are required.");
return show("write");
}
String encodedIcon = null;
if (image != null) {
encodedIcon = Base64.encodeBase64String(image);
}
if (isEmpty(encodedIcon)) {
model.addAttribute("errorMessage", "Name, your thoughts and a picture are required.");
return show("write");
}
Person owner = new Person();
owner.setName(name);
dataService.createPerson(owner);
Thought thought = new Thought();
thought.setCreatedOn(Calendar.getInstance().getTime());
thought.setThought(new Text(userThought));
thought.setOwner(owner);
thought.setThumbnail(new Text(String.format("data:%s;base64,%s", contentType, encodedIcon)));
dataService.createThought(thought);
model.addAttribute("successMessage", "Thought created successfully.");
model.addAttribute("thoughs", dataService.getAllThought());
return "home";
} catch (Exception ex) {
model.addAttribute("errorMessage", "An error occured while storing thought information on server.");
model.addAttribute("thoughs", dataService.getAllThought());
return "home";
}
}
@RequestMapping(value="/update", method = RequestMethod.POST)
public String updateThought(ModelMap model, HttpServletRequest request) {
long id = 0L;
String userThought = null, name = null;
try {
ServletFileUpload upload = new ServletFileUpload();
FileItemIterator iterator = upload.getItemIterator(request);
byte[] image = null;
String contentType = null;
while (iterator.hasNext()) {
FileItemStream fileItem = iterator.next();
InputStream stream = fileItem.openStream();
if (fileItem.isFormField()) {
switch (fileItem.getFieldName()) {
case "thought":
userThought = Streams.asString(stream);
break;
case "name":
name = Streams.asString(stream);
break;
case "id":
id = NumberUtils.toLong(Streams.asString(stream), 0L);
break;
default: break;
}
} else {
if ("image".equals(fileItem.getFieldName())) {
contentType = fileItem.getContentType();
ByteArrayOutputStream out = new ByteArrayOutputStream();
IOUtils.copy(stream, out);
IOUtils.closeQuietly(stream);
IOUtils.closeQuietly(out);
image = out.toByteArray();
}
}
}
if (id == 0L) {
model.addAttribute("errorMessage", "Invalid thought ID.");
model.addAttribute("thoughs", dataService.getAllThought());
return "home";
}
Thought thought = dataService.getThought(id);
if (thought == null) {
model.addAttribute("errorMessage", String.format("Nothing to update. Thought with ID %s not found.", id));
model.addAttribute("thoughs", dataService.getAllThought());
return "home";
}
if (isEmpty(contentType) || isEmpty(name) || isEmpty(userThought)) {
model.addAttribute("errorMessage", "Name, your thoughts and a picture are required.");
return show("write");
}
String encodedIcon = null;
if (image != null) {
encodedIcon = Base64.encodeBase64String(image);
}
if (isEmpty(encodedIcon) && thought.getThumbnail() == null) {
model.addAttribute("errorMessage", "Name, your thoughts and a picture are required.");
return show("write");
}
Person owner = thought.getOwner();
if (!owner.getName().equals(name)) {
owner.setName(name);
dataService.updatePerson(owner);
}
thought.setThought(new Text(userThought));
thought.setOwner(owner);
if (StringUtils.isNotEmpty(encodedIcon)) {
thought.setThumbnail(new Text(String.format("data:%s;base64,%s", contentType, encodedIcon)));
}
dataService.updateThought(thought);
model.addAttribute("successMessage", "Thought updated successfully.");
model.addAttribute("thoughs", dataService.getAllThought());
return "home";
} catch (Exception ex) {
model.addAttribute("errorMessage", "An error occured while storing thought information on server.");
model.addAttribute("thoughs", dataService.getAllThought());
return "home";
}
}
@RequestMapping(value="/update", method = RequestMethod.GET)
public String updateThoughtPage(ModelMap model, HttpServletRequest request) {
long id = NumberUtils.toLong(request.getParameter("id"), 0L);
if (id == 0L) {
model.addAttribute("errorMessage", "Invalid thought ID.");
model.addAttribute("thoughs", dataService.getAllThought());
return "home";
}
Thought thought = dataService.getThought(id);
if (thought == null) {
model.addAttribute("errorMessage", String.format("Nothing to update. Thought with ID %s not found.", id));
model.addAttribute("thoughs", dataService.getAllThought());
return "home";
}
model.addAttribute("thought", thought);
return show("update");
}
@RequestMapping(value="/delete", method = RequestMethod.GET)
public String deleteThoughtPage(ModelMap model, HttpServletRequest request) {
long id = NumberUtils.toLong(request.getParameter("id"), 0L);
if (id == 0L) {
model.addAttribute("errorMessage", "Invalid thought ID.");
model.addAttribute("thoughs", dataService.getAllThought());
return "home";
}
Thought thought = dataService.getThought(id);
if (thought == null) {
model.addAttribute("errorMessage", String.format("Nothing to delete. Thuoght with ID %s not found.", id));
model.addAttribute("thoughs", dataService.getAllThought());
return "home";
}
dataService.removeThought(id);
model.addAttribute("successMessage", String.format("Successfully removed Thuoght with ID %s.", id));
model.addAttribute("thoughs", dataService.getAllThought());
return "home";
}
@RequestMapping(value="/thumbs/{type}/{id}", method = RequestMethod.GET)
public String updateThoughtStats(@PathVariable String type, @PathVariable Long id, ModelMap model, HttpServletRequest request) {
if (id == 0L) {
model.addAttribute("errorMessage", "Invalid thought ID.");
model.addAttribute("thoughs", dataService.getAllThought());
return "home";
}
Thought thought = dataService.getThought(id);
if (thought == null) {
model.addAttribute("errorMessage", String.format("Nothing to delete. Thuoght with ID %s not found.", id));
model.addAttribute("thoughs", dataService.getAllThought());
return "home";
}
switch (type) {
case "up":
thought.incrementThumbsUp();
break;
case "down":
thought.incrementThumbsDown();
break;
default:
model.addAttribute("errorMessage", "Wrong update type.");
model.addAttribute("thoughs", dataService.getAllThought());
return "home";
}
dataService.updateThought(thought);
model.addAttribute("successMessage", "Successfully updated thumbs count.");
model.addAttribute("thoughs", dataService.getAllThought());
return "home";
}
}