Package main

Source Code of main.UserController

/**
*   @author Anas A. Aljuwaiber
@author Vaclav Hnizda
@author Paul Pelafas
*  Knowledge Box
*  Project 2013-14
*  SE491-591 - Software Engineering Studio
*/

package main;


/* Knowledgebox Imports */
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import user.ScoreFactory;
import user.UserFactory;
import user.UserIDJson;
import user.UserQuestionJson;
import user.UserScoreJson;
import user.UserStatusJson;
import group.GroupDetailsJson;
import group.GroupFactory;
import group.GroupInfoJson;
import hibernate.Column;
import hibernate.Group;
import hibernate.Question;
import hibernate.Table;
import hibernate.User;
import hibernate.UserRoleGroup;
import hibernateLogic.DatabasePro;
import hibernateLogic.DatabaseTools;
import hibernateLogic.APIKeyCheck;
import hibernateLogic.ObjectRetrievalTools;















/* Spring Imports */
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import question.QuestionDetailsJson;
import question.QuestionFactory;

@Controller
public class UserController {
 
  /**
   * This method is used to create a new user
   * @param apiKey is the incoming apiKey variable
   * @param firstName is the incoming firstName variable
   * @param lastName is the incoming lastName variable
   * @param email is the incoming email variable
   * @param password is the incoming password variable
   * @return is the return variable
   * @throws Exception
   */
    @RequestMapping(value = "user/create", method=RequestMethod.GET)
  public @ResponseBody UserIDJson createUser(
      @RequestParam(value="apiKey",     required=true) Integer apiKey,
      @RequestParam(value="firstName",   required=true) String firstName,
      @RequestParam(value="lastName",   required=true) String lastName,
      @RequestParam(value="email",     required=true) String email,
      @RequestParam(value="password",   required=true) String password) throws Exception {
     
      if (!APIKeyCheck.exists(apiKey))
      {
        throw new Exception("Failed to find your API Key!");
       
        // Improve Error Handling with the following sites
        // Also set up unique IDs for each error type.
       
        // http://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc
        // http://www.tutorialspoint.com/spring/spring_exception_handling_example.htm
       
      }
      else
      {
        // Set up your database Tools
        DatabaseTools myTools = new DatabaseTools();
       
        // Make sure the email is not already registered
        boolean userExists = myTools.dataSearch("User", "email", email);

      // Return false if a user is found!
      if(userExists){
        return UserFactory.id(0); //ID of zero means failed to find
      }
      else{
        // Not found? Create the new user and add them to the database
        User newUser = UserFactory.createUser(firstName,lastName,email,password);
        int myID = myTools.dataEntry(newUser);
       
        // search the database to confirm
        boolean userFound = myTools.dataSearch("User", "email", newUser.getEmail());
         
        // Respond to let them know it was successful (like login API)
        if(userFound){
          return UserFactory.id(myID); //return ID
        }
        else{
          return UserFactory.id(0); // ID of zero means failed to find
        }       
      }
      }
    }
   
 
 
    /**
     * This method is used to delete a user from the system
     * @param email is the incoming email variable
     * @param password is the incoming password variable
     * @return is the return variable
     */
    @RequestMapping(value = "user/delete", method=RequestMethod.GET)
  public @ResponseBody UserStatusJson deleteUser(
      @RequestParam(value="email",     required=true) String email,
      @RequestParam(value="password",   required=true) String password) {
     
      // Create object to hold the user
      User deleteUser;
     
      // Set up your database Tools
    DatabaseTools myTools = new DatabaseTools();
     
    // Confirm user exists (and correct password)
      boolean userFound = myTools.dataSearch("User", "email", email, "password", password);
   
    // If not found return false response
    if(!userFound){
      return UserFactory.validUser(false);
    }
    // if yes extract the user
    else{
      try {
        deleteUser = myTools.getUser(email, password);
      } catch (Exception e)
      {
        // This method throws an error, we made sure this does not get thrown
        // with the previous search made so you can catch this error here and not worry.
        return UserFactory.validUser(false)
      }
    }
     
      // Remove user from table
    myTools.dataRemoval(deleteUser);
   
    // If user is not found return true! That means successful deletion.
    return UserFactory.validUser(!myTools.dataSearch("User", "email", email, "password", password));
    }
   
 
    @RequestMapping(value = "user/login", method=RequestMethod.GET)
  public @ResponseBody UserIDJson login( // ResponseEntity<StatusOutput>
      @RequestParam(value="apiKey",     required=true) Integer apiKey,
      @RequestParam(value="email",     required=true) String email,
      @RequestParam(value="password",   required=true) String password) throws Exception
  {
      if (!APIKeyCheck.exists(apiKey))
      {
        throw new Exception("Failed to find your API Key!");
       
        // Improve Error Handling with the following sites
        // Also set up unique IDs for each error type.
       
        // http://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc
        // http://www.tutorialspoint.com/spring/spring_exception_handling_example.htm
       
      }
      else
      {
        // Set up your database Tools
        DatabaseTools myTools = new DatabaseTools();
       
        // See if the user exists and if the password is correct
        boolean userFound = myTools.dataSearch("User", "email", email, "password", password);
       
        // If found create StatusOutput=TRUE and return
        if(userFound){
          ObjectRetrievalTools<User> myUser = new ObjectRetrievalTools<User>();
          User test = myUser.getObject(Table.User, "email", email);
        return UserFactory.id(test.getId());
        }
       
        // If not found create StatusOutput=FALSE and return
        else {
        return UserFactory.id(0);
        }
      }
    }
   
