public void processAction(HttpServletRequest request, HttpServletResponse response) throws IOException { System.out.println("processing test driver request ... "); processParams(request); boolean status = false; System.out.println("tc:" + tc); response.setContentType("text/plain"); ServletOutputStream out = response.getOutputStream(); out.println("TestCase: " + tc); if (tc != null) { try { Class<?> c = getClass(); Object t = this; Method[] allMethods = c.getDeclaredMethods(); for (Method m : allMethods) { String mname = m.getName(); if (!mname.equals(tc.trim())) { continue; } System.out.println("Invoking : " + mname); try { m.setAccessible(true); Object o = m.invoke(t); System.out.println("Returned => " + (Boolean) o); status = new Boolean((Boolean) o).booleanValue(); // Handle any methods thrown by method to be invoked } catch (InvocationTargetException x) { Throwable cause = x.getCause(); System.err.format("invocation of %s failed: %s%n", mname, cause.getMessage()); } catch (IllegalAccessException x) { x.printStackTrace(); } } } catch (Exception ex) { ex.printStackTrace(); } if (status) { out.println(tc + ":pass"); } else { out.println(tc + ":fail"); } } }
/** * Gets the current scoreboard and prints the users' names and scores in descending order. * * @return true if the scoreboard is printed successfully */ private boolean getScoreboard() { try { Class.forName("com.mysql.jdbc.Driver").newInstance(); conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/getoffthecouch", "XXXXXX", "XXXXXX"); Statement getScoresStmt = conn.createStatement(); String getScoresQuery = "SELECT user_id, user_name, total_score FROM user ORDER BY total_score DESC"; ResultSet getScoresResult = getScoresStmt.executeQuery(getScoresQuery); String userId = ""; String userName = ""; int totalScore = -1; while (getScoresResult.next()) { userId = getScoresResult.getString("user_id"); userName = getScoresResult.getString("user_name"); totalScore = getScoresResult.getInt("total_score"); out.println(userId + "|" + userName + "|" + totalScore); } getScoresStmt.close(); return true; } catch (InstantiationException e) { e.printStackTrace(out); return false; } catch (IllegalAccessException e) { e.printStackTrace(out); return false; } catch (ClassNotFoundException e) { e.printStackTrace(out); return false; } catch (SQLException e) { e.printStackTrace(out); return false; } }
/** * Processes the request coming to the servlet and grabs the attributes set by the servlet and * uses them to fire off pre-determined methods set in the setupActionMethods function of the * servlet. * * @param request the http request coming from the browser. * @param response the http response going to the browser. * @throws javax.servlet.ServletException * @throws java.io.IOException */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (!actionInitialized) { LogController.write(this, "This dispatcher servlet is not initialized properly!"); return; } if (actionTag == null) { LogController.write(this, "There is no action attribute tag name!"); return; } HttpSession httpSession = request.getSession(); UserSession userSession = (UserSession) httpSession.getAttribute("user_session"); if (userSession == null) { LogController.write(this, "User session is no longer available in this http session."); userSession = new UserSession(); // We always want a user session though... httpSession.setAttribute("user_session", userSession); } String action = (String) request.getAttribute(actionTag); try { if (action == null) { // There is no action attribute specified, check parameters. String external_action = (String) request.getParameter(actionTag); if (external_action != null) { Method method = externalActions.get(external_action); if (method != null) { LogController.write(this, "Performing external action: " + external_action); method.invoke(this, new Object[] {userSession, request, response}); } else { if (defaultExternalMethod != null) { LogController.write(this, "Performing default external action."); defaultExternalMethod.invoke(this, new Object[] {userSession, request, response}); } else { LogController.write(this, "Unable to perform default external action."); } } } else { if (defaultExternalMethod != null) { LogController.write(this, "Performing default external action."); defaultExternalMethod.invoke(this, new Object[] {userSession, request, response}); } else { LogController.write(this, "Unable to perform default external action."); } } } else { Method method = internalActions.get(action); if (method != null) { LogController.write(this, "Performing internal action: " + action); method.invoke(this, new Object[] {userSession, request, response}); } else { if (defaultInternalMethod != null) { LogController.write(this, "Performing default internal action."); defaultInternalMethod.invoke(this, new Object[] {userSession, request, response}); } else { LogController.write(this, "Unable to perform default internal action."); } } request.removeAttribute("application_action"); } } catch (IllegalAccessException accessEx) { LogController.write(this, "Exception while processing request: " + accessEx.getMessage()); } catch (InvocationTargetException invokeEx) { LogController.write(this, "Exception while processing request: " + invokeEx.toString()); invokeEx.printStackTrace(); } catch (Exception ex) { LogController.write(this, "Unknown exception: " + ex.toString()); } }
@Override public void contextInitialized(ServletContextEvent arg0) { final String S_ProcName = "contextInitialized"; Properties props = System.getProperties(); if (null == CFBamSchemaPool.getSchemaPool()) { try { Context ctx = new InitialContext(); String poolClassName = (String) ctx.lookup("java:comp/env/CFBam24PoolClass"); if ((poolClassName == null) || (poolClassName.length() <= 0)) { throw CFLib.getDefaultExceptionFactory() .newNullArgumentException( getClass(), S_ProcName, 0, "JNDI lookup for CFBam24PoolClass"); } Class poolClass = Class.forName(poolClassName); if (poolClass == null) { throw CFLib.getDefaultExceptionFactory() .newNullArgumentException( getClass(), S_ProcName, 0, "CFBam24PoolClass \"" + poolClassName + "\" not found."); } Object obj = poolClass.newInstance(); if (obj instanceof CFBamSchemaPool) { CFBamSchemaPool newPool = (CFBamSchemaPool) obj; newPool.setConfigurationFile(null); newPool.setJndiName("java:comp/env/CFBam24Connection"); CFBamSchemaPool.setSchemaPool(newPool); } else { throw CFLib.getDefaultExceptionFactory() .newRuntimeException( getClass(), S_ProcName, "Problems constructing an instance of " + poolClassName); } String smtpHost = (String) ctx.lookup("java:comp/env/CFBam24SmtpHost"); if ((smtpHost == null) || (smtpHost.length() <= 0)) { throw CFLib.getDefaultExceptionFactory() .newNullArgumentException( getClass(), S_ProcName, 0, "JNDI lookup for CFBam24SmtpHost"); } props.setProperty("mail.smtp.host", smtpHost); String smtpStartTLS = (String) ctx.lookup("java:comp/env/CFBam24SmtpStartTLS"); if ((smtpHost == null) || (smtpHost.length() <= 0)) { throw CFLib.getDefaultExceptionFactory() .newNullArgumentException( getClass(), S_ProcName, 0, "JNDI lookup for CFBam24SmtpStartTLS"); } props.setProperty("mail.smtp.starttls.enable", smtpStartTLS); String smtpSocketFactoryClass = (String) ctx.lookup("java:comp/env/CFBam24SmtpSocketFactoryClass"); if ((smtpSocketFactoryClass == null) || (smtpSocketFactoryClass.length() <= 0)) { throw CFLib.getDefaultExceptionFactory() .newNullArgumentException( getClass(), S_ProcName, 0, "JNDI lookup for CFBam24SmtpSocketFactoryClass"); } props.setProperty("mail.smtp.socketFactory.class", smtpSocketFactoryClass); props.setProperty("mail.smtp.socketFactory.fallback", "false"); String smtpPort = (String) ctx.lookup("java:comp/env/CFBam24SmtpPort"); if ((smtpPort == null) || (smtpPort.length() <= 0)) { throw CFLib.getDefaultExceptionFactory() .newNullArgumentException( getClass(), S_ProcName, 0, "JNDI lookup for CFBam24SmtpPort"); } props.setProperty("mail.smtp.port", smtpPort); props.setProperty("mail.smtp.socketFactory.port", smtpPort); props.setProperty("mail.smtps.auth", "true"); props.put("mail.smtps.quitwait", "false"); String smtpEmailFrom = (String) ctx.lookup("java:comp/env/CFBam24SmtpEmailFrom"); if ((smtpEmailFrom == null) || (smtpEmailFrom.length() <= 0)) { throw CFLib.getDefaultExceptionFactory() .newNullArgumentException( getClass(), S_ProcName, 0, "JNDI lookup for CFBam24SmtpEmailFrom"); } smtpUsername = (String) ctx.lookup("java:comp/env/CFBam24SmtpUsername"); if ((smtpUsername == null) || (smtpUsername.length() <= 0)) { throw CFLib.getDefaultExceptionFactory() .newNullArgumentException( getClass(), S_ProcName, 0, "JNDI lookup for CFBam24SmtpUsername"); } smtpPassword = (String) ctx.lookup("java:comp/env/CFBam24SmtpPassword"); if ((smtpPassword == null) || (smtpPassword.length() <= 0)) { throw CFLib.getDefaultExceptionFactory() .newNullArgumentException( getClass(), S_ProcName, 0, "JNDI lookup for CFBam24SmtpPassword"); } String serverKeyStore; try { serverKeyStore = (String) ctx.lookup("java:comp/env/CFBam24ServerKeyStore"); } catch (NamingException e) { serverKeyStore = null; } String keyStorePassword; try { keyStorePassword = (String) ctx.lookup("java:comp/env/CFBam24KeyStorePassword"); } catch (NamingException e) { keyStorePassword = null; } String keyName; try { keyName = (String) ctx.lookup("java:comp/env/CFBam24KeyName"); } catch (NamingException e) { keyName = null; } String keyPassword; try { keyPassword = (String) ctx.lookup("java:comp/env/CFBam24KeyPassword"); } catch (NamingException e) { keyPassword = null; } if (((serverKeyStore != null) && (serverKeyStore.length() > 0)) && (keyStorePassword != null) && ((keyName != null) && (keyName.length() > 0)) && (keyPassword != null)) { KeyStore keyStore = null; File keystoreFile = new File(serverKeyStore); if (!keystoreFile.exists()) { throw CFLib.getDefaultExceptionFactory() .newUsageException( getClass(), S_ProcName, "CFBam24ServerKeyStore file \"" + serverKeyStore + "\" does not exist."); } else if (!keystoreFile.isFile()) { throw CFLib.getDefaultExceptionFactory() .newUsageException( getClass(), S_ProcName, "CFBam24ServerKeyStore file \"" + serverKeyStore + "\" is not a file."); } else if (!keystoreFile.canRead()) { throw CFLib.getDefaultExceptionFactory() .newUsageException( getClass(), S_ProcName, "Permission denied attempting to read CFBam24ServerKeyStore file \"" + serverKeyStore + "\"."); } try { keyStore = KeyStore.getInstance("jceks"); char[] caPassword = keyStorePassword.toCharArray(); FileInputStream input = new FileInputStream(serverKeyStore); keyStore.load(input, caPassword); input.close(); Certificate publicKeyCertificate = keyStore.getCertificate(keyName); if (publicKeyCertificate == null) { throw CFLib.getDefaultExceptionFactory() .newUsageException( getClass(), S_ProcName, "Could not read CFBam24KeyName \"" + keyName + "\" from CFBam24ServerKeyStore file \"" + serverKeyStore + "\"."); } publicKey = publicKeyCertificate.getPublicKey(); char[] caKeyPassword = keyPassword.toCharArray(); Key key = keyStore.getKey(keyName, caKeyPassword); if (key instanceof PrivateKey) { privateKey = (PrivateKey) key; } else { throw CFLib.getDefaultExceptionFactory() .newUnsupportedClassException(getClass(), S_ProcName, "key", key, "PrivateKey"); } getServerInfo(); } catch (CertificateException x) { publicKey = null; privateKey = null; throw CFLib.getDefaultExceptionFactory() .newRuntimeException( getClass(), S_ProcName, "Could not open keystore due to CertificateException -- " + x.getMessage(), x); } catch (IOException x) { publicKey = null; privateKey = null; throw CFLib.getDefaultExceptionFactory() .newRuntimeException( getClass(), S_ProcName, "Could not open keystore due to IOException -- " + x.getMessage(), x); } catch (KeyStoreException x) { publicKey = null; privateKey = null; throw CFLib.getDefaultExceptionFactory() .newRuntimeException( getClass(), S_ProcName, "Could not open keystore due to KeyStoreException -- " + x.getMessage(), x); } catch (NoSuchAlgorithmException x) { publicKey = null; privateKey = null; throw CFLib.getDefaultExceptionFactory() .newRuntimeException( getClass(), S_ProcName, "Could not open keystore due to NoSuchAlgorithmException -- " + x.getMessage(), x); } catch (UnrecoverableKeyException x) { publicKey = null; privateKey = null; throw CFLib.getDefaultExceptionFactory() .newRuntimeException( getClass(), S_ProcName, "Could not access key due to UnrecoverableKeyException -- " + x.getMessage(), x); } catch (RuntimeException x) { publicKey = null; privateKey = null; throw x; } } else if ((serverKeyStore != null) || (keyStorePassword != null) || (keyName != null) || (keyPassword != null)) { publicKey = null; privateKey = null; throw CFLib.getDefaultExceptionFactory() .newUsageException( getClass(), S_ProcName, "All or none of CFBam24ServerKeyStore, " + "CFBam24KeyStorePassword, " + "CFBam24KeyName, and " + "CFBam24KeyPassword must be configured"); } else { getServerInfo(); try { serverInfo.initServerKeys(); } catch (Exception x) { throw CFLib.getDefaultExceptionFactory() .newRuntimeException( getClass(), S_ProcName, "Caught " + x.getClass().getName() + " during initServerKeys() -- " + x.getMessage(), x); } } } catch (ClassNotFoundException e) { publicKey = null; privateKey = null; throw CFLib.getDefaultExceptionFactory() .newRuntimeException( getClass(), S_ProcName, "Caught ClassNotFoundException -- " + e.getMessage(), e); } catch (IllegalAccessException e) { publicKey = null; privateKey = null; throw CFLib.getDefaultExceptionFactory() .newRuntimeException( getClass(), S_ProcName, "Caught IllegalAccessException trying to construct newInstance() -- " + e.getMessage(), e); } catch (InstantiationException e) { publicKey = null; privateKey = null; throw CFLib.getDefaultExceptionFactory() .newRuntimeException( getClass(), S_ProcName, "Caught InstantiationException trying to construct newInstance() -- " + e.getMessage(), e); } catch (NamingException e) { publicKey = null; privateKey = null; throw CFLib.getDefaultExceptionFactory() .newRuntimeException( getClass(), S_ProcName, "Caught NamingException -- " + e.getMessage(), e); } } }
/** * Gets the invitations from the database and prints their details. * * @param facebookId - Facebook id of the user * @return true if the list of invitation details are printed successfully */ private boolean getInvitations(String facebookId) { try { Class.forName("com.mysql.jdbc.Driver").newInstance(); conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/getoffthecouch", "XXXXXX", "XXXXXX"); Statement checkStmt = conn.createStatement(); String checkQuery = "SELECT COUNT(*) FROM invitation WHERE invitee='" + facebookId + "' AND confirmed=0"; ResultSet checkQueryResult = checkStmt.executeQuery(checkQuery); checkQueryResult.next(); int count = checkQueryResult.getInt(1); if (count == 0) { return false; } Statement getInvitationsStmt = conn.createStatement(); String getInvitationsQuery = "SELECT i.inv_id, l.loc_name, e.date, e.time, u.user_name, e.total_score, l.cat_id, i.event_id, l.photo_thumb " + "FROM invitation i, location l, event e, user u WHERE i.event_id=e.event_id AND e.loc_id = l.loc_id " + "AND i.invitee='" + facebookId + "' AND u.user_id=i.inviter AND i.confirmed=0"; ResultSet getInvitationsResult = getInvitationsStmt.executeQuery(getInvitationsQuery); int invitationId = -1; String locationName = ""; String dateAndTime = ""; String userName = ""; int totalScore = -1; int categoryId = -1; int eventId = -1; String photoThumb = ""; while (getInvitationsResult.next()) { invitationId = getInvitationsResult.getInt("inv_id"); locationName = getInvitationsResult.getString("loc_name"); String date = getInvitationsResult.getString("date"); String time = getInvitationsResult.getString("time"); SimpleDateFormat sqlFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { Date dateObject = sqlFormatter.parse(date + " " + time); SimpleDateFormat outputFormatter = new SimpleDateFormat("d MMM yyyy, HH:mm"); dateAndTime = outputFormatter.format(dateObject); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } userName = getInvitationsResult.getString("user_name"); totalScore = getInvitationsResult.getInt("total_score"); categoryId = getInvitationsResult.getInt("cat_id"); eventId = getInvitationsResult.getInt("event_id"); photoThumb = getInvitationsResult.getString("photo_thumb"); String output = invitationId + "|" + locationName + "|" + dateAndTime + "|" + userName + "|" + totalScore + "|" + categoryId + "|" + eventId + "|" + photoThumb; out.println(output); } getInvitationsStmt.close(); return true; } catch (InstantiationException e) { e.printStackTrace(out); return false; } catch (IllegalAccessException e) { e.printStackTrace(out); return false; } catch (ClassNotFoundException e) { e.printStackTrace(out); return false; } catch (SQLException e) { e.printStackTrace(out); return false; } }
/** * Get Query By Form results throught response output stream. * * @param queryspec Name of XML file containing the Query Specification * @param columnlist List of comma separated column names to retrieve * @param where SQL WHERE clause to apply * @param order by SQL ORDER BY clause to apply * @param showas Output format. One of { "CSV" <i>(comma separated)</i>, "TSV" <i>(tabbed * separated)</i>, "XLS" <i>(Excel)</i> } * @throws IOException * @throws FileNotFoundException * @throws ServletException */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, FileNotFoundException, ServletException { Class oDriver; Connection oConn = null; ServletOutputStream oOut = response.getOutputStream(); QueryByForm oQBF; String sQuerySpec; String sColumnList; String sWhere; String sOrderBy; String sShowAs; String sStorage; if (DebugFile.trace) { DebugFile.writeln("Begin HttpQueryServlet.doGet(...)"); DebugFile.incIdent(); } sStorage = Environment.getProfileVar("hipergate", "storage"); if (DebugFile.trace) DebugFile.writeln("storage=" + sStorage); try { oDriver = Class.forName(jdbcDriverClassName); } catch (ClassNotFoundException ignore) { oDriver = null; if (DebugFile.trace) DebugFile.writeln("Class.forName(" + jdbcDriverClassName + ") : " + ignore.getMessage()); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Database driver not found"); } if (null == oDriver) return; try { sQuerySpec = request.getParameter("queryspec"); sColumnList = request.getParameter("columnlist"); if (null == sColumnList) sColumnList = "*"; sWhere = request.getParameter("where"); if (null == sWhere) sWhere = "1=1"; sOrderBy = request.getParameter("orderby"); if (null == sOrderBy) sOrderBy = ""; sShowAs = request.getParameter("showas"); if (null == sShowAs) sShowAs = "CSV"; if (DebugFile.trace) DebugFile.writeln("queryspec=" + sQuerySpec != null ? sQuerySpec : "null"); if (DebugFile.trace) DebugFile.writeln("where=" + sWhere); if (DebugFile.trace) DebugFile.writeln("orderby=" + sOrderBy); if (hasSqlSignature(sColumnList)) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid Column List Syntax"); return; } oQBF = new QueryByForm("file://" + sStorage + "/qbf/" + sQuerySpec + ".xml"); if (DebugFile.trace) DebugFile.writeln("DriverManager.getConnection(" + jdbcURL + ",...)"); oConn = DriverManager.getConnection(jdbcURL, dbUserName, dbUserPassword); // Send some basic http headers to support binary d/l. if (sShowAs.equalsIgnoreCase("XLS")) { response.setContentType("application/x-msexcel"); response.setHeader( "Content-Disposition", "inline; filename=\"" + oQBF.getTitle(request.getLocale().getLanguage()) + " 1.csv\""); } else if (sShowAs.equalsIgnoreCase("CSV")) { response.setContentType("text/plain"); response.setHeader( "Content-Disposition", "attachment; filename=\"" + oQBF.getTitle(request.getLocale().getLanguage()) + " 1.csv\""); } else if (sShowAs.equalsIgnoreCase("TSV")) { response.setContentType("text/tab-separated-values"); response.setHeader( "Content-Disposition", "attachment; filename=\"" + oQBF.getTitle(request.getLocale().getLanguage()) + " 1.tsv\""); } else { response.setContentType("text/plain"); response.setHeader( "Content-Disposition", "inline; filename=\"" + oQBF.getTitle(request.getLocale().getLanguage()) + " 1.txt\""); } if (0 == sOrderBy.length()) oQBF.queryToStream( oConn, sColumnList, oQBF.getBaseFilter(request) + " " + sWhere, oOut, sShowAs); else oQBF.queryToStream( oConn, sColumnList, oQBF.getBaseFilter(request) + " " + sWhere + " ORDER BY " + sOrderBy, oOut, sShowAs); oConn.close(); oConn = null; oOut.flush(); } catch (SQLException e) { if (DebugFile.trace) DebugFile.writeln("SQLException " + e.getMessage()); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } catch (ClassNotFoundException e) { if (DebugFile.trace) DebugFile.writeln("ClassNotFoundException " + e.getMessage()); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } catch (IllegalAccessException e) { if (DebugFile.trace) DebugFile.writeln("IllegalAccessException " + e.getMessage()); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } catch (Exception e) { if (DebugFile.trace) DebugFile.writeln("Exception " + e.getMessage()); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } finally { try { if (null != oConn) if (!oConn.isClosed()) oConn.close(); } catch (SQLException e) { if (DebugFile.trace) DebugFile.writeln("SQLException " + e.getMessage()); } } if (DebugFile.trace) { DebugFile.decIdent(); DebugFile.writeln("End HttpQueryServlet.doGet()"); } } // doGet()