EditImage.java Source code

Java tutorial

Introduction

Here is the source code for EditImage.java

Source

/***
 *  Takes values from EditForm.java and updates the image
 *  
 *  Taken From:
 *  Copyright 2005 COMPUT 391 Team, CS, UofA                             
 *  Author:  Fan Deng
 *                                                                  
 *  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.
 *
 *  Date: November 26, 2014
 *  Author: Morgan Patzelt
 *
 *  the table shall be created using the following
  CREATE TABLE images (
       photo_id    int,
  owner_name  varchar(24),
  permitted   int,
  subject     varchar(128),
  place       varchar(128),
  timing      date,
  description varchar(2048),
  thumbnail   blob,
  photo       blob,
  PRIMARY KEY(photo_id),
  FOREIGN KEY(owner_name) REFERENCES users,
  FOREIGN KEY(permitted) REFERENCES groups
  );
 *
 *  One may also need to create a sequence using the following 
 *  SQL statement to automatically generate a unique pic_id:
 *
 *   CREATE SEQUENCE pic_id_sequence;
 *
 ***/

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.util.Date;
import java.util.*;
import oracle.sql.*;
import oracle.jdbc.*;
import java.util.Date.*;

/**
 *  The package commons-fileupload-1.0.jar is downloaded from 
 *         http://jakarta.apache.org/commons/fileupload/ 
 *  and it has to be put under WEB-INF/lib/ directory in your servlet context.
 *  One shall also modify the CLASSPATH to include this jar file.
 */
import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.io.FilenameUtils;

public class EditImage extends HttpServlet {
    public String response_message = "Nothing Happened";

    private Connection conn = null;

    // initial values
    String username = "amlee1";
    String password = "splplus719";
    String drivername = "oracle.jdbc.driver.OracleDriver";
    String dbstring = "jdbc:oracle:thin:@gwynne.cs.ualberta.ca:1521:CRS";

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        Security sec = new Security();

        PrintWriter out = response.getWriter();

        // Check to makes sure the user is logged in
        String userid = "";
        Cookie login_cookie = null;
        Cookie cookie = null;
        Cookie[] cookies = null;
        // Get an array of cookies associated with this domain
        cookies = request.getCookies();
        // If any cookies were found, see if any of them contain a valid login.
        if (cookies != null) {
            for (int i = 0; i < cookies.length; i++) {
                cookie = cookies[i];
                // out.println(cookie.getName()+"<br>");
                // However, we only want one cookie, the one whose name matches
                // the
                // userid that has logged in on this browser.
                if (i != 0 && userid == "") {
                    userid = cookie.getName();
                }
            }
        }
        // If no login was detected, redirect the user to the login page.
        if (userid == "") {
            out.println("<a href=login.jsp>Please login to access this site.</a>");
        }
        // Else, we have a valid session.
        else {
            // Gets the photo_id from the Query String
            String photo_id = request.getQueryString();

            // Variables
            String command = "";
            InputStream instream = null;
            Statement stmt = null;
            PreparedStatement updateSub = null;
            PreparedStatement updateLoc = null;
            PreparedStatement updateDate = null;
            PreparedStatement updateDesc = null;
            PreparedStatement updatePrivacy = null;

            // Default variables to add to table
            String subject = null;
            String place = null;
            String timing = null;
            String description = null;
            String permission = null;
            String groupName = null;

            try {

                // Gets the parameters for subject, place, timing, & description
                subject = request.getParameter("subject");
                place = request.getParameter("place");
                timing = request.getParameter("SnapHost_Calendar");
                description = request.getParameter("description");
                permission = request.getParameter("permission");
                groupName = request.getParameter("group");
                response_message = response_message + subject + place + timing + description + "PHOTO ID = "
                        + photo_id;

                // Connect to the database and create a statement
                Connection conn;
                conn = getConnected(drivername, dbstring, username, password);
                stmt = conn.createStatement();
                response_message = response_message + "connection good";

                // Only updates fields that had input
                if (!subject.isEmpty()) {
                    updateSub = conn.prepareStatement(
                            "UPDATE images SET subject = \'" + subject + "\' WHERE photo_id = " + photo_id);
                    updateSub.executeUpdate();
                }

                if (!place.isEmpty()) {
                    updateLoc = conn.prepareStatement(
                            "UPDATE images SET place = \'" + place + "\' WHERE photo_id = " + photo_id);
                    updateLoc.executeUpdate();
                }

                if (!timing.isEmpty()) {
                    updateDate = conn.prepareStatement("UPDATE images SET timing = to_date('" + timing
                            + "', 'YYYY-MM-DD') WHERE photo_id = " + photo_id);
                    updateDate.executeUpdate();
                }

                if (!description.isEmpty()) {
                    updateDesc = conn.prepareStatement(
                            "UPDATE images SET description = \'" + description + "\' WHERE photo_id = " + photo_id);
                    updateDesc.executeUpdate();
                }
                if (!permission.isEmpty()) {
                    // Sets the permissions Value depending on what the user specified
                    // Default is private 
                    int permissionValue = 2;
                    if (permission.equals("everyone")) {
                        permissionValue = 1;
                    } else if (permission.equals("useronly")) {
                        permissionValue = 2;
                    } else if (permission.equals("group")) {
                        // Set permission value to 0 to indicate no
                        // valid group in the case the user does not
                        // supply a valid group ID.
                        permissionValue = 0;
                        // What we actually want is the group ID
                        String groupid = sec.find_group_id(userid, groupName, conn);
                        // If a matching group ID is found, add it.
                        if (groupid != "") {
                            permissionValue = Integer.parseInt(groupid);
                        }

                    }

                    updateDesc = conn.prepareStatement("UPDATE images SET permitted = \'" + permissionValue
                            + "\' WHERE photo_id = " + photo_id);
                    updateDesc.executeUpdate();
                }

                response_message = "Image Updated!";

            } catch (Exception e) {
                response_message = response_message + "uh oh";
            }
            try {
                // Output response to the client
                response.setContentType("text/html");
                out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + "Transitional//EN\">\n" + "<HTML>\n"
                        + "<HEAD><TITLE>Upload Message</TITLE></HEAD>\n" + "<BODY>\n" + "<H1>" + response_message
                        + "</H1>\n" + "</BODY></HTML>");
                out.println("<P><a href=\"GetBigPic?big" + photo_id + "\"> Back To Image </a>");
                out.println("</body>");
                out.println("</html>");
            } catch (Exception e) {
                response_message = response_message + "4";
            }
        }
    }

    /*
     * /* To connect to the specified database
     */
    private static Connection getConnected(String drivername, String dbstring, String username, String password)
            throws Exception {
        Class drvClass = Class.forName(drivername);
        DriverManager.registerDriver((Driver) drvClass.newInstance());
        return (DriverManager.getConnection(dbstring, username, password));
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

}