Package com.lichtfragmente.servlets

Source Code of com.lichtfragmente.servlets.HomeServlet

package com.lichtfragmente.servlets;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
import java.util.Vector;

import com.lichtfragmente.helpers.*;
import com.lichtfragmente.beans.UserBean;
import com.lichtfragmente.beans.NewsBean;
import com.lichtfragmente.beans.ImageBean;

/**
* Servlet displaying the home page for logged in users.
* This servlet is the the page where a freshly logged in users gets redirected to.
* It fetches a list of news articles, latest images, latest images from friends for
* the given user and a featured (randomly selected) image.
* This information is stored into beans and forwarded to the corresponding view.
* Further, this servlet handles AJAX requests coming from the home view, by selecting
* a certain new article from the database, which is then displayed in a modal dialog
* on the home view.
**/
public class HomeServlet extends HttpServlet {
  public void doGet(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
        //check long
        if (!GlobalHelpers.isLoggedIn(request)) {
           response.sendRedirect("/lichtfragmente");
        } else {
            if (request.getParameter("news")!=null) {
                //if user wants to view a certain news article
                //(will be displayed in a modal dialog requested via AJAX)
                NewsBean result=this.getNewsById(request.getParameter("news"));
                request.setAttribute("newsitem",result);

                //dispatch news article
                RequestDispatcher dispatcher=request.getRequestDispatcher("/WEB-INF/jsp/includes/home/news.jsp");
                dispatcher.forward(request,response);
            } else {
                //user want to view the home page
               
                //get titles of latest news articles
                Vector<NewsBean> newslist=this.getNews();
                request.setAttribute("newslist",newslist);
       
                //get latest images which have been uploaded
                Vector<ImageBean> imagelist=this.getLatestImages();
                request.setAttribute("imagelist",imagelist);

                //get images which have been uploaded since the user's last visit
                Vector<ImageBean> newimages=this.getNewImages((Integer)request.getSession().getAttribute("userid"));
                request.setAttribute("newimages",newimages);
                //get featured image
                ImageBean featured=this.getFeatured();
                request.setAttribute("featured",featured);

                //dispatch view
                RequestDispatcher dispatcher=request.getRequestDispatcher(GlobalHelpers.getIncludedUrl("home/home"));
                dispatcher.forward(request,response);
            }
        }
  }

