com.local.ask.model.controller.ModelDAOImpl.java Source code

Java tutorial

Introduction

Here is the source code for com.local.ask.model.controller.ModelDAOImpl.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.local.ask.model.controller;

import com.local.ask.controller.shiro.UserPrincipal;
import com.local.ask.exception.UniqueCorruptionException;
import com.local.ask.exception.UserAlreadyExistException;
import com.local.ask.exception.UserDoesNotExistException;
import com.local.ask.form.QuestionForm;
import com.local.ask.model.Answer;
import com.local.ask.model.PollChoice;
import com.local.ask.model.PollVote;
import com.local.ask.model.Question;
import com.local.ask.model.Tag;
import com.local.ask.model.TagUsed;
import com.local.ask.model.User;
import com.local.ask.model.UserTemp;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.shiro.SecurityUtils;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author Olayinka
 */
@Repository
@Service
@Transactional
public class ModelDAOImpl implements ModelDAO {

    @Autowired
    private SessionFactory SESSION_FACTORY;

    private Session getCurrentSession() {
        return SESSION_FACTORY.getCurrentSession();
    }

    @Override
    public void listUserTemps() {
        try {
            List users = getCurrentSession().createQuery("FROM UserTemp").list();
            for (Iterator iterator = users.iterator(); iterator.hasNext();) {
                UserTemp user = (UserTemp) iterator.next();
                System.out.print("Display Name: " + user.getDisplayName());
                System.out.print("Email: " + user.getEmail());
                System.out.print(" Password: " + user.getPassword());
                System.out.println(" Time joined: " + user.getTimeJoined().toString());
            }
        } catch (HibernateException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void deleteUserTemp(Integer userTempID) {
        try {
            UserTemp userTemp = (UserTemp) getCurrentSession().get(UserTemp.class, userTempID);
            getCurrentSession().delete(userTemp);
        } catch (HibernateException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Integer addUserTemp(UserTemp userTemp) throws UserAlreadyExistException, UniqueCorruptionException {
        UserTemp userTemp1 = getUserTempFromEmail(userTemp);
        User user = getUserFromEmail(new User(userTemp));
        if (userTemp1 != null || user != null) {
            throw new UserAlreadyExistException(userTemp.getEmail());
        }
        Integer userID = null;
        try {
            userID = (Integer) getCurrentSession().save(userTemp);
        } catch (HibernateException e) {
            e.printStackTrace();
        }
        return userID;
    }

    @Override
    public void listUsers() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void deleteUser(Integer userID) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public UserTemp getUserTemp(String code) throws UniqueCorruptionException, UserDoesNotExistException {
        try {
            Query query = getCurrentSession().createQuery("FROM UserTemp U where U.confirmCode = :confirm_code");
            query.setParameter("confirm_code", code);
            List users = query.list();
            if (users.size() == 1) {
                return (UserTemp) users.get(0);
            } else if (users.size() > 1) {
                throw new UniqueCorruptionException("user_temp", "email");
            } else if (users.isEmpty()) {
                throw new UserDoesNotExistException("");
            }
        } catch (HibernateException ex) {
            ex.printStackTrace();
        }
        return null;
    }

    @Override
    public UserTemp getUserTempFromEmail(UserTemp userTemp) throws UniqueCorruptionException {
        try {
            Query query = getCurrentSession().createQuery("FROM UserTemp U where U.email = :email");
            query.setParameter("email", userTemp.getEmail());
            List users = query.list();
            if (users.size() == 1) {
                return (UserTemp) users.get(0);
            } else if (users.size() > 1) {
                throw new UniqueCorruptionException("user_temp", "email");
            } else if (users.isEmpty()) {
                return null;
            }
        } catch (HibernateException ex) {
            ex.printStackTrace();
        }
        return null;
    }

    @Override
    public User getUserFromEmail(User user) throws UniqueCorruptionException {
        try {
            Query query = getCurrentSession().createQuery("FROM User U where U.email = :email");
            query.setParameter("email", user.getEmail());
            List users = query.list();
            if (users.size() == 1) {
                return (User) users.get(0);
            } else if (users.size() > 1) {
                throw new UniqueCorruptionException("user", "email");
            } else if (users.isEmpty()) {
                return null;
            }
        } catch (HibernateException ex) {
            ex.printStackTrace();
        }
        return null;
    }

    @Override
    public Integer addUser(UserTemp userTemp) {
        Integer userID = null;
        try {
            userID = (Integer) getCurrentSession().save(new User(userTemp));
        } catch (HibernateException e) {
            e.printStackTrace();
        }
        deleteUserTemp(userTemp.getId());
        return userID;
    }

    @Override
    public UserTemp updateUserTemp(UserTemp userTemp) throws UserDoesNotExistException, UniqueCorruptionException {
        try {
            userTemp = getUserTempFromEmail(userTemp);
            getCurrentSession().update(userTemp);
            return userTemp;
        } catch (HibernateException ex) {
            ex.printStackTrace();
        }
        return null;
    }

    @Override
    public List<Question> getRecentForHottestQuestions() {
        List<Question> ret = new ArrayList<>(1000);
        try {
            Query query = getCurrentSession().createQuery("FROM Question q ORDER BY q.timeLastViewed desc");
            query.setMaxResults(1000);
            ret = query.list();
        } catch (HibernateException ex) {
            ex.printStackTrace();
        }
        return ret;
    }

    @Override
    public List<Question> getRecentQuestions() {
        List<Question> ret = new ArrayList<>(100);
        try {
            Query query = getCurrentSession().createQuery("FROM Question q ORDER BY q.timeLastEdited desc");
            query.setMaxResults(100);
            ret = query.list();
        } catch (HibernateException ex) {
            ex.printStackTrace();
        }
        return ret;
    }

    @Override
    public Question getQuestion(Integer id) {
        try {
            Question ret = (Question) getCurrentSession().get(Question.class, id);
            return ret;
        } catch (HibernateException ex) {
            ex.printStackTrace();
        }
        return null;
    }

    @Override
    public List<Tag> getRecentTags() {
        System.out.println("queried");
        List<Tag> ret = new ArrayList<>(10);
        try {
            Query query = getCurrentSession().createQuery("FROM Tag t ORDER BY t.timeLastViewed desc");
            query.setMaxResults(10);
            ret = query.list();
        } catch (HibernateException ex) {
            ex.printStackTrace();
        }
        return ret;
    }

    @Override
    public void updateQuestion(Question q) {
        getCurrentSession().update("question", q);
    }

    @Override
    public Question addPost(QuestionForm questionForm) {
        //getCurrentSession().createQuery("INSERT into Question(title, ")
        Question question = new Question();
        question.setTitle(questionForm.getTitle());
        question.setBody(questionForm.getBody());
        question.setUser(getCurrentUser());
        question.setType(questionForm.isPoll() ? "POLL" : "QUESTION");
        getCurrentSession().save(question);

        for (String string : questionForm.getRealTags()) {
            TagUsed tagUsed = new TagUsed();
            Tag tag = getAndCreateTagFromBody(string);
            tagUsed.setQuestion(question);
            tagUsed.setTag(tag);
            getCurrentSession().save(tagUsed);
        }
        if (!question.isQuestion()) {
            for (String string : questionForm.getPollChoices()) {
                if (string == null) {
                    break;
                }
                PollChoice pollChoice = new PollChoice();
                pollChoice.setQuestion(question);
                pollChoice.setBody(string.trim());
                getCurrentSession().save(pollChoice);
            }
        }

        getCurrentSession().persist(question);
        return question;
    }

    private Tag getAndCreateTagFromBody(String string) {
        Query query = getCurrentSession().createQuery("FROM Tag T where T.body = :body").setParameter("body",
                string.toLowerCase());
        List tags = query.list();
        if (tags.size() == 1) {
            return (Tag) tags.get(0);
        } else if (tags.isEmpty()) {
            Tag tag = new Tag();
            tag.setBody(string.toLowerCase());
            getCurrentSession().save(tag);
            return tag;
        }
        return null;
    }

    @Override
    public void castPollVote(Integer pollChoiceId) {
        PollChoice pollChoice = (PollChoice) getCurrentSession().get(PollChoice.class, pollChoiceId);
        PollVote pollVote = new PollVote(), tempPollVote;
        User user = getCurrentUser();
        pollVote.setQuestion(pollChoice.getQuestion());
        pollVote.setUser(user);
        pollVote.setPollChoice(pollChoice);
        if (getCurrentSession().createQuery("FROM PollVote P WHERE P.question = :question and P.user = :user")
                .setParameter("question", pollChoice.getQuestion()).setParameter("user", user).list().isEmpty()) {

            getCurrentSession().save(pollVote);
        }
    }

    @Override
    public PollVote getUserPollVote(Question question) {
        User user = getCurrentUser();
        if (user == null) {
            return null;
        }
        List list = getCurrentSession()
                .createQuery("FROM PollVote P WHERE P.question = :question and P.user = :user")
                .setParameter("question", question).setParameter("user", user).list();
        if (!list.isEmpty()) {
            return (PollVote) list.get(0);
        }
        return null;
    }

    @Override
    public User getCurrentUser() {
        UserPrincipal principal = (UserPrincipal) SecurityUtils.getSubject().getPrincipal();
        if (principal == null) {
            return null;
        }
        User user = (User) getCurrentSession().get(User.class, principal.getId());
        if (user == null) {
            SecurityUtils.getSubject().logout();
        }
        return user;
    }

    @Override
    public void addAnswer(int id, String body) {
        Question question = (Question) getCurrentSession().get(Question.class, id);
        if (question != null) {
            Answer answer = new Answer();
            answer.setQuestion(question);
            User user = getCurrentUser();
            answer.setUser(user);
            answer.setBody(body);
            getCurrentSession().save(answer);
        }
    }

    @Override
    public Answer getAnswer(Integer aId) {
        try {
            Answer ret = (Answer) getCurrentSession().get(Answer.class, aId);
            return ret;
        } catch (HibernateException ex) {
            ex.printStackTrace();
        }
        return null;
    }

    @Override
    public void updateAnswer(Answer answer) {
        getCurrentSession().update("answer", answer);
    }

}