com.notemyweb.controller.RestController.java Source code

Java tutorial

Introduction

Here is the source code for com.notemyweb.controller.RestController.java

Source

/*
 * Copyright 2011 the original author or authors.
 *
 * 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 com.notemyweb.controller;

import java.security.Principal;
import java.util.List;

import org.apache.commons.lang3.Validate;
import org.apache.http.auth.BasicUserPrincipal;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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;

import com.google.common.collect.ImmutableMap;
import com.notemyweb.clients.FacebookClient;
import com.notemyweb.clients.GoogleCalendarClient;
import com.notemyweb.clients.NotesEmailClient;
import com.notemyweb.dao.NotesDao;
import com.notemyweb.dao.model.User;
import com.notemyweb.dao.model.User.Keys;
import com.notemyweb.dao.model.UserPref;
import com.notemyweb.dao.model.favorites.Favorite;
import com.notemyweb.dao.model.favorites.FavoriteList;
import com.notemyweb.dao.model.notes.AwsNote;
import com.notemyweb.dao.model.notes.AwsNotesMap;
import com.notemyweb.dao.model.reminder.Reminder;
import com.notemyweb.dao.model.reminder.ReminderList;
import com.notemyweb.dao.model.todo.Todo;
import com.notemyweb.dao.model.todo.TodoList;
import com.notemyweb.util.NotesUtil;

/**
 * 
 */
@Controller
public class RestController {

    private Logger logger = Logger.getLogger(RestController.class);

    @Autowired
    private NotesDao notesDao;

    @Autowired
    private NotesEmailClient notesEmailClient;

    @Autowired
    private FacebookClient facebookController;

    @Autowired
    private GoogleCalendarClient calendarClient;

    @RequestMapping(value = "/rest/isFbPostEnabled.json", method = RequestMethod.POST)
    public void isFbPostEnabled(Principal user, @RequestParam Boolean isFbPostEnabled) {
        User awsUser = new User(user.getName()).setIsFbPostEnabled(isFbPostEnabled);
        notesDao.updateUser(awsUser);
    }

    @RequestMapping(value = "/rest/sendEmail.json", method = RequestMethod.GET)
    public @ResponseBody String sendEmail(Principal user, @RequestParam String toEmail) {
        logger.info("Sending email to=" + toEmail + " using user session=" + user.getName());
        try {
            return notesEmailClient.sendEmail("notemyweb@notemyweb.com", toEmail, "Easy way to take your notes");
        } catch (Exception e) {
            logger.error("Error while sending email to " + toEmail, e);
            return "Error while sending email to " + toEmail;
        }
    }

    @RequestMapping(value = "/rest/user/update.json", method = RequestMethod.POST)
    public void updateUser(Principal user, @RequestParam String json) {
        UserPref newPref = NotesUtil.fromJson(UserPref.class, json);
        if (newPref == null) {
            return;
        }
        UserPref existingPref = notesDao.getUser(user.getName(), Keys.prefs).getPref();
        existingPref.update(newPref);
        notesDao.updateUser(new User(user.getName()).setPref(existingPref));
    }

    @RequestMapping(value = "/rest/getUser.json", method = RequestMethod.GET)
    public @ResponseBody User getUser(Principal user) {
        return notesDao.getUser(user.getName(), Keys.email, Keys.display_name, Keys.first_name, Keys.last_name,
                Keys.image_url, Keys.isFbPostEnabled, Keys.prefs);
    }

    @RequestMapping(value = "/rest/getWeb.json", method = RequestMethod.GET)
    public @ResponseBody List<User> getWeb(Principal user) {
        return notesDao.getWeb(user.getName());
    }

    @RequestMapping(value = "/rest/deleteWeb.json", method = RequestMethod.POST)
    public @ResponseBody void deleteAllNotes(Principal user, @RequestParam String webUrl) {
        setNotesMap(user, webUrl, new AwsNotesMap());
    }