  public void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
        //no special reaction to POST requests
        this.doGet(request,response);
  }

    /**
     * Get all information associated to a certain news article ID.
     * This method fetches all information of a news article, which is
     * associated with a news ID and returns it wrapped into a bean.
     *
     * This method is used by the modal dialog which displays a certain
     * news article.
     *
     * @param id ID of news article to fetch
     * @return Information associated to ID wrapped into a bean
     **/
    private NewsBean getNewsById(String id)
    throws ServletException {
        NewsBean temp=new NewsBean();

        synchronized(this) {
            try {
                int num_id=Integer.parseInt(id);

                //select specific new article
                PreparedStatement stmt=DBInterface.doQuery("SELECT * FROM news WHERE id=?");
                stmt.setInt(1,num_id);
                ResultSet result=stmt.executeQuery();

                if (result.next()) {
                    temp.setId(result.getInt("id"));
                    temp.setAuthor(result.getInt("author"));
                    temp.setDate(result.getTimestamp("date"));
                    temp.setTitle(result.getString("title"));
                    temp.setContent(GlobalHelpers.nl2br(result.getString("content")));
                }

                result.close();
                stmt.close();
                DBInterface.close();
            } catch (SQLException se) {
                throw new ServletException("Could not retrieve news article: "+se.getMessage());
            } catch (NumberFormatException nfe) {
                throw new ServletException(nfe.getMessage());
            }
        }

        //return bean
        return temp;
    }

    /**
     * Fetch list of latest news articles.
     * This method is used to fetch the ten latest news articles
     * which have been written from the database.
     *
     * @return Vector containing the ten latest news articles
     **/
    private Vector<NewsBean> getNews()
    throws ServletException {
        Vector<NewsBean> resultList=new Vector<NewsBean>();

        synchronized(this) {
            try {
                //select only 10 articles (ordered by date)
                PreparedStatement stmt=DBInterface.doQuery("SELECT n.id, u.name, n.title, n.date " +
                                                           "FROM news n " +
                                                           "INNER JOIN users u ON n.author=u.id " +
                                                           "ORDER BY \"date\" DESC LIMIT 10");
                ResultSet result=stmt.executeQuery();

                while (result.next()) {
                    NewsBean temp=new NewsBean();

                    temp.setId(result.getInt(1));
                    temp.getUserBean().setName(result.getString(2));
                    temp.setTitle(result.getString(3));
                    temp.setDate(result.getTimestamp(4));

                    resultList.add(temp);
                }

                result.close();
                stmt.close();
                DBInterface.close();
            } catch (SQLException se) {
                throw new ServletException("Could not retrieve news: "+se.getMessage());
            }
        }

        return resultList;
    }

    /**
     * Fetch list of latest images.
     * This method is used to fetch the 14 latest images
     * which been uploaded to the system.
     * As the view will only display the thumbnails of the
     * images, we only want to select the image id and title.
     *
     * @return Vector containing the 14 latest images
     **/
    private Vector<ImageBean> getLatestImages()
    throws ServletException {
        Vector<ImageBean> resultList=new Vector<ImageBean>();

        synchronized(this) {
            try {
                //select only 14 images
                PreparedStatement stmt=DBInterface.doQuery("SELECT id,title FROM image ORDER BY id DESC LIMIT 14");
                ResultSet result=stmt.executeQuery();

                while (result.next()) {
                    ImageBean temp=new ImageBean();

                    temp.setId(result.getInt("id"));
                    temp.setTitle(result.getString("title"));

                    resultList.add(temp);
                }

                result.close();
                stmt.close();
                DBInterface.close();
            } catch (SQLException se) {
                throw new ServletException("Could not retrieve latest images: "+se.getMessage());
            }
        }

        return resultList;
    }

    /**
     * Fetch list of new images since last visit.
     * This method is used to fetch a maximum of 14 images
     * which been uploaded to the system since the user was last logged in.
     * As the view will only display the thumbnails of the
     * images, we only want to select the image id and title.
     *
     * @param userid The user's ID to determine the user's last login
     * @return Vector containing at max 14 new images
     **/
    private Vector<ImageBean> getNewImages(int userid)
    throws ServletException {
        Vector<ImageBean> resultList=new Vector<ImageBean>();

        synchronized(this) {
            try {
                //look for the last login in the users table using the id
                //and fetch all images with a newer timestamp
                PreparedStatement stmt=DBInterface.doQuery("SELECT id,title FROM image " +
                                                           "WHERE date>=(SELECT lastlogin FROM users WHERE id=?) " +
                                                           "ORDER BY RANDOM() LIMIT 14");
                stmt.setInt(1,userid);

                ResultSet result=stmt.executeQuery();

                while (result.next()) {
                    ImageBean temp=new ImageBean();

                    temp.setId(result.getInt("id"));
                    temp.setTitle(result.getString("title"));

                    resultList.add(temp);
                }

                result.close();
                stmt.close();
                DBInterface.close();
            } catch (SQLException se) {
                throw new ServletException("Could not retrieve new images: "+se.getMessage());
            }
        }

        return resultList;
    }

    /**
     * Select a featured image from the database.
     * This method selects a random image from the database to be displayed
     * in the 'featured' of the home page.
     *
     * @return Random image wrapped into a bean
     **/
    private ImageBean getFeatured()
    throws ServletException {
        ImageBean temp=new ImageBean();
       
        synchronized(this) {
            try {
                //select a random image from the database
                PreparedStatement stmt=DBInterface.doQuery("SELECT i.id,i.title,u.name " +
                                                           "FROM image i " +
                                                           "INNER JOIN users u ON i.owner=u.id " +
                                                           "ORDER BY RANDOM() LIMIT 1;");
                ResultSet result=stmt.executeQuery();

                //store image information
                if (result.next()) {
                    temp.setId(result.getInt(1));
                    temp.setTitle(result.getString(2));
                    temp.getUserBean().setName(result.getString(3));
                }
            } catch (SQLException se) {
                throw new ServletException("Could not retrieve featured image: "+se.getMessage());
            }
        }

        return temp;
    }
}
TOP

Related Classes of com.lichtfragmente.servlets.HomeServlet

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.