    @RequestMapping(value = "user/update", method=RequestMethod.GET)
    public @ResponseBody UserStatusJson update( // ResponseEntity<StatusOutput>
      @RequestParam(value="firstName",   required=false) String firstName,
      @RequestParam(value="lastName",   required=false) String lastName,
        @RequestParam(value="apiKey",     required=true) Integer apiKey,
        @RequestParam(value="email",     required=true) String email,
        @RequestParam(value="password",   required=true) String password) throws Exception
        {
      if (!APIKeyCheck.exists(apiKey))
      {
        throw new Exception("Failed to find your API Key!");
       
        // Improve Error Handling with the following sites
        // Also set up unique IDs for each error type.
       
        // http://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc
        // http://www.tutorialspoint.com/spring/spring_exception_handling_example.htm
       
      }
      else
      {
        // Set up your database Tools
        DatabaseTools myTools = new DatabaseTools();
       
        // See if the user exists and if the password is correct
        boolean userFound = myTools.dataSearch("User", "email", email, "password", password);
       
        // If found create StatusOutput=TRUE and return
        if(userFound){
          User myUser = myTools.getUser(email, password);
          if(firstName != null){ myUser.setFirstName(firstName);}
          if(lastName != null){ myUser.setLastName(lastName);}
          myTools.dataUpdate(myUser);
          return UserFactory.validUser(true);
        }
       
        // If not found create StatusOutput=FALSE and return
        else {
          return UserFactory.validUser(false);
        }
      }
    }
   