    @RequestMapping(value = "/rest/getWebNotes.json", method = RequestMethod.GET)
    public @ResponseBody AwsNotesMap getWebNotes(Principal user, @RequestParam String webUrl) {
        String domain = NotesUtil.getDomain(webUrl);
        Validate.notEmpty(domain, String.format("Invalid domain for url:%s", webUrl));
        return notesDao.getUser(user.getName(), domain).getAllNote();
    }

    @RequestMapping(value = "/rest/postWebNote.json", method = RequestMethod.POST)
    public void postWebNotes(Principal user, @RequestParam String webUrl, @RequestParam String noteTitle,
            @RequestParam String noteContent) {
        String domain = NotesUtil.getDomain(webUrl);
        Validate.notEmpty(domain, String.format("Invalid domain for url:%s", webUrl));
        setNotesMap(user, webUrl, getWebNotes(user, webUrl).addNote(noteTitle, new AwsNote(noteContent, webUrl)));
        facebookController.postFeed(user.getName(), domain);
    }

    @RequestMapping(value = "/rest/deleteWebNote.json", method = RequestMethod.POST)
    public @ResponseBody void deleteNote(Principal user, @RequestParam String webUrl,
            @RequestParam String noteTitle) {
        setNotesMap(user, webUrl, getWebNotes(user, webUrl).removeNote(noteTitle));
    }

    private void setNotesMap(Principal user, String webUrl, AwsNotesMap notesMap) {
        String domain = NotesUtil.getDomain(webUrl);
        Validate.notEmpty(domain, String.format("Invalid domain for url:%s", webUrl));
        User awsUser = new User(user.getName(), domain);
        notesDao.updateUser(awsUser.setNotes(notesMap));
    }

    @RequestMapping(value = "/rest/todo/getall.json", method = RequestMethod.GET)
    public @ResponseBody TodoList getAllTodo(Principal user, @RequestParam String webUrl) {
        String domain = NotesUtil.getDomain(webUrl);
        Validate.notEmpty(domain, String.format("Invalid domain for url:%s", webUrl));
        return notesDao.getUser(user.getName(), domain, Keys.todos).getTodoList();
    }

    @RequestMapping(value = "/rest/todo/add.json", method = RequestMethod.POST)
    public @ResponseBody void addTodo(Principal user, @RequestParam String webUrl, @RequestParam String todo) {
        setTodoList(user, webUrl, getAllTodo(user, webUrl).addTodo(new Todo(todo)));
    }

    @RequestMapping(value = "/rest/todo/deleteall.json", method = RequestMethod.POST)
    public @ResponseBody void deleteAllTodo(Principal user, @RequestParam String webUrl) {
        setTodoList(user, webUrl, new TodoList());
    }

    @RequestMapping(value = "/rest/todo/delete.json", method = RequestMethod.POST)
    public @ResponseBody void deleteTodo(Principal user, @RequestParam String webUrl, @RequestParam String todo) {
        setTodoList(user, webUrl, getAllTodo(user, webUrl).removeTodo(new Todo(todo)));
    }

    private void setTodoList(Principal user, String webUrl, TodoList todoList) {
        String domain = NotesUtil.getDomain(webUrl);
        Validate.notEmpty(domain, String.format("Invalid domain for url:%s", webUrl));
        User awsUser = new User(user.getName(), domain);
        notesDao.updateUser(awsUser.setTodoList(todoList));
    }

    @RequestMapping(value = "/rest/favorite/getall.json", method = RequestMethod.GET)
    public @ResponseBody FavoriteList getAllFavorite(Principal user, @RequestParam String webUrl) {
        String domain = NotesUtil.getDomain(webUrl);
        Validate.notEmpty(domain, String.format("Invalid domain for url:%s", webUrl));
        return notesDao.getUser(user.getName(), domain, Keys.favorites).getFavoriteList();
    }

    @RequestMapping(value = "/rest/favorite/add.json", method = RequestMethod.POST)
    public @ResponseBody void addFavorite(Principal user, @RequestParam String webUrl,
            @RequestParam String favoriteUrl) {
        setFavoriteList(user, webUrl, getAllFavorite(user, webUrl).addFavorite(new Favorite(favoriteUrl)));
    }

