/*
Copyright 2006 - 2010 Under Dusken
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 no.dusken.aranea.admin.control;
import no.dusken.aranea.admin.editor.GenericCollectionEditor;
import no.dusken.aranea.admin.editor.GenericEditor;
import no.dusken.aranea.model.*;
import no.dusken.aranea.service.*;
import no.dusken.aranea.util.ImageUtils;
import no.dusken.common.service.GenericService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import java.io.File;
import java.io.IOException;
import java.util.List;
/**
* @author Marvin B. Lillehaug <lillehau@underdusken.no>
*/
@Controller
public class ImageUploadController {
@Inject
private StoreImageService storeImageService;
@Inject
private ImageService imageService;
@Inject
private PersonService personService;
@Inject
private TagService tagService;
@Inject
private GenericEditor<Person> personEditor;
@Inject
private GenericEditor<Page> pageEditor;
@Inject
private GenericCollectionEditor<Tag, List> tagsEditor;
@Inject
private PageService pageService;
@Inject
private GenericService<PageImage> pageImageService;
@Inject
private ImageUtils imageUtils;
private Logger log = LoggerFactory.getLogger(getClass());
private File tmpFolder;
private File workDir;
@PostConstruct
public void init() {
workDir = new File(tmpFolder, getClass().getSimpleName());
workDir.deleteOnExit();
workDir.mkdirs();
}
@RequestMapping(value = "/imageUpload/uploadFile.do", method = RequestMethod.POST)
public @ResponseBody String upload(@RequestParam MultipartFile file) throws IOException {
File file1 = new File(workDir, file.getOriginalFilename());
file.transferTo(file1);
file1.deleteOnExit();
return "SUCCESS";
}
@RequestMapping(value = "/imageUpload/handleFiles.do", method = RequestMethod.GET)
public String handleUploadedFiles(Model model, @RequestParam(required = false) Long pageID){
String[] files = workDir.list();
model.addAttribute("numberOfFiles", files.length);
model.addAttribute("tags", tagService.getTags());
model.addAttribute("persons", personService.getPersons());
if (files.length > 0) {
model.addAttribute("filename", files[0]);
model.addAttribute("encodedImage", getEncodedImage(workDir.listFiles()[0]));
}
if(pageID != null){
model.addAttribute("page", pageService.getEntity(pageID));
}
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null) {
String username = authentication.getName();
Person p = personService.getPersonByUsername(username);
if (p != null) {
model.addAttribute("loggedInUser", p);
}
}
return "no/dusken/aranea/base/admin/image/imageUpload";
}
/*
Have not managed to set acceptheaders to json for the normal post, so making it manually.
*/
@RequestMapping(value = "/blank/imageUpload/createImage.do", method= RequestMethod.POST)
public @ResponseBody String handleUpload(@RequestParam MultipartFile file, @RequestParam(required = false) Person photographer, @RequestParam String externalSource,
@RequestParam(required = false, defaultValue = "false") Boolean illustration, @RequestParam(required = false, defaultValue = "") List<Tag> tags,
@RequestParam String description,
@RequestParam(required = false) Page page, @RequestParam(required = false, defaultValue = "") String pageImageText,
@RequestParam(required = false, defaultValue = "1") Integer paragraph){
Image image;
try {
image = storeImageService.createImage(file);
image.setPhotographer(photographer);
image.setDescription(description);
image.setExternalSource(externalSource);
image.setTags(tags);
image.setIllustration(illustration);
image = imageService.saveOrUpdate(image);
} catch (IOException e) {
log.error("Failed to upload image", e);
return new ImageResponse(0L, null, null).toJson();
}
if(page != null){
PageImage pageImage = new PageImage(page, image, pageImageText, paragraph);
pageImageService.saveOrUpdate(pageImage);
return new ImageResponse(image.getID(),pageImage.getID(), null, null).toJson();
}
return new ImageResponse(image.getID(), null, null).toJson();
}
@RequestMapping(value = "/imageUpload/handleFiles.do", method = RequestMethod.POST)
public @ResponseBody ImageResponse handleUploadedFile(@RequestParam String file, @RequestParam(required = false) Person photographer, @RequestParam String externalSource,
@RequestParam(required = false, defaultValue = "false") Boolean illustration, @RequestParam(required = false, defaultValue = "") List<Tag> tags,
@RequestParam String description,
@RequestParam(required = false) Page page, @RequestParam(required = false, defaultValue = "") String pageImageText,
@RequestParam(required = false, defaultValue = "1") Integer paragraph){
Image image;
try {
File f = new File(workDir, file);
if(!f.exists()){
return new ImageResponse(0L, null, null);
}
image = storeImageService.createImage(f);
image.setPhotographer(photographer);
image.setDescription(description);
image.setExternalSource(externalSource);
image.setTags(tags);
image.setIllustration(illustration);
image = imageService.saveOrUpdate(image);
f.delete();
} catch (IOException e) {
log.error("Failed to upload image", e);
return null;
}
String nextFile = null;
String encoded = null;
if(workDir.list().length > 0){
nextFile = workDir.list()[0];
encoded = getEncodedImage(workDir.listFiles()[0]);
}
if(page != null){
PageImage pageImage = new PageImage(page, image, pageImageText, paragraph);
pageImage = pageImageService.saveOrUpdate(pageImage);
return new ImageResponse(image.getID(),pageImage.getID(), nextFile, encoded);
}
return new ImageResponse(image.getID(), nextFile, encoded);
}
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Person.class, personEditor);
binder.registerCustomEditor(Page.class, pageEditor);
binder.registerCustomEditor(List.class, tagsEditor);
}
/*
Return the image encoded with data:image/filesuffix;base64,DATA
*/
private String getEncodedImage(File file){
String fileName = file.getName();
String suffix = fileName.substring(fileName.lastIndexOf("."));
try {
return "data:image/" + suffix + ";base64," + imageUtils.getBase64Image(file, 450, 0);
} catch (IOException e) {
log.error("Error creating base64 image", e);
return null;
}
}
@Value("#{ systemProperties['java.io.tmpdir'] }")
public void setTmpFolder(File tmpFolder) {
this.tmpFolder = tmpFolder;
}
public class ImageResponse{
public Long newImageId;
public Boolean isPageImage;
public Long newPageImageId;
public String nextFileName;
public String encodedImage;
protected ImageResponse(Long id, String nextFile, String encoded) {
newImageId = id;
isPageImage = false;
nextFileName = nextFile;
encodedImage = encoded;
}
protected ImageResponse(Long imageID, Long pageImageID, String nextFile, String encoded){
newImageId = imageID;
newPageImageId = pageImageID;
isPageImage = true;
nextFileName = nextFile;
encodedImage = encoded;
}
public String toJson() {
StringBuilder stringBuilder = new StringBuilder("{");
stringBuilder.append("\"newImageId\":" + newImageId + ",");
stringBuilder.append("\"isPageImage\":" + isPageImage + ",");
stringBuilder.append("\"newPageImageId\":" + newPageImageId + ",");
stringBuilder.append("\"nextFileName\":" + getString(nextFileName) + ",");
stringBuilder.append("\"encodedImage\":" + getString(encodedImage) );
stringBuilder.append("}");
return stringBuilder.toString(); //To change body of created methods use File | Settings | File Templates.
}
private String getString(String value){
if(value != null){
return "\"" + value + "\"";
}
return null;
}
}
}