    /**
     * This API is used to return an list of all the groups this user is associated with
     * @param apiKey
     * @param userId
     * @param password
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "user/listGroups", method=RequestMethod.GET)
  public @ResponseBody GroupDetailsJson[] getGroupList(
      @RequestParam(value="apiKey",     required=true) Integer apiKey,
      @RequestParam(value="userId",     required=true) Integer userId, //This is the unique id number for this user in hibernate
      @RequestParam(value="password",   required=true) String password) throws Exception {
     
     
      if (!APIKeyCheck.exists(apiKey)) {
        throw new Exception("Failed to find API key");
      }
      else {
        // set up database tool set here
        DatabaseTools myTools = new DatabaseTools();
       
        //first confirm id and password are correct
        boolean userFound = myTools.dataSearch("User", "id", userId, "password", password);
       
        if (!userFound) {
          throw new Exception("Failed to find user" );
        }
        else
        {
          //check to see if any UserRoleGroup contain userId
          boolean groupFound = myTools.dataSearch("UserRoleGroup", "userId", userId);
         
          // if there are no groups then return an empty array
          if (!groupFound){
            return new GroupDetailsJson[0];
          }
          //UserRoleGroup table contains userId
          else
          {
           
            //Tool used to pull objects
            ObjectRetrievalTools objRetTools = new ObjectRetrievalTools();
           
            //list to store all the UserRoleGroups a userId belongs to
            List<UserRoleGroup> userUrgList = objRetTools.getObjectList(Table.UserRoleGroup, "userId", userId);
           
            //sets up a list to store the groups a userId belongs to
            List<Group> groups = new ArrayList<>(0);
           
            //iterates the list of UserRoleGroups and extracts the Group based on the groupId of the UserRoleGroup
            //add the Group to the list storing Groups
            for (UserRoleGroup urgIterator : userUrgList)
            {
              Group group = (Group) objRetTools.getObject(Table.Group, "id", urgIterator.getGroupId());
              groups.add(group);
              //System.out.println("\n\n\tThis is a title: " + group.getGroupTitle());
            }
           
            //sets up return object
            GroupDetailsJson[] groupDetailsList = GroupFactory.createGroupDetailsJson(groups.size());
           
            //loops through each Group in the list
            for (int i = 0; i < groups.size(); i++)
            {
              Group groupObj = groups.get(i);
                //get a String representation of the groupId to search into the db
                String groupIdString = Integer.toString(groupObj.getId());
               
               
                //List<Question> questionList = objRetTools.getObjectList(Table.Question, "groupId", groupIdString);
                //int numOfQuestions = questionList.size();
// TO BE CHANGED TO THE REAL #
                int numOfQuestions = 5;
               
                //List<UserRoleGroup> userList = objRetTools.getObjectList(Table.UserRoleGroup, "groupId", groupIdString);
                //int numOfUsersForGroup = userList.size();

// TO BE CHANGED TO THE REAL #
                int numOfUsersForGroup = 5;
                               
                //GroupDetailsJson object to be stored in the GroupDetailsJson array
                GroupDetailsJson groupDetailsJson = GroupFactory.createGroupDetailsJson(groupObj, numOfQuestions, numOfUsersForGroup);
             
                groupDetailsList[i] = groupDetailsJson;
            }                   
              //Once all spaces have been filled return GroupListJson[]
            return groupDetailsList;
          }
        }
      }          
      //Remember if you fail at any time throw an error message
    }
   
    /**
     * This API is used to get a list of all Scores saved for this user across all groups.
     * @param apiKey
     * @param userId
     * @param password
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "user/listScores", method=RequestMethod.GET)
  public @ResponseBody UserScoreJson[] getScoreList(
      @RequestParam(value="apiKey",     required=true) Integer apiKey,
      @RequestParam(value="userId",     required=true) String userId, //This is the unique id number for this user in hibernate
      @RequestParam(value="password",   required=true) String password) throws Exception {
   
    //First confirm id and password
   
    //get a list of Scores they have with tools
   
    //get a list of groups they are part of with tools
   
    //use ScoreFactory to create a userScoreJson[] array of size equal to list of scores
   
    //Return a list of all the scores that this user has.
   
     
      //// DUMMY LOGIC - remove these functions when completing this API ////
      //// Do not use this logic, it is incorrect! ////
   
     
      UserScoreJson[] tempScoreList = ScoreFactory.getUserScoreJson(2);
      tempScoreList[0] = new UserScoreJson();
      tempScoreList[0].setGroupId(1);
      tempScoreList[0].setGroupTitle("Algebra");
      tempScoreList[0].setNumOfQuestions(40);
      tempScoreList[0].setNumOfRightAnswers(35);
      tempScoreList[0].setDateTaken(new Date());
      tempScoreList[1] = new UserScoreJson();
      tempScoreList[1].setGroupId(2);
      tempScoreList[1].setGroupTitle("English");
      tempScoreList[1].setNumOfQuestions(25);
      tempScoreList[1].setNumOfRightAnswers(25);
      tempScoreList[1].setDateTaken(new Date());
    return tempScoreList;
  }
   
   
    /**
     * This API is used to get a list of all the questions posted by this user from all groups they are in.
     * @param apiKey
     * @param userId
     * @param password
     * @return is the return array of QuestionDetailsJson
     * @throws Exception
     */
    @RequestMapping(value = "user/listQuestions", method=RequestMethod.GET)
    public @ResponseBody QuestionDetailsJson[] getQuestionList(
        @RequestParam(value="apiKey",     required=true) Integer apiKey,
        @RequestParam(value="userId",     required=true) Integer userId, //This is the unique id number for this user in hibernate
        @RequestParam(value="password",   required=true) String password) throws Exception {
     
      if (!APIKeyCheck.exists(apiKey)) {
        throw new Exception("Failed to find API key");
      }
     
      else {
       
        //set up db tools
        DatabasePro<User, Integer, String, String> myUserTools = new DatabasePro<>();
       
        //list of user
        List<User> userList = myUserTools.getTypeList(Table.User, Column.id, userId, Column.password, password);
       
        if (userList.size() == 0) {
          throw new Exception("User was not found");
        }
       
        else {
         
          //set up db tools to return user's questions
          DatabasePro<Question, Integer, Integer, String> myQuestionTools = new DatabasePro<>();
          DatabasePro<Group,Integer,Integer,String> myGroupTools = new DatabasePro<>();
         
          //list of user's questions
          List<Question> questionList = myQuestionTools.getTypeList(Table.Question, Column.userId, userId);
         
          //set up return object
          QuestionDetailsJson[] questionArray = new QuestionDetailsJson[questionList.size()];
         
          //counter for question loop
        int counter = 0;
       
       
        //this loop extracts all the questions from the list and creates a new QuestionJson for each.
        for (Iterator<Question> questionIterator = questionList.iterator(); questionIterator.hasNext();) {
              Question myQuestions = questionIterator.next();
             
              // This will find the group associationed with the question
              List<Group> group = myGroupTools.getTypeList(Table.Group, Column.id, myQuestions.getGroupId());
              String groupTitle = group.get(0).getGroupTitle();
             
              //for each question, create a new QuesitonJson via the QuesitonFactory
              QuestionDetailsJson questionJson = QuestionFactory.createQuestionDetailsJson(myQuestions, groupTitle);
             
              //insert QuestionJson into the QuestionJson[] for return
              questionArray[counter] = questionJson;
             
              counter++;
        }       
        return questionArray;
        }
      }
    }
   
}
TOP

Related Classes of main.UserController

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.