    @RequestMapping(value = "/rest/favorite/delete.json", method = RequestMethod.POST)
    public @ResponseBody void deleteFavorite(Principal user, @RequestParam String webUrl,
            @RequestParam String favoriteUrl) {
        setFavoriteList(user, webUrl, getAllFavorite(user, webUrl).removeFavorite(new Favorite(favoriteUrl)));
    }

    private void setFavoriteList(Principal user, String webUrl, FavoriteList favoriteList) {
        String domain = NotesUtil.getDomain(webUrl);
        Validate.notEmpty(domain, String.format("Invalid domain for url:%s", webUrl));
        User awsUser = new User(user.getName(), domain);
        notesDao.updateUser(awsUser.setFavoriteList(favoriteList));
    }

    @RequestMapping(value = "/rest/reminder/getall.json", method = RequestMethod.GET)
    public @ResponseBody ReminderList getAllReminder(Principal user, @RequestParam String webUrl) {
        String domain = NotesUtil.getDomain(webUrl);
        Validate.notEmpty(domain, String.format("Invalid domain for url:%s", webUrl));
        return notesDao.getUser(user.getName(), domain, Keys.reminders).getReminderList();
    }

    @RequestMapping(value = "/rest/reminder/add.json", method = RequestMethod.POST)
    public @ResponseBody void addReminder(Principal user, @RequestParam String webUrl, @RequestParam String json) {
        String domain = NotesUtil.getDomain(webUrl);
        Validate.notEmpty(domain, String.format("Invalid domain for url:%s", webUrl));
        Reminder reminder = NotesUtil.fromJson(Reminder.class, json);
        try {
            calendarClient.createCalendarEvent(user.getName(), domain, reminder.getTime(), reminder.getOffset());
            setReminderList(user, webUrl, getAllReminder(user, webUrl).addReminder(reminder));
        } catch (Exception e) {
            logger.error("Error in creating reminder:", e);
        }
    }

    @RequestMapping(value = "/rest/reminder/delete.json", method = RequestMethod.POST)
    public @ResponseBody void deleteReminder(Principal user, @RequestParam String webUrl,
            @RequestParam String reminderId) {
        setReminderList(user, webUrl, getAllReminder(user, webUrl).removeReminder(reminderId));
    }

    private void setReminderList(Principal user, String webUrl, ReminderList reminderList) {
        String domain = NotesUtil.getDomain(webUrl);
        Validate.notEmpty(domain, String.format("Invalid domain for url:%s", webUrl));
        User awsUser = new User(user.getName(), domain);
        notesDao.updateUser(awsUser.put(reminderList));
    }

    @RequestMapping(value = "/public/reminder/send.json", method = RequestMethod.GET)
    public @ResponseBody void sendReminder(@RequestParam String userId, @RequestParam String webUrl,
            @RequestParam String reminderId) {
        String domain = NotesUtil.getDomain(webUrl);
        Validate.notEmpty(domain, String.format("Invalid domain for url:%s", webUrl));
        try {
            BasicUserPrincipal user = new BasicUserPrincipal(userId);
            ReminderList reminderList = getAllReminder(user, webUrl);
            Reminder reminder = reminderList.getReminder(reminderId);
            if (reminder != null && !reminder.isSent()) {
                facebookController.postReminder(userId, String.format("%s - %s", domain, reminder.getMsg()));
                notesEmailClient.sendReminder(notesDao.getUser(userId, Keys.email).getEmail(),
                        ImmutableMap.of("reminder", reminder.getMsg(), "website", domain));
                reminder.setSent(true);
                reminderList.add(reminder);
                setReminderList(user, webUrl, reminderList);
                logger.info("Reminder is sent:" + reminder);
            } else {
                logger.info("Reminder is not sent:" + reminder);
            }
        } catch (Exception e) {
            logger.error("Error in sending reminder:", e);
        }
    }
}