/** * closes all files * * @author [email protected] * @date Thu Dec 1 22:00:05 2011 */ void closeFiles() { try { m_wrMkdirs.close(); m_wrChmods.close(); } catch (Exception e) { System.err.println("ERROR: failed to close files: " + e.toString()); } }
// Generate files for given node // Given Hashtable mapping node_name to Vector of cluster names // <Node>.ini File format: // [ Clusters ] // cluster = <clustername> // ... private void dumpNodeInfo(Hashtable all_nodes, String path) throws IOException { PrintWriter node_file; // Iterate over hashtable of nodes and write <Node>.ini file for each for (Enumeration e = all_nodes.keys(); e.hasMoreElements(); ) { String node_name = (String) (e.nextElement()); try { if (path != null) { node_file = createPrintWriter(path + File.separator + node_name + ".ini"); } else { node_file = createPrintWriter(node_name + ".ini"); } node_file.println("[ Clusters ]"); Vector clusters = (Vector) all_nodes.get(node_name); for (Enumeration c = clusters.elements(); c.hasMoreElements(); ) { String cluster_name = (String) (c.nextElement()); node_file.println("cluster = " + cluster_name); } node_file.close(); } catch (IOException exc) { System.out.println("IOException: " + exc); System.exit(-1); } } }
// Write <Cluster>.ini file // Given Hashtable mapping cluster name to Vector of plugin names // <Cluster>.ini File format: // [ Cluster ] // uic = <Agentname> // cloned = false // [ Plugins ] // plugin = <pluginname> // ... // private void dumpClusterInfo(Hashtable all_clusters, String path) throws IOException { // Dump hashtable of clusters for (Enumeration e = all_clusters.keys(); e.hasMoreElements(); ) { String cluster_name = (String) e.nextElement(); PrintWriter cluster_file; try { if (path != null) { cluster_file = createPrintWriter(path + File.separator + cluster_name + ".ini"); } else { cluster_file = createPrintWriter(cluster_name + ".ini"); } cluster_file.println("[ Cluster ]"); cluster_file.println("uic = " + cluster_name); cluster_file.println("cloned = false\n"); cluster_file.println("[ Plugins ]"); Vector plugins = (Vector) (all_clusters.get(cluster_name)); for (Enumeration p = plugins.elements(); p.hasMoreElements(); ) { String plugin = (String) (p.nextElement()); cluster_file.println("plugin = " + plugin); } cluster_file.close(); } catch (IOException exc) { System.out.println("IOException: " + exc); System.exit(-1); } } }
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { res.setContentType("text/html"); try { PrintWriter pw = res.getWriter(); pw.println("<html><head><TITLE>Web-Enabled Automated Manufacturing System</TITLE></head>"); pw.println( "<body><br><br><br><form name=modifyuser method=post action='http://peers:8080/servlet/showUser')"); v = U.allUsers(); pw.println("<table align='center' border=0> <tr><td>"); pw.println( "Select User Name To Modify</td><td><SELECT id=select1 name=uid style='HEIGHT: 22px; LEFT: 74px; TOP: 222px; WIDTH: 155px'>"); pw.println("<OPTION selected value=''></OPTION>"); for (i = 0; i < v.size(); i++) pw.println( "<OPTION value=" + (String) v.elementAt(i) + ">" + (String) v.elementAt(i) + "</OPTION>"); pw.println( "</SELECT></td></tr><tr><td></td><td><input type='submit' name='submit' value='Submit'></td></tr></table></form></body></html>"); pw.flush(); pw.close(); } catch (Exception e) { } }
public static void main(String args[]) { wmatrix wmatrix = new wmatrix(); wmatrix.start(); try { PrintWriter profilefout = new PrintWriter( new BufferedWriter( new FileWriter( "profile_" + Data.kinease + "_" + Data.code + "_" + Data.windows_size + ".csv"))); profilefout.print("Position="); for (int j = 0; j < Data.windows_size; j++) { profilefout.print("," + (j - Data.windows_size / 2)); } profilefout.println(); for (int i = 0; i < 20; i++) { for (int j = 0; j < Data.windows_size; j++) { profilefout.print("," + wm[i][j]); } profilefout.println(); } profilefout.close(); } catch (IOException ex) { } }
/** * Utility method that returns a string which contains the stack trace of the given Exception * object. */ public static String getStacktraceFromException(Throwable e) { ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); PrintWriter writer = new PrintWriter(byteOut); e.printStackTrace(writer); writer.close(); String message = new String(byteOut.toByteArray()); return message; }
static void transCommit() { if (outputFiles == false) { try { conn.commit(); } catch (SQLException se) { System.out.println(se.getMessage()); transRollback(); } } else { out.close(); } }
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { Class.forName("com.mysql.jdbc.Driver").newInstance(); Connection con = DriverManager.getConnection(Utility.connection, Utility.username, Utility.password); String email = request.getParameter("email_id"); String number = ""; boolean exists = false; String user_name = ""; int user_id = -1; String str1 = "SELECT USER_ID,NAME,PHONE_NUMBER FROM USERS WHERE EMAIL_ID=?"; PreparedStatement prep1 = con.prepareStatement(str1); prep1.setString(1, email); ResultSet rs1 = prep1.executeQuery(); if (rs1.next()) { exists = true; user_id = rs1.getInt("USER_ID"); user_name = rs1.getString("NAME"); number = rs1.getString("PHONE_NUMBER"); } int verification = 0; JSONObject data = new JSONObject(); if (exists) { verification = (int) (Math.random() * 9535641 % 999999); System.out.println("Number " + number + "\nVerification: " + verification); SMSProvider.sendSMS( number, "Your One Time Verification Code for PeopleConnect Is " + verification); } data.put("user_name", user_name); data.put("user_id", user_id); data.put("verification_code", "" + verification); data.put("phone_number", number); String toSend = data.toJSONString(); out.print(toSend); System.out.println(toSend); } catch (Exception e) { e.printStackTrace(); } finally { out.close(); } }
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter toClient = res.getWriter(); toClient.println("<!DOCTYPE HTML>"); toClient.println("<html>"); toClient.println("<head><title>Books</title></head>"); toClient.println("<body>"); toClient.println("<a href=\"index.html\">Home</A>"); toClient.println("<h2>List of books</h2>"); HttpSession session = req.getSession(false); if (session != null) { String name = (String) session.getAttribute("name"); if (name != null) { toClient.println("<h2>name: " + name + "</h2>"); } } toClient.print("<form action=\"bookOpinion\" method=GET>"); toClient.println("<table border='1'>"); String sql = "Select code, title, author FROM books"; System.out.println(sql); try { Statement statement = connection.createStatement(); ResultSet result = statement.executeQuery(sql); while (result.next()) { toClient.println("<tr>"); String codeStr = result.getString("code"); toClient.println( "<td><input type=\"radio\" name=\"book" + "\" value=\"" + codeStr + "\"></td>"); toClient.println("<td>" + codeStr + "</td>"); toClient.println("<td>" + result.getString("title") + "</td>"); toClient.println("<td>" + result.getString("author") + "</td>"); toClient.println("</tr>"); } } catch (SQLException e) { e.printStackTrace(); System.out.println("Resulset: " + sql + " Exception: " + e); } toClient.println("</table>"); toClient.println("<textarea rows=\"8\" cols=\"60\" name=\"comment\"></textarea><BR>"); toClient.println("<input type=submit>"); toClient.println("</form>"); toClient.println("</body>"); toClient.println("</html>"); toClient.close(); }
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { Class.forName("com.mysql.jdbc.Driver").newInstance(); Connection con = DriverManager.getConnection(Utility.connection, Utility.username, Utility.password); int user_id = Integer.parseInt(request.getParameter("user_id")); int question_id = Integer.parseInt(request.getParameter("question_id")); int option = Integer.parseInt(request.getParameter("option")); System.out.println("uid: " + user_id + "\nquestion: " + question_id + "\noption: " + option); String str1 = "INSERT INTO VOTES(USER_ID, QUESTION_ID,OPTION_VOTED) VALUES (?,?,?)"; PreparedStatement prep1 = con.prepareStatement(str1); prep1.setInt(1, user_id); prep1.setInt(3, option); prep1.setInt(2, question_id); prep1.execute(); String str2 = "SELECT OPTION_" + option + " FROM ARCHIVE_VOTES WHERE QUESTION_ID=?"; PreparedStatement prep2 = con.prepareStatement(str2); prep2.setInt(1, question_id); int count = 0; ResultSet rs2 = prep2.executeQuery(); if (rs2.next()) { count = rs2.getInt("OPTION_" + option); } count++; String str3 = "UPDATE ARCHIVE_VOTES SET OPTION_" + option + "=? WHERE QUESTION_ID=?"; PreparedStatement prep3 = con.prepareStatement(str3); prep3.setInt(1, count); prep3.setInt(2, question_id); prep3.executeUpdate(); out.print("You Vote has been recorded! Thank you!"); System.out.println( "Voted for question " + question_id + ", by user " + user_id + ", for option " + option); } catch (Exception e) { e.printStackTrace(); } finally { out.close(); } }
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); String support = "support"; // valid username HttpSession session = null; session = req.getSession(false); // Get user's session object (no new one) if (session == null) { invalidUser(out); // Intruder - reject return; } String userName = (String) session.getAttribute("user"); // get username if (!userName.equals(support)) { invalidUser(out); // Intruder - reject return; } out.println("<HTML><HEAD><TITLE>Database Upgrade</TITLE></HEAD>"); out.println("<BODY><CENTER>"); out.println( "<BR><BR><H3>This job will check all clubs' session logs for caller=clubster.</H3>"); out.println("<BR><BR>Click 'Continue' to start the job."); out.println("<BR><BR> <A HREF=\"/v5/servlet/Support_main\">Return</A><BR><BR>"); out.println( "<form method=post><input type=submit value=\"Continue\" onclick=\"return confirm('Are you sure?')\">"); out.println(" <input type=hidden value=\"update\" name=\"todo\"></form>"); /* out.println("<form method=post><input type=submit value=\" Test \">"); out.println(" <input type=hidden value=\"test\" name=\"todo\"></form>"); * */ out.println("</CENTER></BODY></HTML>"); out.close(); }
public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { res.setContentType("text/html"); PrintWriter pw = res.getWriter(); PR.deleteProduct(req.getParameter("prid")); pw.println("<html><head><TITLE>Web-Enabled Automated Manufacturing System</TITLE></head>"); pw.println("<table align='center' border=0>"); pw.println("<tr col span=2><th>Web-Enabled Automated Manufacturing Process</th></tr>"); pw.println("<tr><td>Product ID:</td><td>" + req.getParameter("prid") + "</td></tr>"); pw.println("<tr><td>Product data is deleted Click on OK to Continue</td></tr>"); pw.println( "<tr><td align=center><a href='http://peers:8080/servlet/deleteProduct' target='main'>OK</a></td>"); pw.println("<td></td></tr>"); pw.println("</table></form></body></html>"); pw.flush(); pw.close(); }
public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { res.setContentType("text/html"); hs = req.getSession(true); PrintWriter pw = res.getWriter(); uid = req.getParameter("did"); if (!uid.equals("")) { v = D.getDealer(uid); pw.println( "<html><head><TITLE>Web-Enabled Automated Manufacturing System</TITLE><script language=javascript>function set() {"); pw.println( "document.deldealer.select1.value='" + (String) v.elementAt(4) + "'} </script></head><P align=center><FONT color=deepskyblue size=4><STRONG>MODIFY DEALER </STRONG></FONT></P> "); pw.println( "<body onLoad=set()><br><br><form name=deldealer method=post action='http://peers:8080/servlet/DelDealer'>"); pw.println( "<center><TABLE border=0 cellPadding=1 cellSpacing=1 width='75%' style='HEIGHT: 147px; WIDTH: 248px'>"); pw.println( "<TR><TD>DealerId </TD><TD><INPUT id=text1 name=did value=" + (String) v.elementAt(0) + "></TD></TR>"); pw.println( "<TR><TD>DealerName</TD><TD><INPUT id=text2 name=dname value=" + (String) v.elementAt(1) + " ></TD></TR><TR><TD>DealerAddress</TD>"); pw.println( "<TD><INPUT id=text2 type=text name=daddr value=" + (String) v.elementAt(2) + "></TD></TR><TR><TD>CreditLimit</TD><TD><INPUT id=text4 name=cl value=" + v.get(3).toString()); pw.println( "></TD></TR><TR><TD><P>Staus</P></TD><td><SELECT id=select1 name=status style='HEIGHT: 22px; LEFT: 1px; TOP: 1px; WIDTH: 136px'> <OPTION "); pw.println( "selected value=''></OPTION><OPTION value=Active>Active</OPTION><OPTION value=Inactive>Inactive</OPTION></SELECT><INPUT id=submit1 name=submit1 style='LEFT: 151px; TOP: 318px' type=submit value=Delete></TD></TR>"); pw.println("</table></center></form></body></html>"); pw.flush(); pw.close(); } }
// Print <Cluster>-prototype-ini.dat file // File format: // [Prototype] CombatOrganization|CivilanOrganization // [UniqueId] "UTC/CombatOrg" // [UIC] "UIC/<OrganizationName> // [Relationship] // Superior <Superior> "" // Support <Supported> <Role> // [TypeIdentificationPG] // TypeIdentification String "UTC/RTOrg" // Nomenclature String <Nomenclature> // AlternateTypeIdentification String "SRC/<SRC>" // [ClusterPG] // MessageAddress String <OrganizationName> // [OrganizationPG] // Roles Collection<Role> <Role> // [MilitaryOrgPG] // UIC String <UIC> // Echelon String <Echelon> // UTC String <UTC> // SRC String <SRC> // private void dumpOrganizationInfo(Hashtable all_organizations, String path) throws IOException { Hashtable supportedOrgRoles = null; for (Enumeration e = all_organizations.keys(); e.hasMoreElements(); ) { supportedOrgRoles = new Hashtable(); String org_name = (String) e.nextElement(); OrganizationData org_data = (OrganizationData) all_organizations.get(org_name); PrintWriter org_file; try { if (path != null) { org_file = createPrintWriter(path + File.separator + org_name + "-prototype-ini.dat"); } else { org_file = createPrintWriter(org_name + "-prototype-ini.dat"); } org_file.println( "[Prototype] " + (org_data.isCivilan() ? "CivilianOrganization" : "MilitaryOrganization")); org_file.println("\n[UniqueId] " + '"' + "UTC/CombatOrg" + '"'); org_file.println("\n[UIC] " + '"' + "UIC/" + org_name + '"'); // Write out Superior/Support Relationships org_file.println("\n[Relationship]"); if (org_data.mySuperior != null) { org_file.println("Superior " + '"' + org_data.mySuperior + '"' + " " + '"' + '"'); } for (Enumeration rels = org_data.mySupportRelations.elements(); rels.hasMoreElements(); ) { SupportRelation suprel = (SupportRelation) rels.nextElement(); if (!supportedOrgRoles.containsKey(suprel.mySupportedOrganization)) { supportedOrgRoles.put(suprel.mySupportedOrganization, suprel.myRole); } else { String role = (String) supportedOrgRoles.get(suprel.mySupportedOrganization); role = role + ", " + suprel.myRole; supportedOrgRoles.put(suprel.mySupportedOrganization, role); } } for (Enumeration roles = supportedOrgRoles.keys(); roles.hasMoreElements(); ) { String supportedOrg = (String) roles.nextElement(); String role = (String) supportedOrgRoles.get(supportedOrg); org_file.println("Supporting " + '"' + supportedOrg + '"' + " " + '"' + role + '"'); } // Print TypeIdentificationPG fields org_file.println("\n[TypeIdentificationPG]"); org_file.println("TypeIdentification String " + '"' + "UTC/RTOrg" + '"'); org_file.println("Nomenclature String " + '"' + org_data.myNomenclature + '"'); org_file.println( "AlternateTypeIdentification String " + '"' + "SRC/" + org_data.mySRC + '"'); // Print ClusterPG info org_file.println("\n[ClusterPG]"); org_file.println("MessageAddress String " + '"' + org_name + '"'); // Print OrganizationPG (Roles) info org_file.println("\n[OrganizationPG]"); org_file.print("Roles Collection<Role> " + '"'); boolean is_first = true; for (Enumeration roles = org_data.myRoles.elements(); roles.hasMoreElements(); ) { String role = (String) roles.nextElement(); if (!is_first) { org_file.print(", "); } org_file.print(role); is_first = false; } org_file.println('"'); // Print MilitaryOrgPG info org_file.println("\n[MilitaryOrgPG]"); org_file.println("UIC String " + '"' + org_data.myUIC + '"'); if (org_data.myEchelon.intValue() != -1) { org_file.println("Echelon String " + '"' + org_data.myEchelon.intValue() + '"'); } else { org_file.println("Echelon String " + '"' + '"'); } org_file.println("UTC String " + '"' + org_data.myUTC + '"'); org_file.println("SRC String " + '"' + org_data.mySRC + '"'); if (org_data.myIsReserve == true) { org_file.println("IsReserve boolean true"); } else { org_file.println("IsReserve boolean false"); } // Print HomeLocationPG info under Military Org PG org_file.println( "HomeLocation GeolocLocation " + "\"GeolocCode=" + org_data.myHomeGeoLoc + ", InstallationTypeCode=" + org_data.myHomeInstallCode + ", CountryStateCode=" + org_data.myHomeCSCode + ", CountryStateName=" + org_data.myHomeCSName + ", IcaoCode=" + org_data.myHomeICAOCode + ", Name=" + org_data.myHomeLocation + ", Latitude=Latitude " + org_data.myHomeLatitude + "degrees, Longitude=Longitude " + org_data.myHomeLongitude + "degrees\""); /* // Print AssignmentPG info org_file.println("\n[AssignmentPG]"); org_file.println("GeolocCode String "+'"'+org_data.myAssignedGeoLoc+'"'); org_file.println("InstallationTypeCode String "+'"'+org_data.myAssignedInstallCode+'"'); org_file.println("CountryStateCode String "+'"'+org_data.myAssignedCSCode+'"'); org_file.println("CountryStateName String "+'"'+org_data.myAssignedCSName+'"'); org_file.println("IcaoCode String "+'"'+org_data.myAssignedICAOCode+'"'); */ // Print CSSCapabilities info if (org_data.myCSSCapabilities != null) { is_first = true; org_file.println("\n[CSSCapabilityPG]"); org_file.print("Capabilities Collection<CSSCapability> " + '"'); for (Enumeration eCap = org_data.myCSSCapabilities.elements(); eCap.hasMoreElements(); ) { CSSCapabilities cssCap = (CSSCapabilities) eCap.nextElement(); if (!is_first) { org_file.print(", "); } org_file.print(cssCap.capability); org_file.print(" " + cssCap.qty); if (!cssCap.period.equals("")) { org_file.print(" Duration=" + cssCap.period); } is_first = false; } org_file.println('"'); } org_file.close(); } catch (IOException exc) { System.out.println("IOException: " + exc); System.exit(-1); } } }
/** * Add a quiz to a course if not already so. Also write the menu file for the course. Throws * InvalidDBRequestException if quiz already in the course, error occured during insertion, or * other exception occured. Throws FileFailureException if fail to append quiz to the menu. * * @param quizname the quiz name * @param courseID the course id (course number + instructor name) * @throws InvalidDBRequestException */ public void addQuiz(String quizName, String courseID) throws InvalidDBRequestException, FileFailureException { try { Class.forName(GaigsServer.DBDRIVER); db = DriverManager.getConnection(GaigsServer.DBURL, GaigsServer.DBLOGIN, GaigsServer.DBPASSWD); Statement stmt = db.createStatement(); Statement cstmt = db.createStatement(); ResultSet rs, courseRS; int count = 0; // get quiz info courseRS = cstmt.executeQuery( "select menu_text, script_type, visual_type from test where name = '" + quizName + "'"); // check if quiz in the database if (!courseRS.next()) throw new InvalidDBRequestException("Quiz is not registered in the database"); else { // check if quiz already in the course rs = stmt.executeQuery( "select test_name from courseTest where test_name = '" + quizName + "' and course_id = '" + courseID + "'"); if (rs.next()) throw new InvalidDBRequestException("Quiz is already added for the course"); else { count = stmt.executeUpdate( "insert into courseTest (course_id, test_name) values ('" + courseID + "', '" + quizName + "')"); if (count != 1) throw new InvalidDBRequestException("Error occured during insertion"); else { // append quiz info to the course menu try { PrintWriter fileOStream = new PrintWriter( new FileOutputStream("./html_root/cat/" + courseID + ".list", true)); if (debug) System.out.println( courseRS.getString(1).trim() + "\n" + quizName + " " + courseRS.getString(2).trim() + " " + courseRS.getString(3).trim().toLowerCase() + "\n****\n"); fileOStream.print( courseRS.getString(1).trim() + "\n" + quizName + " " + courseRS.getString(2).trim() + " " + courseRS.getString(3).trim().toLowerCase() + "\n****\n"); fileOStream.flush(); fileOStream.close(); } catch (Exception e) { System.err.println("Error in creating the menu: " + e.getMessage()); throw new FileFailureException("Error in creating the menu: " + e.getMessage()); } } } } courseRS.close(); rs.close(); stmt.close(); cstmt.close(); db.close(); } catch (SQLException e) { System.err.println("Invalid SQL in addQuiz: " + e.getMessage()); throw new InvalidDBRequestException("??? "); } catch (ClassNotFoundException e) { System.err.println("Driver Not Loaded"); throw new InvalidDBRequestException("Internal Server Error"); } }
private void doUpdate(PrintWriter out) { Connection con1 = null; // init DB objects Connection con2 = null; PreparedStatement pstmt = null; Statement stmt1 = null; Statement stmt1a = null; Statement stmt2 = null; Statement stmt3 = null; ResultSet rs1 = null; ResultSet rs2 = null; ResultSet rs3 = null; out.println("<HTML><HEAD><TITLE>Database Query</TITLE></HEAD>"); out.println("<BODY><H3>Starting Job to Check for Clubster Users</H3>"); out.flush(); String club = ""; String name = ""; try { con1 = dbConn.Connect(rev); } catch (Exception exc) { // Error connecting to db.... out.println("<BR><BR>Unable to connect to the DB."); out.println("<BR>Exception: " + exc.getMessage()); out.println("<BR><BR> <A HREF=\"/v5/servlet/Support_main\">Return</A>."); out.println("</BODY></HTML>"); return; } // // Get the club names from the 'clubs' table // // Process each club in the table // int x1 = 0; int x2 = 0; int i = 0; boolean skip = true; try { stmt1 = con1.createStatement(); rs1 = stmt1.executeQuery("SELECT clubname, fullname FROM clubs ORDER BY clubname"); while (rs1.next()) { x1++; club = rs1.getString(1); // get a club name name = rs1.getString(2); // get full club name con2 = dbConn.Connect(club); // get a connection to this club's db stmt2 = con2.createStatement(); rs2 = stmt2.executeQuery("SELECT date FROM sessionlog WHERE msg LIKE '%clubster'"); if (rs2.next()) { out.println("<br><br>"); out.print("Club found: " + club + ", " + name); } stmt2.close(); con2.close(); } stmt1.close(); con1.close(); } catch (Exception e) { // Error connecting to db.... out.println("<BR><BR><H3>Fatal Error!</H3>"); out.println("Error performing update to club '" + club + "'."); out.println("<BR>Exception: " + e.getMessage()); out.println("<BR>Message: " + e.toString()); out.println("<BR><BR> <A HREF=\"/v5/servlet/Support_main\">Return</A>."); out.println("</BODY></HTML>"); out.close(); Connect.close(stmt2, con2); Connect.close(stmt1, con1); return; } Connect.close(stmt2, con2); Connect.close(stmt1, con1); out.print("<BR><BR>Done, " + x1 + "clubs checked."); out.println("<BR><BR> <A HREF=\"/v5/servlet/Support_main\">Return</A>"); out.println("</CENTER></BODY></HTML>"); // out.flush(); // out.close(); }
// ***************************************************** // Process the initial request from Proshop_main // ***************************************************** // public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // // Prevent caching so sessions are not mangled // resp.setHeader("Pragma", "no-cache"); // for HTTP 1.0 resp.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); // for HTTP 1.1 resp.setDateHeader("Expires", 0); // prevents caching at the proxy server resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); HttpSession session = SystemUtils.verifyHotel(req, out); // check for intruder if (session == null) { return; } String club = (String) session.getAttribute("club"); // get club name String user = (String) session.getAttribute("user"); if (req.getParameter("clubswitch") != null && req.getParameter("clubswitch").equals("1") && req.getParameter("club") != null) { // // Request is to switch clubs - switch the db (TPC or Demo sites) // String newClub = req.getParameter("club"); Connection con = null; // // release the old connection // ConnHolder holder = (ConnHolder) session.getAttribute("connect"); if (holder != null) { con = holder.getConn(); // get the connection for previous club } if (con != null) { /* // abandon any unfinished transactions try { con.rollback(); } catch (Exception ignore) {} */ // close/release the connection try { con.close(); } catch (Exception ignore) { } } // // Connect to the new club // try { con = dbConn.Connect(newClub); // get connection to this club's db } catch (Exception ignore) { } holder = new ConnHolder(con); session.setAttribute("club", newClub); session.setAttribute("connect", holder); out.println("<HTML><HEAD><Title>Switching Sites</Title>"); out.println("<meta http-equiv=\"Refresh\" content=\"0; url=/" + rev + "/hotel_home.htm\">"); out.println("</HEAD>"); out.println("<BODY><CENTER><BR>"); out.println("<BR><H2>Switching Sites</H2><BR>"); out.println("<a href=\"/" + rev + "/hotel_home.htm\" target=_top>Continue</a><br>"); out.println("</CENTER></BODY></HTML>"); out.close(); return; } // // Call is to display the Home page. // out.println("<html><head>"); out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=windows-1252\">"); out.println("<meta http-equiv=\"Content-Language\" content=\"en-us\">"); out.println("<title> \"ForeTees Hotel Home Page\"</title>"); out.println( "<script language=\"JavaScript\" src=\"/" + rev + "/web utilities/foretees.js\"></script>"); out.println( "<style type=\"text/css\"> body {text-align: center} </style>"); // so body will align on // center out.println("</head>"); out.println("<body bgcolor=\"#CCCCAA\" text=\"#000000\">"); out.println("<div style=\"align:center; margin:0px auto;\">"); if (club.startsWith("tpc") && user.startsWith("passport")) { // if TPC Passport user out.println("<br><H3>Welcome to ForeTees</H3><br>"); String clubname = ""; String fullname = ""; Connection con = null; try { con = dbConn.Connect(rev); // get connection to the Vx db // // Get the club names for each TPC club // PreparedStatement pstmt = con.prepareStatement("SELECT fullname FROM clubs WHERE clubname=?"); pstmt.clearParameters(); pstmt.setString(1, club); ResultSet rs = pstmt.executeQuery(); if (rs.next()) { fullname = rs.getString("fullname"); // get the club's full name } out.println("<p>You are currently connected to: <b>" + fullname + "</b><br><br>"); out.println("To continue with this site, simply use the navigation menus above.<br><br>"); out.println("To switch sites, click on the desired club name below.</p><br>"); // // Get the club names for each TPC club // pstmt = con.prepareStatement( "SELECT clubname, fullname FROM clubs WHERE inactive=0 AND clubname LIKE 'tpc%' ORDER BY fullname"); pstmt.clearParameters(); rs = pstmt.executeQuery(); while (rs.next()) { clubname = rs.getString("clubname"); // get a club name if (clubname.startsWith("tpc")) { fullname = rs.getString("fullname"); // get the club's full name out.println( "<a href=\"Hotel_home?clubswitch=1&club=" + clubname + "\" target=_top>" + fullname + "</a><br>"); } } pstmt.close(); } catch (Exception e) { // Error connecting to db.... out.println( "<BR><BR>Sorry, we encountered an error while trying to connect to the database."); // out.println("<br><br>Error: " + e.toString() + "<br>"); out.println("<BR><BR> <A HREF=\"Hotel_home\">Return</A>."); out.println("</BODY></HTML>"); return; } } else { out.println( "<BR><BR> You have entered here by mistake. Please contact ForeTees Support at 651-765-6006."); out.println("</BODY></HTML>"); } out.println("</div></BODY></HTML>"); } // end of doGet
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { out.println("<html>"); out.println("<head>"); out.println("<title>Please wait while we authenticate your credentials...</title>"); out.println("</head>"); out.println("<body>"); out.println("<h3>Please wait... </h3>"); out.println("</body>"); out.println("</html>"); // Thread.sleep(6000); // out.println("" // + "<script type=\"text/javascript\">" // + "document.body.innerHTML = '';" // + "</script>"); String Username = ""; String Password = ""; Username = request.getParameter("Username"); Password = request.getParameter("Password"); Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager.getConnection(dbUrl, "", ""); Statement stmt = con.createStatement(); query = "select UserId, Username, Password from Login_Credentials where Username='******'"; ResultSet rs = stmt.executeQuery(query); boolean UserAuth = false; if (rs.next()) { DBUserId = rs.getInt("UserId"); DBUser = rs.getString("Username"); DBPass = rs.getString("Password"); UserAuth = DBUser.contains(Username); // .equals(Username); } if (UserAuth) { authenticatorFlag = LOGIN_WRONGPASSWORD; if (DBPass.contains(Password)) // && authenticatorFlag!=LOGIN_UNKNOWNUSERNAME) { // out.println("<br>Comparing <b>"+Password+"</b> to DB value : <b>"+DBPass+"</b>" // + "<br>Password.compareTo(DBPass) returned : // "+Password.compareTo(DBPass)+"<br><br>"); authenticatorFlag = LOGIN_SUCCESS; } } else { authenticatorFlag = LOGIN_UNKNOWNUSERNAME; } if ("".equals(Password) || Password == null) { authenticatorFlag = LOGIN_WRONGPASSWORD; } if ("".equals(Username) || Username == null) { authenticatorFlag = LOGIN_UNKNOWNUSERNAME; } con.close(); // stmt.close(); // rs.close(); // Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // out.println("The user id obtained from the database is : "+DBUserId+"<br><br>"); Connection con2 = DriverManager.getConnection(dbUrl, "", ""); Statement stmt2 = con2.createStatement(); adminSelectQuery = "select UserId from Administrator_List"; // where UserId="+DBUserId; ResultSet rs1 = stmt2.executeQuery(adminSelectQuery); int userID = 0; // int dbID=Integer.parseInt(DBUserId) while (rs1.next()) { userID = rs1.getInt("UserId"); // out.println(userID+"<br>"); if (userID == DBUserId) { // out.println(userID+" == "+DBUserId); userTypeFlag = ADMIN_USER; break; } else { userTypeFlag = NORMAL_USER; } } /* if(userTypeFlag==ADMIN_USER) { out.println("Admin list user identified...<br>User ID : "+DBUserId); } else { out.println("Normal User Identified...<br>User ID : "+DBUserId); } */ if (authenticatorFlag == LOGIN_SUCCESS) { HttpSession newUserSession = request.getSession(true); newUserSession.setMaxInactiveInterval(1800); newUserSession.setAttribute("Username", Username); newUserSession.setAttribute("UserId", DBUserId); if (userTypeFlag == ADMIN_USER) { newUserSession.setAttribute("Privilage", "adminUser"); } else if (userTypeFlag == NORMAL_USER) { newUserSession.setAttribute("Privilage", "normalUser"); } response.sendRedirect("home.jsp"); } else if (authenticatorFlag == LOGIN_WRONGPASSWORD) { out.println( "Please check the password you have entered and try again...<br>"); // entered password: // "+Password+"<br>DB password: "******"<br><a href=\"index.html\">Click here to try again</a>"); } else if (authenticatorFlag == LOGIN_UNKNOWNUSERNAME) { out.println( "The username you have entered" // + " "+Username+" >> "+DBUser+" >> "+UserAuth + " does not exist in our database..."); out.println( "<br><a href=\"index.html\">Click here to try again</a> ... OR ... " + "<a href=\"register.jsp\">Click here to register</a>"); } } catch (Exception e) { out.println( "<br><br><br>It seems we have some error in our login mechanism...<br>Don't worry, we'll get" + "it fixed up pretty soon..." + "<br><br>Here's a bit of technical stuff for debugging : <br><br>"); e.printStackTrace(out); } finally { out.close(); } }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); ResultSet rs = null; try { // SET UP Context environment, to look for Data Pooling Resource Context initCtx = new InitialContext(); Context envCtx = (Context) initCtx.lookup("java:comp/env"); DataSource ds = (DataSource) envCtx.lookup("jdbc/TestDB"); Connection dbcon = ds.getConnection(); // ########### SEARCH INPUT PARAMETERS, EXECUTE search // ##################################################### Vector<String> params = new Vector<String>(); params.add(request.getParameter("fname")); params.add(request.getParameter("lname")); params.add(request.getParameter("title")); params.add(request.getParameter("year")); params.add(request.getParameter("director")); List<Movie> movies = new ArrayList<Movie>(); movies = SQLServices.getMovies(params.toArray(new String[params.size()]), dbcon); // ########## SET DEFAULT SESSION() PARAMETERS #################################### request.getSession().removeAttribute("movies"); request.getSession().removeAttribute("linkedListMovies"); request.getSession().removeAttribute("hasPaged"); request.getSession().setAttribute("hasPaged", "no"); request.getSession().setAttribute("movies", movies); request.getSession().setAttribute("currentIndex", "0"); request.getSession().setAttribute("defaultN", "5"); // ########## IF MOVIES FROM SEARCH NON-EMPTY ########################################### List<String> fields = Movie.fieldNames(); int count = 1; if (!movies.isEmpty()) { request.setAttribute("movies", movies); for (String field : fields) { request.setAttribute("f" + count++, field); } request.getRequestDispatcher("../movieList.jsp").forward(request, response); } else { out.println("<html><head><title>error</title></head>"); out.println("<body><h1>could not find any movies, try your search again.</h1>"); out.println("<p> we are terribly sorry, please go back. </p>"); out.println("<table border>"); out.println("</table>"); } dbcon.close(); } catch (SQLException ex) { while (ex != null) { System.out.println("SQL Exception: " + ex.getMessage()); ex = ex.getNextException(); } } catch (java.lang.Exception ex) { out.println( "<html>" + "<head><title>" + "moviedb: error" + "</title></head>\n<body>" + "<p>SQL error in doGet: " + ex.getMessage() + "</p></body></html>"); return; } out.close(); }
/** * Remove a quiz from a course. Also deletes all the quiz visualization files from the students' * folder who is registered in the course. Caution: vizualisation file will be deleted eventhough * it also relates to anther course if the student is also registered to that course. (FIX ME!) * Throws InvalidDBRequestException if the quiz is not registered in the course, error occured * during deletion, or other exception occured. * * @param quizName quiz name * @param courseID course id (course number + instructor name) * @throws InvalidDBRequestException */ public void deleteQuiz(String quizName, String courseID) throws InvalidDBRequestException, FileFailureException { try { Class.forName(GaigsServer.DBDRIVER); db = DriverManager.getConnection(GaigsServer.DBURL, GaigsServer.DBLOGIN, GaigsServer.DBPASSWD); Statement stmt = db.createStatement(); ResultSet rs; int count = 0; // check if quiz is used in the course rs = stmt.executeQuery( "select test_name from courseTest where test_name = '" + quizName + "' and course_id = '" + courseID + "'"); if (!rs.next()) throw new InvalidDBRequestException("Quiz is not registered for the course"); else { // remove quiz from course count = stmt.executeUpdate( "delete from courseTest where course_id = '" + courseID + "' and test_name = '" + quizName + "'"); if (count != 1) throw new InvalidDBRequestException("Error occured during deletion"); else { // delete quiz visualization files rs = stmt.executeQuery( "select distinct unique_id, scores.user_login from scores, courseRoster " + "where courseRoster.user_login = scores.user_login " + "and course_id = '" + courseID + "' " + "and test_name = '" + quizName + "'"); while (rs.next()) { deleteVisualization(rs.getString(1), rs.getString(2), quizName); count = stmt.executeUpdate( "delete from scores where unique_id = " + rs.getString(1).trim()); } // rewrite the menu for the course rs = stmt.executeQuery( "select distinct menu_text, name, script_type, visual_type from test t, courseTest c " + "where t.name = c.test_name " + "and course_id = '" + courseID + "'"); PrintWriter fileOStream = new PrintWriter(new FileOutputStream("./html_root/cat/" + courseID + ".list")); while (rs.next()) { if (debug) System.out.println( rs.getString(1).trim() + "\n" + rs.getString(2).trim() + " " + rs.getString(3).trim() + " " + rs.getString(4).trim().toLowerCase() + "\n****\n"); fileOStream.print( rs.getString(1).trim() + "\n" + rs.getString(2).trim() + " " + rs.getString(3).trim() + " " + rs.getString(4).trim().toLowerCase() + "\n****\n"); } fileOStream.flush(); fileOStream.close(); } } rs.close(); stmt.close(); db.close(); } catch (SQLException e) { System.err.println("Invalid SQL in addQuiz: " + e.getMessage()); throw new InvalidDBRequestException("??? "); } catch (ClassNotFoundException e) { System.err.println("Driver Not Loaded"); throw new InvalidDBRequestException("Internal Server Error"); } catch (Exception e) { System.err.println("Error in recreating menu for course: " + courseID); System.err.println(e.getMessage()); throw new FileFailureException(); } }
public static void main(String[] argv) throws Exception { String[] sArray = new String[8]; long time = System.currentTimeMillis(); try { FileInputStream fstream = new FileInputStream("system.in"); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); int i = 0; while ((sArray[i] = br.readLine()) != null) { sArray[i] = sArray[i].split("=")[1].trim(); System.out.println(sArray[i]); i++; } in.close(); } catch (Exception e) { } System.out.println("-------- Oracle JDBC Connection Testing ------"); try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException e) { System.out.println("Where is your Oracle JDBC Driver?"); e.printStackTrace(); return; } System.out.println("Oracle JDBC Driver Registered!"); Connection connection = null; try { connection = DriverManager.getConnection( "jdbc:oracle:thin:@//oracle1.cise.ufl.edu:1521/orcl", sArray[0], sArray[1]); } catch (SQLException e) { System.out.println("Connection Failed! Check output console"); e.printStackTrace(); return; } ResultSet rset = null; if (connection != null) { System.out.println(" -|||- "); Process p = Runtime.getRuntime() .exec("sqlplus " + sArray[0] + "@orcl/" + sArray[1] + " @adwords.sql"); p.waitFor(); // CallableStatement cstmt; System.out.println(" ||| "); System.out.println( "Time taken in Milliseconds (establishing connection): " + (System.currentTimeMillis() - time)); time = System.currentTimeMillis(); Process proc3 = Runtime.getRuntime() .exec( "sqlldr " + sArray[0] + "/" + sArray[1] + "@orcl DATA=Keywords.dat CONTROL=Keywords.ctl LOG=Keywords.log"); proc3.waitFor(); Process proc1 = Runtime.getRuntime() .exec( "sqlldr " + sArray[0] + "/" + sArray[1] + "@orcl DATA=Advertisers.dat CONTROL=Advertisers.ctl LOG=Advertiser.log"); proc1.waitFor(); Process proc2 = Runtime.getRuntime() .exec( "sqlldr " + sArray[0] + "/" + sArray[1] + "@orcl DATA=Queries.dat CONTROL=Queries.ctl LOG=Queries.log"); proc2.waitFor(); System.out.println(" ||| "); System.out.println( "Time taken in Milliseconds (loading dat): " + (System.currentTimeMillis() - time)); time = System.currentTimeMillis(); CallableStatement callableStatement = null; String storeProc = "{call sq(?,?,?,?,?,?)}"; try { callableStatement = connection.prepareCall(storeProc); callableStatement.setInt(1, Integer.parseInt(sArray[2])); callableStatement.setInt(2, Integer.parseInt(sArray[3])); callableStatement.setInt(3, Integer.parseInt(sArray[4])); callableStatement.setInt(4, Integer.parseInt(sArray[5])); callableStatement.setInt(5, Integer.parseInt(sArray[6])); callableStatement.setInt(6, Integer.parseInt(sArray[7])); callableStatement.executeUpdate(); } catch (SQLException e) { System.out.println(e.getMessage()); } /*callableStatement = connection.prepareCall("{call sq( " + Integer.parseInt(sArray[2]) + ", " + Integer.parseInt(sArray[3]) + ", " + Integer.parseInt(sArray[4]) + ", " + Integer.parseInt(sArray[5]) + ", " + Integer.parseInt(sArray[6]) + ", " + Integer.parseInt(sArray[7]) + " ) }");*/ System.out.println(" ||| "); System.out.println( "Time taken in Milliseconds (sql procedure): " + (System.currentTimeMillis() - time)); time = System.currentTimeMillis(); FileWriter fw = null; File file = null; PrintWriter pw = null; Statement resStmt = null; ResultSet resRs = null; int qid = 0; int rank; for (int i = 0; i < 6; i++) { file = new File("system.out." + (i + 1)); try { if (!file.exists()) file.createNewFile(); else file.delete(); fw = new FileWriter(file.getPath(), true); } catch (Exception e) { System.out.println(e.getMessage()); } pw = new PrintWriter(fw); resStmt = connection.createStatement(); resRs = resStmt.executeQuery( "SELECT * FROM OUTPUT" + (i + 1) + " order by qid asc, adrank asc"); while (resRs.next()) { qid = resRs.getInt("QID"); rank = (int) resRs.getFloat("ADRANK"); int advertiserId = resRs.getInt("ADVERTISERID"); float balance = resRs.getFloat("BALANCE"); float budget = resRs.getFloat("BUDGET"); StringBuffer resStr = new StringBuffer(); resStr.append(qid + "," + rank + "," + advertiserId + "," + balance + "," + budget); // System.out.println(resStr.toString()); pw.println(resStr.toString()); } pw.close(); } } else { System.out.println("Failed to make connection!"); } System.out.println( "Time taken in Milliseconds (file write): " + (System.currentTimeMillis() - time)); }
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); PreparedStatement pstmt = null; Statement stmt = null; ResultSet rs = null; HttpSession session = SystemUtils.verifyMem(req, out); // check for intruder if (session == null) return; Connection con = Connect.getCon(req); // get DB connection if (con == null) { resp.setContentType("text/html"); out.println(SystemUtils.HeadTitle("DB Connection Error")); out.println("<BODY><CENTER><BR>"); out.println("<BR><BR><H3>Database Connection Error</H3>"); out.println("<BR><BR>Unable to connect to the Database."); out.println("<BR>Please try again later."); out.println("<BR><BR>If problem persists, contact customer support."); out.println("<BR><BR>"); out.println("<a href=\"javascript:history.back(1)\">Return</a>"); out.println("</CENTER></BODY></HTML>"); out.close(); return; } // // Get needed vars out of session obj // String club = (String) session.getAttribute("club"); String user = (String) session.getAttribute("user"); String caller = (String) session.getAttribute("caller"); int activity_id = (Integer) session.getAttribute("activity_id"); int foretees_mode = 0; String stype_id = req.getParameter("type_id"); int type_id = 0; String sgroup_id = req.getParameter("group_id"); int group_id = 0; String sitem_id = req.getParameter("item_id"); int item_id = 0; try { type_id = Integer.parseInt(stype_id); } catch (NumberFormatException ignore) { } try { group_id = Integer.parseInt(sgroup_id); } catch (NumberFormatException ignore) { } try { item_id = Integer.parseInt(sitem_id); } catch (NumberFormatException ignore) { } out.println( "<!-- type_id=" + type_id + ", group_id=" + group_id + ", item_id=" + item_id + " -->"); // // START PAGE OUTPUT // out.println(SystemUtils.HeadTitle("Member Acivities")); out.println("<style>"); out.println(".actLink { color: black }"); out.println(".actLink:hover { color: #336633 }"); // out.println(".playerTD {width:125px}"); out.println("</style>"); out.println( "<body bgcolor=\"#CCCCAA\" text=\"#000000\" link=\"#336633\" vlink=\"#8B8970\" alink=\"#8B8970\">"); SystemUtils.getMemberSubMenu(req, out, caller); // required to allow submenus on this page // // DISPLAY A LIST OF AVAILABLE ACTIVITIES // out.println( "<p align=center><b><font size=5 color=#336633><BR><BR>Available Activities</font></b></p>"); out.println( "<p align=center><b><font size=3 color=#000000>Select your desired activity from the list below.<br>NOTE: You can set your default activity under <a href=\"Member_services\" class=actLink>Settings</a>.</font></b></p>"); out.println("<table align=center>"); try { stmt = con.createStatement(); rs = stmt.executeQuery("SELECT foretees_mode FROM club5 WHERE clubName <> '';"); if (rs.next()) { foretees_mode = rs.getInt(1); } // if they have foretees then give a link in to the golf system if (foretees_mode != 0) { out.println( "<tr><td align=center><b><a href=\"Member_jump?switch&activity_id=0\" class=linkA style=\"color:#336633\" target=_top>Golf</a></b></td></tr>"); // ForeTees } // build a link to any activities they have access to rs = stmt.executeQuery( "SELECT * FROM activities " + "WHERE parent_id = 0 " + "ORDER BY activity_name"); while (rs.next()) { out.println( "<tr><td align=center><b><a href=\"Member_jump?switch&activity_id=" + rs.getInt("activity_id") + "\" class=linkA style=\"color:#336633\" target=_top>" + rs.getString("activity_name") + "</a></b></td></tr>"); } stmt.close(); } catch (Exception exc) { out.println("<p>ERROR:" + exc.toString() + "</p>"); } finally { try { rs.close(); } catch (Exception ignore) { } try { stmt.close(); } catch (Exception ignore) { } } out.println("</table>"); out.println("</body></html>"); /* out.println("<script>"); out.println("function load_types() {"); out.println(" try {document.forms['frmSelect'].item_id.selectedIndex = -1; } catch (err) {}"); out.println(" document.forms['frmSelect'].group_id.selectedIndex = -1;"); out.println(" document.forms['frmSelect'].submit();"); out.println("}"); out.println("function load_groups() {"); out.println(" document.forms['frmSelect'].submit();"); out.println("}"); out.println("function load_times(id) {"); out.println(" top.bot.location.href='Member_gensheets?id=' + id;"); out.println("}"); out.println("</script>"); out.println("<form name=frmSelect>"); // LOAD ACTIVITY TYPES out.println("<select name=type_id onchange=\"load_types()\">"); if (type_id == 0) { out.println("<option>CHOOSE TYPE</option>"); } try { stmt = con.createStatement(); rs = stmt.executeQuery("SELECT * FROM activities WHERE parent_id = 0"); while (rs.next()) { Common_Config.buildOption(rs.getInt("activity_id"), rs.getString("activity_name"), type_id, out); } stmt.close(); } catch (Exception exc) { out.println("<p>ERROR:" + exc.toString() + "</p>"); } out.println(""); out.println("</select>"); // LOAD ACTIVITIES BY GROUP TYPE out.println("<select name=group_id onchange=\"load_groups()\">"); if (type_id == 0) { out.println("<option>CHOOSE TYPE</option>"); } else { try { stmt = con.createStatement(); rs = stmt.executeQuery("SELECT activity_id, activity_name FROM activities WHERE parent_id = " + type_id); rs.last(); if (rs.getRow() == 1) { group_id = rs.getInt("activity_id"); out.println("<!-- ONLY FOUND 1 GROUP -->"); } else { out.println("<option value=\"0\">CHOOSE...</option>"); } rs.beforeFirst(); while (rs.next()) { Common_Config.buildOption(rs.getInt("activity_id"), rs.getString("activity_name"), group_id, out); } stmt.close(); } catch (Exception exc) { out.println("<p>ERROR:" + exc.toString() + "</p>"); } } out.println(""); out.println("</select>"); boolean do_load = false; if (group_id > 0 ) { //|| sitem_id != null // LOAD ACTIVITIES BY ITEM TYPE try { stmt = con.createStatement(); rs = stmt.executeQuery("SELECT activity_id, activity_name FROM activities WHERE parent_id = " + group_id); rs.last(); if (rs.getRow() == 0) { // no sub groups found do_load = true; item_id = group_id; } else if (rs.getRow() == 1) { // single sub group found (pre select it) item_id = rs.getInt("activity_id"); out.println("<!-- ONLY FOUND 1 ITEM -->"); } else { out.println("<select name=item_id onchange=\"load_times(this.options[this.selectedIndex].value)\">"); out.println("<option value=\"0\">CHOOSE...</option>"); } if (!do_load) { rs.beforeFirst(); while (rs.next()) { Common_Config.buildOption(rs.getInt("activity_id"), rs.getString("activity_name"), item_id, out); } } stmt.close(); out.println(""); out.println("</select>"); } catch (Exception exc) { out.println("<p>ERROR:" + exc.toString() + "</p>"); } } out.println("</form>"); out.println("<p><a href=\"Member_genrez\">Reset</a></p>"); try { con.close(); } catch (Exception ignore) {} if (do_load) out.println("<script>load_times(" + item_id + ")</script>"); //out.println("<iframe name=ifSheet src=\"\" style=\"width:640px height:480px\"></iframe>"); */ out.close(); }
public static void main(String[] args) { ////////////////////////// // The values in following 4 lines should be user input int startPos = 200; int endPos = 1000; int totalNumPixel = 1044; double threshhold = 0.0001; ///////////////////////// int numPixel = endPos - startPos; double wavelength[] = new double[totalNumPixel]; double photonCount[] = new double[totalNumPixel]; double SpecNoBk[] = new double[numPixel]; double ThisSpectrum[] = new double[numPixel]; double ThisXaxis[] = new double[numPixel]; double Po[] = new double[numPixel]; double Re[] = new double[numPixel]; double P[] = new double[6]; double Re2[] = new double[numPixel - 1]; double mySUM[] = new double[numPixel]; int ind[]; double DEV; double prevDEV; Connection connection = null; Statement stmt = null; String pattern = "##.##"; try { Scanner in = new Scanner(new FileReader(args[0])); int i = 0; while (in.hasNextDouble()) { wavelength[i] = in.nextDouble(); photonCount[i] = in.nextDouble(); ++i; } } catch (FileNotFoundException e) { e.printStackTrace(); } ThisSpectrum = Arrays.copyOfRange(photonCount, startPos, endPos); ThisXaxis = Arrays.copyOfRange(wavelength, startPos, endPos); final WeightedObservedPoints obs = new WeightedObservedPoints(); for (int i = 0; i < numPixel; i++) { obs.add(ThisXaxis[i], ThisSpectrum[i]); } final PolynomialCurveFitter fitter = PolynomialCurveFitter.create(5); P = fitter.fit(obs.toList()); Polyval pVal = new Polyval(P, ThisXaxis, numPixel); Po = pVal.evl(); for (int i = 0; i < numPixel; i++) { Re[i] = ThisSpectrum[i] - Po[i]; } for (int i = 0; i < numPixel - 1; i++) { Re2[i] = Re[i + 1] - Re[i]; } DEV = Math.sqrt(StatUtils.populationVariance(Re2, 0, Re2.length)); for (int i = 0; i < numPixel; i++) { mySUM[i] = Po[i] + DEV; } int jj = 0; // jj is the length of points to be removed for (int i = 0; i < numPixel; i++) { if (ThisSpectrum[i] > mySUM[i]) { jj++; ; } } ind = new int[jj]; int jjj = 0; for (int i = 0; i < numPixel; i++) { if (ThisSpectrum[i] > mySUM[i]) { ind[jjj] = i; jjj++; } } int indKeepLength = numPixel - ind.length; int indKeep[] = new int[indKeepLength]; int k = 0; for (int i = 0; i < numPixel; i++) { if (!ArrayUtils.contains(ind, i)) { indKeep[k] = i; k++; } } double ThisSpectrumKeep[] = new double[indKeepLength]; double ThisXaxisKeep[] = new double[indKeepLength]; double PoKeep[] = new double[indKeepLength]; double ReKeep[] = new double[indKeepLength]; double Re2Keep[] = new double[indKeepLength - 1]; double mySUMKeep[] = new double[indKeepLength]; for (int i = 0; i < indKeepLength; i++) { ThisSpectrumKeep[i] = ThisSpectrum[indKeep[i]]; ThisXaxisKeep[i] = ThisXaxis[indKeep[i]]; } prevDEV = DEV; // at the point, ThisSpectrum and ThisXaxis should have reduced size final WeightedObservedPoints obs1 = new WeightedObservedPoints(); for (int i = 0; i < indKeepLength; i++) { obs1.add(ThisXaxisKeep[i], ThisSpectrumKeep[i]); } while (true) { final PolynomialCurveFitter fitter1 = PolynomialCurveFitter.create(5); P = fitter1.fit(obs1.toList()); Polyval pVal1 = new Polyval(P, ThisXaxisKeep, indKeepLength); PoKeep = pVal1.evl(); for (int i = 0; i < indKeepLength; i++) { ReKeep[i] = ThisSpectrumKeep[i] - PoKeep[i]; } for (int i = 0; i < indKeepLength - 1; i++) { Re2Keep[i] = ReKeep[i + 1] - ReKeep[i]; } DEV = Math.sqrt(StatUtils.populationVariance(Re2Keep, 0, Re2Keep.length)); for (int i = 0; i < indKeepLength; i++) { mySUMKeep[i] = PoKeep[i] + DEV; } for (int i = 0; i < indKeepLength; i++) { if (ThisSpectrumKeep[i] > mySUMKeep[i]) ThisSpectrumKeep[i] = mySUMKeep[i]; } if ((Math.abs(DEV - prevDEV) / DEV) < threshhold) break; prevDEV = DEV; obs1.clear(); for (int i = 0; i < indKeepLength; i++) { obs1.add(ThisXaxisKeep[i], ThisSpectrumKeep[i]); } } Polyval pVal2 = new Polyval(P, ThisXaxis, numPixel); double FLbk[] = pVal2.evl(); for (int i = 0; i < ThisXaxis.length; i++) { SpecNoBk[i] = ThisSpectrum[i] - FLbk[i]; } // the write-to-file part is only for testing purpose, ThisXaxis and SpecNoBk are two outputs try { FileWriter fr = new FileWriter(args[1]); BufferedWriter br = new BufferedWriter(fr); PrintWriter out = new PrintWriter(br); DecimalFormat df = new DecimalFormat(pattern); for (int j = 0; j < ThisXaxis.length; j++) { if (Double.toString(wavelength[j]) != null) out.write(ThisXaxis[j] + "\t" + SpecNoBk[j]); out.write("\r\n"); } out.close(); } catch (IOException e) { System.out.println(e); } }
static int loadOrder(int whseKount, int distWhseKount, int custDistKount) { int k = 0; int t = 0; PrintWriter outLine = null; PrintWriter outNewOrder = null; try { if (outputFiles == true) { out = new PrintWriter(new FileOutputStream(fileLocation + "order.csv")); System.out.println("\nWriting Order file to: " + fileLocation + "order.csv"); outLine = new PrintWriter(new FileOutputStream(fileLocation + "order-line.csv")); System.out.println("\nWriting Order Line file to: " + fileLocation + "order-line.csv"); outNewOrder = new PrintWriter(new FileOutputStream(fileLocation + "new-order.csv")); System.out.println("\nWriting New Order file to: " + fileLocation + "new-order.csv"); } now = new java.util.Date(); Oorder oorder = new Oorder(); NewOrder new_order = new NewOrder(); OrderLine order_line = new OrderLine(); jdbcIO myJdbcIO = new jdbcIO(); t = (whseKount * distWhseKount * custDistKount); t = (t * 11) + (t / 3); System.out.println( "whse=" + whseKount + ", dist=" + distWhseKount + ", cust=" + custDistKount); System.out.println("\nStart Order-Line-New Load for approx " + t + " rows @ " + now + " ..."); for (int w = 1; w <= whseKount; w++) { for (int d = 1; d <= distWhseKount; d++) { for (int c = 1; c <= custDistKount; c++) { oorder.o_id = c; oorder.o_w_id = w; oorder.o_d_id = d; oorder.o_c_id = jTPCCUtil.randomNumber(1, custDistKount, gen); oorder.o_carrier_id = jTPCCUtil.randomNumber(1, 10, gen); oorder.o_ol_cnt = jTPCCUtil.randomNumber(5, 15, gen); oorder.o_all_local = 1; oorder.o_entry_d = System.currentTimeMillis(); k++; if (outputFiles == false) { myJdbcIO.insertOrder(ordrPrepStmt, oorder); } else { String str = ""; str = str + oorder.o_id + ","; str = str + oorder.o_w_id + ","; str = str + oorder.o_d_id + ","; str = str + oorder.o_c_id + ","; str = str + oorder.o_carrier_id + ","; str = str + oorder.o_ol_cnt + ","; str = str + oorder.o_all_local + ","; Timestamp entry_d = new java.sql.Timestamp(oorder.o_entry_d); str = str + entry_d; out.println(str); } // 900 rows in the NEW-ORDER table corresponding to the last // 900 rows in the ORDER table for that district (i.e., with // NO_O_ID between 2,101 and 3,000) if (c > 2100) { new_order.no_w_id = w; new_order.no_d_id = d; new_order.no_o_id = c; k++; if (outputFiles == false) { myJdbcIO.insertNewOrder(nworPrepStmt, new_order); } else { String str = ""; str = str + new_order.no_w_id + ","; str = str + new_order.no_d_id + ","; str = str + new_order.no_o_id; outNewOrder.println(str); } } // end new order for (int l = 1; l <= oorder.o_ol_cnt; l++) { order_line.ol_w_id = w; order_line.ol_d_id = d; order_line.ol_o_id = c; order_line.ol_number = l; // ol_number order_line.ol_i_id = jTPCCUtil.randomNumber(1, 100000, gen); order_line.ol_delivery_d = oorder.o_entry_d; if (order_line.ol_o_id < 2101) { order_line.ol_amount = 0; } else { // random within [0.01 .. 9,999.99] float f = (float) (jTPCCUtil.randomNumber(1, 999999, gen) / 100.0); order_line.ol_amount = f; // XXX float error line 1. } order_line.ol_supply_w_id = jTPCCUtil.randomNumber(1, numWarehouses, gen); order_line.ol_quantity = 5; order_line.ol_dist_info = jTPCCUtil.randomStr(24); k++; if (outputFiles == false) { myJdbcIO.insertOrderLine(orlnPrepStmt, order_line); } else { String str = ""; str = str + order_line.ol_w_id + ","; str = str + order_line.ol_d_id + ","; str = str + order_line.ol_o_id + ","; str = str + order_line.ol_number + ","; str = str + order_line.ol_i_id + ","; Timestamp delivery_d = new Timestamp(order_line.ol_delivery_d); str = str + delivery_d + ","; str = str + order_line.ol_amount + ","; str = str + order_line.ol_supply_w_id + ","; str = str + order_line.ol_quantity + ","; str = str + order_line.ol_dist_info; outLine.println(str); } if ((k % configCommitCount) == 0) { long tmpTime = new java.util.Date().getTime(); String etStr = " Elasped Time(ms): " + ((tmpTime - lastTimeMS) / 1000.000) + " "; System.out.println(etStr.substring(0, 30) + " Writing record " + k + " of " + t); lastTimeMS = tmpTime; if (outputFiles == false) { ordrPrepStmt.executeBatch(); nworPrepStmt.executeBatch(); orlnPrepStmt.executeBatch(); ordrPrepStmt.clearBatch(); nworPrepStmt.clearBatch(); orlnPrepStmt.clearBatch(); transCommit(); } } } // end for [l] } // end for [c] } // end for [d] } // end for [w] System.out.println(" Writing final records " + k + " of " + t); if (outputFiles == false) { ordrPrepStmt.executeBatch(); nworPrepStmt.executeBatch(); orlnPrepStmt.executeBatch(); } else { outLine.close(); outNewOrder.close(); } transCommit(); now = new java.util.Date(); System.out.println("End Orders Load @ " + now); } catch (Exception e) { e.printStackTrace(); transRollback(); if (outputFiles == true) { outLine.close(); outNewOrder.close(); } } return (k); } // end loadOrder()
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); Connection con = null; // init DB objects PreparedStatement pstmt = null; Statement stmt = null; ResultSet rs = null; try { con = dbConn.Connect("demopaul"); } catch (Exception ignore) { } String stype_id = req.getParameter("type_id"); int type_id = 0; String sgroup_id = req.getParameter("group_id"); int group_id = 0; String sitem_id = req.getParameter("item_id"); int item_id = 0; try { type_id = Integer.parseInt(stype_id); } catch (NumberFormatException ignore) { } try { group_id = Integer.parseInt(sgroup_id); } catch (NumberFormatException ignore) { } try { item_id = Integer.parseInt(sitem_id); } catch (NumberFormatException ignore) { } out.println( "<!-- type_id=" + type_id + ", group_id=" + group_id + ", item_id=" + item_id + " -->"); out.println("<script>"); out.println("function load_types() {"); out.println(" try {document.forms['frmSelect'].item_id.selectedIndex = -1; } catch (err) {}"); out.println(" document.forms['frmSelect'].group_id.selectedIndex = -1;"); out.println(" document.forms['frmSelect'].submit();"); out.println("}"); out.println("function load_groups() {"); out.println(" document.forms['frmSelect'].submit();"); out.println("}"); out.println("</script>"); out.println("<form name=frmSelect>"); // LOAD ACTIVITY TYPES out.println("<select name=type_id onchange=\"load_types()\">"); if (type_id == 0) { out.println("<option>CHOOSE TYPE</option>"); } try { stmt = con.createStatement(); rs = stmt.executeQuery("SELECT * FROM activity_types"); while (rs.next()) { Common_Config.buildOption(rs.getInt("type_id"), rs.getString("type_name"), type_id, out); } stmt.close(); } catch (Exception exc) { out.println("<p>ERROR:" + exc.toString() + "</p>"); } out.println(""); out.println("</select>"); // LOAD ACTIVITIES BY GROUP TYPE out.println("<select name=group_id onchange=\"load_groups()\">"); if (type_id == 0) { out.println("<option>CHOOSE TYPE</option>"); } else { try { stmt = con.createStatement(); rs = stmt.executeQuery( "SELECT group_id, group_name FROM activity_groups WHERE type_id = " + type_id); rs.last(); if (rs.getRow() == 1) { group_id = rs.getInt("group_id"); out.println("<!-- ONLY FOUND 1 GROUP -->"); } else { out.println("<option value=\"0\">CHOOSE...</option>"); } rs.beforeFirst(); while (rs.next()) { Common_Config.buildOption( rs.getInt("group_id"), rs.getString("group_name"), group_id, out); } stmt.close(); } catch (Exception exc) { out.println("<p>ERROR:" + exc.toString() + "</p>"); } } out.println(""); out.println("</select>"); if (group_id > 0) { // || sitem_id != null // LOAD ACTIVITIES BY ITEM TYPE out.println("<select name=item_id onchange=\"load_times()\">"); if (group_id == 0) { out.println("<option value=\"0\">CHOOSE GROUP</option>"); } else { try { stmt = con.createStatement(); rs = stmt.executeQuery( "SELECT item_id, item_name FROM activity_items WHERE group_id = " + group_id); rs.last(); if (rs.getRow() == 1) { item_id = rs.getInt("item_id"); out.println("<!-- ONLY FOUND 1 ITEM -->"); } else { out.println("<option value=\"0\">CHOOSE...</option>"); } rs.beforeFirst(); while (rs.next()) { Common_Config.buildOption( rs.getInt("item_id"), rs.getString("item_name"), item_id, out); } stmt.close(); } catch (Exception exc) { out.println("<p>ERROR:" + exc.toString() + "</p>"); } } out.println(""); out.println("</select>"); } out.println("</form>"); out.println("<p><a href=\"Member_genrez\">Reset</a></p>"); try { con.close(); } catch (Exception ignore) { } out.close(); }
// ***************************************************** // Process the request from Member_sheet // ***************************************************** // public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); PreparedStatement pstmt3 = null; Statement stmt = null; ResultSet rs = null; HttpSession session = SystemUtils.verifyMem(req, out); // check for intruder if (session == null) { return; } Connection con = SystemUtils.getCon(session); // get DB connection if (con == null) { out.println(SystemUtils.HeadTitle("DB Connection Error")); out.println( "<BODY bgcolor=\"#ccccaa\"><CENTER><img src=\"/" + rev + "/images/foretees.gif\"><BR>"); out.println("<hr width=\"40%\">"); out.println("<BR><BR><H3>Database Connection Error</H3>"); out.println("<BR><BR>Unable to connect to the Database."); out.println("<BR>Please try again later."); out.println("<BR><BR>If problem persists, please contact customer support."); out.println("<BR><BR>"); out.println("<font size=\"2\">"); out.println("<form method=\"get\" action=\"javascript:history.back(1)\">"); out.println("<input type=\"submit\" value=\"Return\" style=\"text-decoration:underline;\">"); out.println("</form></font>"); out.println("</CENTER></BODY></HTML>"); out.close(); return; } // Create Json response for later use Gson gson_obj = new Gson(); // HashMap for later use by gson Map<String, Object> hashMap = new HashMap<String, Object>(); // Check if we will only be return json data boolean json_mode = (req.getParameter("jsonMode")) != null; // // See if we are here to VIEW a wait list // if (req.getParameter("view") != null && req.getParameter("waitListId") != null) { if (json_mode) { out.print(gson_obj.toJson(viewSignups(req, out, con, true))); } else { viewSignups(req, out, con); } return; } String jump = "0"; // jump index - default to zero (for _sheet) if (req.getParameter("jump") != null) { // if jump index provided jump = req.getParameter("jump"); } // // Get this session's username // String club = (String) session.getAttribute("club"); String user = (String) session.getAttribute("user"); String name = (String) session.getAttribute("name"); // get users full name String sindex = req.getParameter("index"); // index value of day (needed by Member_sheet when returning) String course = req.getParameter("course"); // Name of Course String id = req.getParameter("waitListId"); // uid of the wait list we are working with String returnCourse = ""; if (req.getParameter("returnCourse") != null) { // if returnCourse provided returnCourse = req.getParameter("returnCourse"); } String sdate = req.getParameter("date"); // date of the request (yyyymmdd) String day_name = req.getParameter("day"); // name of the day String p5 = req.getParameter("p5"); // 5-somes supported int index = 0; int wait_list_id = 0; int count = 0; int mm = 0; int dd = 0; int yy = 0; int date = 0; int time = SystemUtils.getTime(con); // // Convert the values from string to int // try { wait_list_id = Integer.parseInt(id); index = Integer.parseInt(sindex); date = Integer.parseInt(sdate); } catch (NumberFormatException e) { } // get our date parts yy = date / 10000; mm = date - (yy * 10000); dd = mm - (mm / 100) * 100; mm = mm / 100; // // parm block to hold the wait list parameters // parmWaitList parmWL = new parmWaitList(); // allocate a parm block parmWL.wait_list_id = wait_list_id; try { getWaitList.getParms(con, parmWL); // get the wait list config // if members can see the wait list then get the count if (parmWL.member_view == 1) { count = getWaitList.getListCount(wait_list_id, date, index, time, true, con); } } catch (Exception exp) { out.println(exp.getMessage()); } int onlist = 0; try { onlist = getWaitList.onList(user, wait_list_id, date, con); } catch (Exception exp) { out.println(exp.toString()); } String waitlist_notice = ""; if (onlist == 0) { // not on the list try { // out.println("<pre>"); waitlist_notice = getWaitList.getNotice(wait_list_id, con); // out.println("</pre>"); } catch (Exception exp) { } } if (json_mode) { // If in json mode, add data to hashmap // New skin uses Member_waitlist in json mode exclusively. // Group the data we want to send to javascript in a hash map hashMap.put("wait_list_id", wait_list_id); hashMap.put("waitlist_notice", waitlist_notice); hashMap.put("date", "" + mm + "/" + dd + "/" + yy); hashMap.put("start_time", SystemUtils.getSimpleTime(parmWL.start_time)); hashMap.put("end_time", SystemUtils.getSimpleTime(parmWL.end_time)); hashMap.put("member_access", parmWL.member_access); hashMap.put("member_view", parmWL.member_view); hashMap.put("onlist", onlist); hashMap.put("index", index); hashMap.put("course", course); hashMap.put("count", count); hashMap.put("name", parmWL.name); out.print(gson_obj.toJson(hashMap)); return; } else { // If not in json mode, output data directly to user out.println( "<!-- wait_list_id=" + wait_list_id + ", date=" + date + ", count=" + count + " -->"); // // ******************************************************************** // Build a page to display Wait List details to member // ******************************************************************** // out.println("<html>"); out.println("<head>"); out.println( "<link rel=\"stylesheet\" href=\"/" + rev + "/web utilities/foretees2.css\" type=\"text/css\">"); out.println("<title>Member Wait List Registration Page</title>"); out.println("</head>"); out.println( "<body bgcolor=\"#ccccaa\" text=\"#000000\" link=\"#FFFFFF\" vlink=\"#FFFFFF\" alink=\"#FF0000\" topmargin=\"0\">"); out.println("<font face=\"Arial, Helvetica, Sans-serif\"><center>"); out.println( "<table border=\"0\" width=\"100%\" align=\"center\" valign=\"top\">"); // large table for // whole page out.println("<tr><td valign=\"top\" align=\"center\">"); out.println( "<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" bgcolor=\"#336633\" align=\"center\" valign=\"top\">"); out.println("<tr><td align=\"left\" width=\"300\"> "); out.println("<img src=\"/" + rev + "/images/foretees.gif\" border=0>"); out.println("</td>"); out.println("<td align=\"center\">"); out.println("<font color=\"ffffff\" size=\"5\">Member Wait List Registration</font>"); out.println("</font></td>"); out.println("<td align=\"center\" width=\"300\">"); out.println("<font size=\"1\" color=\"#ffffff\">Copyright </font>"); out.println("<font size=\"2\" color=\"#ffffff\">© </font>"); out.println( "<font size=\"1\" color=\"#ffffff\">ForeTees, LLC <br> 2009 All rights reserved."); out.println("</font><font size=\"3\">"); out.println( "<br><br><a href=\"/" + rev + "/member_help.htm\" target=\"_blank\"><b>Help</b></a>"); out.println("</font></td>"); out.println("</tr></table>"); out.println("<br>"); out.println("<table border=\"1\" cols=\"1\" bgcolor=\"#f5f5dc\" cellpadding=\"3\">"); out.println("<tr>"); out.println("<td width=\"620\" align=\"center\">"); out.println("<font size=\"3\">"); out.println("<b>Wait List Registration</b><br></font>"); out.println("<font size=\"2\">"); out.println( "The golf shop is running a wait list " + ((index == 0) ? "today" : "on this day") + ". "); out.println( "The wait list you've selected is running from <nobr>" + SystemUtils.getSimpleTime(parmWL.start_time) + "</nobr> till <nobr>" + SystemUtils.getSimpleTime(parmWL.end_time) + ".</nobr> "); out.println("Review the information below and click on 'Continue With Request' to continue."); out.println( "<br>OR click on 'Cancel Request' to delete the request. To return without changes click on 'Go Back'."); // out.println("<br><br><b>NOTE:</b> Only the person that originates the request will be // allowed to cancel it or change these values."); out.println("</font></td></tr>"); out.println("</table>"); out.println("<br><br>"); out.println("<table border=0>"); out.println("<tr><td><font size=\"2\">"); out.println( "Date: <b>" + day_name + " " + mm + "/" + dd + "/" + yy + "</b></td>"); out.println("<td> </td><td>"); if (!course.equals("")) { out.println("<font size=\"2\">Course: <b>" + course + "</b></font>"); } out.println("</td></tr>"); out.println( "<tr><td><font size=\"2\">Wait List: <b>" + SystemUtils.getSimpleTime(parmWL.start_time) + " to " + SystemUtils.getSimpleTime(parmWL.end_time) + "</b></font></td>"); out.println("<td></td>"); out.println("<td><font size=\"2\">Signups:<b>"); out.print(((parmWL.member_view == 1) ? count : "N/A")); out.println("</b></font></td>"); out.println("</table>"); out.println("<br>"); out.println("<table border=\"0\" align=\"center\">"); // table to contain 2 tables below out.println("<tr>"); out.println("<td align=\"center\" valign=\"top\">"); out.println( "<table border=\"1\" bgcolor=\"#f5f5dc\" align=\"center\" width=\"500\" cellpadding=\"5\" cellspacing=\"5\">"); // table for request details out.println("<tr bgcolor=\"#336633\"><td align=\"center\">"); out.println("<font color=\"ffffff\" size=\"3\">"); out.println( "<b>" + ((!parmWL.name.equals("")) ? parmWL.name : "Wait List Information") + "</b>"); out.println("</font></td></tr>"); out.println("<tr>"); out.println("<form action=\"Member_waitlist_slot\" method=\"post\">"); out.println("<input type=\"hidden\" name=\"waitListId\" value=\"" + wait_list_id + "\">"); out.println("<input type=\"hidden\" name=\"sdate\" value=\"" + date + "\">"); out.println("<input type=\"hidden\" name=\"day\" value=\"" + day_name + "\">"); out.println("<input type=\"hidden\" name=\"index\" value=\"" + sindex + "\">"); out.println("<input type=\"hidden\" name=\"course\" value=\"" + course + "\">"); out.println("<input type=\"hidden\" name=\"returnCourse\" value=\"" + returnCourse + "\">"); out.println("<input type=\"hidden\" name=\"jump\" value=\"" + jump + "\">"); out.println("<td><font size=\"2\"><br>"); // see if they are already on the wait list out.println("<input type=\"hidden\" name=\"signupId\" value=\"" + onlist + "\">"); if (onlist == 0) { // not on the list // out.println("The golf shop is running a wait list " + ((index == 0) ? "today": "on this // day") + ". "); // out.println("The wait list you've selected is running from " + // SystemUtils.getSimpleTime(parmWL.start_time) + " till " + // SystemUtils.getSimpleTime(parmWL.end_time) + ". "); // try { // out.println("<pre>"); // out.print(getWaitList.getNotice(wait_list_id, con)); // out.println("</pre>"); out.print(waitlist_notice); // } catch (Exception exp) { } if (parmWL.member_access == 1) { out.println( "<br><p align=center><input type=submit value=\"Continue With Sign-up\" name=\"continue\"></p>"); } else { out.println("<p align=center><b>Contact the golf shop to get on the wait list.</b></p>"); } } else { // already on this list out.println( "<p align=center><b><i>You are already signed up for this wait list.</b></i></p>"); if (parmWL.member_access == 1) { out.println( "<br><p align=center><input type=submit value=\"Modify Your Sign-up\" name=\"continue\"></p>"); } else { out.println( "<p align=center><b>Contact the golf shop to make changes or cancel your entry.</b></p>"); } } if (parmWL.member_view == 1 && count > 0) { out.println( "<p align=center><input type=button value=\"View Wait List\" name=\"view\" onclick=\"document.forms['frmView'].submit();\"></p>"); } out.println("<br></font></td>"); out.println("</table>"); out.println("</form>"); out.println("<br>"); if (index == 999) { // out.println("<form action=\"Member_teelist\" method=\"GET\">"); out.println("<form action=\"/" + rev + "/member_teemain.htm\" method=\"GET\">"); } else if (index == 995) { // out.println("<form action=\"Member_teelist_list\" method=\"GET\">"); out.println("<form action=\"/" + rev + "/member_teemain2.htm\" method=\"GET\">"); } else { out.println("<form action=\"Member_jump\" method=\"POST\">"); out.println("<input type=\"hidden\" name=\"jump\" value=" + jump + ">"); out.println("<input type=\"hidden\" name=\"index\" value=" + index + ">"); out.println( "<input type=\"hidden\" name=\"course\" value=\"" + ((!returnCourse.equals("")) ? returnCourse : course) + "\">"); } out.println("<font size=2>Return w/o Changes:</font><br>"); out.println("<input type=\"submit\" value=\"Go Back\" name=\"cancel\"></form>"); out.println("<form action=\"Member_waitlist\" method=\"GET\" name=frmView>"); out.println("<input type=\"hidden\" name=\"view\" value=\"current\">"); out.println("<input type=\"hidden\" name=\"waitListId\" value=\"" + wait_list_id + "\">"); out.println("<input type=\"hidden\" name=\"sdate\" value=\"" + date + "\">"); out.println("<input type=\"hidden\" name=\"name\" value=\"" + parmWL.name + "\">"); // out.println("<input type=\"hidden\" name=\"day\" value=\"" + day_name + "\">"); out.println("<input type=\"hidden\" name=\"index\" value=\"" + sindex + "\">"); out.println("<input type=\"hidden\" name=\"course\" value=\"" + parmWL.course + "\">"); out.println("<input type=\"hidden\" name=\"returnCourse\" value=\"" + returnCourse + "\">"); out.println("<input type=\"hidden\" name=\"jump\" value=\"" + jump + "\">"); ; out.println( "<input type=\"hidden\" name=\"start_time\" value=\"" + parmWL.start_time + "\">"); out.println("<input type=\"hidden\" name=\"end_time\" value=\"" + parmWL.end_time + "\">"); out.println("<input type=\"hidden\" name=\"day_name\" value=\"" + day_name + "\">"); // out.println("<input type=submit value=\"View Sign-ups\" name=\"view\">"); out.println("</form>"); } // end json check } // end doPost
static int loadCust(int whseKount, int distWhseKount, int custDistKount) { int k = 0; int t = 0; Customer customer = new Customer(); History history = new History(); PrintWriter outHist = null; try { now = new java.util.Date(); if (outputFiles == true) { out = new PrintWriter(new FileOutputStream(fileLocation + "customer.csv")); System.out.println("\nWriting Customer file to: " + fileLocation + "customer.csv"); outHist = new PrintWriter(new FileOutputStream(fileLocation + "cust-hist.csv")); System.out.println("\nWriting Customer History file to: " + fileLocation + "cust-hist.csv"); } t = (whseKount * distWhseKount * custDistKount * 2); System.out.println("\nStart Cust-Hist Load for " + t + " Cust-Hists @ " + now + " ..."); for (int w = 1; w <= whseKount; w++) { for (int d = 1; d <= distWhseKount; d++) { for (int c = 1; c <= custDistKount; c++) { sysdate = new java.sql.Timestamp(System.currentTimeMillis()); customer.c_id = c; customer.c_d_id = d; customer.c_w_id = w; // discount is random between [0.0000 ... 0.5000] customer.c_discount = (float) (jTPCCUtil.randomNumber(1, 5000, gen) / 10000.0); if (jTPCCUtil.randomNumber(1, 100, gen) <= 10) { customer.c_credit = "BC"; // 10% Bad Credit } else { customer.c_credit = "GC"; // 90% Good Credit } customer.c_last = jTPCCUtil.getLastName(gen); customer.c_first = jTPCCUtil.randomStr(jTPCCUtil.randomNumber(8, 16, gen)); customer.c_credit_lim = 50000; customer.c_balance = -10; customer.c_ytd_payment = 10; customer.c_payment_cnt = 1; customer.c_delivery_cnt = 0; customer.c_street_1 = jTPCCUtil.randomStr(jTPCCUtil.randomNumber(10, 20, gen)); customer.c_street_2 = jTPCCUtil.randomStr(jTPCCUtil.randomNumber(10, 20, gen)); customer.c_city = jTPCCUtil.randomStr(jTPCCUtil.randomNumber(10, 20, gen)); customer.c_state = jTPCCUtil.randomStr(3).toUpperCase(); customer.c_zip = "123456789"; customer.c_phone = "(732)744-1700"; customer.c_since = sysdate.getTime(); customer.c_middle = "OE"; customer.c_data = jTPCCUtil.randomStr(jTPCCUtil.randomNumber(300, 500, gen)); history.h_c_id = c; history.h_c_d_id = d; history.h_c_w_id = w; history.h_d_id = d; history.h_w_id = w; history.h_date = sysdate.getTime(); history.h_amount = 10; history.h_data = jTPCCUtil.randomStr(jTPCCUtil.randomNumber(10, 24, gen)); k = k + 2; if (outputFiles == false) { custPrepStmt.setLong(1, customer.c_id); custPrepStmt.setLong(2, customer.c_d_id); custPrepStmt.setLong(3, customer.c_w_id); custPrepStmt.setDouble(4, customer.c_discount); custPrepStmt.setString(5, customer.c_credit); custPrepStmt.setString(6, customer.c_last); custPrepStmt.setString(7, customer.c_first); custPrepStmt.setDouble(8, customer.c_credit_lim); custPrepStmt.setDouble(9, customer.c_balance); custPrepStmt.setDouble(10, customer.c_ytd_payment); custPrepStmt.setDouble(11, customer.c_payment_cnt); custPrepStmt.setDouble(12, customer.c_delivery_cnt); custPrepStmt.setString(13, customer.c_street_1); custPrepStmt.setString(14, customer.c_street_2); custPrepStmt.setString(15, customer.c_city); custPrepStmt.setString(16, customer.c_state); custPrepStmt.setString(17, customer.c_zip); custPrepStmt.setString(18, customer.c_phone); Timestamp since = new Timestamp(customer.c_since); custPrepStmt.setTimestamp(19, since); custPrepStmt.setString(20, customer.c_middle); custPrepStmt.setString(21, customer.c_data); custPrepStmt.addBatch(); histPrepStmt.setInt(1, history.h_c_id); histPrepStmt.setInt(2, history.h_c_d_id); histPrepStmt.setInt(3, history.h_c_w_id); histPrepStmt.setInt(4, history.h_d_id); histPrepStmt.setInt(5, history.h_w_id); Timestamp hdate = new Timestamp(history.h_date); histPrepStmt.setTimestamp(6, hdate); histPrepStmt.setDouble(7, history.h_amount); histPrepStmt.setString(8, history.h_data); histPrepStmt.addBatch(); if ((k % configCommitCount) == 0) { long tmpTime = new java.util.Date().getTime(); String etStr = " Elasped Time(ms): " + ((tmpTime - lastTimeMS) / 1000.000) + " "; System.out.println(etStr.substring(0, 30) + " Writing record " + k + " of " + t); lastTimeMS = tmpTime; custPrepStmt.executeBatch(); histPrepStmt.executeBatch(); custPrepStmt.clearBatch(); custPrepStmt.clearBatch(); transCommit(); } } else { String str = ""; str = str + customer.c_id + ","; str = str + customer.c_d_id + ","; str = str + customer.c_w_id + ","; str = str + customer.c_discount + ","; str = str + customer.c_credit + ","; str = str + customer.c_last + ","; str = str + customer.c_first + ","; str = str + customer.c_credit_lim + ","; str = str + customer.c_balance + ","; str = str + customer.c_ytd_payment + ","; str = str + customer.c_payment_cnt + ","; str = str + customer.c_delivery_cnt + ","; str = str + customer.c_street_1 + ","; str = str + customer.c_street_2 + ","; str = str + customer.c_city + ","; str = str + customer.c_state + ","; str = str + customer.c_zip + ","; str = str + customer.c_phone; out.println(str); str = ""; str = str + history.h_c_id + ","; str = str + history.h_c_d_id + ","; str = str + history.h_c_w_id + ","; str = str + history.h_d_id + ","; str = str + history.h_w_id + ","; Timestamp hdate = new Timestamp(history.h_date); str = str + hdate + ","; str = str + history.h_amount + ","; str = str + history.h_data; outHist.println(str); if ((k % configCommitCount) == 0) { long tmpTime = new java.util.Date().getTime(); String etStr = " Elasped Time(ms): " + ((tmpTime - lastTimeMS) / 1000.000) + " "; System.out.println(etStr.substring(0, 30) + " Writing record " + k + " of " + t); lastTimeMS = tmpTime; } } } // end for [c] } // end for [d] } // end for [w] long tmpTime = new java.util.Date().getTime(); String etStr = " Elasped Time(ms): " + ((tmpTime - lastTimeMS) / 1000.000) + " "; System.out.println(etStr.substring(0, 30) + " Writing record " + k + " of " + t); lastTimeMS = tmpTime; custPrepStmt.executeBatch(); histPrepStmt.executeBatch(); transCommit(); now = new java.util.Date(); if (outputFiles == true) { outHist.close(); } System.out.println("End Cust-Hist Data Load @ " + now); } catch (SQLException se) { System.out.println(se.getMessage()); transRollback(); if (outputFiles == true) { outHist.close(); } } catch (Exception e) { e.printStackTrace(); transRollback(); if (outputFiles == true) { outHist.close(); } } return (k); } // end loadCust()
public void destroy() { pw.close(); }
// ***************************************************** // Process the initial request from Proshop_main // ***************************************************** // @SuppressWarnings("deprecation") public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // // Prevent caching so sessions are not mangled // resp.setHeader("Pragma", "no-cache"); // for HTTP 1.0 resp.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); // for HTTP 1.1 resp.setDateHeader("Expires", 0); // prevents caching at the proxy server resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); HttpSession session = SystemUtils.verifyPro(req, out); // check for intruder if (session == null) { return; } String club = (String) session.getAttribute("club"); // get club name String templott = (String) session.getAttribute("lottery"); // get lottery support indicator int lottery = Integer.parseInt(templott); // // Call is to display the new features page. // // Display a page to provide a link to the new feature page // out.println("<html><head>"); out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=windows-1252\">"); out.println("<meta http-equiv=\"Content-Language\" content=\"en-us\">"); out.println("<title> \"ForeTees Proshop Announcement Page\"</title>"); // out.println("<link rel=\"stylesheet\" href=\"/" +rev+ "/web utilities/foretees.css\" // type=\"text/css\"></link>"); out.println( "<script language=\"JavaScript\" src=\"/" + rev + "/web utilities/foretees.js\"></script>"); out.println("</head>"); out.println("<body bgcolor=\"#FFFFFF\" text=\"#000000\">"); SystemUtils.getProshopSubMenu(req, out, lottery); File f; FileReader fr; BufferedReader br; String tmp = ""; String path = ""; try { path = req.getRealPath(""); tmp = "/proshop_features.htm"; // "/" +rev+ f = new File(path + tmp); fr = new FileReader(f); br = new BufferedReader(fr); if (!f.isFile()) { // do nothing } } catch (FileNotFoundException e) { out.println("<br><br><p align=center>Missing New Features Page.</p>"); out.println("</BODY></HTML>"); out.close(); return; } catch (SecurityException se) { out.println("<br><br><p align=center>Access Denied.</p>"); out.println("</BODY></HTML>"); out.close(); return; } while ((tmp = br.readLine()) != null) out.println(tmp); br.close(); out.println("</BODY></HTML>"); out.close(); } // end of doGet
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * * @param request servlet request * @param response servlet response */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); HttpSession session = request.getSession(); try { db.connectDB(); String query = "SELECT * FROM Account_Information WHERE AI_ID='" + session.getAttribute("id") + "'"; ResultSet r = db.get_query(query); AccountInfoBean account = new AccountInfoBean(); while (r.next()) { String login = "******" + r.getString("AI_ID"); String password = "******" + r.getString("AI_Password"); String type = " " + r.getString("AI_Type"); String firstName = " " + r.getString("AI_First_Name"); String middleName = " " + r.getString("AI_Mid_Name"); String lastName = " " + r.getString("AI_Last_Name"); String email = " " + r.getString("AI_EMail"); String phone = " " + r.getString("AI_Phone"); String age = " " + r.getString("AI_Age"); String address1 = " " + r.getString("AI_Address1"); String address2 = " " + r.getString("AI_Address2"); String city = " " + r.getString("AI_City"); String state = " " + r.getString("AI_State"); String zip = " " + r.getInt("AI_Zip"); account.setLogin(login.trim()); account.setPassword(password.trim()); account.setPassword2(password.trim()); account.setType(type.trim()); account.setFirstName(firstName.trim()); account.setMiddleName(middleName.trim()); account.setLastName(lastName.trim()); account.setEmail(email.trim()); account.setPhone(phone.trim()); account.setAge(age.trim()); account.setAddress1(address1.trim()); account.setAddress2(address2.trim()); account.setCity(city.trim()); account.setState(state.trim()); account.setZip(zip.trim()); session.setAttribute("account", account); } } catch (Exception e) { System.out.println(e); } response.sendRedirect("accountedit.jsp"); /* TODO output your page here out.println("<html>"); out.println("<head>"); out.println("<title>Servlet</title>"); out.println("</head>"); out.println("<body>"); out.println("</body>"); out.println("</html>"); */ out.close(); }