net.przemkovv.sphinx.web.TaskSolutionController.java Source code

Java tutorial

Introduction

Here is the source code for net.przemkovv.sphinx.web.TaskSolutionController.java

Source

/*
 * The MIT License
 *
 * Copyright 2013 Przemyslaw Walkowiak <przemyslaw.walkowiak@put.poznan.pl>.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package net.przemkovv.sphinx.web;

import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletResponse;
import net.przemkovv.sphinx.model.File;
import net.przemkovv.sphinx.model.Solution;
import net.przemkovv.sphinx.model.Task;
import net.przemkovv.sphinx.service.SolutionService;
import net.przemkovv.sphinx.service.TaskService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

/**
 *
 * @author Przemyslaw Walkowiak <przemyslaw.walkowiak@put.poznan.pl>
 */
@Controller
@RequestMapping(value = "/tasks/{task_id}/solutions")
public class TaskSolutionController {

    private static final Logger logger = LoggerFactory.getLogger(TaskSolutionController.class);
    @Autowired
    TaskService taskService;

    @Autowired
    SolutionService solutionService;

    public TaskSolutionController() {
    }

    //************************** Views ********************************************    
    //########################## Solutions for task ###########################################
    @RequestMapping
    public String getSolutionsForTask(Model model, @PathVariable Long task_id) {
        model.addAttribute("task", taskService.getTask(task_id));
        model.addAttribute("solutions", solutionService.getSolutionsForTask(task_id));
        return "view.solutions.list";
    }

    //########################## Solution ###########################################
    @RequestMapping(value = "/submit", method = RequestMethod.GET)
    @PreAuthorize("isAuthenticated()")
    public String getSubmitSolution(Model model, @PathVariable Long task_id) {
        model.addAttribute("task", taskService.getTask(task_id));
        return "view.solutions.submit";
    }
    //
    //    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    //    public String getViewTask(Model model, @PathVariable Long id) {
    //        model.addAttribute("task", taskService.getTask(id));
    //        return "view.tasks.view";
    //    }
    //
    //    @RequestMapping(value = "/{id}/edit", method = RequestMethod.GET)
    //    public String getEditTask(Model model, @PathVariable Long id) {
    //        model.addAttribute("task", taskService.getTask(id));
    //        return "view.tasks.edit";
    //    }
    //
    //    @RequestMapping(value = "/{id}/delete", method = RequestMethod.GET)
    //    public String getDeleteTask(Model model, @PathVariable Long id) {
    //        model.addAttribute("task", taskService.getTask(id));
    //        return "view.tasks.delete";
    //    }
    //************************** REST ********************************************    
    //########################## Solutions for tasks ###########################################
    //    @RequestMapping(method = RequestMethod.POST)
    //    public String addSolutionForTask(@Valid @PathVariable Long task_id, @ModelAttribute("new_solution") Solution solution, BindingResult result) {
    //        if (result.hasErrors()) {
    //            return "view.solutions.add";
    //        }
    ////        taskService.saveTask(task);
    //        return "redirect:/tasks";
    //    }

    @RequestMapping(headers = { "accept=application/json" }, method = RequestMethod.POST)
    public @ResponseBody Solution uploadFileAndCreateSolutionJson(MultipartHttpServletRequest request,
            HttpServletResponse response, @PathVariable Long task_id) throws IOException {
        logger.debug("Creating solution for task {} and uploading files", task_id);
        Set<File> files = acquireFiles(request);
        logger.debug("Saving files in database {}", files.size());
        Task task = taskService.getTask(task_id);
        Solution solution = solutionService.createSolutionWithFiles(task, files);
        logger.debug("Saving files in database finished");
        return solution;
    }

    @RequestMapping(headers = { "accept=application/json" }, value = "/{solution_id}", method = RequestMethod.POST)
    public @ResponseBody Solution uploadFileAndAddToSolutionJson(MultipartHttpServletRequest request,
            HttpServletResponse response, @PathVariable Long solution_id) throws IOException {
        logger.debug("Start uploading files and adding to solution {}", solution_id);
        Set<File> files = acquireFiles(request);
        logger.debug("Saving files in database {}", files.size());
        Solution solution = solutionService.addFilesToSolution(solution_id, files);
        logger.debug("Saving files in database finished");
        return solution;
    }

    @RequestMapping(method = RequestMethod.POST)
    public String uploadFileAndCreateSolution(Model model, MultipartHttpServletRequest request,
            HttpServletResponse response, @PathVariable Long task_id) throws IOException {
        logger.debug("Creating solution for task {} and uploading files", task_id);
        Set<File> files = acquireFiles(request);
        logger.debug("Saving files in database {}", files.size());
        Task task = taskService.getTask(task_id);
        Solution solution = solutionService.createSolutionWithFiles(task, files);
        logger.debug("Saving files in database finished");
        model.addAttribute("task", taskService.getTask(task_id));
        model.addAttribute("solutions", solutionService.getSolutionsForTask(task_id));
        return "view.solutions.list";
    }

    @RequestMapping(value = "/{solution_id}", method = RequestMethod.POST)
    public String uploadFileAndAddToSolution(Model model, MultipartHttpServletRequest request,
            HttpServletResponse response, @PathVariable Long task_id, @PathVariable Long solution_id)
            throws IOException {
        logger.debug("Start uploading files and adding to solution {}", solution_id);
        Set<File> files = acquireFiles(request);
        logger.debug("Saving files in database {}", files.size());
        Solution solution = solutionService.addFilesToSolution(solution_id, files);
        logger.debug("Saving files in database finished");
        model.addAttribute("task", taskService.getTask(task_id));
        model.addAttribute("solutions", solutionService.getSolutionsForTask(task_id));
        return "view.solutions.list";
    }

    //########################## Task ###########################################
    //    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    //    public String deleteTask(@PathVariable Long id) {
    //        taskService.deleteTask(id);
    //        return "redirect:/tasks";
    //    }
    //
    //    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    //    public String updateTask(@PathVariable Long id, @Valid @ModelAttribute("task") Task task, BindingResult result) {
    //        task.setId(id);
    //        if (result.hasErrors()) {
    //            return "view.tasks.edit";
    //        } else {
    //            taskService.saveTask(task);
    //            return "redirect:/tasks";
    //        }
    //    }
    private Set<File> acquireFiles(MultipartHttpServletRequest request) throws IOException {
        Set<File> files = new HashSet<>();
        //1. build an iterator
        Iterator<String> itr = request.getFileNames();
        List<MultipartFile> multipartFiles = null;
        //2. get each file
        while (itr.hasNext()) {

            //2.1 get next MultipartFile
            multipartFiles = request.getFiles(itr.next());

            for (MultipartFile multipartFile : multipartFiles) {
                if (multipartFile.getSize() == 0)
                    continue;
                ;
                logger.debug("{} uploaded! ", multipartFile.getOriginalFilename());

                //2.3 create new fileMeta
                File fileMeta = new File();
                fileMeta.setName(multipartFile.getOriginalFilename());
                fileMeta.setSize(multipartFile.getSize());
                fileMeta.setMimeType(multipartFile.getContentType());

                fileMeta.setContent(multipartFile.getBytes());
                //2.4 add to files

                files.add(fileMeta);
            }

        }
        // result will be like this
        // [{"fileName":"app_engine-85x77.png","fileSize":"8 Kb","fileType":"image/png"},...]
        return files;
    }
}