org.magnum.dataup.VideoService.java Source code

Java tutorial

Introduction

Here is the source code for org.magnum.dataup.VideoService.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.dataup;

import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicLong;

import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.stereotype.Controller;
import org.magnum.dataup.VideoSvcApi;
import org.magnum.dataup.model.Video;
import org.magnum.dataup.model.VideoStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class VideoService {

    /**
     * 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"
     * 
     * 
        ________  ________  ________  ________          ___       ___  ___  ________  ___  __       
       |\   ____\|\   __  \|\   __  \|\   ___ \        |\  \     |\  \|\  \|\   ____\|\  \|\  \     
       \ \  \___|\ \  \|\  \ \  \|\  \ \  \_|\ \       \ \  \    \ \  \\\  \ \  \___|\ \  \/  /|_   
        \ \  \  __\ \  \\\  \ \  \\\  \ \  \ \\ \       \ \  \    \ \  \\\  \ \  \    \ \   ___  \  
    \ \  \|\  \ \  \\\  \ \  \\\  \ \  \_\\ \       \ \  \____\ \  \\\  \ \  \____\ \  \\ \  \ 
     \ \_______\ \_______\ \_______\ \_______\       \ \_______\ \_______\ \_______\ \__\\ \__\
      \|_______|\|_______|\|_______|\|_______|        \|_______|\|_______|\|_______|\|__| \|__|
                                                                                                                                                                                                                                                                        
     * 
     */

    private Map<Long, Video> videos = new HashMap<Long, Video>();
    private VideoFileManager vfm = null;

    public VideoService() throws IOException {
        vfm = VideoFileManager.get();
    }

    @RequestMapping(value = VideoSvcApi.VIDEO_SVC_PATH, method = RequestMethod.POST)
    public @ResponseBody Video addVideo(@RequestBody Video v) {
        return save(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 videos.values();
    }

    @RequestMapping(value = VideoSvcApi.VIDEO_DATA_PATH, method = RequestMethod.POST)
    public @ResponseBody VideoStatus setVideoData(@PathVariable("id") long id,
            @RequestParam("data") MultipartFile data, HttpServletResponse response) {
        Video v = videos.get(id);
        try {
            vfm.saveVideoData(v, data.getInputStream());
        } catch (Exception e) {
            sendError(response, 404, "Video data could not be saved.");
            return null;
        }
        return new VideoStatus(VideoStatus.VideoState.READY);
    }

    @RequestMapping(value = VideoSvcApi.VIDEO_DATA_PATH, method = RequestMethod.GET)
    public HttpServletResponse getData(@PathVariable("id") long id, HttpServletResponse response) {
        Video v = videos.get(id);
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
        } catch (Exception e) {
            sendError(response, 500, "Internal error.");
        }
        try {
            vfm.copyVideoData(v, out);
            out.flush();
        } catch (Exception e) {
            sendError(response, 404, "Video data could not be found.");
        }
        return response;
    }

    private static final AtomicLong currentId = new AtomicLong(0L);

    public Video save(Video entity) {
        checkAndSetId(entity);
        long id = entity.getId();
        entity.setDataUrl(getDataUrl(id));
        videos.put(id, entity);
        return entity;
    }

    private void checkAndSetId(Video entity) {
        if (entity.getId() == 0) {
            entity.setId(currentId.incrementAndGet());
        }
    }

    private String getDataUrl(long videoId) {
        String url = getUrlBaseForLocalServer() + VideoSvcApi.VIDEO_DATA_PATH;
        url = url.replace("{id}", String.valueOf(videoId));
        return url;
    }

    private String getUrlBaseForLocalServer() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
        String base = "http://" + request.getServerName()
                + ((request.getServerPort() != 80) ? ":" + request.getServerPort() : "");
        return base;
    }

    private String sendError(HttpServletResponse response, int sc, String msg) {
        try {
            response.sendError(sc, msg);
        } catch (Exception e) {
            // ignore
        }
        return msg;
    }
}