IMAGE SHARING APPLICATION (IShA) Akshaya Vishnu Togrikar B.S., University of Mumbai, 2007 PROJECT Submitted in partial satisfaction of the requirements for the degree of MASTER OF SCIENCE in COMPUTER SCIENCE at CALIFORNIA STATE UNIVERSITY, SACRAMENTO FALL 2010 IMAGE SHARING APPLICATION (IShA) A Project by Akshaya Vishnu Togrikar Approved by: __________________________________, Committee Chair Scott Gordon, Ph.D __________________________________, Second Reader Ying Jin, Ph.D ____________________________ Date ii Student: Akshaya Vishnu Togrikar I certify that this student has met the requirements for format contained in the University format manual, and that this project is suitable for shelving in the Library and credit is to be awarded for the Project. __________________________, Graduate Coordinator Nikrouz Faroughi, Ph.D Department of Computer Science iii ________________ Date Abstract of IMAGE SHARING APPLICATION (IShA) by Akshaya Vishnu Togrikar In this work a secure photo sharing application has been developed for increasing the privacy of users by empowering them with more controls to protect images than are typically available in other photo sharing applications. The application allows users to create new login and share photos with friends based on their preference. Specifically, the uploaded photo can be either kept as public or as private, wherein private means only the specified users can access the image. The granularity of sharing is boiled down to the image level rather than account level to improve the privacy of the users. Furthermore, only specified users are allowed to download the images. The access rights of the photos can be modified (allowing access to users or revoking the access) by the owner at any time. The application was developed using Java, J2EE (Java 2 Platform, Enterprise Edition) using a 3-tier approach (Web tier, EJB - Enterprise Java Bean tier, Database tier). The database is maintained in MySQL. The web pages are developed using JSF (Java Server Faces) and JSP (Java Server Pages). The application is browser independent and works on a wide variety of browsers. The application can also be easily deployed on World Wide Web. _______________________, Committee Chair Scott Gordon, Ph.D _______________________ Date iv ACKNOWLEDGMENTS I would like to express my deep-felt gratitude to my advisor, Dr. Scott Gordon of the Computer Science Department at CSUS. v TABLE OF CONTENTS Page Acknowledgments................................................................................................................... iii List of Figures ........................................................................................................................ vii Chapter 1. INTRODUCTION ..................... ………………………………………………………… 1 1.1 Photo Sharing......................................................................................................... 1 1.2 Authentication Issues ............................................................................................ 2 2. BACKGROUND ................................................................................................................ 4 3. DESIGN OF IShA .............................................................................................................. 6 3.1 Web Tier ................................................................................................................. 7 3.2 Managed Bean ........................................................................................................ 9 3.3 Web Services ........................................................................................................ 11 3.4 Enterprise Java Beans ........................................................................................... 13 3.5 Entity Classes ........................................................................................................ 15 3.6 Database Tier ........................................................................................................ 17 3.6.1 Data Dictionary ........................................................................................... 18 3.7 Web Pages............................................................................................................. 19 3.8 Privacy Implementation ........................................................................................ 25 4. CONCLUDING REMARKS ........................................................................................... 27 4.1 Conclusions........................................................................................................... 27 4.2 Future Work .......................................................................................................... 27 Appendix A. ............................................................................................................................ 29 Appendix B. ............................................................................................................................ 40 References ............................................................................................................................... 41 vi LIST OF FIGURES Page 1. Architecture of IShA .......………………………………………………………… 6 2. faces-config.xml.......................................................................................................8 3. web.xml…................................................................................................................9 4. Getter and Setter Methods .......................................................................................9 5. Managed bean parameter reference in XHTML ....................................................10 6. Managed bean method call in XHTML .................................................................10 7. Communication between a JAX-WS Web Service and a Client ..........................11 8. SOAP Request .......................................................................................................12 9. SOAP Response .....................................................................................................12 10. Web service annotations .......................................................................................13 11. Enterprise Java Bean code example ......................................................................15 12. Entity Class named queries example ....................................................................16 13. Mapping between Entity Class property and table column ..................................17 14. userInfo Table .......................................................................................................18 15. photo Table ...........................................................................................................18 16. sharedWith Table ..................................................................................................18 17. Entity Relationship diagram .................................................................................19 18. Login Page ............................................................................................................20 19. Shared with, Viewed by, Downloaded by Page ....................................................20 20. My photos Page.....................................................................................................21 21. Friends’ photos Page .............................................................................................21 22. Upload photos Page ..............................................................................................22 23. Change access Page ..............................................................................................22 24. New user creation Page ..........................................................................................23 25. Login fail Page ......................................................................................................23 26. Upload successful notification Page .....................................................................24 vii 27. Change access success notification Page ..............................................................24 28. Contents of sharedWith Table ..............................................................................25 viii 1 Chapter 1 INTRODUCTION 1.1 Photo Sharing Photo Sharing allows users to publish digital photos online, and share them with others. This function is provided by many websites nowadays that facilitate the upload and display of images. The photo sharing sites provide fast and easy access to billions of images from users around the world. Initially in the 1990s, photo sharing websites were developed for online trading and photo printing. Later on in early 2000, more sophisticated photo sharing websites like Picasa[1], Flickr [2] and Photobucket[3] etc. were introduced. The photo sharing on such websites is classified on the account level. The classification is done as “Family “, “Friends “, “Friends of Friends” and “Public “. In case of Flickr, the public photos are visible to everyone on world wide web and is not limited to the Flickr membership. The Advantages of these websites are: 1. The service provided by these websites have unlimited storage for photos for free. 2. The users create individual photo albums, categorize their photos and place them in the corresponding albums. 3. The users can also set access control to their albums. 4. Allow photo tagging, geotagging and face recognition. Moreover these websites allow cropping, color enhancement and red eye reduction. 2 5. Provide content filtering control over photos being uploaded, which restricts people from uploading offensive photos. 6. Allow users to upload and share videos along with the photos. The Disadvantages of these websites are: 1. The Picasa Web Album uses an unlisted member approach for URLs of private photo albums. This enables the listed user to email a private album's URL to anyone he/she wants; the recipient can view the album without the knowledge of the owner of the album. 2. This unauthorized access of the private albums leads to the unauthorized downloading of the same. 3. The user is not notified and is completely unaware of the viewing and downloading done by other users. 4. The granularity of sharing is on account level rather than the image level which may affect the privacy of the owners. 1.2 Authentication Issues Privacy is very important for each owner. The photos uploaded by the owner can be misused by any other person. These websites do not provide privacy on images completely. As discussed earlier, Flickr allows anyone (member or non-member) to view the photos flagged as public, which might not always be safe. Such photos can be 3 misused at inappropriate places for advertising. In case of Picasa Web Album, albums marked as private can be viewed by any user around the world, if he/she gets the URL to that album. Hence the albums marked as private don't remain private anymore. Picasa uses authentication key to mark album as private, which is part of the URL. The URL with authentication key and the one without key distinguishes private photos and public photos. If anyone gets the authentication key, there is no further checking for the viewing capabilities of the viewer. This is why; anyone can view the album after getting the URL with the key. Furthermore, such unauthorized viewing leads to the unauthorized downloading. Hence, the authentication needs to be done every time before viewing any photos for maintaining privacy. This can be done by enforcing viewer to log into the application and then verifying the capabilities of the viewer for viewing the photo. Chapter 2 discusses the background of the project. Chapter 3 focuses on the architecture and implementation of IShA along with the screenshots of the web pages of IShA. Chapter 4 contains the project conclusions. 4 Chapter 2 BACKGROUND In this chapter, we provide a brief introduction to the general architecture of Java-based multi-user services. IShA is developed using J2EE web development application. “The Java EE application model defines architecture for implementing services as multi-tier applications that deliver the scalability, accessibility, and manageability needed by enterprise-level applications.”[4] The system has following tiers: The Web Tier for displaying GUI of the application using JSF (Java Server Faces) and JSP (Java Server Pages). User inputs are read in these JSF and JSP files and are converted to user requests. Moreover, these web pages print the server response. The Application Tier for Web Services to interact using HTTP (Hyper Text Transfer Protocol) along with SOAP (Simple Object Access Protocol) between Presentation Tier and Business Logic Tier. Web services convert user requests into XML (Extensive Markup Language) and forward the request to server. The response from server is again converted in XML format by web services. XML is used for the requests and response because XML can be implemented by each browser and can be used in any programming language. 5 The Business Tier, that uses EJB (Enterprise Java Beans) which contains the main logic of the system, to interact with the Database. User requests are validated and processed in the business tier. This tier has the capability of communicating and updating the database. The Database Tier uses MySQL for storing data. This tier contains relational database tables to store user information, photo information and the information related to the photo sharing. The user request are sent from web tier to the application tier; from application tier to the business tier and finally from business tier to database tier. The response from the server travels in the opposite direction of the request traversal. 6 Chapter 3 DESIGN OF IShA The architectural design used for the development of IShA is shown in the Figure 3.1. Figure 3.1: Architecture of IShA The user input is taken in web tier using JSF and JSP pages. The user requests are stored in the managed bean variables. The managed bean forwards the request to the web service client. The web service client converts the user request to the XML format and 7 forwards it to the web services on the server. The web services on the server read the requests, extract the user input and forward it to the EJB. The requests are processed in EJB and the results are sent to the web service. The web services convert the result into XML response and forward the response to web service client, which in turn send it to the web tier. 3.1 Web Tier The web pages seen on client machine are part of the web tier. Furthermore, the managed bean and the servlets are part of the web tier used for processing the user inputs. The web pages can be developed using HTML (Hyper Text Markup Language), XHTML (Extended Hyper Text Markup Language), JSP (Java Server Pages), ASP (Active Server Pages), AJAX (Asynchronous JavaScript and XML) etc. In this project, the web page development is done using XHTML also called JSF (Java Server Faces) and JSP. JSF provides event-driven component model. Validations for required field value can be done in JSF without forwarding the request to the next tier. In this work, pages for displaying friends' photos, own photos and login fail page are developed using JSF. JSP is a Java based technology used to help software developers for creating dynamic and interactive web pages. The JSP pages can contain java code; also known as scriptlet; which can be used for simple validations like data format checking. The comparison of password field and confirm password field can be done in JSP page. The pages for logging in, uploading 8 photos, creating new user, seeing viewing and downloading details and the functionality of download button are developed using JSP. When the information is entered on JSF pages, the values are passed to managed bean which provides application logic and the results are read from managed bean for displaying on JSF page. If we consider the example of 'my photos page', when the user clicks on the 'see my photos' link, the getMyPhotos() function in the managed bean is called to get the results. JSF technology has the capability of separating behavior and presentation which makes JSF development very easy. Even a person with very limited knowledge of scripting language can easily access the server-side objects, without writing any scripts. JSF pages have capability of reading the details of database table columns from the object of the entity classes representing the tables in database. The pages developed by JSF technology are linked by specifying the navigation rules in the faces-config.xml file. The faces-config.xml configuration file is as shown in Figure 3.2: Figure 3.2: faces-config.xml The web tier contains another configuration file named web.xml which specifies the start page of the web application and the session timeout value. The web.xml file is as shown in Figure 3.3: 9 Figure 3.3: web.xml 3.2 Managed Bean In a web application with JSF technology, managed beans; also known as backing beans, can be associated with different web page components. Managed beans are the Java beans which contain properties and methods. The properties are associated with component values or component instances. The setter and getter methods are defined and implemented for all properties, in the form of setAbc() and getAbc() methods where Abc is the name of the property. These methods are designed to make the managed bean properties accessible by JSF page. The setter method is used to assign the value to the managed bean property and the managed bean property value can be read through getter method. The getter and setter methods are defined as shown in Figure 3.4: Figure 3.4: Getter and Setter Methods 10 The methods in the managed bean can be used for navigation or validation or performing some operation; and are associated with components in web page. To join a value of the component to the property of the bean or to call a method of the bean from component, Expression Language syntax is used. The managed bean parameters can be referred from JSF pages as shown in Figure 3.5: Figure 3.5: Managed bean parameter reference in XHTML As shown in Figure 3.5, the value entered in the text box of username is assigned to the userName property of PhotoSharingManagedBean. The managed bean methods can be invoked from the JSF page as shown in Figure 3.6: Figure 3.6: Managed bean method call in XHTML As shown in Figure 3.6, the button click event calls the CheckForLogin method of PhotoSharingManagedBean. In the managed bean method, the port corresponding to web service client is created which defines the connection point of the web service. The methods in the web service are invoked using this port. 11 3.3 Web Services The web services reside in the application tier. The web services are platform independent and language independent. The web services establish connection between client and server. JAX-WS (Java API for XML Web Services) and JAX-RS (Java API for REpresentational State Transfer Web Services) are two types of web services. JAX-RS uses RESTfulmechanism which is lightweight in nature and has ability to transmit data directly over HTTP. JAX-WS uses SOAP along with HTTP to transfer data between web service and web service client. The web services are written using WSDL (Web Services Description Language). The web service and web service client communicate with each other using SOAP messages as shown in Figure 3.7. The SOAP messages are in the form of request-response written in XML. Figure 3.7: Communication between a JAX-WS Web Service and a Client [4] In JAX-WS, the SOAP messages are passed between web service and web service client. SOAP Request is as shown in Figure 3.8: 12 Figure 3.8: SOAP Request As shown in Figure 3.8, the request for checking the login is done using XML. As shown in Figure 3.9, the response to the CheckLogin is also given in XML format. The return value is LoginSuccess which means login credentials provided in the request are correct and match each other.SOAP Response is as shown in Figure 3.9: Figure 3.9: SOAP Response Web service client is the java program that accesses methods written in the web service. The calls to the web service client are made through the port creation in managed bean which acts as a proxy to the remote service.The web service code contains @WebService annotation; the class defined below this notation represents the end point 13 of the web service. The methods in web service are written below @WebMethod annotation. The usage of these annotations is as shown in Figure 3.10: Figure 3.10: Web service annotations As shown in Figure 3.10, @EJB annotation is used to inject enterprise java beans in the web services. Just below the annotation, we can create the object of EJB class. @Stateless annotation specifies the web service session is stateless, allowing multiple users to log in concurrently. 3.4 Enterprise Java Beans Enterprise Java Bean (EJB) is the code written on server-side, which contains the business logic of the web application. The EJB tier in web application makes the client code light-weight. In the web applications with EJB tier, the web pages do not contain any business logic. The enterprise beans can be of type session bean or of type message 14 driven bean. In the session bean, messages are transferred synchronously whereas in case of message driven session bean, message passing is done in asynchronous manner. The session beans are further categorized as stateful session bean, stateless session bean and singleton session bean. In case of stateful session beans, only one instance of the bean can be created at a time, which means only one client can communicate with the server. This instance of the bean cannot be shared by any other instance of the bean class. The state of the bean is retained throughout the life of the bean. The stateless session beans allow multiple clients to access the server by creating multiple instances of bean class. The state of the bean is retained only during the execution of the method. The singleton session beans are combination of stateless and stateful session beans. The singleton session bean allows only one instance of the bean class at a time and the state of the bean is retained only during the execution of the method. The stateful session bean is defined using @Stateful annotation just before the bean class definition. In the same manner @Stateless and @Singleton annotations are used for stateless and singleton beans respectively. The enterprise bean can be kept as local or remote. The local enterprise beans are created if the client invoking the bean resides on the same machine using @LocalBean annotation. If the project is distributed and the client and the bean class reside on different machines then bean needs to be declared as remote with @Remote annotation. If the database updates are needed to be done in the enterprise bean class, the persistence context needs to be declared using @PersistenceContext annotation. The persistence context is the set of entity classes where each entity refers to exactly one 15 database table. The instance of EntityManager is created to perform the database table updates. Figure 3.11: Enterprise Java Bean code example As shown in Figure 3.11, the enterprise bean name is PhotoSharingSessionBean which is of type stateless session bean and which is invoked locally by the clients, as the bean definition starts with @LocalBean annotation. Moreover, the persistence context is referred using the persistence unit name which is present in persistence.xml. The entity manager is used for reading the information of the particular photo owner from the database table named Photos. 3.5 Entity Classes An entity class represents a database table that is, is one entity class for each database table. In this project, there are 3 database tables (userInfo, photos and sharedWith) for which there are 3 corresponding entity classes (UserInfo.java, Photos.java and 16 SharedWith.java). Each instance of entity class represents each row of the database table. The entity class instance variables can either be kept as persistent or transient. The variable in entity class is by default persistent unless it is specified as transient. In an entity class, the setter and getter methods are defined for each entity property. Inside entity class, named queries are created using @NamedQueries. The named query is created for each column in the table. Figure 3.12: Entity Class named queries example As shown in Figure 3.12, @Entity annotation is used to mark the class as an entity class. @Table annotation with name as parameter specifies the database table corresponding to the entity class. @NamedQuery is used to define a select query on each column of the table whereas @NamedQueries is the collection of such named queries.The primary key column in the table is written with the @Id annotation in the entity class. @Column annotation is used to specify the mapping between entity class property and the table column. 17 Figure 3.13: Mapping between Entity Class property and table column As shown in Figure 3.13, entity class name is SharedWith which is serialized. @Id annotation indicates that the column name shareId is the primary key column of sharedWith table. 3.6 Database Tier The database is developed in MySQL. The name of the database is PhotoSharing. There are 3 relational database tables, namely userInfo, photos and sharedWith. The userInfo table contains information about the users. The photos table contains information about the photos. The sharedWith table contains information about the sharing of the photos along with the viewing and downloading details of the photos. username column in userInfo table is the primary key which acts as the foreign key for photos and sharedWith table. The photoId column is primary key column in photos table which acts as foreign key in sharedWith table. The shareId column is primary key column in sharedWith table. 18 3.6.1 Data Dictionary The detailed description of each database table is shown in Figure 3.14, Figure 3.15 and Figure 3.16. The information about primary and foreign key columns is also listed in these figures. Figure 3.14: userInfo Table Figure 3.15: photos Table Figure 3.16: sharedWith Table 19 The Entity Relationship diagram can be seen in Figure 3.17: Figure 3.17: Entity Relationship diagram 3.7 Web pages In IShA there are different types of web pages like login page loginFail page myPhotos page friendsPhotos page upload page uploadSuccess page changeAccess page 20 changeAccessSuccess page viewedDownloadedBy page The screenshots of these web pages are shown below: Figure 3.18: Login Page Figure 3.19: Shared with, Viewed by, Downloaded by Page 21 Figure 3.20: My photos Page Figure 3.21: Friends' photos Page 22 Figure 3.22: Upload photos Page Figure 3.23: Change access Page 23 Figure 3.24: New user creation Page Figure 3.25: Login fail Page 24 Figure 3.26: Upload successful notification Page Figure 3.27: Change access success notification Page 25 3.8 Privacy Implementation Maintaining users' privacy is a key part of this project. IShA takes cares of privacy of the users' photos which is not implemented in Picasa. In IShA, users are always asked to login before viewing anyone's photos to make sure that only an authorized user is viewing the photos. After logging in, the login of the user is check against the allowed viewers' username. If the username is present in the allowed viewers' username, the user is allowed to view the photo. The allowed users' usernames are stored in the database table sharedWith in the column userName. Whenever a user uploads a photo, the user is asked to select the option of making the photo public or private. If the photo is made private, the owner is asked to select the usernames of the allowed viewers and downloaders. If the photo is made public, it is made visible to every user. After uploading the photo, an entry is made in the database table sharedWith with share id, photo id, owner's username, and usernames of the users allowed to view and download the photo. This disallows unauthorized users to view other users' private photos and privacy is preserved.The contents of the sharedWith table are as shown in Figure 3.28: Figure 3.28: Contents of sharedWith Table 26 The userName, viewedBy and downloadedBy fields were purposely designed not according to strict relational form for simplicity.The number of values in these fields are not likely to even get very big. In the case of public access, the special value “all” is entered into the fields. Whenever a user views other users' photos, the owner of the photo is notified about the viewing of the photo. The owner can at anytime see the viewing details of each owned photo. Similarly, if the photo is downloaded by any user, the owner is notified about the downloading of the photo. The owner can at anytime view the downloading details of each owned photo. This functionality always allows users to keep track of the viewers and downloaders of their photos. The owner of a photo can also change the access rights of the photo at any time. 27 Chapter 4 CONCLUDING REMARKS 4.1 Conclusions The photo sharing website IShA was successfully developed. In IShA, users can log into the application to upload photos while specifying the users allowed to view and download the photo. IShA allows users to see their own photos, friends' photos as well as the viewing and downloading details of owned photos. IShA users can change the access rights of owned photos and are also allowed to download the photos to which they have authorization. The essential security goals are successfully implemented in IShA, maintaining users' privacy by not allowing unauthorized users to view and download private photos. 4.2 Future Work The purpose of the project was to demonstrate the feasibility of achieving a stronger level of security in photo sharing applications tha exists in curret services. In order to make the IShA system adequate for general world wide web use, a few improvements would probably need to be made such as: Better tools to search for and find users/friends. The application can be extended to import photos from other websites. 28 Web pages could be designed using AJAX (Asynchronous JavaScript and XML) technology. The photo description with geographical location tagging could be implemented. 29 APPENDIX A The web pages are developed using XHTML and JSP. Example of one of the web pages is shown below: login.jsp <%-<!-@Author: Akshaya Togrikar --> --%> <%@page contentType="text/html" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <f:view> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <link href="newcss.css" rel="stylesheet" type="text/css"/> <title>Login</title> </head> <body background="images/sharing1.png"> <h:form id="loginfrm"> <table width="100%" border="10" cellpadding="0" cellspacing="0"> <tr class="head_navigation"> <td align="center" valign="top"> <table cellspacing="0" cellpadding="0" width="100%" border="0" style="background-color: #31659c"> <tr> <td valign="middle" class="pageheader">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td> </tr> <tr> <td valign="middle" class="pageheader">&nbsp; <img alt="logo" id="logo" src="images/sharing91.jpg" height="90" width="135" /> </td> <td valign="middle" class="pageheader">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td> <td valign="middle" align="right" class="pageheader">Photo Sharing System&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td> </tr> <tr> <td valign="middle" class="pageheader">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td> </tr> </table> </td> </tr> <tr> <td> <table width="30%" border="0" cellspacing="1" cellpadding="0" style=" margin-top: 120px; margin-left: 350px; BACKGROUND-COLOR: #ffffff;" > <tr> <td> <table width="100%" border="0" cellpadding="0" cellspacing="0" class="mainTable"> <tr> 30 <td class="dark_blue_header">Login </td> <td class="dark_blue_header"> </td> </tr> <tr> <td class="subtable"><b>User Name </b> </td> <td class="subtable"> <h:inputText id="username" value="#{PhotoSharingManagedBean.userName}" required="true" requiredMessage="Please enter User Name"> </h:inputText> </td> </tr> <tr> <td class="subtable"><b>Password </b> </td> <td class="subtable"> <h:inputSecret id="password" value="#{PhotoSharingManagedBean.passWord}" required="true" requiredMessage="Please Enter the passwoard" /> </td> </tr> <tr> <td class="subtable"> </td> <td class="subtable"> <h:commandButton action="#{PhotoSharingManagedBean.CheckForLogin}" value="Login" /> </td> </tr> <tr> <td class="subtable"> </td> <td class="subtable"> <a href="http://ansel.ucsd.edu:9552/PhotoSharingApp-war/faces/newUser.jsp">Create an Account</a> </td> </tr> <tr> <td class="dark_blue_header">&nbsp;</td> <td class="dark_blue_header"> </td> </tr> </table> </td> </tr> </table> </td> </tr> </table> <!--[if !fail]> <a href="/search.xhtml"></a> <![endif]--> <!--[if !pass]> <a href="/search.xhtml"></a> <![endif]--> </h:form> </f:view> </body> </html> 31 PhotoSharingManagedBaen.java /** * * @Author: Akshaya Togrikar */ package PhotoSharingApp.web; import java.io.IOException; import java.io.Serializable; import java.util.List; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.faces.event.ActionEvent; import javax.servlet.ServletContext; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import javax.xml.ws.WebServiceRef; @ManagedBean(name="PhotoSharingManagedBean") @SessionScoped public class PhotoSharingManagedBean implements Serializable{ @WebServiceRef(wsdlLocation = "WEBINF/wsdl/localhost_9552/PhotoSharingWSService/PhotoSharingWS.wsdl") private PhotoSharingWSService service; public static String uname=null; static List<PhotoSharingApp.web.Photos> result2 = null; public static List<PhotoSharingApp.web.Photos> result = null; String parm1; public String userName, passWord, photo; static String result1; String a=null, b = null; String res = null; public PhotoSharingManagedBean() { } public String CheckForLogin(){ String cal = null; System.out.println("in chk for login"); try { PhotoSharingApp.web.PhotoSharingWS port = service.getPhotoSharingWSPort(); result1 = port.checkForLogin(userName, passWord); uname=userName; System.out.println("Result1 = "+result1); if(result1.equals("pass")) { cal = "/loginPass.jsp"; getMyPhotos(); getFriendsPhotos(); } else cal ="/loginfail.xhtml"; } catch (Exception ex) { 32 } return result1; } public String getMyPhotos() { try { PhotoSharingApp.web.PhotoSharingWS port = service.getPhotoSharingWSPort(); result = port.getMyPhotos(userName); if (result!=null) a="pass"; else a = "fail"; System.out.println("Result = "+result); } catch (Exception ex) { // TODO handle custom exceptions here } return a; } public String getFriendsPhotos() { try { PhotoSharingApp.web.PhotoSharingWS port = service.getPhotoSharingWSPort(); result2 = port.getFriendsPhotos(userName); if (result2!=null) b="viewpass"; else b = "viewfail"; System.out.println("Result2 = "+result2); } catch (Exception ex) { } return b; } public void onDownload(ActionEvent event) { try { byte[] binary_data = null; String filename = "/images/baby1.jpg"; FacesContext fctx = FacesContext.getCurrentInstance(); ExternalContext ectx = fctx.getExternalContext(); HttpServletResponse response = (HttpServletResponse) ectx.getResponse(); response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\""); response.setHeader("Content-Transfer-Encoding", "Binary"); response.setHeader("Pragma", "private"); response.setHeader("cache-control", "private, must-revalidate"); 33 ServletOutputStream outs = response.getOutputStream(); outs.write(binary_data); outs.flush(); outs.close(); response.flushBuffer(); fctx.responseComplete(); } catch (IOException ex) { ex.printStackTrace(); } } public String getParm1() { return parm1; } public void setParm1(String parm1) { this.parm1 = parm1; } public String getuserName(){ return userName; } public void setuserName(String userName){ this.userName = userName; } public String getpassWord(){ return passWord; } public void setpassWord(String passWord){ this.passWord = passWord; } public void setResult(List<PhotoSharingApp.web.Photos> result){ this.result = result; } public List<PhotoSharingApp.web.Photos> getResult(){ return this.result; } public void setResult2(List<PhotoSharingApp.web.Photos> result2){ this.result2 = result2; } public List<PhotoSharingApp.web.Photos> getResult2(){ return this.result2; } public String getresult1(){ return result1; } public void setresult1(String result1){ 34 this.result1 = result1; } public static String logOut() { return "logout"; } } PhotoSharingWS.java /** * * @Author: Akshaya Togrikar */ package PhotoSharing.ws; import PhotoSharingApp.ejb.PhotoSharingSessionBean; import PhotoSharingApp.entity.Photos; import java.util.List; import javax.ejb.EJB; import javax.jws.WebService; import javax.ejb.Stateless; import javax.jws.WebMethod; import javax.jws.WebParam; @WebService() @Stateless() public class PhotoSharingWS { @EJB private PhotoSharingSessionBean ejbRef; @WebMethod(operationName = "CheckForLogin") public String CheckForLogin(@WebParam(name = "UserName") String UserName, @WebParam(name = "PassWord") String PassWord) { return ejbRef.CheckForLogin(UserName, PassWord); } @WebMethod(operationName = "GetMyPhotos") public List<Photos> GetMyPhotos(@WebParam(name = "owner") String owner) { return ejbRef.GetMyPhotos(owner); } @WebMethod(operationName = "GetFriendsPhotos") public List<Photos> GetFriendsPhotos(@WebParam(name = "userName") String userName) { return ejbRef.GetFriendsPhotos(userName); } } PhotoSharingSessionBean.java package PhotoSharingApp.ejb; 35 import PhotoSharingApp.entity.Photos; import PhotoSharingApp.entity.SharedWith; import PhotoSharingApp.entity.UserInfo; import java.util.Iterator; import java.util.List; import javax.ejb.Stateless; import javax.ejb.LocalBean; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; /** * * @Author: Akshaya Togrikar */ @Stateless @LocalBean public class PhotoSharingSessionBean { @PersistenceContext(unitName = "PhotoSharingApp-ejbPU") private EntityManager em; public String CheckForLogin(String UserName, String PassWord) { List<UserInfo> s = em.createQuery("select object(o) from UserInfo as o").getResultList(); System.out.println("Bean - username list is " + s.toString()); for (Iterator it = s.iterator(); it.hasNext();) { UserInfo elem = (UserInfo) it.next(); if (elem.getUserName().compareToIgnoreCase(UserName) == 0 && elem.getPassword().compareTo(PassWord) == 0) { return "pass"; } } return "fail"; } public List <Photos> GetMyPhotos(String owner) { List<PhotoSharingApp.entity.Photos> allPhotos = em.createNamedQuery("Photos.findByOwner").setParameter("owner", owner).getResultList(); for (Iterator it = allPhotos.iterator(); it.hasNext();) { Photos elem = (Photos) it.next(); } return allPhotos; } public List <Photos> GetFriendsPhotos(String userName) { String usr = "%"+userName+"%"; System.out.println("in bean usr="+usr); List<PhotoSharingApp.entity.Photos> allPhotos = em.createQuery("select r.photoId from SharedWith r where r.userName like :userName").setParameter("userName", usr).getResultList(); List<PhotoSharingApp.entity.SharedWith> sharedPhotos = em.createQuery("select r from SharedWith r where r.userName like :userName").setParameter("userName", usr).getResultList(); for (Iterator it = allPhotos.iterator(); it.hasNext();) { Photos elem = (Photos) it.next(); 36 String viewedBy = elem.getOwner(); System.out.println("viewers = "+viewedBy); //Date formatDate = elem.getStartDate(); //System.out.println("Result = "+ formatDate.getDate() +" "+ formatDate.getMonth() + " " + formatDate.getYear() ); } String [] temp; String usr2 = null; int i, flag=-1; for (Iterator it = sharedPhotos.iterator(); it.hasNext();) { SharedWith elem = (SharedWith) it.next(); String viewedBy = elem.getViewedBy(); System.out.println("viewers1 = "+viewedBy); temp=viewedBy.split(";"); //Date formatDate = elem.getStartDate(); //System.out.println("Result = "+ formatDate.getDate() +" "+ formatDate.getMonth() + " " + formatDate.getYear() ); if(viewedBy.equals("") || viewedBy==null) { usr2=userName+";"; elem.setViewedBy(usr2); em.merge(elem); } else { for(i=0; i<temp.length; i++) { if(temp[i].equals(userName)) { flag=1; break; } else flag=0; } } if(flag==0) { //System.out.println(temp[i]); usr2=viewedBy+userName+";"; elem.setViewedBy(usr2); em.merge(elem); } } return allPhotos; } } 37 There are 3 entity classes, UserInfo.java, Photo.java and SharedWith.java. UserInfo.java package PhotoSharingApp.entity; import java.io.Serializable; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; /** * * @author Akshaya Togrikar */ @Entity @Table(name = "userInfo") @NamedQueries({ @NamedQuery(name = "UserInfo.findAll", query = "SELECT u FROM UserInfo u"), @NamedQuery(name = "UserInfo.findByFNAme", query = "SELECT u FROM UserInfo u WHERE u.fNAme = :fNAme"), @NamedQuery(name = "UserInfo.findByLName", query = "SELECT u FROM UserInfo u WHERE u.lName = :lName"), @NamedQuery(name = "UserInfo.findBySsn", query = "SELECT u FROM UserInfo u WHERE u.ssn = :ssn"), @NamedQuery(name = "UserInfo.findByUserName", query = "SELECT u FROM UserInfo u WHERE u.userName = :userName"), @NamedQuery(name = "UserInfo.findByPassword", query = "SELECT u FROM UserInfo u WHERE u.password = :password")}) public class UserInfo implements Serializable { private static final long serialVersionUID = 1L; @Column(name = "fNAme") private String fNAme; @Column(name = "lName") private String lName; @Column(name = "ssn") private Integer ssn; @Id @Basic(optional = false) @Column(name = "userName") private String userName; @Column(name = "password") private String password; public UserInfo() { } public UserInfo(String userName) { this.userName = userName; } public String getFNAme() { return fNAme; } 38 public void setFNAme(String fNAme) { this.fNAme = fNAme; } public String getLName() { return lName; } public void setLName(String lName) { this.lName = lName; } public Integer getSsn() { return ssn; } public void setSsn(Integer ssn) { this.ssn = ssn; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public int hashCode() { int hash = 0; hash += (userName != null ? userName.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof UserInfo)) { return false; } UserInfo other = (UserInfo) object; if ((this.userName == null && other.userName != null) || (this.userName != null && !this.userName.equals(other.userName))) { return false; } return true; } 39 @Override public String toString() { return "PhotoSharingApp.entity.UserInfo[userName=" + userName + "]"; } } 40 APPENDIX B User Guide Login 1. First page of the application is login page. Enter correct username and password to proceed. 2. For new users, click on the “create new user” link on login page, enter the information required and click on submit button. After creating a new username, user can log into the system using new username and password. Navigation 1. After logging into the system, a page containing sharing, viewing and downloading details of the owner’s photos is displayed. By clicking on the different tabs, user can navigate to different views. 2. Navigation can be done to and fro between pages like my photos page, friends’ photos page, change access page, access change success page, upload photos page, upload success page. Functionality 1. Upload photos by navigating to “upload photos” page. For uploading, click on the browse button to read the photo from the local machine, select the option of “public” or “private”, in case of “private”, select the users for allowing access to this photo, from the list of users. 2. For downloading friend’s photos, click on the download button in front of the photo. 3. For viewing sharing, viewing and downloading details of owned photos, navigate to “see viewing and downloading” page. 4. For changing the access permissions of any of the owned photos, navigate to “change access” page, select the name of the photo from the list, select the usernames from the list, select the option of “allow access” or “revoke access” and then click on submit button. By default the action performed would be for allowing access. 41 REFERENCES [1] GooglePicasa, http://picasa.google.com, Accessed Oct 27 2010. [2] Flickr, http://www.flickr.com, Accessed Oct 27 2010. [3] Photobucket, http://www.photobucket.com, Accessed Oct 27 2010. [4] Chinmayee Srivathsa, Devika Gollapudi, Eric Jendrock, Ian Evans, Kim Haase, The Java EE6Tutorial, http://java.sun.com/javaee/6/docs/tutorial/doc/, Accessed Oct 30 2010. [5] JSP, http://en.wikipedia.org/wiki/JavaServerPages, Accessed Oct 27 2010.