Members.java
资源名称:WAPpush.zip [点击查看]
上传用户:weisa_1
上传日期:2007-10-14
资源大小:287k
文件大小:24k
源码类别:
手机WAP编程
开发平台:
Java
- package members;
- import push.Birthday;
- import push.PushService;
- import push.PushInitiator;
- import push.User;
- import feedback.Feedback;
- import javax.servlet.*;
- import javax.servlet.http.*;
- import java.io.*;
- import java.util.*;
- import java.sql.*;
- import java.net.InetAddress;
- import java.net.URL;
- /**
- * Members login
- *
- * @see HttpServlet
- */
- public final class Members extends HttpServlet {
- private static final String XML_VERSION = "<?xml version="1.0"?>";
- private static final String CONTENT_TYPE = "text/vnd.wap.wml";
- private static final String DOC_TYPE = "<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.1//EN"n" +
- " "http://www.wapforum.org/DTD/wml_1.1.xml">";
- private static Connection con;
- private static Statement stmt = null;
- private static String membersFile = null;
- private static final String HOME_PAGE = "/index.jsp";
- private static final String ADMIN_NAME = "admin";
- /* push initiator */
- private static PushInitiator pusher = null;
- /* push proxy gateway url */
- private static String ppgUrl = null;
- private static String authorization = null;
- /* push services */
- private static Vector pushServices = new Vector();
- private static Birthday birthdayChecker = null;
- private static PushService pushServiceServer = null;
- private static String pushSupportFile = null;
- private static String pushAddressType = null;
- /**
- * This is the initialization code that runs only once.
- * The servlet is being placed into service.
- *
- * @exception ServletException if an error occurs
- */
- public void init() throws ServletException {
- String pushServiceStr = getInitParameter("pushservices");
- StringTokenizer st = new StringTokenizer(pushServiceStr, ";");
- String[] service;
- while(st.hasMoreTokens()) {
- try {
- service = new String[2];
- service[0] = st.nextToken().trim();
- service[1] = st.nextToken().trim();
- pushServices.add(service);
- }
- catch (Exception e) {
- System.err.println(e); break;
- }
- }
- // check, if proxy is set
- boolean useProxy = new Boolean(getInitParameter("use-proxy")).booleanValue();
- if(useProxy) {
- // HTTP connections via a proxy server
- String proxyHost = getInitParameter("proxy-host");
- String proxyPort = getInitParameter("proxy-port");
- System.setProperty("http.proxySet", "true");
- System.setProperty("http.proxyHost", proxyHost);
- System.setProperty("http.proxyPort", proxyPort);
- }
- try {
- Class.forName(getInitParameter("dbdriver"));
- con = DriverManager.getConnection(getInitParameter("database"),
- getInitParameter("dbuser"), getInitParameter("dbuserpasswd"));
- stmt = con.createStatement();
- try {
- stmt.executeUpdate("CREATE TABLE IF NOT EXISTS members (name VARCHAR(10) NOT NULL, passwd VARCHAR(10), dob VARCHAR(10), sex CHAR(1), email VARCHAR(30), phone VARCHAR(15), pushservices VARCHAR(20), PRIMARY KEY (name))");
- }
- catch (SQLException e) { System.err.println(e); }
- }
- catch (Exception ex){
- ex.printStackTrace();
- }
- /* Create a push initiator, used to initiate push messages */
- ppgUrl = getInitParameter("ppg-url");
- /* Some ppgs require authorization */
- authorization = getInitParameter("authorization");
- pushSupportFile = getInitParameter("pushsupport");
- pushSupportFile = getServletContext().getRealPath(pushSupportFile);
- /* Get push address type. It is either "IPv4" (default) or "PLMN". */
- pushAddressType = getInitParameter("push-addresstype");
- if(pushAddressType == null) pushAddressType = "IPv4";
- }
- /**
- * Called by the server to allow a servlet to handle a GET request.
- *
- * @param request a <code>HttpServletRequest</code> value
- * @param response a <code>HttpServletResponse</code> value
- * @exception ServletException if an error occurs
- * @exception IOException if an error occurs
- */
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- doPost(request, response);
- }
- /**
- * Called by the server to allow a servlet to handle a POST request.
- *
- * @param request a <code>HttpServletRequest</code> value
- * @param response a <code>HttpServletResponse</code> value
- * @exception ServletException if an error occurs
- * @exception IOException if an error occurs
- */
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- HttpSession session = request.getSession();
- boolean cookiesCheck = request.getHeader("cookie") != null && request.isRequestedSessionIdValid();
- final String jsessionID = cookiesCheck ? "" : ";jsessionid=" + session.getId();
- /* Request parameter "action" has one of the following values:
- - "login"
- - "new"
- - "checkin"
- - "change"
- - "delete"
- - "view"
- - "update"
- - "insert"
- */
- String action = request.getParameter("action");
- if(action == null) action = "login"; // default action
- String name = null;
- String passwd = null;
- String dob = null;
- String sex = null;
- String email = null;
- String phone = null;
- String pushservices = null;
- if(action.equals("new") || action.equals("update") ||
- action.equals("insert") || action.equals("checkin")) {
- name = action.equals("update") ? (String)session.getAttribute("name") : request.getParameter("name");
- passwd = request.getParameter("passwd");
- dob = request.getParameter("dob");
- sex = request.getParameter("sex");
- email = request.getParameter("email");
- phone = request.getParameter("phone");
- pushservices = request.getParameter("pushservices");
- }
- else { // set values from the session attributes
- name = (String)session.getAttribute("name");
- passwd = (String)session.getAttribute("passwd");
- dob = (String)session.getAttribute("dob");
- sex = (String)session.getAttribute("sex");
- email = (String)session.getAttribute("email");
- phone = (String)session.getAttribute("phone");
- pushservices = (String)session.getAttribute("pushservices");
- }
- // check if the client device supports WAP push */
- boolean isPushSupported = pushSupported(request);
- // assing a push-info object into session information of the user */
- if(name != null) {
- if(session.getAttribute("push-info") == null && isPushSupported)
- session.setAttribute("push-info", new User(name, request.getRemoteAddr()));
- }
- if(pusher == null) {
- try {
- URL contextRoot = new URL("http://" + request.getServerName() + ":" +
- request.getServerPort() + request.getContextPath() + "/");
- pusher = new PushInitiator(new URL(contextRoot, ppgUrl), authorization);
- }
- catch (Exception e) { System.err.println(e); }
- }
- /* Create a members' birthday checker thread. A push message is sent when the birthday of a member is
- approaching */
- if(birthdayChecker == null) {
- birthdayChecker = new Birthday(pusher, "http://" + request.getServerName() + ":" +
- request.getServerPort() + request.getContextPath() + HOME_PAGE,
- pushAddressType);
- new Thread(birthdayChecker).start();
- }
- /* Create a push service server thread. The thread sends push messages to users.
- A user will receive push messages if he/she has selected any push services. */
- if(pushServiceServer == null) {
- pushServiceServer = new PushService(pusher, "http://" + request.getServerName() + ":" +
- request.getServerPort() + request.getContextPath(),
- pushAddressType, 24);
- new Thread(pushServiceServer).start();
- }
- // start generating the response ...
- response.setContentType(CONTENT_TYPE);
- // prevent caching of the response
- response.setHeader("cache-control", "no-cache");
- PrintWriter out = response.getWriter();
- out.println(XML_VERSION);
- out.println(DOC_TYPE);
- out.println("<wml>");
- out.println("<!-- provides a way back using the prev element -->n" +
- "<template>" +
- " <do type="prev">" +
- " <prev/>" +
- " </do>" +
- "</template>");
- /* Handle the "login" action */
- if(action.equals("login")) {
- if(name == null) {
- out.println("<card title="Members" id="login1">" +
- " <p>Name: <input name="name"/>" +
- "Password: <input type="password" name="passwd"/><br/>" +
- " <anchor title="Ok">Ok" +
- " <go method="post" href="" + request.getRequestURI() + jsessionID + "">" +
- " <postfield name="name" value="$(name)"/>" +
- " <postfield name="passwd" value="$(passwd)"/>" +
- " <postfield name="action" value="checkin"/>" +
- " </go>" +
- " </anchor><br/>" +
- " <anchor title="New member">New member" +
- " <go method="post" href="" + request.getRequestURI() + jsessionID + "">" +
- " <postfield name="action" value="new"/>" +
- " </go>" +
- " </anchor>" +
- " </p>" +
- " <do type="accept" label="Ok" name="1">" +
- " <go method="post" href="" + request.getRequestURI() + jsessionID + "">" +
- " <postfield name="name" value="$(name)"/>" +
- " <postfield name="passwd" value="$(passwd)"/>" +
- " <postfield name="action" value="checkin"/>" +
- " </go>" +
- " </do>" +
- " <do type="accept" label="New member" name="5">" +
- " <go method="post" href="" + request.getRequestURI() + jsessionID +"">" +
- " <postfield name="action" value="new"/>" +
- " </go>" +
- " </do>" +
- "</card>");
- }
- else { // name != null
- out.println("<card title="Members" id="login">" +
- " <p>Next weekend all members can enjoy a free snack at the Safari restaurant<br/>" +
- " <anchor title="My membership">My membership" +
- " <go href="#membership"/>" +
- " </anchor></p>" +
- "</card>");
- out.println("<card title="My membership" id="membership">" +
- " <p>Member name:  <strong>" + name + "</strong><br/>" +
- " <anchor title="View">View info" +
- " <go method="post" href="" + request.getRequestURI() + jsessionID + "">" +
- " <postfield name="action" value="view"/>" +
- " </go>" +
- " </anchor><br/>" +
- " <anchor title="Change">Edit" +
- " <go method="post" href="" + request.getRequestURI() + jsessionID + "">" +
- " <postfield name="action" value="change"/>" +
- " </go>" +
- " </anchor><br/>" +
- " <anchor title="End membership">End membership" +
- " <go method="post" href="" + request.getRequestURI() + jsessionID + "">" +
- " <postfield name="action" value="delete"/>" +
- " </go>" +
- " </anchor>" +
- " </p>" +
- " <do type="accept" label="View info" name="3">" +
- " <go method="post" href="" + request.getRequestURI() + jsessionID + "">" +
- " <postfield name="action" value="view"/>" +
- " </go>" +
- " </do>" +
- " <do type="accept" label="Edit" name="4">" +
- " <go method="post" href="" + request.getRequestURI() + jsessionID + "">" +
- " <postfield name="action" value="change"/>" +
- " </go>" +
- " </do>" +
- " <do type="accept" label="End membership" name="2">" +
- " <go method="post" href="" + request.getRequestURI() + jsessionID + "">" +
- " <postfield name="action" value="delete"/>" +
- " </go>" +
- " </do>" +
- "</card>");
- }
- }
- // View member information.
- // The "action" request parameter "action" has the value "view".
- else if(action.equals("view")) {
- out.println("<card title="View" id="view">" +
- " <p>Date of birth: " + dob + "<br/>" +
- "Sex: " + sex + "<br/>" +
- "E-Mail: " + email + "<br/>" +
- "Phone: " + phone + "<br/>");
- out.print("Push-Services: ");
- StringTokenizer st = new StringTokenizer(pushservices, ";");
- while (st.hasMoreTokens())
- out.println(((String[])pushServices.get(Integer.parseInt(st.nextToken())))[0]);
- out.println(" </p>" +
- " <do type="accept" label="Ok">" +
- " <go href="" + request.getContextPath() + HOME_PAGE + jsessionID + ""/>" +
- " </do>" +
- "</card>");
- }
- // Delete member information from the database.
- // "action" has the value "delete".
- else if(action.equals("delete")) {
- int nDeletedRows = 0;
- try {
- String sqlDeleteStmt = "DELETE FROM members WHERE name = '" + name +
- "' AND passwd = '" + passwd + "'";
- nDeletedRows = stmt.executeUpdate(sqlDeleteStmt);
- session.removeAttribute("name");
- }
- catch (SQLException E){
- E.printStackTrace();
- }
- out.println("<card id="members">n<p>" +
- ((nDeletedRows > 0) ?
- "Your (" + name + ") membership is now ended, and member information cleared from the database" :
- "Could not remove member (" + name + ")")
- +
- " <do type="accept" label="Ok">" +
- " <go href="" + request.getContextPath() + HOME_PAGE + jsessionID + ""/>" +
- " </do>" +
- "</p></card>");
- }
- /* bind the member name and other parameters (stored in database) to the current session */
- else if(action.equals("checkin")) {
- boolean access = false;
- if (name != null && passwd != null) {
- try {
- ResultSet rs = stmt.executeQuery("SELECT name, passwd, dob, sex, email, phone, pushservices FROM members");
- while (rs.next()) {
- String nameCheck = rs.getString("name");
- String passwdCheck = rs.getString("passwd");
- if (nameCheck.equals(name) && passwdCheck.equals(passwd)){
- access = true;
- setSessionInfo(session, name, passwd, rs.getString("dob"), rs.getString("sex"),
- rs.getString("email"), rs.getString("phone"),
- rs.getString("pushservices"));
- break;
- }
- }
- }
- catch (SQLException E) {
- E.printStackTrace();
- }
- }
- if (access) {
- out.println("<card id="members" title="Members" ontimer="" + request.getContextPath() +
- HOME_PAGE + jsessionID + "">");
- out.println("<timer value="30"/>" +
- "<p align="center">Welcome<br/><strong>" + name + "</strong><br/> to members' site!<br/>");
- if(isPushSupported) {
- out.println("A push message is coming...");
- /* next, send a welcome push message */
- String serviceUrl = "http://" + request.getServerName() + ":" +
- request.getServerPort() + request.getContextPath() + "/services/news.jsp";
- String message = PushInitiator.createSiMessage(serviceUrl, null, null, null,
- null, "Thank you for vising our zoo! Check the latest news and happenings");
- String address = pushAddressType.equals("IPv4") ? request.getRemoteAddr() : getPhoneNumber(name);
- try {
- pusher.sendPushMessage(address, pushAddressType, message, PushService.SI_CONTENT_TYPE);
- } catch(Exception ee) {}
- }
- out.println("</p></card>");
- }
- else {
- out.println("<card title="Name not found" id="notfound">" +
- " <p>Please check username/password.<br/>" +
- " <do type="accept" label="Ok">" +
- " <go href="" + request.getRequestURI() + jsessionID + "">" +
- " <postfield name="action" value="login"/>" +
- " </go>" +
- " </do>" +
- " <anchor title="Try again">Try again" +
- " <go href="" + request.getRequestURI() + jsessionID + "">" +
- " <postfield name="action" value="login"/>" +
- " </go>" +
- " </anchor>" +
- " </p>" +
- "</card>");
- }
- }
- /* insert a new member information into database */
- else if (action.equals("insert")) {
- boolean insertOk=false;
- boolean nameAlreadyExists=false;
- if(name != null && !name.equals("")) {
- // first, check if the name already exists!
- try {
- ResultSet rs = stmt.executeQuery("SELECT * FROM members WHERE name = '" + name + "'");
- if(!rs.next()) {
- int res = stmt.executeUpdate("INSERT INTO members VALUES ('" + name + "','" + passwd +
- "','" + dob + "','" + sex + "','" + email + "','" +
- phone + "','" + pushservices + "')");
- if(res == 1) insertOk = true;
- }
- else nameAlreadyExists=true;
- }
- catch (SQLException E){
- E.printStackTrace();
- }
- if(insertOk) setSessionInfo(session, name, passwd, dob, sex, email, phone, pushservices);
- }
- out.println("<card id="newmember" title="New member">" +
- " <p><strong>" + name + ":</strong> " +
- (insertOk ? "You are now a member of Mobile Zoo!" :
- (nameAlreadyExists ? "Username " + name + " already exists in the database. Please, select an other username" :
- "Missing information? The user information is not added to the database!?")) + "<br/>" +
- " <anchor title="Ok">Ok" +
- " <go href="" + request.getContextPath() + HOME_PAGE + jsessionID + ""/>" +
- " </anchor>" +
- " </p>" +
- " <do type="accept" label="Ok">" +
- " <go href="" + request.getContextPath() + HOME_PAGE + jsessionID + ""/>" +
- " </do>" +
- "</card>");
- }
- /* update member information */
- else if(action.equals("update")) {
- try {
- String sqlUpdateStmt = "UPDATE members SET passwd = '" + passwd + "', dob = '" + dob +
- "', sex = '" + sex + "', email = '" + email + "', phone = '" + phone +
- "', pushservices = '" + pushservices + "' WHERE name = '" + name + "'";
- stmt.executeUpdate(sqlUpdateStmt);
- }
- catch (SQLException E){
- E.printStackTrace();
- }
- setSessionInfo(session, name, passwd, dob, sex, email, phone, pushservices);
- out.println("<card id="members" title="Members">" +
- " <p align="center">Member information of  <strong>" + name + "</strong>  has been updated!<br/>" +
- " <anchor title="Ok">Ok" +
- " <go href="" + request.getContextPath() + HOME_PAGE + jsessionID +""/>" +
- " </anchor>" +
- " </p>" +
- " <do type="accept" label="Ok">" +
- " <go href="" + request.getContextPath() + HOME_PAGE + jsessionID +""/>" +
- " </do>" +
- "</card>");
- }
- /* new member login or changing information */
- else if(action.equals("new") || action.equals("change")) {
- out.println("<card title="New member" id="newmember">");
- out.print("<p>Login name: ");
- if(action.equals("change")) out.println("<em>" + name + "</em><br/>");
- else if(name != null) out.println("<input name="name" value="" + name + ""/>");
- else out.println("<input name="name"/>");
- out.println("Password: <input type="password" name="passwd"" +
- ((passwd != null) ? " value="" + passwd + """ : "") + "/>" +
- "Re-enter password: <input type="password" name="rpasswd"/>" +
- "Date of birth (yyyy.mm.dd): <input format="NNNN\.NN\.NN" name="dob"" +
- ((dob != null) ? " value="" + dob + """ : "") + "/>" +
- "E-Mail: <input name="email"" + ((email != null) ? " value="" + email + """ : "") + "/>" +
- "Phone: <input format = "*N" name="phone"" + ((phone != null) ? " value="" +
- phone + """ : "") + "/>" +
- "Sex: " +
- "<select name="sex"" + ((sex != null) ? " value="" + sex + """ : "") + ">" +
- " <option value="m">Male</option>" +
- " <option value="f">Female</option>" +
- "</select>" +
- "Push-Services: " +
- "<select name="pushservices" title="Push Services" multiple="true"" +
- ((pushservices != null) ? " value="" + pushservices + """ : "") +">");
- for (int i = 0; i < pushServices.size(); ++i){
- out.println("<option value="" + i + "">" + ((String[])pushServices.get(i))[0] + "</option>");
- }
- out.println("</select>" +
- "<anchor title="Ok">Ok" +
- " <go href="" + request.getRequestURI() + jsessionID + "">" +
- " <postfield name="name" value="$(name)"/>" +
- " <postfield name="passwd" value="$(passwd)"/>" +
- " <postfield name="rpasswd" value="$(rpasswd)"/>" +
- " <postfield name="dob" value="$(dob)"/>" +
- " <postfield name="sex" value="$(sex)"/>" +
- " <postfield name="email" value="$(email)"/>" +
- " <postfield name="phone" value="$(phone)"/>" +
- " <postfield name="pushservices" value="$(pushservices)"/>" +
- " <postfield name="action" value="" + (action.equals("new") ? "insert" : "update") + ""/>" +
- " </go>" +
- "</anchor>" +
- "</p>" +
- "<do type="accept" label="Ok" name="1">" +
- " <go href="" + request.getRequestURI() + jsessionID + "">" +
- " <postfield name="name" value="$(name)"/>" +
- " <postfield name="passwd" value="$(passwd)"/>" +
- " <postfield name="rpasswd" value="$(rpasswd)"/>" +
- " <postfield name="dob" value="$(dob)"/>" +
- " <postfield name="sex" value="$(sex)"/>" +
- " <postfield name="email" value="$(email)"/>" +
- " <postfield name="phone" value="$(phone)"/>" +
- " <postfield name="pushservices" value="$(pushservices)"/>" +
- " <postfield name="action" value="" + (action.equals("new") ? "insert" : "update") + ""/>" +
- " </go>" +
- "</do>" +
- "<do type="accept" label="Quit" name="2">" +
- " <go href="" + request.getContextPath() + HOME_PAGE + jsessionID + ""/>" +
- "</do>" +
- "</card>");
- }
- out.println("</wml>");
- }
- /**
- * <code>setSessionInfo</code> relates attributes to session
- *
- * @param s a <code>HttpSession</code> value
- * @param name a <code>String</code> value
- * @param passwd a <code>String</code> value
- * @param dob a <code>String</code> value
- * @param sex a <code>String</code> value
- * @param email a <code>String</code> value
- * @param phone a <code>String</code> value
- * @param pushservices a <code>String</code> value
- */
- private void setSessionInfo(HttpSession s, String name, String passwd, String dob, String sex,
- String email, String phone, String pushservices) {
- s.setMaxInactiveInterval(600); // 10 min
- s.setAttribute("name", name);
- s.setAttribute("passwd", passwd);
- s.setAttribute("dob", dob);
- s.setAttribute("sex", sex);
- s.setAttribute("email", email);
- s.setAttribute("phone", phone);
- s.setAttribute("pushservices", pushservices);
- }
- /**
- * Check if the client phone supports Push functionality.
- * The user-agent header information is utilised.
- *
- * @param request a <code>HttpServletRequest</code> value
- * @return a <code>boolean</code> value
- */
- private static boolean pushSupported(HttpServletRequest request) {
- String userAgent = request.getHeader("User-Agent");
- if(userAgent == null) return false;
- userAgent = userAgent.toLowerCase();
- try {
- BufferedReader reader = new BufferedReader(new FileReader(pushSupportFile));
- String line;
- while((line = reader.readLine()) != null) {
- line = line.trim().toLowerCase();
- if(line.equals("")) break;
- if(userAgent.startsWith(line)) return true;
- }
- }
- catch (java.io.IOException e) {
- System.err.println(e);
- }
- return false;
- }
- /**
- * Finds the user's phone number from the database
- *
- * @param user a <code>String</code> value
- * @return a <code>String</code> value
- */
- public static String getPhoneNumber(String user) {
- try {
- ResultSet rs = stmt.executeQuery("SELECT phone FROM members WHERE name = '" + user + "'");
- return rs.next() ? rs.getString("phone") : null;
- }
- catch (SQLException e) { System.err.println(e); }
- return null;
- }
- /**
- * <code>getInitiator</code> returns the instance of the default push initiator.
- *
- * @return a <code>PushInitiator</code> value
- */
- public static PushInitiator getInitiator() { return pusher; }
- /**
- * <code>getPushService</code>
- *
- * @param id an <code>int</code> value
- * @return an <code>Object</code> value
- */
- public static Object getPushService(int id) { return pushServices.get(id); }
- /**
- * <code>getStatement</code>
- *
- * @return a <code>Statement</code> value
- */
- public static Statement getStatement() { return stmt; }
- /**
- * Returns the push address type (IPv4 or PLMN) to be used
- *
- * @return a <code>String</code> value
- */
- public static String getPushAddressType() { return pushAddressType; }
- }