org.magnum.mobilecloud.video.controller.VideoController.java Source code

Java tutorial

Introduction

Here is the source code for org.magnum.mobilecloud.video.controller.VideoController.java

Source

/*
 * 
 * Copyright 2014 Jules White
 *
 * 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 org.magnum.mobilecloud.video.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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 java.io.IOException;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;

import javax.servlet.http.HttpServletResponse;

import org.magnum.mobilecloud.video.client.VideoSvcApi;
import org.magnum.mobilecloud.video.repository.Video;
import org.magnum.mobilecloud.video.repository.VideoRepository;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.google.common.collect.Lists;

import retrofit.client.Response;

@Controller
public class VideoController {

    public static final String DATA_PARAMETER = "data";

    public static final String ID_PARAMETER = "id";

    public static final String VIDEO_SVC_PATH = "/video";

    public static final String VIDEO_DATA_PATH = VIDEO_SVC_PATH + "/{id}/data";

    public static final String TITLE_PARAMETER = "title";

    public static final String DURATION_PARAMETER = "duration";

    public static final String VIDEO_DURATION_SEARCH_PATH = VIDEO_SVC_PATH + "/search/findByDurationLessThan";

    /**
     * You will need to create one or more Spring controllers to fulfill the
     * requirements of the assignment. If you use this file, please rename it
     * to something other than "AnEmptyController"
     * 
     * 
        ________  ________  ________  ________          ___       ___  ___  ________  ___  __       
       |\   ____\|\   __  \|\   __  \|\   ___ \        |\  \     |\  \|\  \|\   ____\|\  \|\  \     
       \ \  \___|\ \  \|\  \ \  \|\  \ \  \_|\ \       \ \  \    \ \  \\\  \ \  \___|\ \  \/  /|_   
        \ \  \  __\ \  \\\  \ \  \\\  \ \  \ \\ \       \ \  \    \ \  \\\  \ \  \    \ \   ___  \  
    \ \  \|\  \ \  \\\  \ \  \\\  \ \  \_\\ \       \ \  \____\ \  \\\  \ \  \____\ \  \\ \  \ 
     \ \_______\ \_______\ \_______\ \_______\       \ \_______\ \_______\ \_______\ \__\\ \__\
      \|_______|\|_______|\|_______|\|_______|        \|_______|\|_______|\|_______|\|__| \|__|
                                                                                                                                                                                                                                                                        
     * 
     */

    // An in-memory list that the servlet uses to store the
    // videos that are sent to it by clients

    @Autowired
    private VideoRepository videos;
    private static final AtomicLong currentLikes = new AtomicLong(0L);

    // Receives POST requests to /video and converts the HTTP
    // request body, which should contain json, into a Video
    // object before adding it to the list. The @RequestBody
    // annotation on the Video parameter is what tells Spring
    // to interpret the HTTP request body as JSON and convert
    // it into a Video object to pass into the method. The
    // @ResponseBody annotation tells Spring to conver the
    // return value from the method back into JSON and put
    // it into the body of the HTTP response to the client.
    //
    // The VIDEO_SVC_PATH is set to "/video" in the VideoSvcApi
    // interface. We use this constant to ensure that the 
    // client and service paths for the VideoSvc are always
    // in synch.
    //
    // For some ways to improve the validation of the data
    // in the Video object, please see this Spring guide:
    // http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/validation.html#validation-beanvalidation
    //
    @RequestMapping(value = VideoSvcApi.VIDEO_SVC_PATH, method = RequestMethod.POST)
    public @ResponseBody Video addVideo(@RequestBody Video v) {
        videos.save(v);

        System.out.print("The video we are returning is" + v.toString());

        return v;

    }

    // Receives GET requests to /video and returns the current
    // list of videos in memory. Spring automatically converts
    // the list of videos to JSON because of the @ResponseBody
    // annotation.
    @RequestMapping(value = VideoSvcApi.VIDEO_SVC_PATH, method = RequestMethod.GET)
    public @ResponseBody Collection<Video> getVideoList() {
        return Lists.newArrayList(videos.findAll());
    }

    // Receives GET requests to /video/find and returns all Videos
    // that have a title (e.g., Video.name) matching the "title" request
    // parameter value that is passed by the client
    @RequestMapping(value = VideoSvcApi.VIDEO_TITLE_SEARCH_PATH, method = RequestMethod.GET)
    public @ResponseBody Collection<Video> findByTitle(
            // Tell Spring to use the "title" parameter in the HTTP request's query
            // string as the value for the title method parameter
            @RequestParam(TITLE_PARAMETER) String title) {
        return videos.findByName(title);
    }

    @RequestMapping(value = VideoSvcApi.VIDEO_DURATION_SEARCH_PATH, method = RequestMethod.GET)
    public @ResponseBody Collection<Video> findByDurationLessThan(
            // Tell Spring to use the "title" parameter in the HTTP request's query
            // string as the value for the title method parameter
            @RequestParam(DURATION_PARAMETER) long duration) {

        Collection<Video> durationVideos = new ArrayList<Video>();

        Iterable<Video> allVideos = videos.findAll();

        for (Video video : allVideos) {

            if (video.getDuration() < duration) {

                durationVideos.add(video);

            }

        }

        return durationVideos;

    }

    @RequestMapping(value = VIDEO_SVC_PATH + "/{id}", method = RequestMethod.GET)
    public @ResponseBody Video getVideoById(@PathVariable("id") long id, HttpServletResponse response) {

        Video v = videos.findById(id);

        if (v != null) {
            response.setStatus(200);
            return v;

        } else {

            response.setStatus(404);
            return null;

        }

    }

    @RequestMapping(value = VIDEO_SVC_PATH + "/{id}" + "/like", method = RequestMethod.POST)
    public @ResponseBody Video likeVideo(@PathVariable("id") long id, HttpServletResponse response, Principal p) {

        String username = p.getName();

        Video v = videos.findById(id);

        if (v != null) {

            HashSet<String> videoLikes = v.getUserLikes();

            if (videoLikes.contains(username)) {

                response.setStatus(400);
                return v;

            } else {

                System.out.print("These are the videoLikes: " + videoLikes);

                videoLikes.add(username);

                System.out.print("These are the videoLikes: " + videoLikes);

                v.setLikes((long) (v.getLikes() + 1));

                v.setUserLikes(videoLikes);

                response.setStatus(200);

                videos.save(v);

                return v;

            }

        }

        response.setStatus(404);
        return null;

    }

    @RequestMapping(value = VIDEO_SVC_PATH + "/{id}" + "/unlike", method = RequestMethod.POST)
    public @ResponseBody Video unlikeVideo(@PathVariable("id") long id, HttpServletResponse response, Principal p) {

        String username = p.getName();

        Video v = videos.findById(id);

        if (v != null) {

            HashSet<String> videoLikes = v.getUserLikes();

            if (videoLikes.contains(username)) {

                System.out.print("These are the videoLikes: " + videoLikes);

                videoLikes.remove(username);

                System.out.print("These are the videoLikes: " + videoLikes);

                v.setLikes((long) (v.getLikes() - 1));

                v.setUserLikes(videoLikes);

                response.setStatus(200);

                videos.save(v);

                return v;

            } else {

                response.setStatus(400);
                return v;

            }

        }

        response.setStatus(404);
        return null;

    }

    @RequestMapping(value = VIDEO_SVC_PATH + "/{id}" + "/likedby", method = RequestMethod.GET)
    public @ResponseBody HashSet<String> getUsersWhoLikedVideo(@PathVariable("id") long id,
            HttpServletResponse response) {

        Video v = videos.findById(id);

        if (v != null) {
            HashSet<String> usersWhoLiked = v.getUserLikes();
            response.setStatus(200);
            return usersWhoLiked;

        } else {

            response.setStatus(404);
            return null;

        }

    }

}