Advertisement
Guest User

BlogServlet.java

a guest
May 24th, 2013
431
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 18.15 KB | None | 0 0
  1. package de.uniregensburg.inett;
  2.  
  3. import java.io.InputStream;
  4. import java.io.PrintWriter;
  5. import java.io.IOException;
  6. import java.sql.*;
  7. import java.text.SimpleDateFormat;
  8. import java.util.Locale;
  9. import java.util.Scanner;
  10.  
  11. import javax.servlet.ServletConfig;
  12. import javax.servlet.ServletException;
  13. import javax.servlet.annotation.WebServlet;
  14. import javax.servlet.http.HttpServlet;
  15. import javax.servlet.http.HttpServletRequest;
  16. import javax.servlet.http.HttpServletResponse;
  17.  
  18. import org.ocpsoft.prettytime.PrettyTime;
  19.  
  20.  
  21. @WebServlet("/")
  22. public class BlogServlet extends HttpServlet
  23. {
  24.     private static final long serialVersionUID = 1L;
  25.    
  26.     private static final int excerptLength = 20;
  27.     private static final String siteTitle = "InetT Aufgabe 7";
  28.     private static final String siteName = "InetT Aufgabe 7";
  29.    
  30.     // The DB-Connection variable (gets configured in init())
  31.     private static Connection databaseConnection;
  32.    
  33.     // HTTP Parameter names and values
  34.     private static final String postIDParam = "pst_id";
  35.     private static final String postTitleParam = "pst_title";
  36.     private static final String postContentParam = "pst_text";
  37.     private static final String postTagParam = "pst_tags";
  38.     private static final String postCreationDateParam = "pst_creationdate";
  39.     private static final String postCommentAmountParam = "pst_cmtcount";
  40.     private static final String commentIDParam = "cmt_id";
  41.     private static final String commentAuthorParam = "cmt_author";
  42.     private static final String commentTextParam = "cmt_text";
  43.     private static final String commentCreationDateParam = "cmt_creationdate";
  44.     private static final String actionParam = "action";
  45.     private static final String actionCreateView = "createview";
  46.     private static final String actionEditView = "editview";
  47.     private static final String actionCreateEdit = "createedit";
  48.     private static final String actionDelete = "delete";
  49.     private static final String actionCreateComment = "createcmt";
  50.     private static final String actionDeleteComment = "deletecmt";
  51.    
  52.     // HTML Replacement Tags
  53.     private static final String tagTagList = "##TAGLIST##";
  54.     private static final String tagPostID = "##POSTID##";
  55.     private static final String tagCSS = "##CSS##";
  56.     private static final String tagTitle = "##TITLE##";
  57.     private static final String tagSiteName = "##SITENAME##";
  58.     private static final String tagDynamicContent = "##DYNAMIC_CONTENT##";
  59.     private static final String tagPostLink = "##POSTLINK##";
  60.     private static final String tagEditButtonIMG = "##EDITBUTTONIMG##";
  61.     private static final String tagReadOnIMG = "##READONIMG##";
  62.     private static final String tagPostText = "##POSTTEXT##";
  63.     private static final String tagCommentAmount = "##COMMENTAMOUNT##";
  64.     private static final String tagPostAge = "##POSTAGE##";
  65.     private static final String tagPostTitle = "##POSTTITLE##";
  66.     private static final String tagPostLinkComment = "##POSTLINKCOMMENT##";
  67.     private static final String tagPostEditLink = "##POSTEDITLINK##";
  68.     private static final String tagPostDeleteLink = "##POSTDELETELINK##";
  69.     private static final String tagPostList = "##POSTLIST##";
  70.     private static final String tagPostExcerpt = "##POSTEXCERPT##";
  71.     private static final String tagCommentLink = "##COMMENTLINK##";
  72.     private static final String tagCreateEditLink = "##CREATEEDITLINK##";
  73.     private static final String tagCommentList = "##COMMENTLIST##";
  74.     private static final String tagCommentText = "##COMMENTTEXT##";
  75.     private static final String tagCommentID = "##COMMENTID##";
  76.     private static final String tagCommentAuthor = "##COMMENTAUTHOR##";
  77.     private static final String tagCommentAge = "##COMMENTAGE##";
  78.     private static final String tagCommentDeleteLink = "##COMMENTDELETELINK##";
  79.     private static final String tagCommentCreateAction = "##COMMENTCREATEACTION##";
  80.  
  81.  
  82.     private static final String site_static_template_path = "/WEB-INF/html_templates/site_static.txt";
  83.     private static final String post_container_template_path = "/WEB-INF/html_templates/post_container.txt";
  84.     private static final String post_view_template_path = "/WEB-INF/html_templates/post_view.txt";
  85.     private static final String single_post_template_path = "/WEB-INF/html_templates/single_post.txt";
  86.     private static final String create_edit_view_template_path = "/WEB-INF/html_templates/create_edit_view.txt";
  87.     private static final String site_404_template_path = "/WEB-INF/html_templates/site_404.txt";
  88.     private static final String single_comment_template_path = "/WEB-INF/html_templates/single_comment.txt";
  89.  
  90.     private String site_static_template;
  91.     private String post_container_template;
  92.     private String post_view_template;
  93.     private String single_post_template;
  94.     private String create_edit_view_template;
  95.     private String site_404_template;
  96.     private String single_comment_template;
  97.  
  98.     public BlogServlet()
  99.     {
  100.         super();
  101.     }
  102.    
  103.     public void init(ServletConfig config) throws ServletException
  104.     {
  105.         super.init(config);
  106.  
  107.         // Database connection
  108.         String databaseLocation = "localhost";
  109.         String databasePort = "3306";
  110.         String databaseName = "blog";
  111.         String databaseUser = "root";
  112.         String databasePassword = "dbpass";
  113.        
  114.         try
  115.         {
  116.             String connectionString = "jdbc:mysql://" + databaseLocation + ":" + databasePort + "/" + databaseName + "?user=" + databaseUser + "&password=" + databasePassword;
  117.             Class.forName("com.mysql.jdbc.Driver").newInstance();
  118.             databaseConnection = DriverManager.getConnection(connectionString);
  119.         }
  120.         catch (Exception e)
  121.         {
  122.             e.printStackTrace();
  123.         }
  124.        
  125.         try
  126.         {
  127.             // Loading the HTML templates from file
  128.             InputStream input;
  129.            
  130.             input = getServletContext().getResourceAsStream(site_static_template_path);
  131.             site_static_template = readAll(input);
  132.             input.close();
  133.            
  134.             input = getServletContext().getResourceAsStream(site_404_template_path);
  135.             site_404_template = readAll(input);
  136.             input.close();
  137.            
  138.             input = getServletContext().getResourceAsStream(post_container_template_path);
  139.             post_container_template = readAll(input);
  140.             input.close();
  141.            
  142.             input = getServletContext().getResourceAsStream(post_view_template_path);
  143.             post_view_template = readAll(input);
  144.             input.close();
  145.            
  146.             input = getServletContext().getResourceAsStream(single_post_template_path);
  147.             single_post_template = readAll(input);
  148.             input.close();
  149.            
  150.             input = getServletContext().getResourceAsStream(single_comment_template_path);
  151.             single_comment_template = readAll(input);
  152.             input.close();
  153.            
  154.             input = getServletContext().getResourceAsStream(create_edit_view_template_path);
  155.             create_edit_view_template = readAll(input);
  156.             input.close();
  157.         }
  158.         catch (Exception e)
  159.         {
  160.             e.printStackTrace();
  161.         }
  162.     }
  163.    
  164.     public void destroy()
  165.     {
  166.         super.destroy();
  167.     }
  168.    
  169.     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
  170.     {
  171.         handleRequest(request, response);
  172.     }
  173.  
  174.     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
  175.     {
  176.         handleRequest(request, response);
  177.     }
  178.    
  179.     void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
  180.     {        
  181.         String responseString = "";
  182.         String self = request.getRequestURL().toString();
  183.         PrettyTime timeFormatter = new PrettyTime(new Locale("de"));
  184.        
  185.         // Getting the HTTP Parameters
  186.         String postID = request.getParameter(postIDParam);
  187.         String commentID = request.getParameter(commentIDParam);
  188.         String action = request.getParameter(actionParam);
  189.         String postTitle = request.getParameter(postTitleParam);
  190.         String postContent = request.getParameter(postContentParam);
  191.        
  192.         // Getting the basic site template into our response
  193.         String site_static = site_static_template;
  194.         site_static = site_static.replace(tagTitle, siteTitle);
  195.         site_static = site_static.replace(tagSiteName, siteName);
  196.         responseString += site_static;
  197.        
  198.         if (postTitle == null && postContent == null && action == null)
  199.         {
  200.             if (postID == null)
  201.             {
  202.                 // String to write the post list into
  203.                 String postList = "";
  204.                
  205.                 // Getting the list of all posts from the database
  206.                 ResultSet rs = executeStoredProcedure("getAllPosts");
  207.                
  208.                 responseString = responseString.replace(tagDynamicContent, indentEverythingBy(post_container_template, 12));
  209.                
  210.                 try
  211.                 {
  212.                     while (rs.next())
  213.                     {
  214.                         // Replacing the tags with its values
  215.                         String single_post_temp = single_post_template;
  216.                         single_post_temp = single_post_temp.replace(tagPostID, String.valueOf(rs.getInt(postIDParam)));
  217.                         single_post_temp = single_post_temp.replace(tagPostEditLink, self + "?" + postIDParam + "=" + String.valueOf(rs.getInt(postIDParam)) + "&" + actionParam + "=" + actionEditView);
  218.                         single_post_temp = single_post_temp.replace(tagPostDeleteLink, self + "?" + postIDParam + "=" + String.valueOf(rs.getInt(postIDParam)) + "&" + actionParam + "=" + actionDelete);
  219.                         single_post_temp = single_post_temp.replace(tagPostLink, self + "?" + postIDParam + "=" + String.valueOf(rs.getInt(postIDParam)));
  220.                         single_post_temp = single_post_temp.replace(tagPostAge, timeFormatter.format((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).parse(rs.getString(postCreationDateParam))));
  221.                         single_post_temp = single_post_temp.replace(tagCommentAmount, rs.getInt(postCommentAmountParam) == 1 ? (String.valueOf(rs.getInt(postCommentAmountParam)) + " Kommentar") : (String.valueOf(rs.getInt(postCommentAmountParam)) + " Kommentare"));
  222.                         single_post_temp = single_post_temp.replace(tagPostLinkComment, self + "?" + postIDParam + "=" + String.valueOf(rs.getInt(postIDParam)) + "#respond");
  223.                         single_post_temp = single_post_temp.replace(tagPostTitle, rs.getString(postTitleParam));
  224.                         single_post_temp = single_post_temp.replace(tagTagList, rs.getString(postTagParam));
  225.                         single_post_temp = single_post_temp.replace(tagPostExcerpt, rs.getString(postContentParam).substring(0, Math.min(rs.getString(postContentParam).length(), excerptLength)));
  226.                         postList += single_post_temp + "\n";
  227.                     }
  228.                 }
  229.                 catch (Exception e)
  230.                 {
  231.                     e.printStackTrace();
  232.                 }
  233.                
  234.                 postList = postList.substring(0, postList.length() - 1);
  235.                 responseString = responseString.replace(tagPostList,  indentEverythingBy(postList, 24));
  236.             }
  237.             else
  238.             {
  239.                 ResultSet rs = executeStoredProcedure("getPost", postID);
  240.                
  241.                 try
  242.                 {
  243.                     if (rs.next())
  244.                     {
  245.                         String post_view_temp = post_view_template;
  246.                         post_view_temp = post_view_temp.replace(tagPostID, String.valueOf(rs.getInt(postIDParam)));
  247.                         post_view_temp = post_view_temp.replace(tagPostEditLink, self + "?" + postIDParam + "=" + String.valueOf(rs.getInt(postIDParam)) + "&" + actionParam + "=" + actionEditView);
  248.                         post_view_temp = post_view_temp.replace(tagPostDeleteLink, self + "?" + postIDParam + "=" + String.valueOf(rs.getInt(postIDParam)) + "&" + actionParam + "=" + actionDelete);
  249.                         post_view_temp = post_view_temp.replace(tagPostLink, self + "?" + postIDParam + "=" + String.valueOf(rs.getInt(postIDParam)));
  250.                         post_view_temp = post_view_temp.replace(tagPostAge, timeFormatter.format((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).parse(rs.getString(postCreationDateParam))));
  251.                         post_view_temp = post_view_temp.replace(tagCommentAmount, rs.getInt(postCommentAmountParam) == 1 ? (String.valueOf(rs.getInt(postCommentAmountParam)) + " Kommentar") : (String.valueOf(rs.getInt(postCommentAmountParam)) + " Kommentare"));
  252.                         post_view_temp = post_view_temp.replace(tagPostLinkComment, self + "?" + postIDParam + "=" + String.valueOf(rs.getInt(postIDParam)) + "#respond");
  253.                         post_view_temp = post_view_temp.replace(tagPostTitle, rs.getString(postTitleParam));
  254.                         post_view_temp = post_view_temp.replace(tagTagList, rs.getString(postTagParam));
  255.                         post_view_temp = post_view_temp.replace(tagPostText, rs.getString(postContentParam));
  256.                         post_view_temp = post_view_temp.replace(tagCommentLink, self);
  257.                         post_view_temp = post_view_temp.replace(tagCommentCreateAction, actionCreateComment);
  258.                        
  259.                         rs = executeStoredProcedure("getPostComments", postID);
  260.                         String commentList = "";
  261.                        
  262.                         while (rs.next())
  263.                         {
  264.                             String single_comment_temp = single_comment_template;
  265.                             single_comment_temp = single_comment_temp.replace(tagCommentID, String.valueOf(rs.getInt(commentIDParam)));
  266.                             single_comment_temp = single_comment_temp.replace(tagCommentAuthor, rs.getString(commentAuthorParam) == "" ? "Anonym" : rs.getString(commentAuthorParam));
  267.                             single_comment_temp = single_comment_temp.replace(tagCommentAge, timeFormatter.format((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).parse(rs.getString(commentCreationDateParam))));
  268.                             single_comment_temp = single_comment_temp.replace(tagCommentDeleteLink, self + "?" + commentIDParam + "=" + String.valueOf(rs.getInt(commentIDParam)) + "&" + actionParam + "=" + actionDeleteComment);
  269.                             single_comment_temp = single_comment_temp.replace(tagCommentText, rs.getString(commentTextParam));
  270.                             commentList += single_comment_temp + "\n";
  271.                         }
  272.                        
  273.                         commentList = commentList.substring(0, commentList.length() - 1);
  274.                         post_view_temp = post_view_temp.replace(tagCommentList, indentEverythingBy(commentList, 20));
  275.                         responseString = responseString.replace(tagDynamicContent, indentEverythingBy(post_view_temp, 12));
  276.                        
  277.                        
  278.                         // ID valid
  279.                         // Post-View
  280.                        
  281.                     }
  282.                     else
  283.                     {
  284.                         // 404
  285.                         responseString = responseString.replace(tagDynamicContent, indentEverythingBy(site_404_template, 12));
  286.                     }
  287.                 }
  288.                 catch (Exception e)
  289.                 {
  290.                     e.printStackTrace();
  291.                 }
  292.             }
  293.         }
  294.         else if (action == actionCreateView)
  295.         {
  296.             // Create / Edit Page in Create-Mode (Title and Content empty, postID = 0)
  297.         }
  298.         else if (action == actionEditView)
  299.         {
  300.             // Create / Edit Page in Edit-Mode (Title and Content prefilled, postID accordingly)
  301.         }
  302.         else if (action == actionCreateEdit)
  303.         {
  304.             if (postTitle != null && postContent != null && postTitle != "" && postContent != "")
  305.             {
  306.                 if(postID == "0")
  307.                 {
  308.                     // Create new post
  309.                 }
  310.                 else
  311.                 {
  312.                     // Check for valid ID / 404
  313.                     // Edit existing post
  314.                 }
  315.                 // Post-View
  316.             }
  317.             else
  318.             {
  319.                 // Title or content unfilled Page
  320.             }
  321.         }
  322.         else if (action == actionDelete)
  323.         {
  324.             // Check for valid ID / 404
  325.             // Delete Post from database
  326.             // Overview Page
  327.         }
  328.            
  329.            
  330.         PrintWriter writer = response.getWriter();
  331.         writer.write(responseString);
  332.         writer.close();
  333.     }
  334.    
  335.     public ResultSet executeStoredProcedure(String name, String parameters)
  336.     {
  337.         try
  338.         {
  339.             CallableStatement proc = databaseConnection.prepareCall("{call " + name + "(" + parameters + ")}");
  340.             return proc.executeQuery();
  341.         }
  342.         catch(Exception e)
  343.         {
  344.             e.printStackTrace();
  345.         }
  346.         return null;
  347.     }
  348.    
  349.     public ResultSet executeStoredProcedure(String name)
  350.     {
  351.         return executeStoredProcedure(name, "");
  352.     }
  353.    
  354.     public String indentEverythingBy(String text, int indent)
  355.     {
  356.         text = text.replace("\n", "\n" + repeatChar(' ', indent));
  357.        
  358.         return text;
  359.     }
  360.    
  361.     public String repeatChar(char c, int length)
  362.     {
  363.         String temp = "";
  364.        
  365.         for (int i = 0; i < length; i++)
  366.         {
  367.             temp += c;
  368.         }
  369.        
  370.         return temp;
  371.     }
  372.    
  373.     public String readAll (InputStream input)
  374.     {
  375.         Scanner s = new Scanner(input);
  376.         s.useDelimiter("\\A");
  377.         String temp = s.hasNext() ? s.next() : "";
  378.         s.close();
  379.         return temp;
  380.     }
  381. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement