repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/OrdersAlertFilter.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web; import java.io.IOException; import java.util.Collection; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import com.ibm.websphere.samples.daytrader.TradeAction; import com.ibm.websphere.samples.daytrader.TradeServices; import com.ibm.websphere.samples.daytrader.util.Log; import com.ibm.websphere.samples.daytrader.util.TradeConfig; @WebFilter(filterName = "OrdersAlertFilter", urlPatterns = "/app") public class OrdersAlertFilter implements Filter { /** * Constructor for CompletedOrdersAlertFilter */ public OrdersAlertFilter() { super(); } /** * @see Filter#init(FilterConfig) */ private FilterConfig filterConfig = null; @Override public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig = filterConfig; } /** * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain) */ @Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { if (filterConfig == null) { return; } if (TradeConfig.getDisplayOrderAlerts() == true) { try { String action = req.getParameter("action"); if (action != null) { action = action.trim(); if ((action.length() > 0) && (!action.equals("logout"))) { String userID; if (action.equals("login")) { userID = req.getParameter("uid"); } else { userID = (String) ((HttpServletRequest) req).getSession().getAttribute("uidBean"); } if ((userID != null) && (userID.trim().length() > 0)) { TradeServices tAction = null; tAction = new TradeAction(); Collection<?> closedOrders = tAction.getClosedOrders(userID); if ((closedOrders != null) && (closedOrders.size() > 0)) { req.setAttribute("closedOrders", closedOrders); } if (Log.doTrace()) { Log.printCollection("OrderAlertFilter: userID=" + userID + " closedOrders=", closedOrders); } } } } } catch (Exception e) { Log.error(e, "OrdersAlertFilter - Error checking for closedOrders"); } } chain.doFilter(req, resp/* wrapper */); } /** * @see Filter#destroy() */ @Override public void destroy() { this.filterConfig = null; } }
3,723
33.481481
124
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/TestServlet.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web; import java.io.IOException; import java.math.BigDecimal; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ibm.websphere.samples.daytrader.TradeAction; import com.ibm.websphere.samples.daytrader.util.Log; import com.ibm.websphere.samples.daytrader.util.TradeConfig; @WebServlet(name = "TestServlet", urlPatterns = { "/TestServlet" }) public class TestServlet extends HttpServlet { private static final long serialVersionUID = -2927579146688173127L; @Override public void init(ServletConfig config) throws ServletException { super.init(config); } /** * Process incoming HTTP GET requests * * @param request * Object that encapsulates the request to the servlet * @param response * Object that encapsulates the response from the servlet */ @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { performTask(request, response); } /** * Process incoming HTTP POST requests * * @param request * Object that encapsulates the request to the servlet * @param response * Object that encapsulates the response from the servlet */ @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { performTask(request, response); } /** * Main service method for TradeAppServlet * * @param request * Object that encapsulates the request to the servlet * @param response * Object that encapsulates the response from the servlet */ public void performTask(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { Log.debug("Enter TestServlet doGet"); TradeConfig.runTimeMode = TradeConfig.DIRECT; for (int i = 0; i < 10; i++) { new TradeAction().createQuote("s:" + i, "Company " + i, new BigDecimal(i * 1.1)); } /* * * AccountDataBean accountData = new TradeAction().register("user1", * "password", "fullname", "address", "email", "creditCard", new * BigDecimal(123.45), false); * * OrderDataBean orderData = new TradeAction().buy("user1", "s:1", * 100.0); orderData = new TradeAction().buy("user1", "s:2", 200.0); * Thread.sleep(5000); accountData = new * TradeAction().getAccountData("user1"); Collection * holdingDataBeans = new TradeAction().getHoldings("user1"); * PrintWriter out = resp.getWriter(); * resp.setContentType("text/html"); * out.write("<HEAD></HEAD><BODY><BR><BR>"); * out.write(accountData.toString()); * Log.printCollection("user1 Holdings", holdingDataBeans); * ServletContext sc = getServletContext(); * req.setAttribute("results", "Success"); * req.setAttribute("accountData", accountData); * req.setAttribute("holdingDataBeans", holdingDataBeans); * getServletContext * ().getRequestDispatcher("/tradehome.jsp").include(req, resp); * out.write("<BR><BR>done.</BODY>"); */ } catch (Exception e) { Log.error("TestServletException", e); } } }
4,355
37.892857
119
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/TradeAppServlet.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web; import java.io.IOException; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.ibm.websphere.samples.daytrader.util.Log; import com.ibm.websphere.samples.daytrader.util.TradeConfig; /** * * TradeAppServlet provides the standard web interface to Trade and can be * accessed with the Go Trade! link. Driving benchmark load using this interface * requires a sophisticated web load generator that is capable of filling HTML * forms and posting dynamic data. */ @WebServlet(name = "TradeAppServlet", urlPatterns = { "/app" }) public class TradeAppServlet extends HttpServlet { private static final long serialVersionUID = 481530522846648373L; /** * Servlet initialization method. */ @Override public void init(ServletConfig config) throws ServletException { super.init(config); java.util.Enumeration<String> en = config.getInitParameterNames(); while (en.hasMoreElements()) { String parm = en.nextElement(); String value = config.getInitParameter(parm); TradeConfig.setConfigParam(parm, value); } try { // TODO: Uncomment this once split-tier issue is resolved // TradeDirect.init(); } catch (Exception e) { Log.error(e, "TradeAppServlet:init -- Error initializing TradeDirect"); } } /** * Returns a string that contains information about TradeScenarioServlet * * @return The servlet information */ @Override public java.lang.String getServletInfo() { return "TradeAppServlet provides the standard web interface to Trade"; } /** * Process incoming HTTP GET requests * * @param request * Object that encapsulates the request to the servlet * @param response * Object that encapsulates the response from the servlet */ @Override public void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws ServletException, IOException { performTask(request, response); } /** * Process incoming HTTP POST requests * * @param request * Object that encapsulates the request to the servlet * @param response * Object that encapsulates the response from the servlet */ @Override public void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws ServletException, IOException { performTask(request, response); } /** * Main service method for TradeAppServlet * * @param request * Object that encapsulates the request to the servlet * @param response * Object that encapsulates the response from the servlet */ public void performTask(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String action = null; String userID = null; // String to create full dispatch path to TradeAppServlet w/ request // Parameters resp.setContentType("text/html"); TradeServletAction tsAction = new TradeServletAction(); // Dyna - need status string - prepended to output action = req.getParameter("action"); ServletContext ctx = getServletConfig().getServletContext(); if (action == null) { tsAction.doWelcome(ctx, req, resp, ""); return; } else if (action.equals("login")) { userID = req.getParameter("uid"); String passwd = req.getParameter("passwd"); tsAction.doLogin(ctx, req, resp, userID, passwd); return; } else if (action.equals("register")) { userID = req.getParameter("user id"); String passwd = req.getParameter("passwd"); String cpasswd = req.getParameter("confirm passwd"); String fullname = req.getParameter("Full Name"); String ccn = req.getParameter("Credit Card Number"); String money = req.getParameter("money"); String email = req.getParameter("email"); String smail = req.getParameter("snail mail"); tsAction.doRegister(ctx, req, resp, userID, passwd, cpasswd, fullname, ccn, money, email, smail); return; } // The rest of the operations require the user to be logged in - // Get the Session and validate the user. HttpSession session = req.getSession(); userID = (String) session.getAttribute("uidBean"); if (userID == null) { System.out.println("TradeAppServlet service error: User Not Logged in"); tsAction.doWelcome(ctx, req, resp, "User Not Logged in"); return; } if (action.equals("quotes")) { String symbols = req.getParameter("symbols"); tsAction.doQuotes(ctx, req, resp, userID, symbols); } else if (action.equals("buy")) { String symbol = req.getParameter("symbol"); String quantity = req.getParameter("quantity"); tsAction.doBuy(ctx, req, resp, userID, symbol, quantity); } else if (action.equals("sell")) { int holdingID = Integer.parseInt(req.getParameter("holdingID")); tsAction.doSell(ctx, req, resp, userID, new Integer(holdingID)); } else if (action.equals("portfolio") || action.equals("portfolioNoEdge")) { tsAction.doPortfolio(ctx, req, resp, userID, "Portfolio as of " + new java.util.Date()); } else if (action.equals("logout")) { tsAction.doLogout(ctx, req, resp, userID); } else if (action.equals("home")) { tsAction.doHome(ctx, req, resp, userID, "Ready to Trade"); } else if (action.equals("account")) { tsAction.doAccount(ctx, req, resp, userID, ""); } else if (action.equals("update_profile")) { String password = req.getParameter("password"); String cpassword = req.getParameter("cpassword"); String fullName = req.getParameter("fullname"); String address = req.getParameter("address"); String creditcard = req.getParameter("creditcard"); String email = req.getParameter("email"); tsAction.doAccountUpdate(ctx, req, resp, userID, password == null ? "" : password.trim(), cpassword == null ? "" : cpassword.trim(), fullName == null ? "" : fullName.trim(), address == null ? "" : address.trim(), creditcard == null ? "" : creditcard.trim(), email == null ? "" : email.trim()); } else if (action.equals("mksummary")) { tsAction.doMarketSummary(ctx, req, resp, userID); } else { System.out.println("TradeAppServlet: Invalid Action=" + action); tsAction.doWelcome(ctx, req, resp, "TradeAppServlet: Invalid Action" + action); } } }
7,936
40.554974
157
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/TradeBuildDB.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.math.BigDecimal; import java.util.ArrayList; import com.ibm.websphere.samples.daytrader.direct.TradeDirect; import com.ibm.websphere.samples.daytrader.entities.AccountDataBean; import com.ibm.websphere.samples.daytrader.util.Log; import com.ibm.websphere.samples.daytrader.util.TradeConfig; /** * TradeBuildDB uses operations provided by the TradeApplication to (a) create the Database tables * (b)populate a DayTrader database without creating the tables. Specifically, a * new DayTrader User population is created using UserIDs of the form "uid:xxx" * where xxx is a sequential number (e.g. uid:0, uid:1, etc.). New stocks are also created of the * form "s:xxx", again where xxx represents sequential numbers (e.g. s:1, s:2, etc.) */ public class TradeBuildDB { /** * Populate a Trade DB using standard out as a log */ public TradeBuildDB() throws Exception { this(new java.io.PrintWriter(System.out), null); } /** * Re-create the DayTrader db tables and populate them OR just populate a DayTrader DB, logging to the provided output stream */ public TradeBuildDB(java.io.PrintWriter out, InputStream ddlFile) throws Exception { String symbol, companyName; int errorCount = 0; // Give up gracefully after 10 errors // Build db in direct mode because it is faster TradeDirect tradeDirect = new TradeDirect(); // TradeStatistics.statisticsEnabled=false; // disable statistics out.println("<HEAD><BR><EM> TradeBuildDB: Building DayTrader Database...</EM><BR> This operation will take several minutes. Please wait...</HEAD>"); out.println("<BODY>"); if (ddlFile != null) { //out.println("<BR>TradeBuildDB: **** warPath= "+warPath+" ****</BR></BODY>"); boolean success = false; Object[] sqlBuffer = null; //parse the DDL file and fill the SQL commands into a buffer try { sqlBuffer = parseDDLToBuffer(ddlFile); } catch (Exception e) { Log.error(e, "TradeBuildDB: Unable to parse DDL file"); out.println("<BR>TradeBuildDB: **** Unable to parse DDL file for the specified database ****</BR></BODY>"); return; } if ((sqlBuffer == null) || (sqlBuffer.length == 0)) { out.println("<BR>TradeBuildDB: **** Parsing DDL file returned empty buffer, please check that a valid DB specific DDL file is available and retry ****</BR></BODY>"); return; } // send the sql commands buffer to drop and recreate the Daytrader tables out.println("<BR>TradeBuildDB: **** Dropping and Recreating the DayTrader tables... ****</BR>"); try { success = tradeDirect.recreateDBTables(sqlBuffer, out); } catch (Exception e) { Log.error(e, "TradeBuildDB: Unable to drop and recreate DayTrader Db Tables, please check for database consistency before continuing"); out.println("TradeBuildDB: Unable to drop and recreate DayTrader Db Tables, please check for database consistency before continuing"); return; } if (!success) { out.println("<BR>TradeBuildDB: **** Unable to drop and recreate DayTrader Db Tables, please check for database consistency before continuing ****</BR></BODY>"); return; } out.println("<BR>TradeBuildDB: **** DayTrader tables successfully created! ****</BR><BR><b> Please Stop and Re-start your Daytrader application (or your application server) and then use the \"Repopulate Daytrader Database\" link to populate your database.</b></BR><BR><BR></BODY>"); return; } // end of createDBTables out.println("<BR>TradeBuildDB: **** Creating " + TradeConfig.getMAX_QUOTES() + " Quotes ****</BR>"); //Attempt to delete all of the Trade users and Trade Quotes first try { tradeDirect.resetTrade(true); } catch (Exception e) { Log.error(e, "TradeBuildDB: Unable to delete Trade users (uid:0, uid:1, ...) and Trade Quotes (s:0, s:1, ...)"); } for (int i = 0; i < TradeConfig.getMAX_QUOTES(); i++) { symbol = "s:" + i; companyName = "S" + i + " Incorporated"; try { tradeDirect.createQuote(symbol, companyName, new java.math.BigDecimal(TradeConfig.rndPrice())); if (i % 10 == 0) { out.print("....." + symbol); if (i % 100 == 0) { out.println(" -<BR>"); out.flush(); } } } catch (Exception e) { if (errorCount++ >= 10) { String error = "Populate Trade DB aborting after 10 create quote errors. Check the EJB datasource configuration. Check the log for details <BR><BR> Exception is: <BR> " + e.toString(); Log.error(e, error); throw e; } } } out.println("<BR>"); out.println("<BR>**** Registering " + TradeConfig.getMAX_USERS() + " Users **** "); errorCount = 0; //reset for user registrations // Registration is a formal operation in Trade 2. for (int i = 0; i < TradeConfig.getMAX_USERS(); i++) { String userID = "uid:" + i; String fullname = TradeConfig.rndFullName(); String email = TradeConfig.rndEmail(userID); String address = TradeConfig.rndAddress(); String creditcard = TradeConfig.rndCreditCard(); double initialBalance = (double) (TradeConfig.rndInt(100000)) + 200000; if (i == 0) { initialBalance = 1000000; // uid:0 starts with a cool million. } try { AccountDataBean accountData = tradeDirect.register(userID, "xxx", fullname, address, email, creditcard, new BigDecimal(initialBalance)); if (accountData != null) { if (i % 50 == 0) { out.print("<BR>Account# " + accountData.getAccountID() + " userID=" + userID); } // end-if int holdings = TradeConfig.rndInt(TradeConfig.getMAX_HOLDINGS() + 1); // 0-MAX_HOLDING (inclusive), avg holdings per user = (MAX-0)/2 double quantity = 0; for (int j = 0; j < holdings; j++) { symbol = TradeConfig.rndSymbol(); quantity = TradeConfig.rndQuantity(); tradeDirect.buy(userID, symbol, quantity, TradeConfig.orderProcessingMode); } // end-for if (i % 50 == 0) { out.println(" has " + holdings + " holdings."); out.flush(); } // end-if } else { out.println("<BR>UID " + userID + " already registered.</BR>"); out.flush(); } // end-if } catch (Exception e) { if (errorCount++ >= 10) { String error = "Populate Trade DB aborting after 10 user registration errors. Check the log for details. <BR><BR> Exception is: <BR>" + e.toString(); Log.error(e, error); throw e; } } } // end-for out.println("</BODY>"); } public Object[] parseDDLToBuffer(InputStream ddlFile) throws Exception { BufferedReader br = null; ArrayList<String> sqlBuffer = new ArrayList<String>(30); //initial capacity 30 assuming we have 30 ddl-sql statements to read try { if (Log.doTrace()) Log.traceEnter("TradeBuildDB:parseDDLToBuffer - " + ddlFile); br = new BufferedReader(new InputStreamReader(ddlFile)); String s; String sql = new String(); while ((s = br.readLine()) != null) { s = s.trim(); if ((s.length() != 0) && (s.charAt(0) != '#')) // Empty lines or lines starting with "#" are ignored { sql = sql + " " + s; if (s.endsWith(";")) { // reached end of sql statement sql = sql.replace(';', ' '); //remove the semicolon sqlBuffer.add(sql); sql = ""; } } } } catch (IOException ex) { Log.error("TradeBuildDB:parseDDLToBuffer Exeception during open/read of File: " + ddlFile, ex); throw ex; } finally { if (br != null) { try { br.close(); } catch (IOException ex) { Log.error("TradeBuildDB:parseDDLToBuffer Failed to close BufferedReader", ex); } } } return sqlBuffer.toArray(); } public static void main(String[] args) throws Exception { new TradeBuildDB(); } }
10,060
44.731818
294
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/TradeConfigServlet.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web; import java.io.IOException; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ibm.websphere.samples.daytrader.TradeAction; import com.ibm.websphere.samples.daytrader.beans.RunStatsDataBean; import com.ibm.websphere.samples.daytrader.direct.TradeDirect; import com.ibm.websphere.samples.daytrader.util.Log; import com.ibm.websphere.samples.daytrader.util.TradeConfig; /** * TradeConfigServlet provides a servlet interface to adjust DayTrader runtime parameters. * TradeConfigServlet updates values in the {@link com.ibm.websphere.samples.daytrader.web.TradeConfig} JavaBean holding * all configuration and runtime parameters for the Trade application * */ @WebServlet(name = "TradeConfigServlet", urlPatterns = { "/config" }) public class TradeConfigServlet extends HttpServlet { private static final long serialVersionUID = -1910381529792500095L; /** * Servlet initialization method. */ @Override public void init(ServletConfig config) throws ServletException { super.init(config); } /** * Create the TradeConfig bean and pass it the config.jsp page * to display the current Trade runtime configuration * Creation date: (2/8/2000 3:43:59 PM) */ void doConfigDisplay(HttpServletRequest req, HttpServletResponse resp, String results) throws Exception { TradeConfig currentConfig = new TradeConfig(); req.setAttribute("tradeConfig", currentConfig); req.setAttribute("status", results); getServletConfig().getServletContext().getRequestDispatcher(TradeConfig.getPage(TradeConfig.CONFIG_PAGE)).include(req, resp); } void doResetTrade(HttpServletRequest req, HttpServletResponse resp, String results) throws Exception { RunStatsDataBean runStatsData = new RunStatsDataBean(); TradeConfig currentConfig = new TradeConfig(); try { runStatsData = new TradeAction().resetTrade(false); req.setAttribute("runStatsData", runStatsData); req.setAttribute("tradeConfig", currentConfig); results += "Trade Reset completed successfully"; req.setAttribute("status", results); } catch (Exception e) { results += "Trade Reset Error - see log for details"; Log.error(e, results); throw e; } getServletConfig().getServletContext().getRequestDispatcher(TradeConfig.getPage(TradeConfig.STATS_PAGE)).include(req, resp); } /** * Update Trade runtime configuration paramaters * Creation date: (2/8/2000 3:44:24 PM) */ void doConfigUpdate(HttpServletRequest req, HttpServletResponse resp) throws Exception { String currentConfigStr = "\n\n########## Trade configuration update. Current config:\n\n"; String runTimeModeStr = req.getParameter("RunTimeMode"); if (runTimeModeStr != null) { try { int i = Integer.parseInt(runTimeModeStr); if ((i >= 0) && (i < TradeConfig.runTimeModeNames.length)) //Input validation TradeConfig.setRunTimeMode(i); } catch (Exception e) { //>>rjm Log.error(e, "TradeConfigServlet.doConfigUpdate(..): minor exception caught", "trying to set runtimemode to " + runTimeModeStr, "reverting to current value"); } // If the value is bad, simply revert to current } currentConfigStr += "\t\tRunTimeMode:\t\t\t" + TradeConfig.runTimeModeNames[TradeConfig.runTimeMode] + "\n"; String useRemoteEJBInterface = req.getParameter("UseRemoteEJBInterface"); if (useRemoteEJBInterface != null) TradeConfig.setUseRemoteEJBInterface(true); else TradeConfig.setDisplayOrderAlerts(false); currentConfigStr += "\t\tUse Remote EJB Interface:\t" + TradeConfig.useRemoteEJBInterface() + "\n"; String orderProcessingModeStr = req.getParameter("OrderProcessingMode"); if (orderProcessingModeStr != null) { try { int i = Integer.parseInt(orderProcessingModeStr); if ((i >= 0) && (i < TradeConfig.orderProcessingModeNames.length)) //Input validation TradeConfig.setOrderProcessingMode(i); } catch (Exception e) { //>>rjm Log.error(e, "TradeConfigServlet.doConfigUpdate(..): minor exception caught", "trying to set orderProcessing to " + orderProcessingModeStr, "reverting to current value"); } // If the value is bad, simply revert to current } currentConfigStr += "\t\tOrderProcessingMode:\t\t" + TradeConfig.orderProcessingModeNames[TradeConfig.orderProcessingMode] + "\n"; String webInterfaceStr = req.getParameter("WebInterface"); if (webInterfaceStr != null) { try { int i = Integer.parseInt(webInterfaceStr); if ((i >= 0) && (i < TradeConfig.webInterfaceNames.length)) //Input validation TradeConfig.setWebInterface(i); } catch (Exception e) { Log.error(e, "TradeConfigServlet.doConfigUpdate(..): minor exception caught", "trying to set WebInterface to " + webInterfaceStr, "reverting to current value"); } // If the value is bad, simply revert to current } currentConfigStr += "\t\tWeb Interface:\t\t\t" + TradeConfig.webInterfaceNames[TradeConfig.webInterface] + "\n"; /* String cachingTypeStr = req.getParameter("CachingType"); if (cachingTypeStr != null) { try { int i = Integer.parseInt(cachingTypeStr); if ((i >= 0) && (i < TradeConfig.cachingTypeNames.length)) //Input validation TradeConfig.setCachingType(i); } catch (Exception e) { Log.error(e, "TradeConfigServlet.doConfigUpdate(..): minor exception caught", "trying to set CachingType to " + cachingTypeStr, "reverting to current value"); } // If the value is bad, simply revert to current } currentConfigStr += "\t\tCachingType:\t\t\t" + TradeConfig.cachingTypeNames[TradeConfig.cachingType] + "\n"; String distMapCacheSize = req.getParameter("DistMapCacheSize"); if ((distMapCacheSize != null) && (distMapCacheSize.length() > 0)) { try { TradeConfig.setDistributedMapCacheSize(Integer.parseInt(distMapCacheSize)); } catch (Exception e) { Log.error(e, "TradeConfigServlet: minor exception caught", "trying to set DistributedMapCacheSize, error on parsing int " + distMapCacheSize, "reverting to current value " + TradeConfig.getPrimIterations()); } } currentConfigStr += "\t\tDMap Cache Size:\t\t" + TradeConfig.getDistributedMapCacheSize() + "\n"; */ String parm = req.getParameter("MaxUsers"); if ((parm != null) && (parm.length() > 0)) { try { TradeConfig.setMAX_USERS(Integer.parseInt(parm)); } catch (Exception e) { Log.error(e, "TradeConfigServlet.doConfigUpdate(..): minor exception caught", "Setting maxusers, probably error parsing string to int:" + parm, "revertying to current value: " + TradeConfig.getMAX_USERS()); } //On error, revert to saved } parm = req.getParameter("MaxQuotes"); if ((parm != null) && (parm.length() > 0)) { try { TradeConfig.setMAX_QUOTES(Integer.parseInt(parm)); } catch (Exception e) { //>>rjm Log.error(e, "TradeConfigServlet: minor exception caught", "trying to set max_quotes, error on parsing int " + parm, "reverting to current value " + TradeConfig.getMAX_QUOTES()); //<<rjm } //On error, revert to saved } currentConfigStr += "\t\tTrade Users:\t\t\t" + TradeConfig.getMAX_USERS() + "\n"; currentConfigStr += "\t\tTrade Quotes:\t\t\t" + TradeConfig.getMAX_QUOTES() + "\n"; parm = req.getParameter("marketSummaryInterval"); if ((parm != null) && (parm.length() > 0)) { try { TradeConfig.setMarketSummaryInterval(Integer.parseInt(parm)); } catch (Exception e) { Log.error(e, "TradeConfigServlet: minor exception caught", "trying to set marketSummaryInterval, error on parsing int " + parm, "reverting to current value " + TradeConfig.getMarketSummaryInterval()); } } currentConfigStr += "\t\tMarket Summary Interval:\t" + TradeConfig.getMarketSummaryInterval() + "\n"; parm = req.getParameter("primIterations"); if ((parm != null) && (parm.length() > 0)) { try { TradeConfig.setPrimIterations(Integer.parseInt(parm)); } catch (Exception e) { Log.error(e, "TradeConfigServlet: minor exception caught", "trying to set primIterations, error on parsing int " + parm, "reverting to current value " + TradeConfig.getPrimIterations()); } } currentConfigStr += "\t\tPrimitive Iterations:\t\t" + TradeConfig.getPrimIterations() + "\n"; String enablePublishQuotePriceChange = req.getParameter("EnablePublishQuotePriceChange"); if (enablePublishQuotePriceChange != null) TradeConfig.setPublishQuotePriceChange(true); else TradeConfig.setPublishQuotePriceChange(false); currentConfigStr += "\t\tTradeStreamer MDB Enabled:\t" + TradeConfig.getPublishQuotePriceChange() + "\n"; parm = req.getParameter("percentSentToWebsocket"); if ((parm != null) && (parm.length() > 0)) { try { TradeConfig.setPercentSentToWebsocket(Integer.parseInt(parm)); } catch (Exception e) { Log.error(e, "TradeConfigServlet: minor exception caught", "trying to set percentSentToWebSocket, error on parsing int " + parm, "reverting to current value " + TradeConfig.getPercentSentToWebsocket()); } } currentConfigStr += "\t\t% of trades on Websocket:\t" + TradeConfig.getPercentSentToWebsocket() + "\n"; String enableLongRun = req.getParameter("EnableLongRun"); if (enableLongRun != null) TradeConfig.setLongRun(true); else TradeConfig.setLongRun(false); currentConfigStr += "\t\tLong Run Enabled:\t\t" + TradeConfig.getLongRun() + "\n"; String displayOrderAlerts = req.getParameter("DisplayOrderAlerts"); if (displayOrderAlerts != null) TradeConfig.setDisplayOrderAlerts(true); else TradeConfig.setDisplayOrderAlerts(false); currentConfigStr += "\t\tDisplay Order Alerts:\t\t" + TradeConfig.getDisplayOrderAlerts() + "\n"; String enableTrace = req.getParameter("EnableTrace"); if (enableTrace != null) Log.setTrace(true); else Log.setTrace(false); currentConfigStr += "\t\tTrace Enabled:\t\t\t" + TradeConfig.getTrace() + "\n"; String enableActionTrace = req.getParameter("EnableActionTrace"); if (enableActionTrace != null) Log.setActionTrace(true); else Log.setActionTrace(false); currentConfigStr += "\t\tAction Trace Enabled:\t\t" + TradeConfig.getActionTrace() + "\n"; System.out.println(currentConfigStr); } @Override public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String action = null; String result = ""; resp.setContentType("text/html"); try { action = req.getParameter("action"); if (action == null) { doConfigDisplay(req, resp, result + "<b><br>Current DayTrader Configuration:</br></b>"); return; } else if (action.equals("updateConfig")) { doConfigUpdate(req, resp); result = "<B><BR>DayTrader Configuration Updated</BR></B>"; } else if (action.equals("resetTrade")) { doResetTrade(req, resp, ""); return; } else if (action.equals("buildDB")) { resp.setContentType("text/html"); new TradeBuildDB(resp.getWriter(), null); result = "DayTrader Database Built - " + TradeConfig.getMAX_USERS() + "users created"; } else if (action.equals("buildDBTables")) { resp.setContentType("text/html"); //Find out the Database being used TradeDirect tradeDirect = new TradeDirect(); String dbProductName = null; try { dbProductName = tradeDirect.checkDBProductName(); } catch (Exception e) { Log.error(e, "TradeBuildDB: Unable to check DB Product name"); } if (dbProductName == null) { resp.getWriter().println( "<BR>TradeBuildDB: **** Unable to check DB Product name, please check Database/AppServer configuration and retry ****</BR></BODY>"); return; } String ddlFile = null; //Locate DDL file for the specified database try { resp.getWriter().println("<BR>TradeBuildDB: **** Database Product detected: " + dbProductName + " ****</BR>"); if (dbProductName.startsWith("DB2/")) {// if db is DB2 ddlFile = "/dbscripts/db2/Table.ddl"; } else if (dbProductName.startsWith("DB2 UDB for AS/400")) { //if db is DB2 on IBM i ddlFile = "/dbscripts/db2i/Table.ddl"; } else if (dbProductName.startsWith("Apache Derby")) { //if db is Derby ddlFile = "/dbscripts/derby/Table.ddl"; } else if (dbProductName.startsWith("Oracle")) { // if the Db is Oracle ddlFile = "/dbscripts/oracle/Table.ddl"; } else {// Unsupported "Other" Database, try derby ddl ddlFile = "/dbscripts/derby/Table.ddl"; resp.getWriter().println("<BR>TradeBuildDB: **** This Database is unsupported/untested use at your own risk ****</BR>"); } resp.getWriter().println("<BR>TradeBuildDB: **** The DDL file at path <I>" + ddlFile + "</I> will be used ****</BR>"); resp.getWriter().flush(); } catch (Exception e) { Log.error(e, "TradeBuildDB: Unable to locate DDL file for the specified database"); resp.getWriter().println("<BR>TradeBuildDB: **** Unable to locate DDL file for the specified database ****</BR></BODY>"); return; } new TradeBuildDB(resp.getWriter(), getServletContext().getResourceAsStream(ddlFile)); } doConfigDisplay(req, resp, result + "Current DayTrader Configuration:"); } catch (Exception e) { Log.error(e, "TradeConfigServlet.service(...)", "Exception trying to perform action=" + action); resp.sendError(500, "TradeConfigServlet.service(...)" + "Exception trying to perform action=" + action + "\nException details: " + e.toString()); } } }
16,637
46.673352
160
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/TradeScenarioServlet.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web; import java.io.IOException; import java.io.PrintWriter; import java.util.Collection; import java.util.Iterator; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.ibm.websphere.samples.daytrader.entities.HoldingDataBean; import com.ibm.websphere.samples.daytrader.util.Log; import com.ibm.websphere.samples.daytrader.util.TradeConfig; /** * TradeScenarioServlet emulates a population of web users by generating a * specific Trade operation for a randomly chosen user on each access to the * URL. Test this servlet by clicking Trade Scenario and hit "Reload" on your * browser to step through a Trade Scenario. To benchmark using this URL aim * your favorite web load generator (such as AKStress) at the Trade Scenario URL * and fire away. */ @WebServlet(name = "TradeScenarioServlet", urlPatterns = { "/scenario" }) public class TradeScenarioServlet extends HttpServlet { private static final long serialVersionUID = 1410005249314201829L; /** * Servlet initialization method. */ @Override public void init(ServletConfig config) throws ServletException { super.init(config); java.util.Enumeration<String> en = config.getInitParameterNames(); while (en.hasMoreElements()) { String parm = en.nextElement(); String value = config.getInitParameter(parm); TradeConfig.setConfigParam(parm, value); } } /** * Returns a string that contains information about TradeScenarioServlet * * @return The servlet information */ @Override public java.lang.String getServletInfo() { return "TradeScenarioServlet emulates a population of web users"; } /** * Process incoming HTTP GET requests * * @param request * Object that encapsulates the request to the servlet * @param response * Object that encapsulates the response from the servlet */ @Override public void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws ServletException, IOException { performTask(request, response); } /** * Process incoming HTTP POST requests * * @param request * Object that encapsulates the request to the servlet * @param response * Object that encapsulates the response from the servlet */ @Override public void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws ServletException, IOException { performTask(request, response); } /** * Main service method for TradeScenarioServlet * * @param request * Object that encapsulates the request to the servlet * @param response * Object that encapsulates the response from the servlet */ public void performTask(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Scenario generator for Trade2 char action = ' '; String userID = null; // String to create full dispatch path to TradeAppServlet w/ request // Parameters String dispPath = null; // Dispatch Path to TradeAppServlet resp.setContentType("text/html"); String scenarioAction = req.getParameter("action"); if ((scenarioAction != null) && (scenarioAction.length() >= 1)) { action = scenarioAction.charAt(0); if (action == 'n') { // null; try { // resp.setContentType("text/html"); PrintWriter out = new PrintWriter(resp.getOutputStream()); out.println("<HTML><HEAD>TradeScenarioServlet</HEAD><BODY>Hello</BODY></HTML>"); out.close(); return; } catch (Exception e) { Log.error("trade_client.TradeScenarioServlet.service(...)" + "error creating printwriter from responce.getOutputStream", e); resp.sendError(500, "trade_client.TradeScenarioServlet.service(...): erorr creating and writing to PrintStream created from response.getOutputStream()"); } // end of catch } // end of action=='n' } ServletContext ctx = null; HttpSession session = null; try { ctx = getServletConfig().getServletContext(); // These operations require the user to be logged in. Verify the // user and if not logged in // change the operation to a login session = req.getSession(true); userID = (String) session.getAttribute("uidBean"); } catch (Exception e) { Log.error("trade_client.TradeScenarioServlet.service(...): performing " + scenarioAction + "error getting ServletContext,HttpSession, or UserID from session" + "will make scenarioAction a login and try to recover from there", e); userID = null; action = 'l'; } if (userID == null) { action = 'l'; // change to login TradeConfig.incrementScenarioCount(); } else if (action == ' ') { // action is not specified perform a random operation according to // current mix // Tell getScenarioAction if we are an original user or a registered // user // -- sellDeficits should only be compensated for with original // users. action = TradeConfig.getScenarioAction(userID.startsWith(TradeConfig.newUserPrefix)); } switch (action) { case 'q': // quote dispPath = tasPathPrefix + "quotes&symbols=" + TradeConfig.rndSymbols(); ctx.getRequestDispatcher(dispPath).include(req, resp); break; case 'a': // account dispPath = tasPathPrefix + "account"; ctx.getRequestDispatcher(dispPath).include(req, resp); break; case 'u': // update account profile dispPath = tasPathPrefix + "account"; ctx.getRequestDispatcher(dispPath).include(req, resp); String fullName = "rnd" + System.currentTimeMillis(); String address = "rndAddress"; String password = "xxx"; String email = "rndEmail"; String creditcard = "rndCC"; dispPath = tasPathPrefix + "update_profile&fullname=" + fullName + "&password=" + password + "&cpassword=" + password + "&address=" + address + "&email=" + email + "&creditcard=" + creditcard; ctx.getRequestDispatcher(dispPath).include(req, resp); break; case 'h': // home dispPath = tasPathPrefix + "home"; ctx.getRequestDispatcher(dispPath).include(req, resp); break; case 'l': // login userID = TradeConfig.getUserID(); String password2 = "xxx"; dispPath = tasPathPrefix + "login&inScenario=true&uid=" + userID + "&passwd=" + password2; ctx.getRequestDispatcher(dispPath).include(req, resp); // login is successful if the userID is written to the HTTP session if (session.getAttribute("uidBean") == null) { System.out.println("TradeScenario login failed. Reset DB between runs"); } break; case 'o': // logout dispPath = tasPathPrefix + "logout"; ctx.getRequestDispatcher(dispPath).include(req, resp); break; case 'p': // portfolio dispPath = tasPathPrefix + "portfolio"; ctx.getRequestDispatcher(dispPath).include(req, resp); break; case 'r': // register // Logout the current user to become a new user // see note in TradeServletAction req.setAttribute("TSS-RecreateSessionInLogout", Boolean.TRUE); dispPath = tasPathPrefix + "logout"; ctx.getRequestDispatcher(dispPath).include(req, resp); userID = TradeConfig.rndNewUserID(); String passwd = "yyy"; fullName = TradeConfig.rndFullName(); creditcard = TradeConfig.rndCreditCard(); String money = TradeConfig.rndBalance(); email = TradeConfig.rndEmail(userID); String smail = TradeConfig.rndAddress(); dispPath = tasPathPrefix + "register&Full Name=" + fullName + "&snail mail=" + smail + "&email=" + email + "&user id=" + userID + "&passwd=" + passwd + "&confirm passwd=" + passwd + "&money=" + money + "&Credit Card Number=" + creditcard; ctx.getRequestDispatcher(dispPath).include(req, resp); break; case 's': // sell dispPath = tasPathPrefix + "portfolioNoEdge"; ctx.getRequestDispatcher(dispPath).include(req, resp); Collection<?> holdings = (Collection<?>) req.getAttribute("holdingDataBeans"); int numHoldings = holdings.size(); if (numHoldings > 0) { // sell first available security out of holding Iterator<?> it = holdings.iterator(); boolean foundHoldingToSell = false; while (it.hasNext()) { HoldingDataBean holdingData = (HoldingDataBean) it.next(); if (!(holdingData.getPurchaseDate().equals(new java.util.Date(0)))) { Integer holdingID = holdingData.getHoldingID(); dispPath = tasPathPrefix + "sell&holdingID=" + holdingID; ctx.getRequestDispatcher(dispPath).include(req, resp); foundHoldingToSell = true; break; } } if (foundHoldingToSell) { break; } if (Log.doTrace()) { Log.trace("TradeScenario: No holding to sell -switch to buy -- userID = " + userID + " Collection count = " + numHoldings); } } // At this point: A TradeScenario Sell was requested with No Stocks // in Portfolio // This can happen when a new registered user happens to request a // sell before a buy // In this case, fall through and perform a buy instead /* * Trade 2.037: Added sell_deficit counter to maintain correct * buy/sell mix. When a users portfolio is reduced to 0 holdings, a * buy is requested instead of a sell. This throws off the buy/sell * mix by 1. This results in unwanted holding table growth To fix * this we increment a sell deficit counter to maintain the correct * ratio in getScenarioAction The 'z' action from getScenario * denotes that this is a sell action that was switched from a buy * to reduce a sellDeficit */ if (userID.startsWith(TradeConfig.newUserPrefix) == false) { TradeConfig.incrementSellDeficit(); } case 'b': // buy String symbol = TradeConfig.rndSymbol(); String amount = TradeConfig.rndQuantity() + ""; dispPath = tasPathPrefix + "quotes&symbols=" + symbol; ctx.getRequestDispatcher(dispPath).include(req, resp); dispPath = tasPathPrefix + "buy&quantity=" + amount + "&symbol=" + symbol; ctx.getRequestDispatcher(dispPath).include(req, resp); break; } // end of switch statement } // URL Path Prefix for dispatching to TradeAppServlet private static final String tasPathPrefix = "/app?action="; }
12,795
41.939597
161
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/TradeServletAction.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web; import java.io.IOException; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.ibm.websphere.samples.daytrader.TradeAction; import com.ibm.websphere.samples.daytrader.TradeServices; import com.ibm.websphere.samples.daytrader.entities.AccountDataBean; import com.ibm.websphere.samples.daytrader.entities.AccountProfileDataBean; import com.ibm.websphere.samples.daytrader.entities.HoldingDataBean; import com.ibm.websphere.samples.daytrader.entities.OrderDataBean; import com.ibm.websphere.samples.daytrader.entities.QuoteDataBean; import com.ibm.websphere.samples.daytrader.util.Log; import com.ibm.websphere.samples.daytrader.util.TradeConfig; /** * TradeServletAction provides servlet specific client side access to each of * the Trade brokerage user operations. These include login, logout, buy, sell, * getQuote, etc. TradeServletAction manages a web interface to Trade handling * HttpRequests/HttpResponse objects and forwarding results to the appropriate * JSP page for the web interface. TradeServletAction invokes * {@link TradeAction} methods to actually perform each trading operation. * */ public class TradeServletAction { private TradeServices tAction = null; TradeServletAction() { tAction = new TradeAction(); } /** * Display User Profile information such as address, email, etc. for the * given Trader Dispatch to the Trade Account JSP for display * * @param userID * The User to display profile info * @param ctx * the servlet context * @param req * the HttpRequest object * @param resp * the HttpResponse object * @param results * A short description of the results/success of this web request * provided on the web page * @exception javax.servlet.ServletException * If a servlet specific exception is encountered * @exception javax.io.IOException * If an exception occurs while writing results back to the * user * */ void doAccount(ServletContext ctx, HttpServletRequest req, HttpServletResponse resp, String userID, String results) throws javax.servlet.ServletException, java.io.IOException { try { AccountDataBean accountData = tAction.getAccountData(userID); AccountProfileDataBean accountProfileData = tAction.getAccountProfileData(userID); Collection<?> orderDataBeans = (TradeConfig.getLongRun() ? new ArrayList<Object>() : (Collection<?>) tAction.getOrders(userID)); req.setAttribute("accountData", accountData); req.setAttribute("accountProfileData", accountProfileData); req.setAttribute("orderDataBeans", orderDataBeans); req.setAttribute("results", results); requestDispatch(ctx, req, resp, userID, TradeConfig.getPage(TradeConfig.ACCOUNT_PAGE)); } catch (java.lang.IllegalArgumentException e) { // this is a user // error so I will // forward them to another page rather than throw a 500 req.setAttribute("results", results + "could not find account for userID = " + userID); requestDispatch(ctx, req, resp, userID, TradeConfig.getPage(TradeConfig.HOME_PAGE)); // log the exception with an error level of 3 which means, handled // exception but would invalidate a automation run Log.error("TradeServletAction.doAccount(...)", "illegal argument, information should be in exception string", e); } catch (Exception e) { // log the exception with error page throw new ServletException("TradeServletAction.doAccount(...)" + " exception user =" + userID, e); } } /** * Update User Profile information such as address, email, etc. for the * given Trader Dispatch to the Trade Account JSP for display If any in put * is incorrect revert back to the account page w/ an appropriate message * * @param userID * The User to upddate profile info * @param password * The new User password * @param cpassword * Confirm password * @param fullname * The new User fullname info * @param address * The new User address info * @param cc * The new User credit card info * @param email * The new User email info * @param ctx * the servlet context * @param req * the HttpRequest object * @param resp * the HttpResponse object * @exception javax.servlet.ServletException * If a servlet specific exception is encountered * @exception javax.io.IOException * If an exception occurs while writing results back to the * user * */ void doAccountUpdate(ServletContext ctx, HttpServletRequest req, HttpServletResponse resp, String userID, String password, String cpassword, String fullName, String address, String creditcard, String email) throws javax.servlet.ServletException, java.io.IOException { String results = ""; // First verify input data boolean doUpdate = true; if (password.equals(cpassword) == false) { results = "Update profile error: passwords do not match"; doUpdate = false; } else if (password.length() <= 0 || fullName.length() <= 0 || address.length() <= 0 || creditcard.length() <= 0 || email.length() <= 0) { results = "Update profile error: please fill in all profile information fields"; doUpdate = false; } AccountProfileDataBean accountProfileData = new AccountProfileDataBean(userID, password, fullName, address, email, creditcard); try { if (doUpdate) { accountProfileData = tAction.updateAccountProfile(accountProfileData); results = "Account profile update successful"; } } catch (java.lang.IllegalArgumentException e) { // this is a user // error so I will // forward them to another page rather than throw a 500 req.setAttribute("results", results + "invalid argument, check userID is correct, and the database is populated" + userID); Log.error(e, "TradeServletAction.doAccount(...)", "illegal argument, information should be in exception string", "treating this as a user error and forwarding on to a new page"); } catch (Exception e) { // log the exception with error page throw new ServletException("TradeServletAction.doAccountUpdate(...)" + " exception user =" + userID, e); } doAccount(ctx, req, resp, userID, results); } /** * Buy a new holding of shares for the given trader Dispatch to the Trade * Portfolio JSP for display * * @param userID * The User buying shares * @param symbol * The stock to purchase * @param amount * The quantity of shares to purchase * @param ctx * the servlet context * @param req * the HttpRequest object * @param resp * the HttpResponse object * @exception javax.servlet.ServletException * If a servlet specific exception is encountered * @exception javax.io.IOException * If an exception occurs while writing results back to the * user * */ void doBuy(ServletContext ctx, HttpServletRequest req, HttpServletResponse resp, String userID, String symbol, String quantity) throws ServletException, IOException { String results = ""; try { OrderDataBean orderData = tAction.buy(userID, symbol, new Double(quantity).doubleValue(), TradeConfig.orderProcessingMode); req.setAttribute("orderData", orderData); req.setAttribute("results", results); } catch (java.lang.IllegalArgumentException e) { // this is a user // error so I will // forward them to another page rather than throw a 500 req.setAttribute("results", results + "illegal argument:"); requestDispatch(ctx, req, resp, userID, TradeConfig.getPage(TradeConfig.HOME_PAGE)); // log the exception with an error level of 3 which means, handled // exception but would invalidate a automation run Log.error(e, "TradeServletAction.doBuy(...)", "illegal argument. userID = " + userID, "symbol = " + symbol); } catch (Exception e) { // log the exception with error page throw new ServletException("TradeServletAction.buy(...)" + " exception buying stock " + symbol + " for user " + userID, e); } requestDispatch(ctx, req, resp, userID, TradeConfig.getPage(TradeConfig.ORDER_PAGE)); } /** * Create the Trade Home page with personalized information such as the * traders account balance Dispatch to the Trade Home JSP for display * * @param ctx * the servlet context * @param req * the HttpRequest object * @param resp * the HttpResponse object * @param results * A short description of the results/success of this web request * provided on the web page * @exception javax.servlet.ServletException * If a servlet specific exception is encountered * @exception javax.io.IOException * If an exception occurs while writing results back to the * user * */ void doHome(ServletContext ctx, HttpServletRequest req, HttpServletResponse resp, String userID, String results) throws javax.servlet.ServletException, java.io.IOException { try { AccountDataBean accountData = tAction.getAccountData(userID); Collection<?> holdingDataBeans = tAction.getHoldings(userID); // Edge Caching: // Getting the MarketSummary has been moved to the JSP // MarketSummary.jsp. This makes the MarketSummary a // standalone "fragment", and thus is a candidate for // Edge caching. // marketSummaryData = tAction.getMarketSummary(); req.setAttribute("accountData", accountData); req.setAttribute("holdingDataBeans", holdingDataBeans); // See Edge Caching above // req.setAttribute("marketSummaryData", marketSummaryData); req.setAttribute("results", results); } catch (java.lang.IllegalArgumentException e) { // this is a user // error so I will // forward them to another page rather than throw a 500 req.setAttribute("results", results + "check userID = " + userID + " and that the database is populated"); requestDispatch(ctx, req, resp, userID, TradeConfig.getPage(TradeConfig.HOME_PAGE)); // log the exception with an error level of 3 which means, handled // exception but would invalidate a automation run Log.error("TradeServletAction.doHome(...)" + "illegal argument, information should be in exception string" + "treating this as a user error and forwarding on to a new page", e); } catch (javax.ejb.FinderException e) { // this is a user error so I will // forward them to another page rather than throw a 500 req.setAttribute("results", results + "\nCould not find account for + " + userID); // requestDispatch(ctx, req, resp, // TradeConfig.getPage(TradeConfig.HOME_PAGE)); // log the exception with an error level of 3 which means, handled // exception but would invalidate a automation run Log.error("TradeServletAction.doHome(...)" + "Error finding account for user " + userID + "treating this as a user error and forwarding on to a new page", e); } catch (Exception e) { // log the exception with error page throw new ServletException("TradeServletAction.doHome(...)" + " exception user =" + userID, e); } requestDispatch(ctx, req, resp, userID, TradeConfig.getPage(TradeConfig.HOME_PAGE)); } /** * Login a Trade User. Dispatch to the Trade Home JSP for display * * @param userID * The User to login * @param passwd * The password supplied by the trader used to authenticate * @param ctx * the servlet context * @param req * the HttpRequest object * @param resp * the HttpResponse object * @param results * A short description of the results/success of this web request * provided on the web page * @exception javax.servlet.ServletException * If a servlet specific exception is encountered * @exception javax.io.IOException * If an exception occurs while writing results back to the * user * */ void doLogin(ServletContext ctx, HttpServletRequest req, HttpServletResponse resp, String userID, String passwd) throws javax.servlet.ServletException, java.io.IOException { String results = ""; try { // Got a valid userID and passwd, attempt login AccountDataBean accountData = tAction.login(userID, passwd); if (accountData != null) { HttpSession session = req.getSession(true); session.setAttribute("uidBean", userID); session.setAttribute("sessionCreationDate", new java.util.Date()); results = "Ready to Trade"; doHome(ctx, req, resp, userID, results); return; } else { req.setAttribute("results", results + "\nCould not find account for + " + userID); // log the exception with an error level of 3 which means, // handled exception but would invalidate a automation run Log.log("TradeServletAction.doLogin(...)", "Error finding account for user " + userID + "", "user entered a bad username or the database is not populated"); } } catch (java.lang.IllegalArgumentException e) { // this is a user // error so I will // forward them to another page rather than throw a 500 req.setAttribute("results", results + "illegal argument:" + e.getMessage()); // log the exception with an error level of 3 which means, handled // exception but would invalidate a automation run Log.error(e, "TradeServletAction.doLogin(...)", "illegal argument, information should be in exception string", "treating this as a user error and forwarding on to a new page"); } catch (Exception e) { // log the exception with error page throw new ServletException("TradeServletAction.doLogin(...)" + "Exception logging in user " + userID + "with password" + passwd, e); } requestDispatch(ctx, req, resp, userID, TradeConfig.getPage(TradeConfig.WELCOME_PAGE)); } /** * Logout a Trade User Dispatch to the Trade Welcome JSP for display * * @param userID * The User to logout * @param ctx * the servlet context * @param req * the HttpRequest object * @param resp * the HttpResponse object * @param results * A short description of the results/success of this web request * provided on the web page * @exception javax.servlet.ServletException * If a servlet specific exception is encountered * @exception javax.io.IOException * If an exception occurs while writing results back to the * user * */ void doLogout(ServletContext ctx, HttpServletRequest req, HttpServletResponse resp, String userID) throws ServletException, IOException { String results = ""; try { tAction.logout(userID); } catch (java.lang.IllegalArgumentException e) { // this is a user // error so I will // forward them to another page, at the end of the page. req.setAttribute("results", results + "illegal argument:" + e.getMessage()); // log the exception with an error level of 3 which means, handled // exception but would invalidate a automation run Log.error(e, "TradeServletAction.doLogout(...)", "illegal argument, information should be in exception string", "treating this as a user error and forwarding on to a new page"); } catch (Exception e) { // log the exception and foward to a error page Log.error(e, "TradeServletAction.doLogout(...):", "Error logging out" + userID, "fowarding to an error page"); // set the status_code to 500 throw new ServletException("TradeServletAction.doLogout(...)" + "exception logging out user " + userID, e); } HttpSession session = req.getSession(); if (session != null) { session.invalidate(); } // Added to actually remove a user from the authentication cache req.logout(); Object o = req.getAttribute("TSS-RecreateSessionInLogout"); if (o != null && ((Boolean) o).equals(Boolean.TRUE)) { // Recreate Session object before writing output to the response // Once the response headers are written back to the client the // opportunity // to create a new session in this request may be lost // This is to handle only the TradeScenarioServlet case session = req.getSession(true); } requestDispatch(ctx, req, resp, userID, TradeConfig.getPage(TradeConfig.WELCOME_PAGE)); } /** * Retrieve the current portfolio of stock holdings for the given trader * Dispatch to the Trade Portfolio JSP for display * * @param userID * The User requesting to view their portfolio * @param ctx * the servlet context * @param req * the HttpRequest object * @param resp * the HttpResponse object * @param results * A short description of the results/success of this web request * provided on the web page * @exception javax.servlet.ServletException * If a servlet specific exception is encountered * @exception javax.io.IOException * If an exception occurs while writing results back to the * user * */ void doPortfolio(ServletContext ctx, HttpServletRequest req, HttpServletResponse resp, String userID, String results) throws ServletException, IOException { try { // Get the holdiings for this user Collection<QuoteDataBean> quoteDataBeans = new ArrayList<QuoteDataBean>(); Collection<?> holdingDataBeans = tAction.getHoldings(userID); // Walk through the collection of user // holdings and creating a list of quotes if (holdingDataBeans.size() > 0) { Iterator<?> it = holdingDataBeans.iterator(); while (it.hasNext()) { HoldingDataBean holdingData = (HoldingDataBean) it.next(); QuoteDataBean quoteData = tAction.getQuote(holdingData.getQuoteID()); quoteDataBeans.add(quoteData); } } else { results = results + ". Your portfolio is empty."; } req.setAttribute("results", results); req.setAttribute("holdingDataBeans", holdingDataBeans); req.setAttribute("quoteDataBeans", quoteDataBeans); requestDispatch(ctx, req, resp, userID, TradeConfig.getPage(TradeConfig.PORTFOLIO_PAGE)); } catch (java.lang.IllegalArgumentException e) { // this is a user // error so I will // forward them to another page rather than throw a 500 req.setAttribute("results", results + "illegal argument:" + e.getMessage()); requestDispatch(ctx, req, resp, userID, TradeConfig.getPage(TradeConfig.PORTFOLIO_PAGE)); // log the exception with an error level of 3 which means, handled // exception but would invalidate a automation run Log.error(e, "TradeServletAction.doPortfolio(...)", "illegal argument, information should be in exception string", "user error"); } catch (Exception e) { // log the exception with error page throw new ServletException("TradeServletAction.doPortfolio(...)" + " exception user =" + userID, e); } } /** * Retrieve the current Quote for the given stock symbol Dispatch to the * Trade Quote JSP for display * * @param userID * The stock symbol used to get the current quote * @param ctx * the servlet context * @param req * the HttpRequest object * @param resp * the HttpResponse object * @exception javax.servlet.ServletException * If a servlet specific exception is encountered * @exception javax.io.IOException * If an exception occurs while writing results back to the * user * */ void doQuotes(ServletContext ctx, HttpServletRequest req, HttpServletResponse resp, String userID, String symbols) throws ServletException, IOException { // Edge Caching: // Getting Quotes has been moved to the JSP // Quote.jsp. This makes each Quote a // standalone "fragment", and thus is a candidate for // Edge caching. // requestDispatch(ctx, req, resp, userID, TradeConfig.getPage(TradeConfig.QUOTE_PAGE)); } /** * Register a new trader given the provided user Profile information such as * address, email, etc. Dispatch to the Trade Home JSP for display * * @param userID * The User to create * @param passwd * The User password * @param fullname * The new User fullname info * @param ccn * The new User credit card info * @param money * The new User opening account balance * @param address * The new User address info * @param email * The new User email info * @return The userID of the new trader * @param ctx * the servlet context * @param req * the HttpRequest object * @param resp * the HttpResponse object * @exception javax.servlet.ServletException * If a servlet specific exception is encountered * @exception javax.io.IOException * If an exception occurs while writing results back to the * user * */ void doRegister(ServletContext ctx, HttpServletRequest req, HttpServletResponse resp, String userID, String passwd, String cpasswd, String fullname, String ccn, String openBalanceString, String email, String address) throws ServletException, IOException { String results = ""; try { // Validate user passwords match and are atleast 1 char in length if ((passwd.equals(cpasswd)) && (passwd.length() >= 1)) { AccountDataBean accountData = tAction.register(userID, passwd, fullname, address, email, ccn, new BigDecimal(openBalanceString)); if (accountData == null) { results = "Registration operation failed;"; System.out.println(results); req.setAttribute("results", results); requestDispatch(ctx, req, resp, userID, TradeConfig.getPage(TradeConfig.REGISTER_PAGE)); } else { doLogin(ctx, req, resp, userID, passwd); results = "Registration operation succeeded; Account " + accountData.getAccountID() + " has been created."; req.setAttribute("results", results); } } else { // Password validation failed results = "Registration operation failed, your passwords did not match"; System.out.println(results); req.setAttribute("results", results); requestDispatch(ctx, req, resp, userID, TradeConfig.getPage(TradeConfig.REGISTER_PAGE)); } } catch (Exception e) { // log the exception with error page throw new ServletException("TradeServletAction.doRegister(...)" + " exception user =" + userID, e); } } /** * Sell a current holding of stock shares for the given trader. Dispatch to * the Trade Portfolio JSP for display * * @param userID * The User buying shares * @param symbol * The stock to sell * @param indx * The unique index identifying the users holding to sell * @param ctx * the servlet context * @param req * the HttpRequest object * @param resp * the HttpResponse object * @exception javax.servlet.ServletException * If a servlet specific exception is encountered * @exception javax.io.IOException * If an exception occurs while writing results back to the * user * */ void doSell(ServletContext ctx, HttpServletRequest req, HttpServletResponse resp, String userID, Integer holdingID) throws ServletException, IOException { String results = ""; try { OrderDataBean orderData = tAction.sell(userID, holdingID, TradeConfig.orderProcessingMode); req.setAttribute("orderData", orderData); req.setAttribute("results", results); } catch (java.lang.IllegalArgumentException e) { // this is a user // error so I will // just log the exception and then later on I will redisplay the // portfolio page // because this is just a user exception Log.error(e, "TradeServletAction.doSell(...)", "illegal argument, information should be in exception string", "user error"); } catch (Exception e) { // log the exception with error page throw new ServletException("TradeServletAction.doSell(...)" + " exception selling holding " + holdingID + " for user =" + userID, e); } requestDispatch(ctx, req, resp, userID, TradeConfig.getPage(TradeConfig.ORDER_PAGE)); } void doWelcome(ServletContext ctx, HttpServletRequest req, HttpServletResponse resp, String status) throws ServletException, IOException { req.setAttribute("results", status); requestDispatch(ctx, req, resp, null, TradeConfig.getPage(TradeConfig.WELCOME_PAGE)); } private void requestDispatch(ServletContext ctx, HttpServletRequest req, HttpServletResponse resp, String userID, String page) throws ServletException, IOException { ctx.getRequestDispatcher(page).include(req, resp); } void doMarketSummary(ServletContext ctx, HttpServletRequest req, HttpServletResponse resp, String userID) throws ServletException, IOException { req.setAttribute("results", "test"); requestDispatch(ctx, req, resp, userID, TradeConfig.getPage(TradeConfig.MARKET_SUMMARY_PAGE)); } }
29,124
45.156894
160
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/TradeWebContextListener.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web; import java.io.InputStream; import java.util.Properties; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; import com.ibm.websphere.samples.daytrader.direct.TradeDirect; import com.ibm.websphere.samples.daytrader.util.Log; import com.ibm.websphere.samples.daytrader.util.TradeConfig; @WebListener() public class TradeWebContextListener implements ServletContextListener { // receieve trade web app startup/shutown events to start(initialized)/stop // TradeDirect @Override public void contextInitialized(ServletContextEvent event) { Log.trace("TradeWebContextListener contextInitialized -- initializing TradeDirect"); // Load settings from properties file (if it exists) Properties prop = new Properties(); InputStream stream = event.getServletContext().getResourceAsStream("/properties/daytrader.properties"); try { prop.load(stream); System.out.println("Settings from daytrader.properties: " + prop); TradeConfig.setRunTimeMode(Integer.parseInt(prop.getProperty("runtimeMode"))); TradeConfig.setUseRemoteEJBInterface(Boolean.parseBoolean(prop.getProperty("useRemoteEJBInterface"))); TradeConfig.setOrderProcessingMode(Integer.parseInt(prop.getProperty("orderProcessingMode"))); TradeConfig.setWebInterface(Integer.parseInt(prop.getProperty("webInterface"))); //TradeConfig.setCachingType(Integer.parseInt(prop.getProperty("cachingType"))); //TradeConfig.setDistributedMapCacheSize(Integer.parseInt(prop.getProperty("cacheSize"))); TradeConfig.setMAX_USERS(Integer.parseInt(prop.getProperty("maxUsers"))); TradeConfig.setMAX_QUOTES(Integer.parseInt(prop.getProperty("maxQuotes"))); TradeConfig.setMarketSummaryInterval(Integer.parseInt(prop.getProperty("marketSummaryInterval"))); TradeConfig.setPrimIterations(Integer.parseInt(prop.getProperty("primIterations"))); TradeConfig.setPublishQuotePriceChange(Boolean.parseBoolean(prop.getProperty("publishQuotePriceChange"))); TradeConfig.setPercentSentToWebsocket(Integer.parseInt(prop.getProperty("percentSentToWebsocket"))); TradeConfig.setDisplayOrderAlerts(Boolean.parseBoolean(prop.getProperty("displayOrderAlerts"))); TradeConfig.setLongRun(Boolean.parseBoolean(prop.getProperty("longRun"))); TradeConfig.setTrace(Boolean.parseBoolean(prop.getProperty("trace"))); TradeConfig.setActionTrace(Boolean.parseBoolean(prop.getProperty("actionTrace"))); } catch (Exception e) { System.out.println("daytrader.properties not found"); } TradeDirect.init(); } @Override public void contextDestroyed(ServletContextEvent event) { Log.trace("TradeWebContextListener contextDestroy calling TradeDirect:destroy()"); // TradeDirect.destroy(); } }
3,692
48.24
118
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/jsf/AccountDataJSF.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.jsf; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.Iterator; import javax.annotation.PostConstruct; import javax.enterprise.context.RequestScoped; import javax.faces.context.ExternalContext; import javax.inject.Inject; import javax.inject.Named; import javax.servlet.http.HttpSession; import com.ibm.websphere.samples.daytrader.TradeAction; import com.ibm.websphere.samples.daytrader.entities.AccountDataBean; import com.ibm.websphere.samples.daytrader.entities.OrderDataBean; import com.ibm.websphere.samples.daytrader.util.FinancialUtils; import com.ibm.websphere.samples.daytrader.util.TradeConfig; @Named("accountdata") @RequestScoped public class AccountDataJSF { @Inject private ExternalContext facesExternalContext; @Inject private TradeAction tradeAction; private Date sessionCreationDate; private Date currentTime; private String profileID; private Integer accountID; private Date creationDate; private int loginCount; private Date lastLogin; private int logoutCount; private BigDecimal balance; private BigDecimal openBalance; private Integer numberHoldings; private BigDecimal holdingsTotal; private BigDecimal sumOfCashHoldings; private BigDecimal gain; private BigDecimal gainPercent; private OrderData[] closedOrders; private OrderData[] allOrders; private Integer numberOfOrders = 0; private Integer numberOfOrderRows = 5; public void toggleShowAllRows() { setNumberOfOrderRows(0); } @PostConstruct public void home() { try { HttpSession session = (HttpSession) facesExternalContext.getSession(true); // Get the data and then parse String userID = (String) session.getAttribute("uidBean"); AccountDataBean accountData = tradeAction.getAccountData(userID); Collection<?> holdingDataBeans = tradeAction.getHoldings(userID); if (TradeConfig.getDisplayOrderAlerts()) { Collection<?> closedOrders = tradeAction.getClosedOrders(userID); if (closedOrders != null && closedOrders.size() > 0) { session.setAttribute("closedOrders", closedOrders); OrderData[] orderjsfs = new OrderData[closedOrders.size()]; Iterator<?> it = closedOrders.iterator(); int i = 0; while (it.hasNext()) { OrderDataBean order = (OrderDataBean) it.next(); OrderData r = new OrderData(order.getOrderID(), order.getOrderStatus(), order.getOpenDate(), order.getCompletionDate(), order.getOrderFee(), order.getOrderType(), order.getQuantity(), order.getSymbol()); orderjsfs[i] = r; i++; } setClosedOrders(orderjsfs); } } Collection<?> orderDataBeans = (TradeConfig.getLongRun() ? new ArrayList<Object>() : (Collection<?>) tradeAction.getOrders(userID)); if (orderDataBeans != null && orderDataBeans.size() > 0) { session.setAttribute("orderDataBeans", orderDataBeans); OrderData[] orderjsfs = new OrderData[orderDataBeans.size()]; Iterator<?> it = orderDataBeans.iterator(); int i = 0; while (it.hasNext()) { OrderDataBean order = (OrderDataBean) it.next(); OrderData r = new OrderData(order.getOrderID(), order.getOrderStatus(), order.getOpenDate(), order.getCompletionDate(), order.getOrderFee(), order.getOrderType(), order.getQuantity(), order.getSymbol(),order.getPrice()); orderjsfs[i] = r; i++; } setNumberOfOrders(orderDataBeans.size()); setAllOrders(orderjsfs); } setSessionCreationDate((Date) session.getAttribute("sessionCreationDate")); setCurrentTime(new java.util.Date()); doAccountData(accountData, holdingDataBeans); } catch (Exception e) { e.printStackTrace(); } } private void doAccountData(AccountDataBean accountData, Collection<?> holdingDataBeans) { setProfileID(accountData.getProfileID()); setAccountID(accountData.getAccountID()); setCreationDate(accountData.getCreationDate()); setLoginCount(accountData.getLoginCount()); setLogoutCount(accountData.getLogoutCount()); setLastLogin(accountData.getLastLogin()); setOpenBalance(accountData.getOpenBalance()); setBalance(accountData.getBalance()); setNumberHoldings(holdingDataBeans.size()); setHoldingsTotal(FinancialUtils.computeHoldingsTotal(holdingDataBeans)); setSumOfCashHoldings(balance.add(holdingsTotal)); setGain(FinancialUtils.computeGain(sumOfCashHoldings, openBalance)); setGainPercent(FinancialUtils.computeGainPercent(sumOfCashHoldings, openBalance)); } public Date getSessionCreationDate() { return sessionCreationDate; } public void setSessionCreationDate(Date sessionCreationDate) { this.sessionCreationDate = sessionCreationDate; } public Date getCurrentTime() { return currentTime; } public void setCurrentTime(Date currentTime) { this.currentTime = currentTime; } public String getProfileID() { return profileID; } public void setProfileID(String profileID) { this.profileID = profileID; } public void setAccountID(Integer accountID) { this.accountID = accountID; } public Integer getAccountID() { return accountID; } public void setCreationDate(Date creationDate) { this.creationDate = creationDate; } public Date getCreationDate() { return creationDate; } public void setLoginCount(int loginCount) { this.loginCount = loginCount; } public int getLoginCount() { return loginCount; } public void setBalance(BigDecimal balance) { this.balance = balance; } public BigDecimal getBalance() { return balance; } public void setOpenBalance(BigDecimal openBalance) { this.openBalance = openBalance; } public BigDecimal getOpenBalance() { return openBalance; } public void setHoldingsTotal(BigDecimal holdingsTotal) { this.holdingsTotal = holdingsTotal; } public BigDecimal getHoldingsTotal() { return holdingsTotal; } public void setSumOfCashHoldings(BigDecimal sumOfCashHoldings) { this.sumOfCashHoldings = sumOfCashHoldings; } public BigDecimal getSumOfCashHoldings() { return sumOfCashHoldings; } public void setGain(BigDecimal gain) { this.gain = gain; } public BigDecimal getGain() { return gain; } public void setGainPercent(BigDecimal gainPercent) { this.gainPercent = gainPercent.setScale(2); } public BigDecimal getGainPercent() { return gainPercent; } public void setNumberHoldings(Integer numberHoldings) { this.numberHoldings = numberHoldings; } public Integer getNumberHoldings() { return numberHoldings; } public OrderData[] getClosedOrders() { return closedOrders; } public void setClosedOrders(OrderData[] closedOrders) { this.closedOrders = closedOrders; } public void setLastLogin(Date lastLogin) { this.lastLogin = lastLogin; } public Date getLastLogin() { return lastLogin; } public void setLogoutCount(int logoutCount) { this.logoutCount = logoutCount; } public int getLogoutCount() { return logoutCount; } public void setAllOrders(OrderData[] allOrders) { this.allOrders = allOrders; } public OrderData[] getAllOrders() { return allOrders; } public String getGainHTML() { return FinancialUtils.printGainHTML(gain); } public String getGainPercentHTML() { return FinancialUtils.printGainPercentHTML(gainPercent); } public Integer getNumberOfOrderRows() { return numberOfOrderRows; } public void setNumberOfOrderRows(Integer numberOfOrderRows) { this.numberOfOrderRows = numberOfOrderRows; } public Integer getNumberOfOrders() { return numberOfOrders; } public void setNumberOfOrders(Integer numberOfOrders) { this.numberOfOrders = numberOfOrders; } }
9,437
29.642857
144
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/jsf/ExternalContextProducer.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.jsf; import javax.enterprise.context.RequestScoped; import javax.enterprise.inject.Produces; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; public class ExternalContextProducer { @Produces @RequestScoped public ExternalContext produceFacesExternalContext() { return FacesContext.getCurrentInstance().getExternalContext(); } }
1,039
33.666667
75
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/jsf/HoldingData.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.jsf; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; import javax.enterprise.context.SessionScoped; import javax.inject.Named; import com.ibm.websphere.samples.daytrader.util.FinancialUtils; @Named @SessionScoped public class HoldingData implements Serializable { private static final long serialVersionUID = -4760036695773749721L; private Integer holdingID; private double quantity; private BigDecimal purchasePrice; private Date purchaseDate; private String quoteID; private BigDecimal price; private BigDecimal basis; private BigDecimal marketValue; private BigDecimal gain; public void setHoldingID(Integer holdingID) { this.holdingID = holdingID; } public Integer getHoldingID() { return holdingID; } public void setQuantity(double quantity) { this.quantity = quantity; } public double getQuantity() { return quantity; } public void setPurchasePrice(BigDecimal purchasePrice) { this.purchasePrice = purchasePrice; } public BigDecimal getPurchasePrice() { return purchasePrice; } public void setPurchaseDate(Date purchaseDate) { this.purchaseDate = purchaseDate; } public Date getPurchaseDate() { return purchaseDate; } public void setQuoteID(String quoteID) { this.quoteID = quoteID; } public String getQuoteID() { return quoteID; } public void setPrice(BigDecimal price) { this.price = price; } public BigDecimal getPrice() { return price; } public void setBasis(BigDecimal basis) { this.basis = basis; } public BigDecimal getBasis() { return basis; } public void setMarketValue(BigDecimal marketValue) { this.marketValue = marketValue; } public BigDecimal getMarketValue() { return marketValue; } public void setGain(BigDecimal gain) { this.gain = gain; } public BigDecimal getGain() { return gain; } public String getGainHTML() { return FinancialUtils.printGainHTML(gain); } }
2,836
22.840336
75
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/jsf/JSFLoginFilter.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.jsf; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; //import javax.servlet.annotation.WebFilter; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; @WebFilter(filterName = "JSFLoginFilter", urlPatterns = "*.faces") public class JSFLoginFilter implements Filter { public JSFLoginFilter() { super(); } /** * @see Filter#init(FilterConfig) */ private FilterConfig filterConfig = null; @Override public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig = filterConfig; } /** * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain) */ @Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { if (filterConfig == null) { return; } HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) resp; HttpSession session = request.getSession(); String userID = (String) session.getAttribute("uidBean"); // If user has not logged in and is trying access account information, // redirect to login page. if (userID == null) { String url = request.getServletPath(); if (url.contains("home") || url.contains("account") || url.contains("portfolio") || url.contains("quote") || url.contains("order") || url.contains("marketSummary")) { System.out.println("JSF service error: User Not Logged in"); response.sendRedirect("welcome.faces"); return; } } chain.doFilter(req, resp/* wrapper */); } /** * @see Filter#destroy() */ @Override public void destroy() { this.filterConfig = null; } }
2,833
30.842697
142
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/jsf/LoginValidator.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.jsf; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.faces.application.FacesMessage; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.validator.FacesValidator; import javax.faces.validator.Validator; import javax.faces.validator.ValidatorException; import com.ibm.websphere.samples.daytrader.util.Log; @FacesValidator("loginValidator") public class LoginValidator implements Validator{ static String loginRegex = "uid:\\d+"; static Pattern pattern = Pattern.compile(loginRegex); static Matcher matcher; // Simple JSF validator to make sure username starts with uid: and at least 1 number. public LoginValidator() { } @Override public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException { if (Log.doTrace()) { Log.trace("LoginValidator.validate","Validating submitted login name -- " + value.toString()); } matcher = pattern.matcher(value.toString()); if (!matcher.matches()) { FacesMessage msg = new FacesMessage("Username validation failed. Please provide username in this format: uid:#"); msg.setSeverity(FacesMessage.SEVERITY_ERROR); throw new ValidatorException(msg); } } }
1,924
34
117
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/jsf/MarketSummaryJSF.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.jsf; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.Collection; import java.util.Date; import java.util.Iterator; import javax.annotation.PostConstruct; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.inject.Named; import com.ibm.websphere.samples.daytrader.TradeAction; import com.ibm.websphere.samples.daytrader.beans.MarketSummaryDataBean; import com.ibm.websphere.samples.daytrader.entities.QuoteDataBean; import com.ibm.websphere.samples.daytrader.util.FinancialUtils; @Named("marketdata") @RequestScoped public class MarketSummaryJSF { @Inject private TradeAction tradeAction; private BigDecimal TSIA; private BigDecimal openTSIA; private double volume; private QuoteData[] topGainers; private QuoteData[] topLosers; private Date summaryDate; // cache the gainPercent once computed for this bean private BigDecimal gainPercent = null; @PostConstruct public void getMarketSummary() { try { MarketSummaryDataBean marketSummaryData = tradeAction.getMarketSummary(); setSummaryDate(marketSummaryData.getSummaryDate()); setTSIA(marketSummaryData.getTSIA()); setVolume(marketSummaryData.getVolume()); setGainPercent(marketSummaryData.getGainPercent()); Collection<?> topGainers = marketSummaryData.getTopGainers(); Iterator<?> gainers = topGainers.iterator(); int count = 0; QuoteData[] gainerjsfs = new QuoteData[5]; while (gainers.hasNext() && (count < 5)) { QuoteDataBean quote = (QuoteDataBean) gainers.next(); QuoteData r = new QuoteData(quote.getPrice(), quote.getOpen(), quote.getSymbol()); gainerjsfs[count] = r; count++; } setTopGainers(gainerjsfs); Collection<?> topLosers = marketSummaryData.getTopLosers(); QuoteData[] loserjsfs = new QuoteData[5]; count = 0; Iterator<?> losers = topLosers.iterator(); while (losers.hasNext() && (count < 5)) { QuoteDataBean quote = (QuoteDataBean) losers.next(); QuoteData r = new QuoteData(quote.getPrice(), quote.getOpen(), quote.getSymbol()); loserjsfs[count] = r; count++; } setTopLosers(loserjsfs); } catch (Exception e) { e.printStackTrace(); } } public void setTSIA(BigDecimal tSIA) { TSIA = tSIA; } public BigDecimal getTSIA() { return TSIA; } public void setOpenTSIA(BigDecimal openTSIA) { this.openTSIA = openTSIA; } public BigDecimal getOpenTSIA() { return openTSIA; } public void setVolume(double volume) { this.volume = volume; } public double getVolume() { return volume; } public void setTopGainers(QuoteData[] topGainers) { this.topGainers = topGainers; } public QuoteData[] getTopGainers() { return topGainers; } public void setTopLosers(QuoteData[] topLosers) { this.topLosers = topLosers; } public QuoteData[] getTopLosers() { return topLosers; } public void setSummaryDate(Date summaryDate) { this.summaryDate = summaryDate; } public Date getSummaryDate() { return summaryDate; } public void setGainPercent(BigDecimal gainPercent) { this.gainPercent = gainPercent.setScale(2,RoundingMode.HALF_UP); } public BigDecimal getGainPercent() { return gainPercent; } public String getGainPercentHTML() { return FinancialUtils.printGainPercentHTML(gainPercent); } }
4,459
27.774194
98
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/jsf/OrderData.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.jsf; import java.math.BigDecimal; import java.util.Date; public class OrderData { private Integer orderID; private String orderStatus; private Date openDate; private Date completionDate; private BigDecimal orderFee; private String orderType; private double quantity; private String symbol; private BigDecimal total; private BigDecimal price; public OrderData(Integer orderID, String orderStatus, Date openDate, Date completeDate, BigDecimal orderFee, String orderType, double quantity, String symbol) { this.orderID = orderID; this.completionDate = completeDate; this.openDate = openDate; this.orderFee = orderFee; this.orderType = orderType; this.orderStatus = orderStatus; this.quantity = quantity; this.symbol = symbol; } public OrderData(Integer orderID, String orderStatus, Date openDate, Date completeDate, BigDecimal orderFee, String orderType, double quantity, String symbol, BigDecimal price) { this.orderID = orderID; this.completionDate = completeDate; this.openDate = openDate; this.orderFee = orderFee; this.orderType = orderType; this.orderStatus = orderStatus; this.quantity = quantity; this.symbol = symbol; this.price = price; this.total = price.multiply(new BigDecimal(quantity)); } public void setOrderID(Integer orderID) { this.orderID = orderID; } public Integer getOrderID() { return orderID; } public void setOrderStatus(String orderStatus) { this.orderStatus = orderStatus; } public String getOrderStatus() { return orderStatus; } public void setOpenDate(Date openDate) { this.openDate = openDate; } public Date getOpenDate() { return openDate; } public void setCompletionDate(Date completionDate) { this.completionDate = completionDate; } public Date getCompletionDate() { return completionDate; } public void setOrderFee(BigDecimal orderFee) { this.orderFee = orderFee; } public BigDecimal getOrderFee() { return orderFee; } public void setOrderType(String orderType) { this.orderType = orderType; } public String getOrderType() { return orderType; } public void setQuantity(double quantity) { this.quantity = quantity; } public double getQuantity() { return quantity; } public void setSymbol(String symbol) { this.symbol = symbol; } public String getSymbol() { return symbol; } public void setTotal(BigDecimal total) { this.total = total; } public BigDecimal getTotal() { return total; } public void setPrice(BigDecimal price) { this.price = price; } public BigDecimal getPrice() { return price; } }
3,650
24.893617
147
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/jsf/OrderDataJSF.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.jsf; import java.math.BigDecimal; import java.util.ArrayList; import javax.annotation.PostConstruct; import javax.faces.context.ExternalContext; import javax.inject.Inject; import javax.inject.Named; import javax.servlet.http.HttpSession; import com.ibm.websphere.samples.daytrader.TradeAction; import com.ibm.websphere.samples.daytrader.entities.OrderDataBean; import com.ibm.websphere.samples.daytrader.util.TradeConfig; @Named("orderdata") public class OrderDataJSF { @Inject private ExternalContext facesExternalContext; @Inject private TradeAction tradeAction; private OrderData[] allOrders; private OrderData orderData; public OrderDataJSF() { } public void getAllOrder() { try { HttpSession session = (HttpSession) facesExternalContext.getSession(true); String userID = (String) session.getAttribute("uidBean"); ArrayList<?> orderDataBeans = (TradeConfig.getLongRun() ? new ArrayList<Object>() : (ArrayList<?>) tradeAction.getOrders(userID)); OrderData[] orders = new OrderData[orderDataBeans.size()]; int count = 0; for (Object order : orderDataBeans) { OrderData r = new OrderData(((OrderDataBean) order).getOrderID(), ((OrderDataBean) order).getOrderStatus(), ((OrderDataBean) order).getOpenDate(), ((OrderDataBean) order).getCompletionDate(), ((OrderDataBean) order).getOrderFee(), ((OrderDataBean) order).getOrderType(), ((OrderDataBean) order).getQuantity(), ((OrderDataBean) order).getSymbol()); r.setPrice(((OrderDataBean) order).getPrice()); r.setTotal(r.getPrice().multiply(new BigDecimal(r.getQuantity()))); orders[count] = r; count++; } setAllOrders(orders); } catch (Exception e) { e.printStackTrace(); } } @PostConstruct public void getOrder() { HttpSession session = (HttpSession) facesExternalContext.getSession(true); OrderData order = (OrderData) session.getAttribute("orderData"); if (order != null) { setOrderData(order); } } public void setAllOrders(OrderData[] allOrders) { this.allOrders = allOrders; } public OrderData[] getAllOrders() { return allOrders; } public void setOrderData(OrderData orderData) { this.orderData = orderData; } public OrderData getOrderData() { return orderData; } }
3,211
31.77551
146
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/jsf/PortfolioJSF.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.jsf; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import javax.annotation.PostConstruct; import javax.enterprise.context.RequestScoped; import javax.faces.component.html.HtmlDataTable; import javax.faces.context.ExternalContext; import javax.inject.Inject; import javax.inject.Named; import javax.servlet.http.HttpSession; import com.ibm.websphere.samples.daytrader.TradeAction; import com.ibm.websphere.samples.daytrader.entities.HoldingDataBean; import com.ibm.websphere.samples.daytrader.entities.OrderDataBean; import com.ibm.websphere.samples.daytrader.entities.QuoteDataBean; import com.ibm.websphere.samples.daytrader.util.FinancialUtils; import com.ibm.websphere.samples.daytrader.util.TradeConfig; @Named("portfolio") @RequestScoped public class PortfolioJSF { @Inject private ExternalContext facesExternalContext; @Inject private TradeAction tradeAction; private BigDecimal balance; private BigDecimal openBalance; private Integer numberHoldings; private BigDecimal holdingsTotal; private BigDecimal sumOfCashHoldings; private BigDecimal totalGain = new BigDecimal(0.0); private BigDecimal totalValue = new BigDecimal(0.0); private BigDecimal totalBasis = new BigDecimal(0.0); private BigDecimal totalGainPercent = new BigDecimal(0.0); private ArrayList<HoldingData> holdingDatas; private HtmlDataTable dataTable; @PostConstruct public void getPortfolio() { try { HttpSession session = (HttpSession) facesExternalContext.getSession(true); String userID = (String) session.getAttribute("uidBean"); Collection<?> holdingDataBeans = tradeAction.getHoldings(userID); numberHoldings = holdingDataBeans.size(); // Walk through the collection of user holdings and creating a list // of quotes if (holdingDataBeans.size() > 0) { Iterator<?> it = holdingDataBeans.iterator(); holdingDatas = new ArrayList<HoldingData>(holdingDataBeans.size()); while (it.hasNext()) { HoldingDataBean holdingData = (HoldingDataBean) it.next(); QuoteDataBean quoteData = tradeAction.getQuote(holdingData.getQuoteID()); BigDecimal basis = holdingData.getPurchasePrice().multiply(new BigDecimal(holdingData.getQuantity())); BigDecimal marketValue = quoteData.getPrice().multiply(new BigDecimal(holdingData.getQuantity())); totalBasis = totalBasis.add(basis); totalValue = totalValue.add(marketValue); BigDecimal gain = marketValue.subtract(basis); totalGain = totalGain.add(gain); HoldingData h = new HoldingData(); h.setHoldingID(holdingData.getHoldingID()); h.setPurchaseDate(holdingData.getPurchaseDate()); h.setQuoteID(holdingData.getQuoteID()); h.setQuantity(holdingData.getQuantity()); h.setPurchasePrice(holdingData.getPurchasePrice()); h.setBasis(basis); h.setGain(gain); h.setMarketValue(marketValue); h.setPrice(quoteData.getPrice()); holdingDatas.add(h); } // dataTable setTotalGainPercent(FinancialUtils.computeGainPercent(totalValue, totalBasis)); } } catch (Exception e) { e.printStackTrace(); } } public String sell() { HttpSession session = (HttpSession) facesExternalContext.getSession(true); String userID = (String) session.getAttribute("uidBean"); TradeAction tAction = new TradeAction(); OrderDataBean orderDataBean = null; HoldingData holdingData = (HoldingData) dataTable.getRowData(); try { orderDataBean = tAction.sell(userID, holdingData.getHoldingID(), TradeConfig.orderProcessingMode); holdingDatas.remove(holdingData); } catch (Exception e) { e.printStackTrace(); } OrderData orderData = new OrderData(orderDataBean.getOrderID(), orderDataBean.getOrderStatus(), orderDataBean.getOpenDate(), orderDataBean.getCompletionDate(), orderDataBean.getOrderFee(), orderDataBean.getOrderType(), orderDataBean.getQuantity(), orderDataBean.getSymbol()); session.setAttribute("orderData", orderData); return "sell"; } public void setDataTable(HtmlDataTable dataTable) { this.dataTable = dataTable; } public HtmlDataTable getDataTable() { return dataTable; } public void setBalance(BigDecimal balance) { this.balance = balance; } public BigDecimal getBalance() { return balance; } public void setOpenBalance(BigDecimal openBalance) { this.openBalance = openBalance; } public BigDecimal getOpenBalance() { return openBalance; } public void setHoldingsTotal(BigDecimal holdingsTotal) { this.holdingsTotal = holdingsTotal; } public BigDecimal getHoldingsTotal() { return holdingsTotal; } public void setSumOfCashHoldings(BigDecimal sumOfCashHoldings) { this.sumOfCashHoldings = sumOfCashHoldings; } public BigDecimal getSumOfCashHoldings() { return sumOfCashHoldings; } public void setNumberHoldings(Integer numberHoldings) { this.numberHoldings = numberHoldings; } public Integer getNumberHoldings() { return numberHoldings; } public void setTotalGain(BigDecimal totalGain) { this.totalGain = totalGain; } public BigDecimal getTotalGain() { return totalGain; } public void setTotalValue(BigDecimal totalValue) { this.totalValue = totalValue; } public BigDecimal getTotalValue() { return totalValue; } public void setTotalBasis(BigDecimal totalBasis) { this.totalBasis = totalBasis; } public BigDecimal getTotalBasis() { return totalBasis; } public void setHoldingDatas(ArrayList<HoldingData> holdingDatas) { this.holdingDatas = holdingDatas; } public ArrayList<HoldingData> getHoldingDatas() { return holdingDatas; } public void setTotalGainPercent(BigDecimal totalGainPercent) { this.totalGainPercent = totalGainPercent; } public BigDecimal getTotalGainPercent() { return totalGainPercent; } public String getTotalGainPercentHTML() { return FinancialUtils.printGainPercentHTML(totalGainPercent); } }
7,465
32.630631
138
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/jsf/QuoteData.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.jsf; import java.math.BigDecimal; import java.text.DecimalFormat; import com.ibm.websphere.samples.daytrader.util.FinancialUtils; public class QuoteData { private BigDecimal price; private BigDecimal open; private String symbol; private BigDecimal high; private BigDecimal low; private String companyName; private double volume; private double change; private String range; private BigDecimal gainPercent; private BigDecimal gain; public QuoteData(BigDecimal price, BigDecimal open, String symbol) { this.open = open; this.price = price; this.symbol = symbol; this.change = price.subtract(open).setScale(2).doubleValue(); } public QuoteData(BigDecimal open, BigDecimal price, String symbol, BigDecimal high, BigDecimal low, String companyName, Double volume, Double change) { this.open = open; this.price = price; this.symbol = symbol; this.high = high; this.low = low; this.companyName = companyName; this.volume = volume; this.change = change; this.range = high.toString() + "-" + low.toString(); this.gainPercent = FinancialUtils.computeGainPercent(price, open).setScale(2); this.gain = FinancialUtils.computeGain(price, open).setScale(2); } public void setSymbol(String symbol) { this.symbol = symbol; } public String getSymbol() { return symbol; } public void setPrice(BigDecimal price) { this.price = price; } public BigDecimal getPrice() { return price; } public void setOpen(BigDecimal open) { this.open = open; } public BigDecimal getOpen() { return open; } public void setHigh(BigDecimal high) { this.high = high; } public BigDecimal getHigh() { return high; } public void setLow(BigDecimal low) { this.low = low; } public BigDecimal getLow() { return low; } public void setCompanyName(String companyName) { this.companyName = companyName; } public String getCompanyName() { return companyName; } public void setVolume(double volume) { this.volume = volume; } public double getVolume() { return volume; } public void setChange(double change) { this.change = change; } public double getChange() { return change; } public void setRange(String range) { this.range = range; } public String getRange() { return range; } public void setGainPercent(BigDecimal gainPercent) { this.gainPercent = gainPercent.setScale(2); } public BigDecimal getGainPercent() { return gainPercent; } public void setGain(BigDecimal gain) { this.gain = gain; } public BigDecimal getGain() { return gain; } public String getGainPercentHTML() { return FinancialUtils.printGainPercentHTML(gainPercent); } public String getGainHTML() { return FinancialUtils.printGainHTML(gain); } public String getChangeHTML() { String htmlString, arrow; if (change < 0.0) { htmlString = "<FONT color=\"#cc0000\">"; arrow = "arrowdown.gif"; } else { htmlString = "<FONT color=\"#009900\">"; arrow = "arrowup.gif"; } DecimalFormat df = new DecimalFormat("####0.00"); htmlString += df.format(change) + "</FONT><IMG src=\"images/" + arrow + "\" width=\"10\" height=\"10\" border=\"0\"></IMG>"; return htmlString; } }
4,331
24.785714
155
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/jsf/QuoteJSF.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.jsf; import javax.annotation.PostConstruct; import javax.enterprise.context.RequestScoped; import javax.faces.component.html.HtmlDataTable; import javax.faces.context.ExternalContext; import javax.inject.Inject; import javax.inject.Named; import javax.servlet.http.HttpSession; import com.ibm.websphere.samples.daytrader.TradeAction; import com.ibm.websphere.samples.daytrader.entities.OrderDataBean; import com.ibm.websphere.samples.daytrader.entities.QuoteDataBean; import com.ibm.websphere.samples.daytrader.util.Log; import com.ibm.websphere.samples.daytrader.util.TradeConfig; @Named("quotedata") @RequestScoped public class QuoteJSF { @Inject private ExternalContext facesExternalContext; @Inject private TradeAction tradeAction; private QuoteData[] quotes; private String symbols = null; private HtmlDataTable dataTable; private Integer quantity = 100; @PostConstruct public void getAllQuotes() { getQuotesBySymbols(); } public String getQuotesBySymbols() { HttpSession session = (HttpSession) facesExternalContext.getSession(true); if (symbols == null && (session.getAttribute("symbols") == null)) { setSymbols("s:0,s:1,s:2,s:3,s:4"); session.setAttribute("symbols", getSymbols()); } else if (symbols == null && session.getAttribute("symbols") != null) { setSymbols((String) session.getAttribute("symbols")); } else { session.setAttribute("symbols", getSymbols()); } java.util.StringTokenizer st = new java.util.StringTokenizer(symbols, " ,"); QuoteData[] quoteDatas = new QuoteData[st.countTokens()]; int count = 0; while (st.hasMoreElements()) { String symbol = st.nextToken(); try { QuoteDataBean quoteData = tradeAction.getQuote(symbol); quoteDatas[count] = new QuoteData(quoteData.getOpen(), quoteData.getPrice(), quoteData.getSymbol(), quoteData.getHigh(), quoteData.getLow(), quoteData.getCompanyName(), quoteData.getVolume(), quoteData.getChange()); count++; } catch (Exception e) { Log.error(e.toString()); } } setQuotes(quoteDatas); return "quotes"; } public String buy() { HttpSession session = (HttpSession) facesExternalContext.getSession(true); String userID = (String) session.getAttribute("uidBean"); QuoteData quoteData = (QuoteData) dataTable.getRowData(); OrderDataBean orderDataBean; try { orderDataBean = tradeAction.buy(userID, quoteData.getSymbol(), new Double(this.quantity).doubleValue(), TradeConfig.orderProcessingMode); OrderData orderData = new OrderData(orderDataBean.getOrderID(), orderDataBean.getOrderStatus(), orderDataBean.getOpenDate(), orderDataBean.getCompletionDate(), orderDataBean.getOrderFee(), orderDataBean.getOrderType(), orderDataBean.getQuantity(), orderDataBean.getSymbol()); session.setAttribute("orderData", orderData); } catch (Exception e) { Log.error(e.toString()); e.printStackTrace(); } return "buy"; } public void setQuotes(QuoteData[] quotes) { this.quotes = quotes; } public QuoteData[] getQuotes() { return quotes; } public void setSymbols(String symbols) { this.symbols = symbols; } public String getSymbols() { return symbols; } public void setDataTable(HtmlDataTable dataTable) { this.dataTable = dataTable; } public HtmlDataTable getDataTable() { return dataTable; } public void setQuantity(Integer quantity) { this.quantity = quantity; } public Integer getQuantity() { return quantity; } }
4,582
32.452555
156
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/jsf/TradeActionProducer.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.jsf; import javax.enterprise.context.RequestScoped; import javax.enterprise.inject.Produces; import com.ibm.websphere.samples.daytrader.TradeAction; public class TradeActionProducer { @Produces @RequestScoped public TradeAction produceTradeAction() { return new TradeAction(); } }
954
30.833333
75
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/jsf/TradeAppJSF.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.jsf; import java.io.Serializable; import java.math.BigDecimal; import javax.enterprise.context.SessionScoped; import javax.faces.context.ExternalContext; import javax.inject.Inject; import javax.inject.Named; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import com.ibm.websphere.samples.daytrader.TradeAction; import com.ibm.websphere.samples.daytrader.entities.AccountDataBean; import com.ibm.websphere.samples.daytrader.entities.AccountProfileDataBean; import com.ibm.websphere.samples.daytrader.util.Log; @Named("tradeapp") @SessionScoped public class TradeAppJSF implements Serializable { @Inject private ExternalContext facesExternalContext; @Inject private TradeAction tradeAction; private static final long serialVersionUID = 2L; private String userID = "uid:0"; private String password = "xxx"; private String cpassword; private String results; private String fullname; private String address; private String email; private String ccn; private String money; public String login() { try { AccountDataBean accountData = tradeAction.login(userID, password); AccountProfileDataBean accountProfileData = tradeAction.getAccountProfileData(userID); if (accountData != null) { HttpSession session = (HttpSession) facesExternalContext.getSession(true); session.setAttribute("uidBean", userID); session.setAttribute("sessionCreationDate", new java.util.Date()); setResults("Ready to Trade"); // Get account profile information setAddress(accountProfileData.getAddress()); setCcn(accountProfileData.getCreditCard()); setEmail(accountProfileData.getEmail()); setFullname(accountProfileData.getFullName()); setCpassword(accountProfileData.getPassword()); return "Ready to Trade"; } else { Log.log("TradeServletAction.doLogin(...)", "Error finding account for user " + userID + "", "user entered a bad username or the database is not populated"); throw new NullPointerException("User does not exist or password is incorrect!"); } } catch (Exception se) { // Go to welcome page setResults("Could not find account"); return "welcome"; } } public String register() { TradeAction tAction = new TradeAction(); // Validate user passwords match and are atleast 1 char in length try { if ((password.equals(cpassword)) && (password.length() >= 1)) { AccountDataBean accountData = tAction.register(userID, password, fullname, address, email, ccn, new BigDecimal(money)); if (accountData == null) { setResults("Registration operation failed;"); // Go to register page return "Registration operation failed"; } else { login(); setResults("Registration operation succeeded; Account " + accountData.getAccountID() + " has been created."); return "Registration operation succeeded"; } } else { // Password validation failed setResults("Registration operation failed, your passwords did not match"); // Go to register page return "Registration operation failed"; } } catch (Exception e) { // log the exception with error page Log.log("TradeServletAction.doRegister(...)" + " exception user =" + userID); try { throw new Exception("TradeServletAction.doRegister(...)" + " exception user =" + userID, e); } catch (Exception e1) { e1.printStackTrace(); } } return "Registration operation succeeded"; } public String updateProfile() { TradeAction tAction = new TradeAction(); // First verify input data boolean doUpdate = true; if (password.equals(cpassword) == false) { results = "Update profile error: passwords do not match"; doUpdate = false; } AccountProfileDataBean accountProfileData = new AccountProfileDataBean(userID, password, fullname, address, email, ccn); try { if (doUpdate) { accountProfileData = tAction.updateAccountProfile(accountProfileData); results = "Account profile update successful"; } } catch (java.lang.IllegalArgumentException e) { // this is a user error so I will // forward them to another page rather than throw a 500 setResults("invalid argument, check userID is correct, and the database is populated" + userID); Log.error(e, "TradeServletAction.doAccount(...)", "illegal argument, information should be in exception string", "treating this as a user error and forwarding on to a new page"); } catch (Exception e) { // log the exception with error page e.printStackTrace(); } // Go to account.xhtml return "Go to account"; } public String logout() { TradeAction tAction = new TradeAction(); try { setResults(""); tAction.logout(userID); } catch (java.lang.IllegalArgumentException e) { // this is a user error so I will // forward them to another page, at the end of the page. setResults("illegal argument:" + e.getMessage()); // log the exception with an error level of 3 which means, handled // exception but would invalidate a automation run Log.error(e, "TradeServletAction.doLogout(...)", "illegal argument, information should be in exception string", "treating this as a user error and forwarding on to a new page"); } catch (Exception e) { // log the exception and foward to a error page Log.error(e, "TradeAppJSF.logout():", "Error logging out" + userID, "fowarding to an error page"); } HttpSession session = (HttpSession) facesExternalContext.getSession(false); if (session != null) { session.invalidate(); } // Added to actually remove a user from the authentication cache try { ((HttpServletRequest) facesExternalContext.getRequest()).logout(); } catch (ServletException e) { Log.error(e, "TradeAppJSF.logout():", "Error logging out request" + userID, "fowarding to an error page"); } // Go to welcome page return "welcome"; } public String getUserID() { return userID; } public void setUserID(String userID) { this.userID = userID; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getCpassword() { return cpassword; } public void setCpassword(String cpassword) { this.cpassword = cpassword; } public String getFullname() { return fullname; } public void setFullname(String fullname) { this.fullname = fullname; } public String getResults() { String tempResults=results; results=""; return tempResults; } public void setResults(String results) { this.results = results; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getCcn() { return ccn; } public void setCcn(String ccn) { this.ccn = ccn; } public String getMoney() { return money; } public void setMoney(String money) { this.money = money; } };
9,036
32.47037
135
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/jsf/TradeConfigJSF.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.jsf; import javax.enterprise.context.RequestScoped; import javax.faces.context.ExternalContext; import javax.inject.Inject; import javax.inject.Named; import javax.servlet.http.HttpSession; import com.ibm.websphere.samples.daytrader.TradeAction; import com.ibm.websphere.samples.daytrader.beans.RunStatsDataBean; import com.ibm.websphere.samples.daytrader.direct.TradeDirect; import com.ibm.websphere.samples.daytrader.util.Log; import com.ibm.websphere.samples.daytrader.util.TradeConfig; import com.ibm.websphere.samples.daytrader.web.TradeBuildDB; @Named("tradeconfig") @RequestScoped public class TradeConfigJSF { @Inject private ExternalContext facesExternalContext; private String runtimeMode = TradeConfig.runTimeModeNames[TradeConfig.getRunTimeMode()]; private String orderProcessingMode = TradeConfig.orderProcessingModeNames[TradeConfig.getOrderProcessingMode()]; //private String cachingType = TradeConfig.cachingTypeNames[TradeConfig.getCachingType()]; //private int distributedMapCacheSize = TradeConfig.getDistributedMapCacheSize(); private int maxUsers = TradeConfig.getMAX_USERS(); private int maxQuotes = TradeConfig.getMAX_QUOTES(); private int marketSummaryInterval = TradeConfig.getMarketSummaryInterval(); private String webInterface = TradeConfig.webInterfaceNames[TradeConfig.getWebInterface()]; private int primIterations = TradeConfig.getPrimIterations(); private int percentSentToWebsocket = TradeConfig.getPercentSentToWebsocket(); private boolean publishQuotePriceChange = TradeConfig.getPublishQuotePriceChange(); private boolean longRun = TradeConfig.getLongRun(); private boolean displayOrderAlerts = TradeConfig.getDisplayOrderAlerts(); private boolean useRemoteEJBInterface = TradeConfig.useRemoteEJBInterface(); private boolean actionTrace = TradeConfig.getActionTrace(); private boolean trace = TradeConfig.getTrace(); private String[] runtimeModeList = TradeConfig.runTimeModeNames; private String[] orderProcessingModeList = TradeConfig.orderProcessingModeNames; //private String[] cachingTypeList = TradeConfig.cachingTypeNames; private String[] webInterfaceList = TradeConfig.webInterfaceNames; private String result = ""; public void updateConfig() { String currentConfigStr = "\n\n########## Trade configuration update. Current config:\n\n"; String runTimeModeStr = this.runtimeMode; if (runTimeModeStr != null) { try { for (int i = 0; i < runtimeModeList.length; i++) { if (runTimeModeStr.equals(runtimeModeList[i])) { TradeConfig.setRunTimeMode(i); } } } catch (Exception e) { Log.error(e, "TradeConfigJSF.updateConfig(..): minor exception caught", "trying to set runtimemode to " + runTimeModeStr, "reverting to current value"); } // If the value is bad, simply revert to current } currentConfigStr += "\t\tRunTimeMode:\t\t\t" + TradeConfig.runTimeModeNames[TradeConfig.getRunTimeMode()] + "\n"; TradeConfig.setUseRemoteEJBInterface(useRemoteEJBInterface); currentConfigStr += "\t\tUse Remote EJB Interface:\t" + TradeConfig.useRemoteEJBInterface() + "\n"; String orderProcessingModeStr = this.orderProcessingMode; if (orderProcessingModeStr != null) { try { for (int i = 0; i < orderProcessingModeList.length; i++) { if (orderProcessingModeStr.equals(orderProcessingModeList[i])) { TradeConfig.orderProcessingMode = i; } } } catch (Exception e) { Log.error(e, "TradeConfigJSF.updateConfig(..): minor exception caught", "trying to set orderProcessing to " + orderProcessingModeStr, "reverting to current value"); } // If the value is bad, simply revert to current } currentConfigStr += "\t\tOrderProcessingMode:\t\t" + TradeConfig.orderProcessingModeNames[TradeConfig.orderProcessingMode] + "\n"; /* String cachingTypeStr = this.cachingType; if (cachingTypeStr != null) { try { for (int i = 0; i < cachingTypeList.length; i++) { if (cachingTypeStr.equals(cachingTypeList[i])) { TradeConfig.cachingType = i; } } } catch (Exception e) { Log.error(e, "TradeConfigJSF.updateConfig(..): minor exception caught", "trying to set cachingType to " + cachingTypeStr, "reverting to current value"); } // If the value is bad, simply revert to current } currentConfigStr += "\t\tCachingType:\t\t\t" + TradeConfig.cachingTypeNames[TradeConfig.cachingType] + "\n"; int distMapCacheSize = this.distributedMapCacheSize; try { TradeConfig.setDistributedMapCacheSize(distMapCacheSize); } catch (Exception e) { Log.error(e, "TradeConfigJSF.updateConfig(..): minor exception caught", "trying to set distributedMapCacheSize", "reverting to current value"); } // If the value is bad, simply revert to current currentConfigStr += "\t\tDMapCacheSize:\t\t\t" + TradeConfig.getDistributedMapCacheSize() + "\n"; */ String webInterfaceStr = webInterface; if (webInterfaceStr != null) { try { for (int i = 0; i < webInterfaceList.length; i++) { if (webInterfaceStr.equals(webInterfaceList[i])) { TradeConfig.webInterface = i; } } } catch (Exception e) { Log.error(e, "TradeConfigJSF.updateConfig(..): minor exception caught", "trying to set WebInterface to " + webInterfaceStr, "reverting to current value"); } // If the value is bad, simply revert to current } currentConfigStr += "\t\tWeb Interface:\t\t\t" + TradeConfig.webInterfaceNames[TradeConfig.webInterface] + "\n"; TradeConfig.setMAX_USERS(maxUsers); TradeConfig.setMAX_QUOTES(maxQuotes); currentConfigStr += "\t\tTrade Users:\t\t\t" + TradeConfig.getMAX_USERS() + "\n"; currentConfigStr += "\t\tTrade Quotes:\t\t\t" + TradeConfig.getMAX_QUOTES() + "\n"; TradeConfig.setMarketSummaryInterval(marketSummaryInterval); currentConfigStr += "\t\tMarket Summary Interval:\t" + TradeConfig.getMarketSummaryInterval() + "\n"; TradeConfig.setPrimIterations(primIterations); currentConfigStr += "\t\tPrimitive Iterations:\t\t" + TradeConfig.getPrimIterations() + "\n"; TradeConfig.setPublishQuotePriceChange(publishQuotePriceChange); currentConfigStr += "\t\tTradeStreamer MDB Enabled:\t" + TradeConfig.getPublishQuotePriceChange() + "\n"; TradeConfig.setPercentSentToWebsocket(percentSentToWebsocket); currentConfigStr += "\t\t% of trades on Websocket:\t" + TradeConfig.getPercentSentToWebsocket() + "\n"; TradeConfig.setLongRun(longRun); currentConfigStr += "\t\tLong Run Enabled:\t\t" + TradeConfig.getLongRun() + "\n"; TradeConfig.setDisplayOrderAlerts(displayOrderAlerts); currentConfigStr += "\t\tDisplay Order Alerts:\t\t" + TradeConfig.getDisplayOrderAlerts() + "\n"; Log.setTrace(trace); currentConfigStr += "\t\tTrace Enabled:\t\t\t" + TradeConfig.getTrace() + "\n"; Log.setActionTrace(actionTrace); currentConfigStr += "\t\tAction Trace Enabled:\t\t" + TradeConfig.getActionTrace() + "\n"; System.out.println(currentConfigStr); setResult("DayTrader Configuration Updated"); } public String resetTrade() { RunStatsDataBean runStatsData = new RunStatsDataBean(); TradeConfig currentConfig = new TradeConfig(); HttpSession session = (HttpSession) facesExternalContext.getSession(true); try { // Do not inject TradeAction on this class because we dont want the // config to initialiaze at startup. TradeAction tradeAction = new TradeAction(); runStatsData = tradeAction.resetTrade(false); session.setAttribute("runStatsData", runStatsData); session.setAttribute("tradeConfig", currentConfig); result += "Trade Reset completed successfully"; } catch (Exception e) { result += "Trade Reset Error - see log for details"; session.setAttribute("result", result); Log.error(e, result); } return "stats"; } public String populateDatabase() { try { new TradeBuildDB(new java.io.PrintWriter(System.out), null); } catch (Exception e) { e.printStackTrace(); } result = "TradeBuildDB: **** DayTrader Database Built - " + TradeConfig.getMAX_USERS() + " users created, " + TradeConfig.getMAX_QUOTES() + " quotes created. ****<br/>"; result += "TradeBuildDB: **** Check System.Out for any errors. ****<br/>"; return "database"; } public String buildDatabaseTables() { try { //Find out the Database being used TradeDirect tradeDirect = new TradeDirect(); String dbProductName = null; try { dbProductName = tradeDirect.checkDBProductName(); } catch (Exception e) { Log.error(e, "TradeBuildDB: Unable to check DB Product name"); } if (dbProductName == null) { result += "TradeBuildDB: **** Unable to check DB Product name, please check Database/AppServer configuration and retry ****<br/>"; return "database"; } String ddlFile = null; //Locate DDL file for the specified database try { result = result + "TradeBuildDB: **** Database Product detected: " + dbProductName + " ****<br/>"; if (dbProductName.startsWith("DB2/")) { // if db is DB2 ddlFile = "/dbscripts/db2/Table.ddl"; } else if (dbProductName.startsWith("DB2 UDB for AS/400")) { //if db is DB2 on IBM i ddlFile = "/dbscripts/db2i/Table.ddl"; } else if (dbProductName.startsWith("Apache Derby")) { //if db is Derby ddlFile = "/dbscripts/derby/Table.ddl"; } else if (dbProductName.startsWith("Oracle")) { // if the Db is Oracle ddlFile = "/dbscripts/oracle/Table.ddl"; } else { // Unsupported "Other" Database ddlFile = "/dbscripts/derby/Table.ddl"; result = result + "TradeBuildDB: **** This Database is unsupported/untested use at your own risk ****<br/>"; } result = result + "TradeBuildDB: **** The DDL file at path" + ddlFile + " will be used ****<br/>"; } catch (Exception e) { Log.error(e, "TradeBuildDB: Unable to locate DDL file for the specified database"); result = result + "TradeBuildDB: **** Unable to locate DDL file for the specified database ****<br/>"; return "database"; } new TradeBuildDB(new java.io.PrintWriter(System.out), facesExternalContext.getResourceAsStream(ddlFile)); result = result + "TradeBuildDB: **** DayTrader Database Created, Check System.Out for any errors. ****<br/>"; } catch (Exception e) { e.printStackTrace(); } // Go to configure.xhtml return "database"; } public void setRuntimeMode(String runtimeMode) { this.runtimeMode = runtimeMode; } public String getRuntimeMode() { return runtimeMode; } public void setOrderProcessingMode(String orderProcessingMode) { this.orderProcessingMode = orderProcessingMode; } public String getOrderProcessingMode() { return orderProcessingMode; } /* public void setCachingType(String cachingType) { this.cachingType = cachingType; } public String getCachingType() { return cachingType; } public void setDistributedMapCacheSize(int distributedMapCacheSize) { this.distributedMapCacheSize = distributedMapCacheSize; } public int getDistributedMapCacheSize() { return distributedMapCacheSize; }*/ public void setMaxUsers(int maxUsers) { this.maxUsers = maxUsers; } public int getMaxUsers() { return maxUsers; } public void setmaxQuotes(int maxQuotes) { this.maxQuotes = maxQuotes; } public int getMaxQuotes() { return maxQuotes; } public void setMarketSummaryInterval(int marketSummaryInterval) { this.marketSummaryInterval = marketSummaryInterval; } public int getMarketSummaryInterval() { return marketSummaryInterval; } public void setPrimIterations(int primIterations) { this.primIterations = primIterations; } public int getPrimIterations() { return primIterations; } public void setPublishQuotePriceChange(boolean publishQuotePriceChange) { this.publishQuotePriceChange = publishQuotePriceChange; } public boolean isPublishQuotePriceChange() { return publishQuotePriceChange; } public void setPercentSentToWebsocket(int percentSentToWebsocket) { this. percentSentToWebsocket = percentSentToWebsocket; } public int getPercentSentToWebsocket() { return percentSentToWebsocket; } public void setDisplayOrderAlerts(boolean displayOrderAlerts) { this.displayOrderAlerts = displayOrderAlerts; } public boolean isDisplayOrderAlerts() { return displayOrderAlerts; } public void setUseRemoteEJBInterface(boolean useRemoteEJBInterface) { this.useRemoteEJBInterface = useRemoteEJBInterface; } public boolean isUseRemoteEJBInterface() { return useRemoteEJBInterface; } public void setLongRun(boolean longRun) { this.longRun = longRun; } public boolean isLongRun() { return longRun; } public void setTrace(boolean trace) { this.trace = trace; } public boolean isTrace() { return trace; } public void setRuntimeModeList(String[] runtimeModeList) { this.runtimeModeList = runtimeModeList; } public String[] getRuntimeModeList() { return runtimeModeList; } public void setOrderProcessingModeList(String[] orderProcessingModeList) { this.orderProcessingModeList = orderProcessingModeList; } public String[] getOrderProcessingModeList() { return orderProcessingModeList; } /*public void setCachingTypeList(String[] cachingTypeList) { this.cachingTypeList = cachingTypeList; } public String[] getCachingTypeList() { return cachingTypeList; }*/ public void setWebInterface(String webInterface) { this.webInterface = webInterface; } public String getWebInterface() { return webInterface; } public void setWebInterfaceList(String[] webInterfaceList) { this.webInterfaceList = webInterfaceList; } public String[] getWebInterfaceList() { return webInterfaceList; } public void setActionTrace(boolean actionTrace) { this.actionTrace = actionTrace; } public boolean isActionTrace() { return actionTrace; } public void setResult(String result) { this.result = result; } public String getResult() { return result; } }
16,606
36.915525
155
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/prims/ExplicitGC.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.prims; import java.io.IOException; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ibm.websphere.samples.daytrader.util.Log; /** * * ExplicitGC invokes System.gc(). This allows one to gather min / max heap * statistics. * */ @WebServlet(name = "ExplicitGC", urlPatterns = { "/servlet/ExplicitGC" }) public class ExplicitGC extends HttpServlet { private static final long serialVersionUID = -3758934393801102408L; private static String initTime; private static int hitCount; /** * forwards post requests to the doGet method Creation date: (01/29/2006 * 20:10:00 PM) * * @param res * javax.servlet.http.HttpServletRequest * @param res2 * javax.servlet.http.HttpServletResponse */ @Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doGet(req, res); } /** * this is the main method of the servlet that will service all get * requests. * * @param request * HttpServletRequest * @param responce * HttpServletResponce **/ @Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { try { res.setContentType("text/html"); ServletOutputStream out = res.getOutputStream(); hitCount++; long totalMemory = Runtime.getRuntime().totalMemory(); long maxMemoryBeforeGC = Runtime.getRuntime().maxMemory(); long freeMemoryBeforeGC = Runtime.getRuntime().freeMemory(); long startTime = System.currentTimeMillis(); System.gc(); // Invoke the GC. long endTime = System.currentTimeMillis(); long maxMemoryAfterGC = Runtime.getRuntime().maxMemory(); long freeMemoryAfterGC = Runtime.getRuntime().freeMemory(); out.println("<html><head><title>ExplicitGC</title></head>" + "<body><HR><BR><FONT size=\"+2\" color=\"#000066\">Explicit Garbage Collection<BR></FONT><FONT size=\"+1\" color=\"#000066\">Init time : " + initTime + "<BR><BR></FONT> <B>Hit Count: " + hitCount + "<br>" + "<table border=\"0\"><tr>" + "<td align=\"right\">Total Memory</td><td align=\"right\">" + totalMemory + "</td>" + "</tr></table>" + "<table width=\"350\"><tr><td colspan=\"2\" align=\"left\">" + "Statistics before GC</td></tr>" + "<tr><td align=\"right\">" + "Max Memory</td><td align=\"right\">" + maxMemoryBeforeGC + "</td></tr>" + "<tr><td align=\"right\">" + "Free Memory</td><td align=\"right\">" + freeMemoryBeforeGC + "</td></tr>" + "<tr><td align=\"right\">" + "Used Memory</td><td align=\"right\">" + (totalMemory - freeMemoryBeforeGC) + "</td></tr>" + "<tr><td colspan=\"2\" align=\"left\">Statistics after GC</td></tr>" + "<tr><td align=\"right\">" + "Max Memory</td><td align=\"right\">" + maxMemoryAfterGC + "</td></tr>" + "<tr><td align=\"right\">" + "Free Memory</td><td align=\"right\">" + freeMemoryAfterGC + "</td></tr>" + "<tr><td align=\"right\">" + "Used Memory</td><td align=\"right\">" + (totalMemory - freeMemoryAfterGC) + "</td></tr>" + "<tr><td align=\"right\">" + "Total Time in GC</td><td align=\"right\">" + Float.toString((endTime - startTime) / 1000) + "s</td></tr>" + "</table>" + "</body></html>"); } catch (Exception e) { Log.error(e, "ExplicitGC.doGet(...): general exception caught"); res.sendError(500, e.toString()); } } /** * returns a string of information about the servlet * * @return info String: contains info about the servlet **/ @Override public String getServletInfo() { return "Generate Explicit GC to VM"; } /** * called when the class is loaded to initialize the servlet * * @param config * ServletConfig: **/ @Override public void init(ServletConfig config) throws ServletException { super.init(config); initTime = new java.util.Date().toString(); hitCount = 0; } }
5,851
35.805031
160
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/prims/PingBean.java
/** * (C) Copyright IBM Corporation 2016. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.prims; /** * Simple bean to get and set messages */ public class PingBean { private String msg; /** * returns the message contained in the bean * * @return message String **/ public String getMsg() { return msg; } /** * sets the message contained in the bean param message String **/ public void setMsg(String s) { msg = s; } }
1,057
24.804878
75
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/prims/PingCDIBean.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.prims; import java.util.Set; import javax.enterprise.context.RequestScoped; import javax.enterprise.inject.spi.Bean; import javax.enterprise.inject.spi.BeanManager; import javax.enterprise.inject.spi.CDI; import javax.naming.InitialContext; @RequestScoped @PingInterceptorBinding public class PingCDIBean { private static int helloHitCount = 0; private static int getBeanManagerHitCountJNDI = 0; private static int getBeanManagerHitCountSPI = 0; public int hello() { return ++helloHitCount; } public int getBeanMangerViaJNDI() throws Exception { BeanManager beanManager = (BeanManager) new InitialContext().lookup("java:comp/BeanManager"); Set<Bean<?>> beans = beanManager.getBeans(Object.class); if (beans.size() > 0) { return ++getBeanManagerHitCountJNDI; } return 0; } public int getBeanMangerViaCDICurrent() throws Exception { BeanManager beanManager = CDI.current().getBeanManager(); Set<Bean<?>> beans = beanManager.getBeans(Object.class); if (beans.size() > 0) { return ++getBeanManagerHitCountSPI; } return 0; } }
1,846
29.783333
101
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/prims/PingCDIJSFBean.java
/** * (C) Copyright IBM Corporation 2016. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.prims; import java.io.Serializable; import javax.enterprise.context.SessionScoped; import javax.inject.Named; @Named @SessionScoped public class PingCDIJSFBean implements Serializable { private static final long serialVersionUID = -7475815494313679416L; private int hitCount = 0; public int getHitCount() { return ++hitCount; } }
1,008
28.676471
75
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/prims/PingEJBIFace.java
/** * (C) Copyright IBM Corporation 2016. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.prims; /** * EJB interface */ public interface PingEJBIFace { public String getMsg(); }
745
28.84
75
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/prims/PingEJBLocal.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.prims; import javax.ejb.Local; import javax.ejb.Stateful; /** * */ @Stateful @Local public class PingEJBLocal implements PingEJBIFace { private static int hitCount; /* * (non-Javadoc) * * @see com.ibm.websphere.samples.daytrader.web.prims.EJBIFace#getMsg() */ @Override public String getMsg() { return "PingEJBLocal: " + hitCount++; } }
1,043
23.857143
75
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/prims/PingEJBLocalDecorator.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.prims; import javax.annotation.Priority; import javax.decorator.Decorator; import javax.decorator.Delegate; import javax.inject.Inject; import javax.interceptor.Interceptor; @Decorator @Priority(Interceptor.Priority.APPLICATION) public class PingEJBLocalDecorator implements PingEJBIFace { /* * (non-Javadoc) * * @see com.ibm.websphere.samples.daytrader.web.prims.EJBIFace#getMsg() */ @Delegate @Inject PingEJBIFace ejb; @Override public String getMsg() { return "Decorated " + ejb.getMsg(); } }
1,208
26.477273
75
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/prims/PingInterceptor.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.prims; import java.io.Serializable; import javax.annotation.Priority; import javax.interceptor.AroundInvoke; import javax.interceptor.Interceptor; import javax.interceptor.InvocationContext; /** * */ @PingInterceptorBinding @Interceptor @Priority(Interceptor.Priority.APPLICATION) public class PingInterceptor implements Serializable { /** */ private static final long serialVersionUID = 1L; @AroundInvoke public Object methodInterceptor(InvocationContext ctx) throws Exception { //noop return ctx.proceed(); } }
1,207
27.093023
77
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/prims/PingInterceptorBinding.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.prims; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import javax.interceptor.InterceptorBinding; /** * */ @InterceptorBinding @Target({ ElementType.TYPE, ElementType.CONSTRUCTOR }) @Retention(RetentionPolicy.RUNTIME) public @interface PingInterceptorBinding { }
1,033
29.411765
75
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/prims/PingJDBCRead.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.prims; import java.io.IOException; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ibm.websphere.samples.daytrader.direct.TradeDirect; import com.ibm.websphere.samples.daytrader.entities.QuoteDataBean; import com.ibm.websphere.samples.daytrader.util.Log; import com.ibm.websphere.samples.daytrader.util.TradeConfig; /** * * PingJDBCReadPrepStmt uses a prepared statement for database read access. This * primative uses * {@link com.ibm.websphere.samples.daytrader.direct.TradeDirect} to set the * price of a random stock (generated by * {@link com.ibm.websphere.samples.daytrader.util.TradeConfig}) through the use * of prepared statements. * */ @WebServlet(name = "PingJDBCRead", urlPatterns = { "/servlet/PingJDBCRead" }) public class PingJDBCRead extends HttpServlet { private static final long serialVersionUID = -8810390150632488526L; private static String initTime; private static int hitCount; /** * forwards post requests to the doGet method Creation date: (11/6/2000 * 10:52:39 AM) * * @param res * javax.servlet.http.HttpServletRequest * @param res2 * javax.servlet.http.HttpServletResponse */ @Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doGet(req, res); } /** * this is the main method of the servlet that will service all get * requests. * * @param request * HttpServletRequest * @param responce * HttpServletResponce **/ @Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); java.io.PrintWriter out = res.getWriter(); String symbol = null; StringBuffer output = new StringBuffer(100); try { // TradeJDBC uses prepared statements so I am going to make use of // it's code. TradeDirect trade = new TradeDirect(); symbol = TradeConfig.rndSymbol(); QuoteDataBean quoteData = null; int iter = TradeConfig.getPrimIterations(); for (int ii = 0; ii < iter; ii++) { quoteData = trade.getQuote(symbol); } output.append("<html><head><title>Ping JDBC Read w/ Prepared Stmt.</title></head>" + "<body><HR><FONT size=\"+2\" color=\"#000066\">Ping JDBC Read w/ Prep Stmt:</FONT><HR><FONT size=\"-1\" color=\"#000066\">Init time : " + initTime); hitCount++; output.append("<BR>Hit Count: " + hitCount); output.append("<HR>Quote Information <BR><BR>: " + quoteData.toHTML()); output.append("<HR></body></html>"); out.println(output.toString()); } catch (Exception e) { Log.error(e, "PingJDBCRead w/ Prep Stmt -- error getting quote for symbol", symbol); res.sendError(500, "PingJDBCRead Exception caught: " + e.toString()); } } /** * returns a string of information about the servlet * * @return info String: contains info about the servlet **/ @Override public String getServletInfo() { return "Basic JDBC Read using a prepared statment, makes use of TradeJDBC class"; } /** * called when the class is loaded to initialize the servlet * * @param config * ServletConfig: **/ @Override public void init(ServletConfig config) throws ServletException { super.init(config); hitCount = 0; initTime = new java.util.Date().toString(); } }
4,580
34.511628
157
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/prims/PingJDBCRead2JSP.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.prims; import java.io.IOException; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ibm.websphere.samples.daytrader.direct.TradeDirect; import com.ibm.websphere.samples.daytrader.entities.QuoteDataBean; import com.ibm.websphere.samples.daytrader.util.Log; import com.ibm.websphere.samples.daytrader.util.TradeConfig; /** * * PingJDBCReadPrepStmt uses a prepared statement for database read access. This * primative uses * {@link com.ibm.websphere.samples.daytrader.direct.TradeDirect} to set the * price of a random stock (generated by * {@link com.ibm.websphere.samples.daytrader.util.TradeConfig}) through the use * of prepared statements. * */ @WebServlet(name = "PingJDBCRead2JSP", urlPatterns = { "/servlet/PingJDBCRead2JSP" }) public class PingJDBCRead2JSP extends HttpServlet { private static final long serialVersionUID = 1118803761565654806L; /** * forwards post requests to the doGet method Creation date: (11/6/2000 * 10:52:39 AM) * * @param res * javax.servlet.http.HttpServletRequest * @param res2 * javax.servlet.http.HttpServletResponse */ @Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doGet(req, res); } /** * this is the main method of the servlet that will service all get * requests. * * @param request * HttpServletRequest * @param responce * HttpServletResponce **/ @Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String symbol = null; QuoteDataBean quoteData = null; ServletContext ctx = getServletConfig().getServletContext(); try { // TradeJDBC uses prepared statements so I am going to make use of // it's code. TradeDirect trade = new TradeDirect(); symbol = TradeConfig.rndSymbol(); int iter = TradeConfig.getPrimIterations(); for (int ii = 0; ii < iter; ii++) { quoteData = trade.getQuote(symbol); } req.setAttribute("quoteData", quoteData); // req.setAttribute("hitCount", hitCount); // req.setAttribute("initTime", initTime); ctx.getRequestDispatcher("/quoteDataPrimitive.jsp").include(req, res); } catch (Exception e) { Log.error(e, "PingJDBCRead2JPS -- error getting quote for symbol", symbol); res.sendError(500, "PingJDBCRead2JSP Exception caught: " + e.toString()); } } /** * returns a string of information about the servlet * * @return info String: contains info about the servlet **/ @Override public String getServletInfo() { return "Basic JDBC Read using a prepared statment forwarded to a JSP, makes use of TradeJDBC class"; } /** * called when the class is loaded to initialize the servlet * * @param config * ServletConfig: **/ @Override public void init(ServletConfig config) throws ServletException { super.init(config); // hitCount = 0; // initTime = new java.util.Date().toString(); } }
4,203
33.178862
110
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/prims/PingJDBCWrite.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.prims; import java.io.IOException; import java.math.BigDecimal; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ibm.websphere.samples.daytrader.direct.TradeDirect; import com.ibm.websphere.samples.daytrader.entities.QuoteDataBean; import com.ibm.websphere.samples.daytrader.util.Log; import com.ibm.websphere.samples.daytrader.util.TradeConfig; /** * * PingJDBCReadPrepStmt uses a prepared statement for database update. Statement * parameters are set dynamically on each request. This primative uses * {@link com.ibm.websphere.samples.daytrader.direct.TradeDirect} to set the * price of a random stock (generated by * {@link com.ibm.websphere.samples.daytrader.util.TradeConfig}) through the use * of prepared statements. * */ @WebServlet(name = "PingJDBCWrite", urlPatterns = { "/servlet/PingJDBCWrite" }) public class PingJDBCWrite extends HttpServlet { private static final long serialVersionUID = -4938035109655376503L; private static String initTime; private static int hitCount; /** * this is the main method of the servlet that will service all get * requests. * * @param request * HttpServletRequest * @param responce * HttpServletResponce **/ @Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String symbol = null; BigDecimal newPrice; StringBuffer output = new StringBuffer(100); res.setContentType("text/html"); java.io.PrintWriter out = res.getWriter(); try { // get a random symbol to update and a random price. symbol = TradeConfig.rndSymbol(); newPrice = TradeConfig.getRandomPriceChangeFactor(); // TradeJDBC makes use of prepared statements so I am going to reuse // the existing code. TradeDirect trade = new TradeDirect(); // update the price of our symbol QuoteDataBean quoteData = null; int iter = TradeConfig.getPrimIterations(); for (int ii = 0; ii < iter; ii++) { quoteData = trade.updateQuotePriceVolumeInt(symbol, newPrice, 100.0, false); } // write the output output.append("<html><head><title>Ping JDBC Write w/ Prepared Stmt.</title></head>" + "<body><HR><FONT size=\"+2\" color=\"#000066\">Ping JDBC Write w/ Prep Stmt:</FONT><FONT size=\"-1\" color=\"#000066\"><HR>Init time : " + initTime); hitCount++; output.append("<BR>Hit Count: " + hitCount); output.append("<HR>Update Information<BR>"); output.append("<BR>" + quoteData.toHTML() + "<HR></FONT></BODY></HTML>"); out.println(output.toString()); } catch (Exception e) { Log.error(e, "PingJDBCWrite -- error updating quote for symbol", symbol); res.sendError(500, "PingJDBCWrite Exception caught: " + e.toString()); } } /** * returns a string of information about the servlet * * @return info String: contains info about the servlet **/ @Override public String getServletInfo() { return "Basic JDBC Write using a prepared statment makes use of TradeJDBC code."; } /** * called when the class is loaded to initialize the servlet * * @param config * ServletConfig: **/ @Override public void init(ServletConfig config) throws ServletException { super.init(config); initTime = new java.util.Date().toString(); hitCount = 0; } /** * forwards post requests to the doGet method Creation date: (11/6/2000 * 10:52:39 AM) * * @param res * javax.servlet.http.HttpServletRequest * @param res2 * javax.servlet.http.HttpServletResponse */ @Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doGet(req, res); } }
4,958
34.934783
158
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/prims/PingJSONP.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.prims; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import javax.json.Json; import javax.json.stream.JsonGenerator; import javax.json.stream.JsonParser; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ibm.websphere.samples.daytrader.util.Log; /** * * PingJSONP tests JSON generating and parsing * */ @WebServlet(name = "PingJSONP", urlPatterns = { "/servlet/PingJSONP" }) public class PingJSONP extends HttpServlet { /** * */ private static final long serialVersionUID = -5348806619121122708L; private static String initTime; private static int hitCount; /** * forwards post requests to the doGet method Creation date: (11/6/2000 * 10:52:39 AM) * * @param res * javax.servlet.http.HttpServletRequest * @param res2 * javax.servlet.http.HttpServletResponse */ @Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doGet(req, res); } /** * this is the main method of the servlet that will service all get * requests. * * @param request * HttpServletRequest * @param responce * HttpServletResponce **/ @Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { try { res.setContentType("text/html"); ServletOutputStream out = res.getOutputStream(); hitCount++; // JSON generate StringWriter sw = new StringWriter(); JsonGenerator generator = Json.createGenerator(sw); generator.writeStartObject(); generator.write("initTime",initTime); generator.write("hitCount", hitCount); generator.writeEnd(); generator.flush(); String generatedJSON = sw.toString(); StringBuffer parsedJSON = new StringBuffer(); // JSON parse JsonParser parser = Json.createParser(new StringReader(generatedJSON)); while (parser.hasNext()) { JsonParser.Event event = parser.next(); switch(event) { case START_ARRAY: case END_ARRAY: case START_OBJECT: case END_OBJECT: case VALUE_FALSE: case VALUE_NULL: case VALUE_TRUE: break; case KEY_NAME: parsedJSON.append(parser.getString() + ":"); break; case VALUE_STRING: case VALUE_NUMBER: parsedJSON.append(parser.getString() + " "); break; } } out.println("<html><head><title>Ping JSONP</title></head>" + "<body><HR><BR><FONT size=\"+2\" color=\"#000066\">Ping JSONP</FONT><BR>Generated JSON: " + generatedJSON + "<br>Parsed JSON: " + parsedJSON + "</body></html>"); } catch (Exception e) { Log.error(e, "PingJSONP.doGet(...): general exception caught"); res.sendError(500, e.toString()); } } /** * returns a string of information about the servlet * * @return info String: contains info about the servlet **/ @Override public String getServletInfo() { return "Basic JSON generation and parsing in a servlet"; } /** * called when the class is loaded to initialize the servlet * * @param config * ServletConfig: **/ @Override public void init(ServletConfig config) throws ServletException { super.init(config); initTime = new java.util.Date().toString(); hitCount = 0; } }
4,874
31.284768
183
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/prims/PingManagedExecutor.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.prims; import java.io.IOException; import javax.annotation.Resource; import javax.enterprise.concurrent.ManagedExecutorService; import javax.servlet.AsyncContext; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet(asyncSupported=true,name = "PingManagedExecutor", urlPatterns = { "/servlet/PingManagedExecutor" }) public class PingManagedExecutor extends HttpServlet{ private static final long serialVersionUID = -4695386150928451234L; private static String initTime; private static int hitCount; @Resource private ManagedExecutorService mes; /** * forwards post requests to the doGet method Creation date: (03/18/2014 * 10:52:39 AM) * * @param res * javax.servlet.http.HttpServletRequest * @param res2 * javax.servlet.http.HttpServletResponse */ @Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doGet(req, res); } /** * this is the main method of the servlet that will service all get * requests. * * @param request * HttpServletRequest * @param responce * HttpServletResponce **/ @Override protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { final AsyncContext asyncContext = req.startAsync(); final ServletOutputStream out = res.getOutputStream(); try { res.setContentType("text/html"); out.println("<html><head><title>Ping ManagedExecutor</title></head>" + "<body><HR><BR><FONT size=\"+2\" color=\"#000066\">Ping ManagedExecutor<BR></FONT><FONT size=\"+1\" color=\"#000066\">Init time : " + initTime + "<BR><BR></FONT> </body></html>"); // Runnable task mes.submit(new Runnable() { @Override public void run() { try { out.println("<b>HitCount: " + ++hitCount +"</b><br/>"); } catch (IOException e) { e.printStackTrace(); } asyncContext.complete(); } }); } catch (Exception e) { e.printStackTrace(); } } /** * returns a string of information about the servlet * * @return info String: contains info about the servlet **/ @Override public String getServletInfo() { return "Tests a ManagedExecutor"; } /** * called when the class is loaded to initialize the servlet * * @param config * ServletConfig: **/ @Override public void init(ServletConfig config) throws ServletException { super.init(config); initTime = new java.util.Date().toString(); hitCount = 0; } }
3,734
29.867769
164
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/prims/PingManagedThread.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.prims; import java.io.IOException; import javax.annotation.Resource; import javax.enterprise.concurrent.ManagedThreadFactory; import javax.servlet.AsyncContext; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ibm.websphere.samples.daytrader.util.Log; @WebServlet(asyncSupported=true,name = "PingManagedThread", urlPatterns = { "/servlet/PingManagedThread" }) public class PingManagedThread extends HttpServlet{ private static final long serialVersionUID = -4695386150928451234L; private static String initTime; private static int hitCount; @Resource private ManagedThreadFactory managedThreadFactory; /** * forwards post requests to the doGet method Creation date: (03/18/2014 * 10:52:39 AM) * * @param res * javax.servlet.http.HttpServletRequest * @param res2 * javax.servlet.http.HttpServletResponse */ @Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doGet(req, res); } /** * this is the main method of the servlet that will service all get * requests. * * @param request * HttpServletRequest * @param responce * HttpServletResponce **/ @Override protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { final AsyncContext asyncContext = req.startAsync(); final ServletOutputStream out = res.getOutputStream(); try { res.setContentType("text/html"); out.println("<html><head><title>Ping ManagedThread</title></head>" + "<body><HR><BR><FONT size=\"+2\" color=\"#000066\">Ping ManagedThread<BR></FONT><FONT size=\"+1\" color=\"#000066\">Init time : " + initTime + "<BR/><BR/></FONT>"); Thread thread = managedThreadFactory.newThread(new Runnable() { @Override public void run() { try { out.println("<b>HitCount: " + ++hitCount +"</b><br/>"); } catch (IOException e) { e.printStackTrace(); } asyncContext.complete(); } }); thread.start(); } catch (Exception e) { Log.error(e, "PingManagedThreadServlet.doGet(...): general exception caught"); res.sendError(500, e.toString()); } } /** * returns a string of information about the servlet * * @return info String: contains info about the servlet **/ @Override public String getServletInfo() { return "Tests a ManagedThread asynchronous servlet"; } /** * called when the class is loaded to initialize the servlet * * @param config * ServletConfig: **/ @Override public void init(ServletConfig config) throws ServletException { super.init(config); initTime = new java.util.Date().toString(); hitCount = 0; } }
3,854
29.354331
189
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/prims/PingReentryServlet.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.prims; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet(name = "PingReentryServlet", urlPatterns = { "/servlet/PingReentryServlet" }) public class PingReentryServlet extends HttpServlet { private static final long serialVersionUID = -2536027021580175706L; @Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doGet(req, res); } /** * this is the main method of the servlet that will service all get * requests. * * @param request * HttpServletRequest * @param responce * HttpServletResponce **/ @Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { try { res.setContentType("text/html"); // The following 2 lines are the difference between PingServlet and // PingServletWriter // the latter uses a PrintWriter for output versus a binary output // stream. ServletOutputStream out = res.getOutputStream(); // java.io.PrintWriter out = res.getWriter(); int numReentriesLeft; int sleepTime; if(req.getParameter("numReentries") != null){ numReentriesLeft = Integer.parseInt(req.getParameter("numReentries")); } else { numReentriesLeft = 0; } if(req.getParameter("sleep") != null){ sleepTime = Integer.parseInt(req.getParameter("sleep")); } else { sleepTime = 0; } if(numReentriesLeft <= 0) { Thread.sleep(sleepTime); out.println(numReentriesLeft); } else { String hostname = req.getServerName(); int port = req.getServerPort(); req.getContextPath(); int saveNumReentriesLeft = numReentriesLeft; int nextNumReentriesLeft = numReentriesLeft - 1; // Recursively call into the same server, decrementing the counter by 1. String url = "http://" + hostname + ":" + port + "/" + req.getRequestURI() + "?numReentries=" + nextNumReentriesLeft + "&sleep=" + sleepTime; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("GET"); con.setRequestProperty("User-Agent", "Mozilla/5.0"); //Append the recursion count to the response and return it. BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); Thread.sleep(sleepTime); out.println(saveNumReentriesLeft + response.toString()); } } catch (Exception e) { //Log.error(e, "PingReentryServlet.doGet(...): general exception caught"); res.sendError(500, e.toString()); } } /** * returns a string of information about the servlet * * @return info String: contains info about the servlet **/ @Override public String getServletInfo() { return "Basic dynamic HTML generation through a servlet"; } /** * called when the class is loaded to initialize the servlet * * @param config * ServletConfig: **/ @Override public void init(ServletConfig config) throws ServletException { super.init(config); } }
5,046
35.309353
110
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/prims/PingServlet.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.prims; import java.io.IOException; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ibm.websphere.samples.daytrader.util.Log; /** * * PingServlet tests fundamental dynamic HTML creation functionality through * server side servlet processing. * */ @WebServlet(name = "PingServlet", urlPatterns = { "/servlet/PingServlet" }) public class PingServlet extends HttpServlet { private static final long serialVersionUID = 7097023236709683760L; private static String initTime; private static int hitCount; /** * forwards post requests to the doGet method Creation date: (11/6/2000 * 10:52:39 AM) * * @param res * javax.servlet.http.HttpServletRequest * @param res2 * javax.servlet.http.HttpServletResponse */ @Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doGet(req, res); } /** * this is the main method of the servlet that will service all get * requests. * * @param request * HttpServletRequest * @param responce * HttpServletResponce **/ @Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { try { res.setContentType("text/html"); // The following 2 lines are the difference between PingServlet and // PingServletWriter // the latter uses a PrintWriter for output versus a binary output // stream. ServletOutputStream out = res.getOutputStream(); // java.io.PrintWriter out = res.getWriter(); hitCount++; out.println("<html><head><title>Ping Servlet</title></head>" + "<body><HR><BR><FONT size=\"+2\" color=\"#000066\">Ping Servlet<BR></FONT><FONT size=\"+1\" color=\"#000066\">Init time : " + initTime + "<BR><BR></FONT> <B>Hit Count: " + hitCount + "</B></body></html>"); } catch (Exception e) { Log.error(e, "PingServlet.doGet(...): general exception caught"); res.sendError(500, e.toString()); } } /** * returns a string of information about the servlet * * @return info String: contains info about the servlet **/ @Override public String getServletInfo() { return "Basic dynamic HTML generation through a servlet"; } /** * called when the class is loaded to initialize the servlet * * @param config * ServletConfig: **/ @Override public void init(ServletConfig config) throws ServletException { super.init(config); initTime = new java.util.Date().toString(); hitCount = 0; } }
3,718
32.205357
156
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/prims/PingServlet2DB.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.prims; import java.io.IOException; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ibm.websphere.samples.daytrader.direct.TradeDirect; import com.ibm.websphere.samples.daytrader.util.Log; /** * * PingServlet2DB tests the path of a servlet making a JDBC connection to a * database * */ @WebServlet(name = "PingServlet2DB", urlPatterns = { "/servlet/PingServlet2DB" }) public class PingServlet2DB extends HttpServlet { private static final long serialVersionUID = -6456675185605592049L; private static String initTime; private static int hitCount; /** * forwards post requests to the doGet method Creation date: (11/6/2000 * 10:52:39 AM) * * @param res * javax.servlet.http.HttpServletRequest * @param res2 * javax.servlet.http.HttpServletResponse */ @Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doGet(req, res); } /** * this is the main method of the servlet that will service all get * requests. * * @param request * HttpServletRequest * @param responce * HttpServletResponce **/ @Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); java.io.PrintWriter out = res.getWriter(); String symbol = null; StringBuffer output = new StringBuffer(100); try { // TradeJDBC uses prepared statements so I am going to make use of // it's code. TradeDirect trade = new TradeDirect(); trade.getConnPublic(); output.append("<html><head><title>PingServlet2DB.</title></head>" + "<body><HR><FONT size=\"+2\" color=\"#000066\">PingServlet2DB:</FONT><HR><FONT size=\"-1\" color=\"#000066\">Init time : " + initTime); hitCount++; output.append("<BR>Hit Count: " + hitCount); output.append("<HR></body></html>"); out.println(output.toString()); } catch (Exception e) { Log.error(e, "PingServlet2DB -- error getting connection to the database", symbol); res.sendError(500, "PingServlet2DB Exception caught: " + e.toString()); } } /** * returns a string of information about the servlet * * @return info String: contains info about the servlet **/ @Override public String getServletInfo() { return "Basic JDBC Read using a prepared statment, makes use of TradeJDBC class"; } /** * called when the class is loaded to initialize the servlet * * @param config * ServletConfig: **/ @Override public void init(ServletConfig config) throws ServletException { super.init(config); hitCount = 0; initTime = new java.util.Date().toString(); } }
3,861
32.877193
157
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/prims/PingServlet2Include.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.prims; import java.io.IOException; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ibm.websphere.samples.daytrader.util.Log; import com.ibm.websphere.samples.daytrader.util.TradeConfig; /** * * PingServlet2Include tests servlet to servlet request dispatching. Servlet 1, * the controller, creates a new JavaBean object forwards the servlet request * with the JavaBean added to Servlet 2. Servlet 2 obtains access to the * JavaBean through the Servlet request object and provides the dynamic HTML * output based on the JavaBean data. PingServlet2Servlet is the initial servlet * that sends a request to {@link PingServlet2ServletRcv} * */ @WebServlet(name = "PingServlet2Include", urlPatterns = { "/servlet/PingServlet2Include" }) public class PingServlet2Include extends HttpServlet { private static final long serialVersionUID = 1063447780151198793L; private static String initTime; private static int hitCount; /** * forwards post requests to the doGet method Creation date: (11/6/2000 * 10:52:39 AM) * * @param res * javax.servlet.http.HttpServletRequest * @param res2 * javax.servlet.http.HttpServletResponse */ @Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doGet(req, res); } /** * this is the main method of the servlet that will service all get * requests. * * @param request * HttpServletRequest * @param responce * HttpServletResponce **/ @Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { try { res.setContentType("text/html"); int iter = TradeConfig.getPrimIterations(); for (int ii = 0; ii < iter; ii++) { getServletConfig().getServletContext().getRequestDispatcher("/servlet/PingServlet2IncludeRcv").include(req, res); } // ServletOutputStream out = res.getOutputStream(); java.io.PrintWriter out = res.getWriter(); out.println("<html><head><title>Ping Servlet 2 Include</title></head>" + "<body><HR><BR><FONT size=\"+2\" color=\"#000066\">Ping Servlet 2 Include<BR></FONT><FONT size=\"+1\" color=\"#000066\">Init time : " + initTime + "<BR><BR></FONT> <B>Hit Count: " + hitCount++ + "</B></body></html>"); } catch (Exception ex) { Log.error(ex, "PingServlet2Include.doGet(...): general exception"); res.sendError(500, "PingServlet2Include.doGet(...): general exception" + ex.toString()); } } /** * called when the class is loaded to initialize the servlet * * @param config * ServletConfig: **/ @Override public void init(ServletConfig config) throws ServletException { super.init(config); initTime = new java.util.Date().toString(); hitCount = 0; } }
3,926
36.4
155
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/prims/PingServlet2IncludeRcv.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.prims; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * PingServlet2Include tests servlet to servlet request dispatching. Servlet 1, * the controller, creates a new JavaBean object forwards the servlet request * with the JavaBean added to Servlet 2. Servlet 2 obtains access to the * JavaBean through the Servlet request object and provides the dynamic HTML * output based on the JavaBean data. PingServlet2Servlet is the initial servlet * that sends a request to {@link PingServlet2ServletRcv} * */ @WebServlet(name = "PingServlet2IncludeRcv", urlPatterns = { "/servlet/PingServlet2IncludeRcv" }) public class PingServlet2IncludeRcv extends HttpServlet { private static final long serialVersionUID = 2628801298561220872L; /** * forwards post requests to the doGet method Creation date: (11/6/2000 * 10:52:39 AM) * * @param res * javax.servlet.http.HttpServletRequest * @param res2 * javax.servlet.http.HttpServletResponse */ @Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doGet(req, res); } /** * this is the main method of the servlet that will service all get * requests. * * @param request * HttpServletRequest * @param responce * HttpServletResponce **/ @Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // do nothing but get included by PingServlet2Include } }
2,444
34.955882
110
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/prims/PingServlet2JNDI.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.prims; import java.io.IOException; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ibm.websphere.samples.daytrader.util.Log; /** * * PingServlet2JNDI performs a basic JNDI lookup of a JDBC DataSource * */ @WebServlet(name = "PingServlet2JNDI", urlPatterns = { "/servlet/PingServlet2JNDI" }) public class PingServlet2JNDI extends HttpServlet { private static final long serialVersionUID = -8236271998141415347L; private static String initTime; private static int hitCount; /** * forwards post requests to the doGet method Creation date: (11/6/2000 * 10:52:39 AM) * * @param res * javax.servlet.http.HttpServletRequest * @param res2 * javax.servlet.http.HttpServletResponse */ @Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doGet(req, res); } /** * this is the main method of the servlet that will service all get * requests. * * @param request * HttpServletRequest * @param responce * HttpServletResponce **/ @Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); java.io.PrintWriter out = res.getWriter(); StringBuffer output = new StringBuffer(100); try { output.append("<html><head><title>Ping JNDI -- lookup of JDBC DataSource</title></head>" + "<body><HR><FONT size=\"+2\" color=\"#000066\">Ping JNDI -- lookup of JDBC DataSource</FONT><HR><FONT size=\"-1\" color=\"#000066\">Init time : " + initTime); hitCount++; output.append("</FONT><BR>Hit Count: " + hitCount); output.append("<HR></body></html>"); out.println(output.toString()); } catch (Exception e) { Log.error(e, "PingServlet2JNDI -- error look up of a JDBC DataSource"); res.sendError(500, "PingServlet2JNDI Exception caught: " + e.toString()); } } /** * returns a string of information about the servlet * * @return info String: contains info about the servlet **/ @Override public String getServletInfo() { return "Basic JNDI look up of a JDBC DataSource"; } /** * called when the class is loaded to initialize the servlet * * @param config * ServletConfig: **/ @Override public void init(ServletConfig config) throws ServletException { super.init(config); hitCount = 0; initTime = new java.util.Date().toString(); } }
3,597
32.009174
167
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/prims/PingServlet2Jsp.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.prims; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ibm.websphere.samples.daytrader.util.Log; /** * * PingServlet2JSP tests a call from a servlet to a JavaServer Page providing * server-side dynamic HTML through JSP scripting. * */ @WebServlet(name = "PingServlet2Jsp", urlPatterns = { "/servlet/PingServlet2Jsp" }) public class PingServlet2Jsp extends HttpServlet { private static final long serialVersionUID = -5199543766883932389L; private static int hitCount = 0; /** * forwards post requests to the doGet method Creation date: (11/6/2000 * 10:52:39 AM) * * @param res * javax.servlet.http.HttpServletRequest * @param res2 * javax.servlet.http.HttpServletResponse */ @Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doGet(req, res); } /** * this is the main method of the servlet that will service all get * requests. * * @param request * HttpServletRequest * @param responce * HttpServletResponce **/ @Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { PingBean ab; try { ab = new PingBean(); hitCount++; ab.setMsg("Hit Count: " + hitCount); req.setAttribute("ab", ab); getServletConfig().getServletContext().getRequestDispatcher("/PingServlet2Jsp.jsp").forward(req, res); } catch (Exception ex) { Log.error(ex, "PingServlet2Jsp.doGet(...): request error"); res.sendError(500, "PingServlet2Jsp.doGet(...): request error" + ex.toString()); } } }
2,640
32.858974
114
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/prims/PingServlet2PDF.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.prims; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.IOException; import java.net.URL; import java.net.URLConnection; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ibm.websphere.samples.daytrader.util.Log; /** * * PingServlet2PDF tests a call to a servlet which then loads a PDF document. * */ @WebServlet(name = "PingServlet2PDF", urlPatterns = { "/servlet/PingServlet2PDF" }) public class PingServlet2PDF extends HttpServlet { private static final long serialVersionUID = -1321793174442755868L; private static int hitCount = 0; private static final int BUFFER_SIZE = 1024 * 8; // 8 KB /** * forwards post requests to the doGet method Creation date: (11/6/2000 * 10:52:39 AM) * * @param res * javax.servlet.http.HttpServletRequest * @param res2 * javax.servlet.http.HttpServletResponse */ @Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doGet(req, res); } /** * this is the main method of the servlet that will service all get * requests. * * @param request * HttpServletRequest * @param responce * HttpServletResponce **/ @Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { PingBean ab; BufferedInputStream bis = null; BufferedOutputStream bos = null; try { ab = new PingBean(); hitCount++; ab.setMsg("Hit Count: " + hitCount); req.setAttribute("ab", ab); ServletOutputStream out = res.getOutputStream(); // MIME type for pdf doc res.setContentType("application/pdf"); // Open an InputStream to the PDF document String fileURL = "http://localhost:9080/daytrader/WAS_V7_64-bit_performance.pdf"; URL url = new URL(fileURL); URLConnection conn = url.openConnection(); bis = new BufferedInputStream(conn.getInputStream()); // Transfer the InputStream (PDF Document) to OutputStream (servlet) bos = new BufferedOutputStream(out); byte[] buff = new byte[BUFFER_SIZE]; int bytesRead; // Simple read/write loop. while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) { bos.write(buff, 0, bytesRead); } } catch (Exception ex) { Log.error(ex, "PingServlet2Jsp.doGet(...): request error"); res.sendError(500, "PingServlet2Jsp.doGet(...): request error" + ex.toString()); } finally { if (bis != null) { bis.close(); } if (bos != null) { bos.close(); } } } }
3,804
32.086957
110
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/prims/PingServlet2Servlet.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.prims; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ibm.websphere.samples.daytrader.util.Log; /** * * PingServlet2Servlet tests servlet to servlet request dispatching. Servlet 1, * the controller, creates a new JavaBean object forwards the servlet request * with the JavaBean added to Servlet 2. Servlet 2 obtains access to the * JavaBean through the Servlet request object and provides the dynamic HTML * output based on the JavaBean data. PingServlet2Servlet is the initial servlet * that sends a request to {@link PingServlet2ServletRcv} * */ @WebServlet(name = "PingServlet2Servlet", urlPatterns = { "/servlet/PingServlet2Servlet" }) public class PingServlet2Servlet extends HttpServlet { private static final long serialVersionUID = -955942781902636048L; private static int hitCount = 0; /** * forwards post requests to the doGet method Creation date: (11/6/2000 * 10:52:39 AM) * * @param res * javax.servlet.http.HttpServletRequest * @param res2 * javax.servlet.http.HttpServletResponse */ @Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doGet(req, res); } /** * this is the main method of the servlet that will service all get * requests. * * @param request * HttpServletRequest * @param responce * HttpServletResponce **/ @Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { PingBean ab; try { ab = new PingBean(); hitCount++; ab.setMsg("Hit Count: " + hitCount); req.setAttribute("ab", ab); getServletConfig().getServletContext().getRequestDispatcher("/servlet/PingServlet2ServletRcv").forward(req, res); } catch (Exception ex) { Log.error(ex, "PingServlet2Servlet.doGet(...): general exception"); res.sendError(500, "PingServlet2Servlet.doGet(...): general exception" + ex.toString()); } } }
2,996
35.54878
125
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/prims/PingServlet2ServletRcv.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.prims; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ibm.websphere.samples.daytrader.util.Log; /** * * PingServlet2Servlet tests servlet to servlet request dispatching. Servlet 1, * the controller, creates a new JavaBean object forwards the servlet request * with the JavaBean added to Servlet 2. Servlet 2 obtains access to the * JavaBean through the Servlet request object and provides the dynamic HTML * output based on the JavaBean data. PingServlet2ServletRcv receives a request * from {@link PingServlet2Servlet} and displays output. * */ @WebServlet(name = "PingServlet2ServletRcv", urlPatterns = { "/servlet/PingServlet2ServletRcv" }) public class PingServlet2ServletRcv extends HttpServlet { private static final long serialVersionUID = -5241563129216549706L; private static String initTime = null; /** * forwards post requests to the doGet method Creation date: (11/6/2000 * 10:52:39 AM) * * @param res * javax.servlet.http.HttpServletRequest * @param res2 * javax.servlet.http.HttpServletResponse */ @Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doGet(req, res); } /** * this is the main method of the servlet that will service all get * requests. * * @param request * HttpServletRequest * @param responce * HttpServletResponce **/ @Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { PingBean ab; try { ab = (PingBean) req.getAttribute("ab"); res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("<html><head><title>Ping Servlet2Servlet</title></head>" + "<body><HR><BR><FONT size=\"+2\" color=\"#000066\">PingServlet2Servlet:<BR></FONT><FONT size=\"+1\" color=\"#000066\">Init time: " + initTime + "</FONT><BR><BR><B>Message from Servlet: </B>" + ab.getMsg() + "</body></html>"); } catch (Exception ex) { Log.error(ex, "PingServlet2ServletRcv.doGet(...): general exception"); res.sendError(500, "PingServlet2ServletRcv.doGet(...): general exception" + ex.toString()); } } /** * called when the class is loaded to initialize the servlet * * @param config * ServletConfig: **/ @Override public void init(ServletConfig config) throws ServletException { super.init(config); initTime = new java.util.Date().toString(); } }
3,614
36.268041
152
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/prims/PingServlet30Async.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.prims; import java.io.IOException; import javax.servlet.AsyncContext; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.ServletInputStream; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; //import com.ibm.websphere.samples.daytrader.util.Log; /** * * PingServlet31Async tests fundamental dynamic HTML creation functionality through * server side servlet processing asynchronously. * */ @WebServlet(name = "PingServlet30Async", urlPatterns = { "/servlet/PingServlet30Async" }, asyncSupported=true) public class PingServlet30Async extends HttpServlet { private static final long serialVersionUID = 8731300373855056660L; private static String initTime; private static int hitCount; /** * forwards post requests to the doGet method Creation date: (11/6/2000 * 10:52:39 AM) * * @param res * javax.servlet.http.HttpServletRequest * @param res2 * javax.servlet.http.HttpServletResponse */ @Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); AsyncContext ac = req.startAsync(); StringBuilder sb = new StringBuilder(); ServletInputStream input = req.getInputStream(); byte[] b = new byte[1024]; int len = -1; while ((len = input.read(b)) != -1) { String data = new String(b, 0, len); sb.append(data); } ServletOutputStream output = res.getOutputStream(); output.println("<html><head><title>Ping Servlet 3.0 Async</title></head>" + "<body><hr/><br/><font size=\"+2\" color=\"#000066\">Ping Servlet 3.0 Async</font><br/>" + "<font size=\"+1\" color=\"#000066\">Init time : " + initTime + "</font><br/><br/><b>Hit Count: " + ++hitCount + "</b><br/>Data Received: "+ sb.toString() + "</body></html>"); ac.complete(); } /** * this is the main method of the servlet that will service all get * requests. * * @param request * HttpServletRequest * @param responce * HttpServletResponce **/ @Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doPost(req,res); } /** * returns a string of information about the servlet * * @return info String: contains info about the servlet **/ @Override public String getServletInfo() { return "Basic dynamic HTML generation through a servlet"; } /** * called when the class is loaded to initialize the servlet * * @param config * ServletConfig: **/ @Override public void init(ServletConfig config) throws ServletException { super.init(config); initTime = new java.util.Date().toString(); hitCount = 0; } }
3,893
32
129
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/prims/PingServlet31Async.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.prims; import java.io.IOException; import java.util.Queue; import java.util.concurrent.LinkedBlockingQueue; import javax.servlet.AsyncContext; import javax.servlet.ReadListener; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.ServletInputStream; import javax.servlet.ServletOutputStream; import javax.servlet.WriteListener; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; //import com.ibm.websphere.samples.daytrader.util.Log; /** * * PingServlet31Async tests fundamental dynamic HTML creation functionality through * server side servlet processing asynchronously with non-blocking i/o. * */ @WebServlet(name = "PingServlet31Async", urlPatterns = { "/servlet/PingServlet31Async" }, asyncSupported=true) public class PingServlet31Async extends HttpServlet { private static final long serialVersionUID = 8731300373855056660L; private static String initTime; private static int hitCount; /** * forwards post requests to the doGet method Creation date: (11/6/2000 * 10:52:39 AM) * * @param res * javax.servlet.http.HttpServletRequest * @param res2 * javax.servlet.http.HttpServletResponse */ @Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); AsyncContext ac = req.startAsync(); ServletInputStream input = req.getInputStream(); ReadListener readListener = new ReadListenerImpl(input, res, ac); input.setReadListener(readListener); } class ReadListenerImpl implements ReadListener { private ServletInputStream input = null; private HttpServletResponse res = null; private AsyncContext ac = null; private Queue<String> queue = new LinkedBlockingQueue<String>(); ReadListenerImpl(ServletInputStream in, HttpServletResponse r, AsyncContext c) { input = in; res = r; ac = c; } public void onDataAvailable() throws IOException { StringBuilder sb = new StringBuilder(); int len = -1; byte b[] = new byte[1024]; while (input.isReady() && (len = input.read(b)) != -1) { String data = new String(b, 0, len); sb.append(data); } queue.add(sb.toString()); } public void onAllDataRead() throws IOException { ServletOutputStream output = res.getOutputStream(); WriteListener writeListener = new WriteListenerImpl(output, queue, ac); output.setWriteListener(writeListener); } public void onError(final Throwable t) { ac.complete(); t.printStackTrace(); } } class WriteListenerImpl implements WriteListener { private ServletOutputStream output = null; private Queue<String> queue = null; private AsyncContext ac = null; WriteListenerImpl(ServletOutputStream sos, Queue<String> q, AsyncContext c) { output = sos; queue = q; ac = c; try { output.print("<html><head><title>Ping Servlet 3.1 Async</title></head>" + "<body><hr/><br/><font size=\"+2\" color=\"#000066\">Ping Servlet 3.1 Async</font>" + "<br/><font size=\"+1\" color=\"#000066\">Init time : " + initTime + "</font><br/><br/><b>Hit Count: " + ++hitCount + "</b><br/>Data Received: "); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void onWritePossible() throws IOException { while (queue.peek() != null && output.isReady()) { String data = (String) queue.poll(); output.print(data); } if (queue.peek() == null) { output.println("</body></html>"); ac.complete(); } } public void onError(final Throwable t) { ac.complete(); t.printStackTrace(); } } /** * this is the main method of the servlet that will service all get * requests. * * @param request * HttpServletRequest * @param responce * HttpServletResponce **/ @Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doPost(req,res); } /** * returns a string of information about the servlet * * @return info String: contains info about the servlet **/ @Override public String getServletInfo() { return "Basic dynamic HTML generation through a servlet"; } /** * called when the class is loaded to initialize the servlet * * @param config * ServletConfig: **/ @Override public void init(ServletConfig config) throws ServletException { super.init(config); initTime = new java.util.Date().toString(); hitCount = 0; } }
6,140
32.016129
110
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/prims/PingServlet31AsyncRead.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.prims; import java.io.IOException; import javax.servlet.AsyncContext; import javax.servlet.ReadListener; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.ServletInputStream; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; //import com.ibm.websphere.samples.daytrader.util.Log; /** * * PingServlet31Async tests fundamental dynamic HTML creation functionality through * server side servlet processing asynchronously with non-blocking i/o. * */ @WebServlet(name = "PingServlet31AsyncRead", urlPatterns = { "/servlet/PingServlet31AsyncRead" }, asyncSupported=true) public class PingServlet31AsyncRead extends HttpServlet { private static final long serialVersionUID = 8731300373855056660L; private static String initTime; private static int hitCount; /** * forwards post requests to the doGet method Creation date: (11/6/2000 * 10:52:39 AM) * * @param res * javax.servlet.http.HttpServletRequest * @param res2 * javax.servlet.http.HttpServletResponse */ @Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); AsyncContext ac = req.startAsync(); ServletInputStream input = req.getInputStream(); ReadListener readListener = new ReadListenerImpl(input, res, ac); input.setReadListener(readListener); } class ReadListenerImpl implements ReadListener { private ServletInputStream input = null; private HttpServletResponse res = null; private AsyncContext ac = null; private StringBuilder sb = new StringBuilder(); ReadListenerImpl(ServletInputStream in, HttpServletResponse r, AsyncContext c) { input = in; res = r; ac = c; } public void onDataAvailable() throws IOException { int len = -1; byte b[] = new byte[1024]; while (input.isReady() && (len = input.read(b)) != -1) { String data = new String(b, 0, len); sb.append(data); } } public void onAllDataRead() throws IOException { ServletOutputStream output = res.getOutputStream(); output.println("<html><head><title>Ping Servlet 3.1 Async</title></head>" + "<body><hr/><br/><font size=\"+2\" color=\"#000066\">Ping Servlet 3.1 AsyncRead</font>" + "<br/><font size=\"+1\" color=\"#000066\">Init time : " + initTime + "</font><br/><br/><b>Hit Count: " + ++hitCount + "</b><br/>Data Received: " + sb.toString() + "</body></html>"); ac.complete(); } public void onError(final Throwable t) { ac.complete(); t.printStackTrace(); } } /** * this is the main method of the servlet that will service all get * requests. * * @param request * HttpServletRequest * @param responce * HttpServletResponce **/ @Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doPost(req,res); } /** * returns a string of information about the servlet * * @return info String: contains info about the servlet **/ @Override public String getServletInfo() { return "Basic dynamic HTML generation through a servlet"; } /** * called when the class is loaded to initialize the servlet * * @param config * ServletConfig: **/ @Override public void init(ServletConfig config) throws ServletException { super.init(config); initTime = new java.util.Date().toString(); hitCount = 0; } }
4,824
32.275862
134
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/prims/PingServletCDI.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.prims; import java.io.IOException; import java.io.PrintWriter; import javax.ejb.EJB; import javax.inject.Inject; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ibm.websphere.samples.daytrader.web.prims.PingCDIBean; @WebServlet("/servlet/PingServletCDI") public class PingServletCDI extends HttpServlet { private static final long serialVersionUID = -1803544618879689949L; private static String initTime; @Inject PingCDIBean cdiBean; @EJB PingEJBIFace ejb; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { PrintWriter pw = response.getWriter(); pw.write("<html><head><title>Ping Servlet CDI</title></head>" + "<body><HR><BR><FONT size=\"+2\" color=\"#000066\">Ping Servlet CDI<BR></FONT><FONT size=\"+1\" color=\"#000066\">Init time : " + initTime + "<BR><BR></FONT>"); pw.write("<B>hitCount: " + cdiBean.hello() + "</B><BR>"); pw.write("<B>hitCount: " + ejb.getMsg() + "</B><BR>"); pw.flush(); pw.close(); } /** * called when the class is loaded to initialize the servlet * * @param config * ServletConfig: **/ @Override public void init(ServletConfig config) throws ServletException { super.init(config); initTime = new java.util.Date().toString(); } }
2,284
30.30137
157
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/prims/PingServletCDIBeanManagerViaCDICurrent.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.prims; import java.io.IOException; import java.io.PrintWriter; import javax.inject.Inject; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ibm.websphere.samples.daytrader.web.prims.PingCDIBean; @WebServlet("/servlet/PingServletCDIBeanManagerViaCDICurrent") public class PingServletCDIBeanManagerViaCDICurrent extends HttpServlet { private static final long serialVersionUID = -1803544618879689949L; private static String initTime; @Inject PingCDIBean cdiBean; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { PrintWriter pw = response.getWriter(); pw.write("<html><head><title>Ping Servlet CDI Bean Manager</title></head>" + "<body><HR><BR><FONT size=\"+2\" color=\"#000066\">Ping Servlet CDI Bean Manager<BR></FONT><FONT size=\"+1\" color=\"#000066\">Init time : " + initTime + "<BR><BR></FONT>"); try { pw.write("<B>hitCount: " + cdiBean.getBeanMangerViaCDICurrent() + "</B></body></html>"); } catch (Exception e) { e.printStackTrace(); } pw.flush(); pw.close(); } /** * called when the class is loaded to initialize the servlet * * @param config * ServletConfig: **/ @Override public void init(ServletConfig config) throws ServletException { super.init(config); initTime = new java.util.Date().toString(); } }
2,371
31.054054
170
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/prims/PingServletCDIBeanManagerViaJNDI.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.prims; import java.io.IOException; import java.io.PrintWriter; import javax.inject.Inject; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ibm.websphere.samples.daytrader.web.prims.PingCDIBean; @WebServlet("/servlet/PingServletCDIBeanManagerViaJNDI") public class PingServletCDIBeanManagerViaJNDI extends HttpServlet { private static final long serialVersionUID = -1803544618879689949L; private static String initTime; @Inject PingCDIBean cdiBean; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { PrintWriter pw = response.getWriter(); pw.write("<html><head><title>Ping Servlet CDI Bean Manager</title></head>" + "<body><HR><BR><FONT size=\"+2\" color=\"#000066\">Ping Servlet CDI Bean Manager<BR></FONT><FONT size=\"+1\" color=\"#000066\">Init time : " + initTime + "<BR><BR></FONT>"); try { pw.write("<B>hitCount: " + cdiBean.getBeanMangerViaJNDI() + "</B></body></html>"); } catch (Exception e) { e.printStackTrace(); } pw.flush(); pw.close(); } /** * called when the class is loaded to initialize the servlet * * @param config * ServletConfig: **/ @Override public void init(ServletConfig config) throws ServletException { super.init(config); initTime = new java.util.Date().toString(); } }
2,353
30.810811
170
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/prims/PingServletLargeContentLength.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.prims; import java.io.IOException; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * PingServletSetContentLength tests fundamental dynamic HTML creation * functionality through server side servlet processing. * */ @WebServlet(name = "PingServletLargeContentLength", urlPatterns = { "/servlet/PingServletLargeContentLength" }) public class PingServletLargeContentLength extends HttpServlet { /** * */ private static final long serialVersionUID = -7979576220528252408L; /** * forwards post requests to the doGet method Creation date: (02/07/2013 * 10:52:39 AM) * * @param res * javax.servlet.http.HttpServletRequest * @param res2 * javax.servlet.http.HttpServletResponse */ @Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { System.out.println("Length: " + req.getContentLengthLong()); } /** * this is the main method of the servlet that will service all get * requests. * * @param request * HttpServletRequest * @param responce * HttpServletResponce **/ @Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doPost(req,res); } /** * returns a string of information about the servlet * * @return info String: contains info about the servlet **/ @Override public String getServletInfo() { return "Basic dynamic HTML generation through a servlet, with " + "contentLength set by contentLength parameter."; } /** * called when the class is loaded to initialize the servlet * * @param config * ServletConfig: **/ @Override public void init(ServletConfig config) throws ServletException { super.init(config); } }
2,835
28.852632
122
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/prims/PingServletSetContentLength.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.prims; import java.io.IOException; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ibm.websphere.samples.daytrader.util.Log; /** * * PingServletSetContentLength tests fundamental dynamic HTML creation * functionality through server side servlet processing. * */ @WebServlet(name = "PingServletSetContentLength", urlPatterns = { "/servlet/PingServletSetContentLength" }) public class PingServletSetContentLength extends HttpServlet { private static final long serialVersionUID = 8731300373855056661L; /** * forwards post requests to the doGet method Creation date: (02/07/2013 * 10:52:39 AM) * * @param res * javax.servlet.http.HttpServletRequest * @param res2 * javax.servlet.http.HttpServletResponse */ @Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doGet(req, res); } /** * this is the main method of the servlet that will service all get * requests. * * @param request * HttpServletRequest * @param responce * HttpServletResponce **/ @Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { try { res.setContentType("text/html"); String lengthParam = req.getParameter("contentLength"); Integer length; if (lengthParam == null) { length = 0; } else { length = Integer.parseInt(lengthParam); } ServletOutputStream out = res.getOutputStream(); // Add characters (a's) to the SOS to equal the requested length // 167 is the smallest length possible. int i = 0; String buffer = ""; while (i + 167 < length) { buffer = buffer + "a"; i++; } out.println("<html><head><title>Ping Servlet</title></head>" + "<body><HR><BR><FONT size=\"+2\" color=\"#000066\">Ping Servlet<BR></FONT><FONT size=\"+1\" color=\"#000066\">" + buffer + "</B></body></html>"); } catch (Exception e) { Log.error(e, "PingServlet.doGet(...): general exception caught"); res.sendError(500, e.toString()); } } /** * returns a string of information about the servlet * * @return info String: contains info about the servlet **/ @Override public String getServletInfo() { return "Basic dynamic HTML generation through a servlet, with " + "contentLength set by contentLength parameter."; } /** * called when the class is loaded to initialize the servlet * * @param config * ServletConfig: **/ @Override public void init(ServletConfig config) throws ServletException { super.init(config); } }
3,912
31.338843
142
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/prims/PingServletWriter.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.prims; import java.io.IOException; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ibm.websphere.samples.daytrader.util.Log; /** * * PingServlet extends PingServlet by using a PrintWriter for formatted output * vs. the output stream used by {@link PingServlet}. * */ @WebServlet(name = "PingServletWriter", urlPatterns = { "/servlet/PingServletWriter" }) public class PingServletWriter extends HttpServlet { private static final long serialVersionUID = -267847365014523225L; private static String initTime; private static int hitCount; /** * forwards post requests to the doGet method Creation date: (11/6/2000 * 10:52:39 AM) * * @param res * javax.servlet.http.HttpServletRequest * @param res2 * javax.servlet.http.HttpServletResponse */ @Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doGet(req, res); } /** * this is the main method of the servlet that will service all get * requests. * * @param request * HttpServletRequest * @param responce * HttpServletResponce **/ @Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { try { res.setContentType("text/html"); // The following 2 lines are the difference between PingServlet and // PingServletWriter // the latter uses a PrintWriter for output versus a binary output // stream. // ServletOutputStream out = res.getOutputStream(); java.io.PrintWriter out = res.getWriter(); hitCount++; out.println("<html><head><title>Ping Servlet Writer</title></head>" + "<body><HR><BR><FONT size=\"+2\" color=\"#000066\">Ping Servlet Writer:<BR></FONT><FONT size=\"+1\" color=\"#000066\">Init time : " + initTime + "<BR><BR></FONT> <B>Hit Count: " + hitCount + "</B></body></html>"); } catch (Exception e) { Log.error(e, "PingServletWriter.doGet(...): general exception caught"); res.sendError(500, e.toString()); } } /** * returns a string of information about the servlet * * @return info String: contains info about the servlet **/ @Override public String getServletInfo() { return "Basic dynamic HTML generation through a servlet using a PrintWriter"; } /** * called when the class is loaded to initialize the servlet * * @param config * ServletConfig: **/ @Override public void init(ServletConfig config) throws ServletException { super.init(config); hitCount = 0; initTime = new java.util.Date().toString(); } }
3,761
33.2
153
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/prims/PingSession1.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.prims; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.ibm.websphere.samples.daytrader.util.Log; /** * * PingHTTPSession1 - SessionID tests fundamental HTTP session functionality by * creating a unique session ID for each individual user. The ID is stored in * the users session and is accessed and displayed on each user request. * */ @WebServlet(name = "PingSession1", urlPatterns = { "/servlet/PingSession1" }) public class PingSession1 extends HttpServlet { private static final long serialVersionUID = -3703858656588519807L; private static int count; // For each new session created, add a session ID of the form "sessionID:" + // count private static String initTime; private static int hitCount; /** * forwards post requests to the doGet method Creation date: (11/6/2000 * 10:52:39 AM) * * @param res * javax.servlet.http.HttpServletRequest * @param res2 * javax.servlet.http.HttpServletResponse */ @Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doGet(req, res); } /** * this is the main method of the servlet that will service all get * requests. * * @param request * HttpServletRequest * @param responce * HttpServletResponce **/ @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = null; try { try { // get the users session, if the user does not have a session // create one. session = request.getSession(true); } catch (Exception e) { Log.error(e, "PingSession1.doGet(...): error getting session"); // rethrow the exception for handling in one place. throw e; } // Get the session data value Integer ival = (Integer) session.getAttribute("sessiontest.counter"); // if their is not a counter create one. if (ival == null) { ival = new Integer(count++); session.setAttribute("sessiontest.counter", ival); } String SessionID = "SessionID:" + ival.toString(); // Output the page response.setContentType("text/html"); response.setHeader("SessionKeyTest-SessionID", SessionID); PrintWriter out = response.getWriter(); out.println("<html><head><title>HTTP Session Key Test</title></head><body><HR><BR><FONT size=\"+2\" color=\"#000066\">HTTP Session Test 1: Session Key<BR></FONT><FONT size=\"+1\" color=\"#000066\">Init time: " + initTime + "</FONT><BR><BR>"); hitCount++; out.println("<B>Hit Count: " + hitCount + "<BR>Your HTTP Session key is " + SessionID + "</B></body></html>"); } catch (Exception e) { // log the excecption Log.error(e, "PingSession1.doGet(..l.): error."); // set the server responce to 500 and forward to the web app defined // error page response.sendError(500, "PingSession1.doGet(...): error. " + e.toString()); } } /** * returns a string of information about the servlet * * @return info String: contains info about the servlet **/ @Override public String getServletInfo() { return "HTTP Session Key: Tests management of a read only unique id"; } /** * called when the class is loaded to initialize the servlet * * @param config * ServletConfig: **/ @Override public void init(ServletConfig config) throws ServletException { super.init(config); count = 0; hitCount = 0; initTime = new java.util.Date().toString(); } }
4,940
35.330882
221
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/prims/PingSession2.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.prims; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.ibm.websphere.samples.daytrader.util.Log; /** * * PingHTTPSession2 session create/destroy further extends the previous test by * invalidating the HTTP Session on every 5th user access. This results in * testing HTTPSession create and destroy * */ @WebServlet(name = "PingSession2", urlPatterns = { "/servlet/PingSession2" }) public class PingSession2 extends HttpServlet { private static final long serialVersionUID = -273579463475455800L; private static String initTime; private static int hitCount; /** * forwards post requests to the doGet method Creation date: (11/6/2000 * 10:52:39 AM) * * @param res * javax.servlet.http.HttpServletRequest * @param res2 * javax.servlet.http.HttpServletResponse */ @Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doGet(req, res); } /** * this is the main method of the servlet that will service all get * requests. * * @param request * HttpServletRequest * @param responce * HttpServletResponce **/ @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = null; try { try { session = request.getSession(true); } catch (Exception e) { Log.error(e, "PingSession2.doGet(...): error getting session"); // rethrow the exception for handling in one place. throw e; } // Get the session data value Integer ival = (Integer) session.getAttribute("sessiontest.counter"); // if there is not a counter then create one. if (ival == null) { ival = new Integer(1); } else { ival = new Integer(ival.intValue() + 1); } session.setAttribute("sessiontest.counter", ival); // if the session count is equal to five invalidate the session if (ival.intValue() == 5) { session.invalidate(); } try { // Output the page response.setContentType("text/html"); response.setHeader("SessionTrackingTest-counter", ival.toString()); PrintWriter out = response.getWriter(); out.println("<html><head><title>Session Tracking Test 2</title></head><body><HR><BR><FONT size=\"+2\" color=\"#000066\">HTTP Session Test 2: Session create/invalidate <BR></FONT><FONT size=\"+1\" color=\"#000066\">Init time: " + initTime + "</FONT><BR><BR>"); hitCount++; out.println("<B>Hit Count: " + hitCount + "<BR>Session hits: " + ival + "</B></body></html>"); } catch (Exception e) { Log.error(e, "PingSession2.doGet(...): error getting session information"); // rethrow the exception for handling in one place. throw e; } } catch (Exception e) { // log the excecption Log.error(e, "PingSession2.doGet(...): error."); // set the server responce to 500 and forward to the web app defined // error page response.sendError(500, "PingSession2.doGet(...): error. " + e.toString()); } } // end of the method /** * returns a string of information about the servlet * * @return info String: contains info about the servlet **/ @Override public String getServletInfo() { return "HTTP Session Key: Tests management of a read/write unique id"; } /** * called when the class is loaded to initialize the servlet * * @param config * ServletConfig: **/ @Override public void init(ServletConfig config) throws ServletException { super.init(config); hitCount = 0; initTime = new java.util.Date().toString(); } }
5,158
34.57931
242
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/prims/PingSession3.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.prims; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.ibm.websphere.samples.daytrader.util.Log; /** * * PingHTTPSession3 tests the servers ability to manage and persist large * HTTPSession data objects. The servlet creates the large custom java object * {@link PingSession3Object}. This large session object is retrieved and stored * to the session on each user request. The default settings result in approx * 2024 bits being retrieved and stored upon each request. * */ @WebServlet(name = "PingSession3", urlPatterns = { "/servlet/PingSession3" }) public class PingSession3 extends HttpServlet { private static final long serialVersionUID = -6129599971684210414L; private static int NUM_OBJECTS = 2; private static String initTime = null; private static int hitCount = 0; /** * forwards post requests to the doGet method Creation date: (11/6/2000 * 10:52:39 AM) * * @param res * javax.servlet.http.HttpServletRequest * @param res2 * javax.servlet.http.HttpServletResponse */ @Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doGet(req, res); } /** * this is the main method of the servlet that will service all get * requests. * * @param request * HttpServletRequest * @param responce * HttpServletResponce **/ @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); // Using a StringBuffer to output all at once. StringBuffer outputBuffer = new StringBuffer(); HttpSession session = null; PingSession3Object[] sessionData; response.setContentType("text/html"); // this is a general try/catch block. The catch block at the end of this // will forward the responce // to an error page if there is an exception try { try { session = request.getSession(true); } catch (Exception e) { Log.error(e, "PingSession3.doGet(...): error getting session"); // rethrow the exception for handling in one place. throw e; } // Each PingSession3Object in the PingSession3Object array is 1K in // size // NUM_OBJECTS sets the size of the array to allocate and thus set // the size in KBytes of the session object // NUM_OBJECTS can be initialized by the servlet // Here we check for the request parameter to change the size and // invalidate the session if it exists // NOTE: Current user sessions will remain the same (i.e. when // NUM_OBJECTS is changed, all user thread must be restarted // for the change to fully take effect String num_objects; if ((num_objects = request.getParameter("num_objects")) != null) { // validate input try { int x = Integer.parseInt(num_objects); if (x > 0) { NUM_OBJECTS = x; } } catch (Exception e) { Log.error(e, "PingSession3.doGet(...): input should be an integer, input=" + num_objects); } // revert to current value on exception outputBuffer.append("<html><head> Session object size set to " + NUM_OBJECTS + "K bytes </head><body></body></html>"); if (session != null) { session.invalidate(); } out.print(outputBuffer.toString()); out.close(); return; } // Get the session data value sessionData = (PingSession3Object[]) session.getAttribute("sessiontest.sessionData"); if (sessionData == null) { sessionData = new PingSession3Object[NUM_OBJECTS]; for (int i = 0; i < NUM_OBJECTS; i++) { sessionData[i] = new PingSession3Object(); } } session.setAttribute("sessiontest.sessionData", sessionData); // Each PingSession3Object is about 1024 bits, there are 8 bits in a // byte. int num_bytes = (NUM_OBJECTS * 1024) / 8; response.setHeader("SessionTrackingTest-largeSessionData", num_bytes + "bytes"); outputBuffer .append("<html><head><title>Session Large Data Test</title></head><body><HR><BR><FONT size=\"+2\" color=\"#000066\">HTTP Session Test 3: Large Data<BR></FONT><FONT size=\"+1\" color=\"#000066\">Init time: ") .append(initTime).append("</FONT><BR><BR>"); hitCount++; outputBuffer.append("<B>Hit Count: ").append(hitCount) .append("<BR>Session object updated. Session Object size = " + num_bytes + " bytes </B></body></html>"); // output the Buffer to the printWriter. out.println(outputBuffer.toString()); } catch (Exception e) { // log the excecption Log.error(e, "PingSession3.doGet(..l.): error."); // set the server responce to 500 and forward to the web app defined // error page response.sendError(500, "PingSession3.doGet(...): error. " + e.toString()); } } /** * returns a string of information about the servlet * * @return info String: contains info about the servlet **/ @Override public String getServletInfo() { return "HTTP Session Object: Tests management of a large custom session class"; } /** * called when the class is loaded to initialize the servlet * * @param config * ServletConfig: **/ @Override public void init(ServletConfig config) throws ServletException { super.init(config); hitCount = 0; initTime = new java.util.Date().toString(); } }
7,154
38.313187
227
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/prims/PingSession3Object.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.prims; import java.io.Serializable; /** * * An object that contains approximately 1024 bits of information. This is used * by {@link PingSession3} * */ public class PingSession3Object implements Serializable { // PingSession3Object represents a BLOB of session data of various. // Each instantiation of this class is approximately 1K in size (not // including overhead for arrays and Strings) // Using different datatype exercises the various serialization algorithms // for each type private static final long serialVersionUID = 1452347702903504717L; byte[] byteVal = new byte[16]; // 8 * 16 = 128 bits char[] charVal = new char[8]; // 16 * 8 = 128 bits int a, b, c, d; // 4 * 32 = 128 bits float e, f, g, h; // 4 * 32 = 128 bits double i, j; // 2 * 64 = 128 bits // Primitive type size = ~5*128= 640 String s1 = new String("123456789012"); String s2 = new String("abcdefghijkl"); // String type size = ~2*12*16 = 384 // Total blob size (w/o overhead) = 1024 // The Session blob must be filled with data to avoid compression of the // blob during serialization PingSession3Object() { int index; byte b = 0x8; for (index = 0; index < 16; index++) { byteVal[index] = (byte) (b + 2); } char c = 'a'; for (index = 0; index < 8; index++) { charVal[index] = (char) (c + 2); } a = 1; b = 2; c = 3; d = 5; e = (float) 7.0; f = (float) 11.0; g = (float) 13.0; h = (float) 17.0; i = 19.0; j = 23.0; } /** * Main method to test the serialization of the Session Data blob object * Creation date: (4/3/2000 3:07:34 PM) * * @param args * java.lang.String[] */ /** * Since the following main method were written for testing purpose, we * comment them out public static void main(String[] args) { try { * PingSession3Object data = new PingSession3Object(); * * FileOutputStream ostream = new * FileOutputStream("c:\\temp\\datablob.xxx"); ObjectOutputStream p = new * ObjectOutputStream(ostream); p.writeObject(data); p.flush(); * ostream.close(); } catch (Exception e) { System.out.println("Exception: " * + e.toString()); } } */ }
3,019
31.826087
80
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/prims/PingUpgradeServlet.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.prims; import java.io.IOException; import javax.servlet.ReadListener; import javax.servlet.ServletException; import javax.servlet.ServletInputStream; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpUpgradeHandler; import javax.servlet.http.WebConnection; import javax.servlet.annotation.WebServlet; import com.ibm.websphere.samples.daytrader.util.Log; @WebServlet(name = "PingUpgradeServlet", urlPatterns = { "/servlet/PingUpgradeServlet" }, asyncSupported=true) public class PingUpgradeServlet extends HttpServlet { private static final long serialVersionUID = -6955518532146927509L; @Override protected void doGet(final HttpServletRequest req, final HttpServletResponse res) throws ServletException, IOException { doPost(req,res); } @Override protected void doPost(final HttpServletRequest req, final HttpServletResponse res) throws ServletException, IOException { if (Log.doTrace()) { Log.trace("PingUpgradeServlet:doPost"); } if ("echo".equals(req.getHeader("Upgrade"))) { if (Log.doTrace()) { Log.trace("PingUpgradeServlet:doPost -- found echo, doing upgrade"); } res.setStatus(101); res.setHeader("Upgrade", "echo"); res.setHeader("Connection", "Upgrade"); req.upgrade(Handler.class); } else { if (Log.doTrace()) { Log.trace("PingUpgradeServlet:doPost -- did not find echo, no upgrade"); } res.getWriter().println("No upgrade: " + req.getHeader("Upgrade")); } } public static class Handler implements HttpUpgradeHandler { @Override public void init(final WebConnection wc) { Listener listener = null; try { listener = new Listener(wc); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { if (Log.doTrace()) { Log.trace("PingUpgradeServlet$Handler.init() -- Initializing Handler"); } // flush headers if any wc.getOutputStream().flush(); wc.getInputStream().setReadListener(listener); } catch (IOException e) { throw new IllegalArgumentException(e); } } @Override public void destroy() { if (Log.doTrace()) { Log.trace("PingUpgradeServlet$Handler.destroy() -- Destroying Handler"); } } } private static class Listener implements ReadListener { private final WebConnection connection; private ServletInputStream input = null; private ServletOutputStream output = null; private Listener(final WebConnection connection) throws IOException { this.connection = connection; this.input = connection.getInputStream(); this.output = connection.getOutputStream(); } @Override public void onDataAvailable() throws IOException { if (Log.doTrace()) { Log.trace("PingUpgradeServlet$Listener.onDataAvailable() called"); } byte[] data = new byte[1024]; int len = -1; while (input.isReady() && (len = input.read(data)) != -1) { String dataRead = new String(data, 0, len); if (Log.doTrace()) { Log.trace("PingUpgradeServlet$Listener.onDataAvailable() -- Adding data to queue -->" + dataRead + "<--"); } output.println(dataRead); output.flush(); } closeConnection(); } private void closeConnection() { try { connection.close(); } catch (Exception e) { if (Log.doTrace()) { Log.error(e.toString()); } } } @Override public void onAllDataRead() throws IOException { closeConnection(); } @Override public void onError(final Throwable t) { closeConnection(); } } }
5,384
31.636364
130
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/prims/PingWebSocketBinary.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.prims; import java.io.IOException; import java.nio.ByteBuffer; import javax.websocket.CloseReason; import javax.websocket.EndpointConfig; import javax.websocket.OnClose; import javax.websocket.OnError; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; /** This class a simple websocket that echos the binary it has been sent. */ @ServerEndpoint(value = "/pingBinary") public class PingWebSocketBinary { private Session currentSession = null; @OnOpen public void onOpen(final Session session, EndpointConfig ec) { currentSession = session; } @OnMessage public void ping(ByteBuffer data) { currentSession.getAsyncRemote().sendBinary(data); } @OnError public void onError(Throwable t) { t.printStackTrace(); } @OnClose public void onClose(Session session, CloseReason reason) { try { if (session.isOpen()) { session.close(); } } catch (IOException e) { e.printStackTrace(); } } }
1,793
26.181818
76
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/prims/PingWebSocketJson.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.prims; import java.io.IOException; import javax.enterprise.concurrent.ManagedThreadFactory; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.websocket.CloseReason; import javax.websocket.EndpointConfig; import javax.websocket.OnClose; import javax.websocket.OnError; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; import com.ibm.websphere.samples.daytrader.web.websocket.JsonDecoder; import com.ibm.websphere.samples.daytrader.web.websocket.JsonEncoder; import com.ibm.websphere.samples.daytrader.web.websocket.JsonMessage; /** This class a simple websocket that sends the number of times it has been pinged. */ @ServerEndpoint(value = "/pingWebSocketJson",encoders=JsonEncoder.class ,decoders=JsonDecoder.class) public class PingWebSocketJson { private Session currentSession = null; private Integer sentHitCount = null; private Integer receivedHitCount = null; @OnOpen public void onOpen(final Session session, EndpointConfig ec) { currentSession = session; sentHitCount = 0; receivedHitCount = 0; InitialContext context; ManagedThreadFactory mtf = null; try { context = new InitialContext(); mtf = (ManagedThreadFactory) context.lookup("java:comp/DefaultManagedThreadFactory"); } catch (NamingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } Thread thread = mtf.newThread(new Runnable() { @Override public void run() { try { Thread.sleep(500); while (currentSession.isOpen()) { sentHitCount++; JsonMessage response = new JsonMessage(); response.setKey("sentHitCount"); response.setValue(sentHitCount.toString()); currentSession.getAsyncRemote().sendObject(response); Thread.sleep(100); } } catch (InterruptedException e) { e.printStackTrace(); } } }); thread.start(); } @OnMessage public void ping(JsonMessage message) throws IOException { receivedHitCount++; JsonMessage response = new JsonMessage(); response.setKey("receivedHitCount"); response.setValue(receivedHitCount.toString()); currentSession.getAsyncRemote().sendObject(response); } @OnError public void onError(Throwable t) { t.printStackTrace(); } @OnClose public void onClose(Session session, CloseReason reason) { } }
3,679
30.452991
100
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/prims/PingWebSocketTextAsync.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.prims; import javax.websocket.CloseReason; import javax.websocket.EndpointConfig; import javax.websocket.OnClose; import javax.websocket.OnError; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; /** This class a simple websocket that sends the number of times it has been pinged. */ @ServerEndpoint(value = "/pingTextAsync") public class PingWebSocketTextAsync { private Session currentSession = null; private Integer hitCount = null; @OnOpen public void onOpen(final Session session, EndpointConfig ec) { currentSession = session; hitCount = 0; } @OnMessage public void ping(String text) { hitCount++; currentSession.getAsyncRemote().sendText(hitCount.toString()); } @OnError public void onError(Throwable t) { t.printStackTrace(); } @OnClose public void onClose(Session session, CloseReason reason) { } }
1,665
27.237288
87
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/prims/PingWebSocketTextSync.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.prims; import java.io.IOException; //import java.util.Collections; //import java.util.HashSet; //import java.util.Set; import javax.websocket.CloseReason; import javax.websocket.EndpointConfig; import javax.websocket.OnClose; import javax.websocket.OnError; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; /** This class a simple websocket that sends the number of times it has been pinged. */ @ServerEndpoint(value = "/pingTextSync") public class PingWebSocketTextSync { private Session currentSession = null; private Integer hitCount = null; @OnOpen public void onOpen(final Session session, EndpointConfig ec) { currentSession = session; hitCount = 0; } @OnMessage public void ping(String text) { hitCount++; try { currentSession.getBasicRemote().sendText(hitCount.toString()); } catch (IOException e) { e.printStackTrace(); } } @OnError public void onError(Throwable t) { t.printStackTrace(); } @OnClose public void onClose(Session session, CloseReason reason) { } }
1,885
26.735294
87
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/prims/ejb3/PingServlet2Entity.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.prims.ejb3; import java.io.IOException; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ibm.websphere.samples.daytrader.entities.QuoteDataBean; import com.ibm.websphere.samples.daytrader.util.Log; import com.ibm.websphere.samples.daytrader.util.TradeConfig; /** * * Primitive designed to run within the TradeApplication and makes use of * {@link trade_client.TradeConfig} for config parameters and random stock * symbols. Servlet will generate a random stock symbol and get the price of * that symbol using a {@link trade.Quote} Entity EJB This tests the common path * of a Servlet calling an Entity EJB to get data * */ public class PingServlet2Entity extends HttpServlet { private static final long serialVersionUID = -9004026114063894842L; private static String initTime; private static int hitCount; @PersistenceContext(unitName = "daytrader") private EntityManager em; @Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doGet(req, res); } @Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { res.setContentType("text/html"); java.io.PrintWriter out = res.getWriter(); QuoteDataBean quote = null; String symbol = null; StringBuffer output = new StringBuffer(100); output.append("<html><head><title>Servlet2Entity</title></head>" + "<body><HR><FONT size=\"+2\" color=\"#000066\">PingServlet2Entity<BR></FONT>" + "<FONT size=\"-1\" color=\"#000066\"><BR>PingServlet2Entity accesses an EntityManager" + " using a PersistenceContext annotaion and then gets the price of a random symbol (generated by TradeConfig)" + " through the EntityManager find method"); try { // generate random symbol try { int iter = TradeConfig.getPrimIterations(); for (int ii = 0; ii < iter; ii++) { // get a random symbol to look up and get the key to that // symbol. symbol = TradeConfig.rndSymbol(); // find the EntityInstance. quote = em.find(QuoteDataBean.class, symbol); } } catch (Exception e) { Log.error("web_primtv.PingServlet2Entity.doGet(...): error performing find"); throw e; } // get the price and print the output. output.append("<HR>initTime: " + initTime + "<BR>Hit Count: ").append(hitCount++); output.append("<HR>Quote Information<BR><BR> " + quote.toHTML()); output.append("</font><HR></body></html>"); out.println(output.toString()); } catch (Exception e) { Log.error(e, "PingServlet2Entity.doGet(...): error"); // this will send an Error to teh web applications defined error // page. res.sendError(500, "PingServlet2Entity.doGet(...): error" + e.toString()); } } @Override public String getServletInfo() { return "web primitive, tests Servlet to Entity EJB path"; } @Override public void init(ServletConfig config) throws ServletException { super.init(config); hitCount = 0; initTime = new java.util.Date().toString(); } }
4,345
37.803571
152
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/prims/ejb3/PingServlet2MDBQueue.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.prims.ejb3; import java.io.IOException; import javax.annotation.Resource; import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.JMSContext; import javax.jms.Queue; import javax.jms.TextMessage; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ibm.websphere.samples.daytrader.util.Log; import com.ibm.websphere.samples.daytrader.util.TradeConfig; /** * This primitive is designed to run inside the TradeApplication and relies upon * the {@link com.ibm.websphere.samples.daytrader.util.TradeConfig} class to set * configuration parameters. PingServlet2MDBQueue tests key functionality of a * servlet call to a post a message to an MDB Queue. The TradeBrokerMDB receives * the message This servlet makes use of the MDB EJB * {@link com.ibm.websphere.samples.daytrader.ejb3.DTBroker3MDB} by posting a * message to the MDB Queue */ @WebServlet(name = "ejb3.PingServlet2MDBQueue", urlPatterns = { "/ejb3/PingServlet2MDBQueue" }) public class PingServlet2MDBQueue extends HttpServlet { private static final long serialVersionUID = 2637271552188745216L; private static String initTime; private static int hitCount; @Resource(name = "jms/QueueConnectionFactory") private ConnectionFactory queueConnectionFactory; @Resource(name = "jms/BrokerQueue") private Queue tradeBrokerQueue; @Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doGet(req, res); } @Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { res.setContentType("text/html"); java.io.PrintWriter out = res.getWriter(); // use a stringbuffer to avoid concatenation of Strings StringBuffer output = new StringBuffer(100); output.append("<html><head><title>PingServlet2MDBQueue</title></head>" + "<body><HR><FONT size=\"+2\" color=\"#000066\">PingServlet2MDBQueue<BR></FONT>" + "<FONT size=\"-1\" color=\"#000066\">" + "Tests the basic operation of a servlet posting a message to an EJB MDB through a JMS Queue.<BR>" + "<FONT color=\"red\"><B>Note:</B> Not intended for performance testing.</FONT>"); try { Connection conn = queueConnectionFactory.createConnection(); try { TextMessage message = null; int iter = TradeConfig.getPrimIterations(); for (int ii = 0; ii < iter; ii++) { /*Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); try { MessageProducer producer = sess.createProducer(tradeBrokerQueue); message = sess.createTextMessage(); String command = "ping"; message.setStringProperty("command", command); message.setLongProperty("publishTime", System.currentTimeMillis()); message.setText("Ping message for queue java:comp/env/jms/TradeBrokerQueue sent from PingServlet2MDBQueue at " + new java.util.Date()); producer.send(message); } finally { sess.close(); }*/ JMSContext context = queueConnectionFactory.createContext(); message = context.createTextMessage(); message.setStringProperty("command", "ping"); message.setLongProperty("publishTime", System.currentTimeMillis()); message.setText("Ping message for queue java:comp/env/jms/TradeBrokerQueue sent from PingServlet2MDBQueue at " + new java.util.Date()); context.createProducer().send(tradeBrokerQueue, message); } // write out the output output.append("<HR>initTime: ").append(initTime); output.append("<BR>Hit Count: ").append(hitCount++); output.append("<HR>Posted Text message to java:comp/env/jms/TradeBrokerQueue destination"); output.append("<BR>Message: ").append(message); output.append("<BR><BR>Message text: ").append(message.getText()); output.append("<BR><HR></FONT></BODY></HTML>"); out.println(output.toString()); } catch (Exception e) { Log.error("PingServlet2MDBQueue.doGet(...):exception posting message to TradeBrokerQueue destination "); throw e; } finally { conn.close(); } } // this is where I actually handle the exceptions catch (Exception e) { Log.error(e, "PingServlet2MDBQueue.doGet(...): error"); res.sendError(500, "PingServlet2MDBQueue.doGet(...): error, " + e.toString()); } } @Override public String getServletInfo() { return "web primitive, configured with trade runtime configs, tests Servlet to Session EJB path"; } @Override public void init(ServletConfig config) throws ServletException { super.init(config); hitCount = 0; initTime = new java.util.Date().toString(); } }
6,174
41.006803
159
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/prims/ejb3/PingServlet2MDBTopic.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.prims.ejb3; import java.io.IOException; import javax.annotation.Resource; import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.JMSContext; import javax.jms.TextMessage; import javax.jms.Topic; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ibm.websphere.samples.daytrader.util.Log; import com.ibm.websphere.samples.daytrader.util.TradeConfig; /** * This primitive is designed to run inside the TradeApplication and relies upon * the {@link com.ibm.websphere.samples.daytrader.util.TradeConfig} class to set * configuration parameters. PingServlet2MDBQueue tests key functionality of a * servlet call to a post a message to an MDB Topic. The TradeStreamerMDB (and * any other subscribers) receives the message This servlet makes use of the MDB * EJB {@link com.ibm.websphere.samples.daytrader.ejb3.DTStreamer3MDB} by * posting a message to the MDB Topic */ @WebServlet(name = "ejb3.PingServlet2MDBTopic", urlPatterns = { "/ejb3/PingServlet2MDBTopic" }) public class PingServlet2MDBTopic extends HttpServlet { private static final long serialVersionUID = 5925470158886928225L; private static String initTime; private static int hitCount; @Resource(name = "jms/TopicConnectionFactory") private ConnectionFactory topicConnectionFactory; @Resource(name = "jms/StreamerTopic") private Topic tradeStreamerTopic; @Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doGet(req, res); } @Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { res.setContentType("text/html"); java.io.PrintWriter out = res.getWriter(); // use a stringbuffer to avoid concatenation of Strings StringBuffer output = new StringBuffer(100); output.append("<html><head><title>PingServlet2MDBTopic</title></head>" + "<body><HR><FONT size=\"+2\" color=\"#000066\">PingServlet2MDBTopic<BR></FONT>" + "<FONT size=\"-1\" color=\"#000066\">" + "Tests the basic operation of a servlet posting a message to an EJB MDB (and other subscribers) through a JMS Topic.<BR>" + "<FONT color=\"red\"><B>Note:</B> Not intended for performance testing.</FONT>"); // we only want to look up the JMS resources once try { Connection conn = topicConnectionFactory.createConnection(); try { TextMessage message = null; int iter = TradeConfig.getPrimIterations(); for (int ii = 0; ii < iter; ii++) { /*Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); try { MessageProducer producer = sess.createProducer(tradeStreamerTopic); message = sess.createTextMessage(); String command = "ping"; message.setStringProperty("command", command); message.setLongProperty("publishTime", System.currentTimeMillis()); message.setText("Ping message for topic java:comp/env/jms/TradeStreamerTopic sent from PingServlet2MDBTopic at " + new java.util.Date()); producer.send(message); } finally { sess.close(); }*/ JMSContext context = topicConnectionFactory.createContext(); message = context.createTextMessage(); message.setStringProperty("command", "ping"); message.setLongProperty("publishTime", System.currentTimeMillis()); message.setText("Ping message for topic java:comp/env/jms/TradeStreamerTopic sent from PingServlet2MDBTopic at " + new java.util.Date()); context.createProducer().send(tradeStreamerTopic, message); } // write out the output output.append("<HR>initTime: ").append(initTime); output.append("<BR>Hit Count: ").append(hitCount++); output.append("<HR>Posted Text message to java:comp/env/jms/TradeStreamerTopic topic"); output.append("<BR>Message: ").append(message); output.append("<BR><BR>Message text: ").append(message.getText()); output.append("<BR><HR></FONT></BODY></HTML>"); out.println(output.toString()); } catch (Exception e) { Log.error("PingServlet2MDBTopic.doGet(...):exception posting message to TradeStreamerTopic topic"); throw e; } finally { conn.close(); } } // this is where I actually handle the exceptions catch (Exception e) { Log.error(e, "PingServlet2MDBTopic.doGet(...): error"); res.sendError(500, "PingServlet2MDBTopic.doGet(...): error, " + e.toString()); } } @Override public String getServletInfo() { return "web primitive, configured with trade runtime configs, tests Servlet to Session EJB path"; } @Override public void init(ServletConfig config) throws ServletException { super.init(config); hitCount = 0; initTime = new java.util.Date().toString(); } }
6,291
41.513514
161
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/prims/ejb3/PingServlet2Session2CMROne2Many.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.prims.ejb3; import java.io.IOException; import java.util.Collection; import java.util.Iterator; import javax.ejb.EJB; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ibm.websphere.samples.daytrader.ejb3.TradeSLSBBean; import com.ibm.websphere.samples.daytrader.entities.OrderDataBean; import com.ibm.websphere.samples.daytrader.util.Log; import com.ibm.websphere.samples.daytrader.util.TradeConfig; /** * Primitive to test Entity Container Managed Relationshiop One to One Servlet * will generate a random userID and get the profile for that user using a * {@link trade.Account} Entity EJB This tests the common path of a Servlet * calling a Session to Entity EJB to get CMR One to One data * */ @WebServlet(name = "ejb3.PingServlet2Session2CMR2One2Many", urlPatterns = { "/ejb3/PingServlet2Session2CMR2One2Many" }) public class PingServlet2Session2CMROne2Many extends HttpServlet { private static final long serialVersionUID = -8658929449987440032L; private static String initTime; private static int hitCount; @EJB(lookup="java:app/daytrader-ee7-ejb/TradeSLSBBean!com.ibm.websphere.samples.daytrader.ejb3.TradeSLSBLocal") private TradeSLSBBean tradeSLSBLocal; @Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doGet(req, res); } @Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { res.setContentType("text/html"); java.io.PrintWriter out = res.getWriter(); String userID = null; StringBuffer output = new StringBuffer(100); output.append("<html><head><title>Servlet2Session2CMROne20ne</title></head>" + "<body><HR><FONT size=\"+2\" color=\"#000066\">PingServlet2Session2CMROne2Many<BR></FONT>" + "<FONT size=\"-1\" color=\"#000066\"><BR>PingServlet2Session2CMROne2Many uses the Trade Session EJB" + " to get the orders for a user using an EJB 3.0 Entity CMR one to many relationship"); try { Collection<?> orderDataBeans = null; int iter = TradeConfig.getPrimIterations(); for (int ii = 0; ii < iter; ii++) { userID = TradeConfig.rndUserID(); // get the users orders and print the output. orderDataBeans = tradeSLSBLocal.getOrders(userID); } output.append("<HR>initTime: " + initTime + "<BR>Hit Count: ").append(hitCount++); output.append("<HR>One to Many CMR access of Account Orders from Account Entity<BR> "); output.append("<HR>User: " + userID + " currently has " + orderDataBeans.size() + " stock orders:"); Iterator<?> it = orderDataBeans.iterator(); while (it.hasNext()) { OrderDataBean orderData = (OrderDataBean) it.next(); output.append("<BR>" + orderData.toHTML()); } output.append("</font><HR></body></html>"); out.println(output.toString()); } catch (Exception e) { Log.error(e, "PingServlet2Session2CMROne2Many.doGet(...): error"); // this will send an Error to teh web applications defined error // page. res.sendError(500, "PingServlet2Session2CMROne2Many.doGet(...): error" + e.toString()); } } @Override public String getServletInfo() { return "web primitive, tests Servlet to Entity EJB path"; } @Override public void init(ServletConfig config) throws ServletException { super.init(config); hitCount = 0; initTime = new java.util.Date().toString(); } }
4,584
39.9375
119
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/prims/ejb3/PingServlet2Session2CMROne2One.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.prims.ejb3; import java.io.IOException; import javax.ejb.EJB; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ibm.websphere.samples.daytrader.ejb3.TradeSLSBBean; import com.ibm.websphere.samples.daytrader.entities.AccountProfileDataBean; import com.ibm.websphere.samples.daytrader.util.Log; import com.ibm.websphere.samples.daytrader.util.TradeConfig; /** * Primitive to test Entity Container Managed Relationshiop One to One Servlet * will generate a random userID and get the profile for that user using a * {@link trade.Account} Entity EJB This tests the common path of a Servlet * calling a Session to Entity EJB to get CMR One to One data * */ @WebServlet(name = "ejb3.PingServlet2Session2CMR2One2One", urlPatterns = { "/ejb3/PingServlet2Session2CMR2One2One" }) public class PingServlet2Session2CMROne2One extends HttpServlet { private static final long serialVersionUID = 567062418489199248L; private static String initTime; private static int hitCount; @EJB(lookup="java:app/daytrader-ee7-ejb/TradeSLSBBean!com.ibm.websphere.samples.daytrader.ejb3.TradeSLSBLocal") private TradeSLSBBean tradeSLSBLocal; @Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doGet(req, res); } @Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { res.setContentType("text/html"); java.io.PrintWriter out = res.getWriter(); String userID = null; StringBuffer output = new StringBuffer(100); output.append("<html><head><title>Servlet2Session2CMROne20ne</title></head>" + "<body><HR><FONT size=\"+2\" color=\"#000066\">PingServlet2Session2CMROne2One<BR></FONT>" + "<FONT size=\"-1\" color=\"#000066\"><BR>PingServlet2Session2CMROne2One uses the Trade Session EJB" + " to get the profile for a user using an EJB 3.0 CMR one to one relationship"); try { AccountProfileDataBean accountProfileData = null; int iter = TradeConfig.getPrimIterations(); for (int ii = 0; ii < iter; ii++) { userID = TradeConfig.rndUserID(); // get the price and print the output. accountProfileData = tradeSLSBLocal.getAccountProfileData(userID); } output.append("<HR>initTime: " + initTime + "<BR>Hit Count: ").append(hitCount++); output.append("<HR>One to One CMR access of AccountProfile Information from Account Entity<BR><BR> " + accountProfileData.toHTML()); output.append("</font><HR></body></html>"); out.println(output.toString()); } catch (Exception e) { Log.error(e, "PingServlet2Session2CMROne2One.doGet(...): error"); // this will send an Error to teh web applications defined error // page. res.sendError(500, "PingServlet2Session2CMROne2One.doGet(...): error" + e.toString()); } } @Override public String getServletInfo() { return "web primitive, tests Servlet to Entity EJB path"; } @Override public void init(ServletConfig config) throws ServletException { super.init(config); hitCount = 0; initTime = new java.util.Date().toString(); } }
4,240
40.174757
144
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/prims/ejb3/PingServlet2Session2Entity.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.prims.ejb3; import java.io.IOException; import javax.ejb.EJB; import javax.naming.InitialContext; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ibm.websphere.samples.daytrader.ejb3.TradeSLSBBean; import com.ibm.websphere.samples.daytrader.entities.QuoteDataBean; import com.ibm.websphere.samples.daytrader.util.Log; import com.ibm.websphere.samples.daytrader.util.TradeConfig; /** * * PingServlet2Session2Entity tests key functionality of a servlet call to a * stateless SessionEJB, and then to a Entity EJB representing data in a * database. This servlet makes use of the Stateless Session EJB {@link Trade}, * and then uses {@link TradeConfig} to generate a random stock symbol. The * stocks price is looked up using the Quote Entity EJB. * */ @WebServlet(name = "ejb3.PingServlet2Session2Entity", urlPatterns = { "/ejb3/PingServlet2Session2Entity" }) public class PingServlet2Session2Entity extends HttpServlet { private static final long serialVersionUID = -5043457201022265012L; private static String initTime; private static int hitCount; @EJB(lookup="java:app/daytrader-ee7-ejb/TradeSLSBBean!com.ibm.websphere.samples.daytrader.ejb3.TradeSLSBLocal") private TradeSLSBBean tradeSLSBLocal; @Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doGet(req, res); } @Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { res.setContentType("text/html"); java.io.PrintWriter out = res.getWriter(); String symbol = null; QuoteDataBean quoteData = null; StringBuffer output = new StringBuffer(100); output.append("<html><head><title>PingServlet2Session2Entity</title></head>" + "<body><HR><FONT size=\"+2\" color=\"#000066\">PingServlet2Session2Entity<BR></FONT>" + "<FONT size=\"-1\" color=\"#000066\">" + "PingServlet2Session2Entity tests the common path of a Servlet calling a Session EJB " + "which in turn calls an Entity EJB.<BR>"); try { try { int iter = TradeConfig.getPrimIterations(); for (int ii = 0; ii < iter; ii++) { symbol = TradeConfig.rndSymbol(); // getQuote will call findQuote which will instaniate the // Quote Entity Bean // and then will return a QuoteObject quoteData = tradeSLSBLocal.getQuote(symbol); } } catch (Exception ne) { Log.error(ne, "PingServlet2Session2Entity.goGet(...): exception getting QuoteData through Trade"); throw ne; } output.append("<HR>initTime: " + initTime).append("<BR>Hit Count: " + hitCount++); output.append("<HR>Quote Information<BR><BR>" + quoteData.toHTML()); out.println(output.toString()); } catch (Exception e) { Log.error(e, "PingServlet2Session2Entity.doGet(...): General Exception caught"); res.sendError(500, "General Exception caught, " + e.toString()); } } @Override public String getServletInfo() { return "web primitive, tests Servlet to Session to Entity EJB path"; } @Override public void init(ServletConfig config) throws ServletException { super.init(config); hitCount = 0; initTime = new java.util.Date().toString(); if (tradeSLSBLocal == null) { Log.error("PingServlet2Session2Entity:init - Injection of tradeSLSBLocal failed - performing JNDI lookup!"); try { InitialContext context = new InitialContext(); tradeSLSBLocal = (TradeSLSBBean) context.lookup("java:comp/env/ejb/TradeSLSBBean"); } catch (Exception ex) { Log.error("PingServlet2Session2Entity:init - Lookup of tradeSLSBLocal failed!!!"); ex.printStackTrace(); } } } }
4,935
39.459016
149
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/prims/ejb3/PingServlet2Session2Entity2JSP.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.prims.ejb3; import java.io.IOException; import javax.ejb.EJB; import javax.naming.InitialContext; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ibm.websphere.samples.daytrader.ejb3.TradeSLSBBean; import com.ibm.websphere.samples.daytrader.entities.QuoteDataBean; import com.ibm.websphere.samples.daytrader.util.Log; import com.ibm.websphere.samples.daytrader.util.TradeConfig; /** * * PingServlet2Session2Entity tests key functionality of a servlet call to a * stateless SessionEJB, and then to a Entity EJB representing data in a * database. This servlet makes use of the Stateless Session EJB {@link Trade}, * and then uses {@link TradeConfig} to generate a random stock symbol. The * stocks price is looked up using the Quote Entity EJB. * */ @WebServlet(name = "ejb3.PingServlet2Session2Entity2JSP", urlPatterns = { "/ejb3/PingServlet2Session2Entity2JSP" }) public class PingServlet2Session2Entity2JSP extends HttpServlet { private static final long serialVersionUID = -8966014710582651693L; @EJB(lookup="java:app/daytrader-ee7-ejb/TradeSLSBBean!com.ibm.websphere.samples.daytrader.ejb3.TradeSLSBLocal") private TradeSLSBBean tradeSLSBLocal; @Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doGet(req, res); } @Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { String symbol = null; QuoteDataBean quoteData = null; ServletContext ctx = getServletConfig().getServletContext(); try { try { int iter = TradeConfig.getPrimIterations(); for (int ii = 0; ii < iter; ii++) { symbol = TradeConfig.rndSymbol(); // getQuote will call findQuote which will instaniate the // Quote Entity Bean // and then will return a QuoteObject quoteData = tradeSLSBLocal.getQuote(symbol); } req.setAttribute("quoteData", quoteData); // req.setAttribute("hitCount", hitCount); // req.setAttribute("initTime", initTime); ctx.getRequestDispatcher("/quoteDataPrimitive.jsp").include(req, res); } catch (Exception ne) { Log.error(ne, "PingServlet2Session2Entity2JSP.goGet(...): exception getting QuoteData through Trade"); throw ne; } } catch (Exception e) { Log.error(e, "PingServlet2Session2Entity2JSP.doGet(...): General Exception caught"); res.sendError(500, "General Exception caught, " + e.toString()); } } @Override public String getServletInfo() { return "web primitive, tests Servlet to Session to Entity EJB to JSP path"; } @Override public void init(ServletConfig config) throws ServletException { super.init(config); // hitCount = 0; // initTime = new java.util.Date().toString(); if (tradeSLSBLocal == null) { Log.error("PingServlet2Session2Entity2JSP:init - Injection of tradeSLSBLocal failed - performing JNDI lookup!"); try { InitialContext context = new InitialContext(); tradeSLSBLocal = (TradeSLSBBean) context.lookup("java:comp/env/ejb/TradeSLSBBean"); } catch (Exception ex) { Log.error("PingServlet2Session2EntityJSP:init - Lookup of tradeSLSBLocal failed!!!"); ex.printStackTrace(); } } } }
4,527
38.719298
124
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/prims/ejb3/PingServlet2Session2EntityCollection.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.prims.ejb3; import java.io.IOException; import java.util.Collection; import java.util.Iterator; import javax.ejb.EJB; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ibm.websphere.samples.daytrader.ejb3.TradeSLSBBean; import com.ibm.websphere.samples.daytrader.entities.HoldingDataBean; import com.ibm.websphere.samples.daytrader.util.Log; import com.ibm.websphere.samples.daytrader.util.TradeConfig; /** * * PingServlet2Session2Entity tests key functionality of a servlet call to a * stateless SessionEJB, and then to a Entity EJB representing data in a * database. This servlet makes use of the Stateless Session EJB {@link Trade}, * and then uses {@link TradeConfig} to generate a random user. The users * portfolio is looked up using the Holding Entity EJB returnin a collection of * Holdings * */ @WebServlet(name = "ejb3.PingServlet2Session2EntityCollection", urlPatterns = { "/ejb3/PingServlet2Session2EntityCollection" }) public class PingServlet2Session2EntityCollection extends HttpServlet { private static final long serialVersionUID = 6171380014749902308L; private static String initTime; private static int hitCount; @EJB(lookup="java:app/daytrader-ee7-ejb/TradeSLSBBean!com.ibm.websphere.samples.daytrader.ejb3.TradeSLSBLocal") private TradeSLSBBean tradeSLSBLocal; @Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doGet(req, res); } @Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { res.setContentType("text/html"); java.io.PrintWriter out = res.getWriter(); String userID = null; Collection<?> holdingDataBeans = null; StringBuffer output = new StringBuffer(100); output.append("<html><head><title>PingServlet2Session2EntityCollection</title></head>" + "<body><HR><FONT size=\"+2\" color=\"#000066\">PingServlet2Session2EntityCollection<BR></FONT>" + "<FONT size=\"-1\" color=\"#000066\">" + "PingServlet2Session2EntityCollection tests the common path of a Servlet calling a Session EJB " + "which in turn calls a finder on an Entity EJB returning a collection of Entity EJBs.<BR>"); try { try { int iter = TradeConfig.getPrimIterations(); for (int ii = 0; ii < iter; ii++) { userID = TradeConfig.rndUserID(); // getQuote will call findQuote which will instaniate the // Quote Entity Bean // and then will return a QuoteObject holdingDataBeans = tradeSLSBLocal.getHoldings(userID); // trade.remove(); } } catch (Exception ne) { Log.error(ne, "PingServlet2Session2EntityCollection.goGet(...): exception getting HoldingData collection through Trade for user " + userID); throw ne; } output.append("<HR>initTime: " + initTime).append("<BR>Hit Count: " + hitCount++); output.append("<HR>User: " + userID + " is currently holding " + holdingDataBeans.size() + " stock holdings:"); Iterator<?> it = holdingDataBeans.iterator(); while (it.hasNext()) { HoldingDataBean holdingData = (HoldingDataBean) it.next(); output.append("<BR>" + holdingData.toHTML()); } out.println(output.toString()); } catch (Exception e) { Log.error(e, "PingServlet2Session2EntityCollection.doGet(...): General Exception caught"); res.sendError(500, "General Exception caught, " + e.toString()); } } @Override public String getServletInfo() { return "web primitive, tests Servlet to Session to Entity returning a collection of Entity EJBs"; } @Override public void init(ServletConfig config) throws ServletException { super.init(config); hitCount = 0; initTime = new java.util.Date().toString(); } }
4,999
41.016807
156
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/prims/ejb3/PingServlet2SessionLocal.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.prims.ejb3; import java.io.IOException; import javax.ejb.EJB; import javax.naming.InitialContext; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ibm.websphere.samples.daytrader.ejb3.TradeSLSBLocal; import com.ibm.websphere.samples.daytrader.util.Log; import com.ibm.websphere.samples.daytrader.util.TradeConfig; /** * * This primitive is designed to run inside the TradeApplication and relies upon * the {@link trade_client.TradeConfig} class to set configuration parameters. * PingServlet2SessionEJB tests key functionality of a servlet call to a * stateless SessionEJB. This servlet makes use of the Stateless Session EJB * {@link trade.Trade} by calling calculateInvestmentReturn with three random * numbers. * */ @WebServlet(name = "ejb3.PingServlet2SessionLocal", urlPatterns = { "/ejb3/PingServlet2SessionLocal" }) public class PingServlet2SessionLocal extends HttpServlet { private static final long serialVersionUID = 6854998080392777053L; private static String initTime; private static int hitCount; @EJB(lookup="java:app/daytrader-ee7-ejb/TradeSLSBBean!com.ibm.websphere.samples.daytrader.ejb3.TradeSLSBLocal") private TradeSLSBLocal tradeSLSBLocal; @Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doGet(req, res); } @Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { res.setContentType("text/html"); java.io.PrintWriter out = res.getWriter(); // use a stringbuffer to avoid concatenation of Strings StringBuffer output = new StringBuffer(100); output.append("<html><head><title>PingServlet2SessionLocal</title></head>" + "<body><HR><FONT size=\"+2\" color=\"#000066\">PingServlet2SessionLocal<BR></FONT>" + "<FONT size=\"-1\" color=\"#000066\">" + "Tests the basis path from a Servlet to a Session Bean."); try { try { // create three random numbers double rnd1 = Math.random() * 1000000; double rnd2 = Math.random() * 1000000; // use a function to do some work. double increase = 0.0; int iter = TradeConfig.getPrimIterations(); for (int ii = 0; ii < iter; ii++) { increase = tradeSLSBLocal.investmentReturn(rnd1, rnd2); } // write out the output output.append("<HR>initTime: " + initTime); output.append("<BR>Hit Count: " + hitCount++); output.append("<HR>Investment Return Information <BR><BR>investment: " + rnd1); output.append("<BR>current Value: " + rnd2); output.append("<BR>investment return " + increase + "<HR></FONT></BODY></HTML>"); out.println(output.toString()); } catch (Exception e) { Log.error("PingServlet2Session.doGet(...):exception calling trade.investmentReturn "); throw e; } } // this is where I actually handle the exceptions catch (Exception e) { Log.error(e, "PingServlet2Session.doGet(...): error"); res.sendError(500, "PingServlet2Session.doGet(...): error, " + e.toString()); } } @Override public String getServletInfo() { return "web primitive, configured with trade runtime configs, tests Servlet to Session EJB path"; } @Override public void init(ServletConfig config) throws ServletException { super.init(config); hitCount = 0; initTime = new java.util.Date().toString(); if (tradeSLSBLocal == null) { Log.error("PingServlet2SessionLocal:init - Injection of TradeSLSBLocal failed - performing JNDI lookup!"); try { InitialContext context = new InitialContext(); tradeSLSBLocal = (TradeSLSBLocal) context.lookup("java:comp/env/ejb/TradeSLSBBean"); } catch (Exception ex) { Log.error("PingServlet2SessionLocal:init - Lookup of TradeSLSBLocal failed!!!"); ex.printStackTrace(); } } } }
5,149
38.922481
142
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/prims/ejb3/PingServlet2SessionRemote.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.prims.ejb3; import java.io.IOException; import javax.ejb.EJB; import javax.naming.InitialContext; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ibm.websphere.samples.daytrader.ejb3.TradeSLSBRemote; import com.ibm.websphere.samples.daytrader.util.Log; import com.ibm.websphere.samples.daytrader.util.TradeConfig; /** * * This primitive is designed to run inside the TradeApplication and relies upon * the {@link trade_client.TradeConfig} class to set configuration parameters. * PingServlet2SessionEJB tests key functionality of a servlet call to a * stateless SessionEJB. This servlet makes use of the Stateless Session EJB * {@link trade.Trade} by calling calculateInvestmentReturn with three random * numbers. * */ @WebServlet(name = "ejb3.PingServlet2SessionRemote", urlPatterns = { "/ejb3/PingServlet2SessionRemote" }) public class PingServlet2SessionRemote extends HttpServlet { private static final long serialVersionUID = -6328388347808212784L; private static String initTime; private static int hitCount; @EJB(lookup="java:app/daytrader-ee7-ejb/TradeSLSBBean!com.ibm.websphere.samples.daytrader.ejb3.TradeSLSBRemote") private TradeSLSBRemote tradeSLSBRemote; @Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doGet(req, res); } @Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { res.setContentType("text/html"); java.io.PrintWriter out = res.getWriter(); // use a stringbuffer to avoid concatenation of Strings StringBuffer output = new StringBuffer(100); output.append("<html><head><title>PingServlet2SessionRemote</title></head>" + "<body><HR><FONT size=\"+2\" color=\"#000066\">PingServlet2SessionRemote<BR></FONT>" + "<FONT size=\"-1\" color=\"#000066\">" + "Tests the basis path from a Servlet to a Session Bean."); try { try { // create three random numbers double rnd1 = Math.random() * 1000000; double rnd2 = Math.random() * 1000000; // use a function to do some work. double increase = 0.0; int iter = TradeConfig.getPrimIterations(); for (int ii = 0; ii < iter; ii++) { increase = tradeSLSBRemote.investmentReturn(rnd1, rnd2); } // write out the output output.append("<HR>initTime: " + initTime); output.append("<BR>Hit Count: " + hitCount++); output.append("<HR>Investment Return Information <BR><BR>investment: " + rnd1); output.append("<BR>current Value: " + rnd2); output.append("<BR>investment return " + increase + "<HR></FONT></BODY></HTML>"); out.println(output.toString()); } catch (Exception e) { Log.error("PingServlet2Session.doGet(...):exception calling trade.investmentReturn "); throw e; } } // this is where I actually handle the exceptions catch (Exception e) { Log.error(e, "PingServlet2Session.doGet(...): error"); res.sendError(500, "PingServlet2Session.doGet(...): error, " + e.toString()); } } @Override public String getServletInfo() { return "web primitive, configured with trade runtime configs, tests Servlet to Session EJB path"; } @Override public void init(ServletConfig config) throws ServletException { super.init(config); hitCount = 0; initTime = new java.util.Date().toString(); if (tradeSLSBRemote == null) { Log.error("PingServlet2Session:init - Injection of tradeSLSBRemote failed - performing JNDI lookup!"); try { InitialContext context = new InitialContext(); tradeSLSBRemote = (TradeSLSBRemote) context.lookup("java:comp/env/ejb/TradeSLSBBeanRemote"); } catch (Exception ex) { Log.error("PingServlet2Session:init - Lookup of tradeSLSBRemote failed!!!"); ex.printStackTrace(); } } } }
5,145
39.203125
170
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/prims/ejb3/PingServlet2TwoPhase.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.prims.ejb3; import java.io.IOException; import javax.ejb.EJB; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.ibm.websphere.samples.daytrader.ejb3.TradeSLSBBean; import com.ibm.websphere.samples.daytrader.entities.QuoteDataBean; import com.ibm.websphere.samples.daytrader.util.Log; import com.ibm.websphere.samples.daytrader.util.TradeConfig; /** * * PingServlet2TwoPhase tests key functionality of a TwoPhase commit In this * primitive a servlet calls a Session EJB which begins a global txn The Session * EJB then reads a DB row and sends a message to JMS Queue The txn is closed w/ * a 2-phase commit * */ @WebServlet(name = "ejb3.PingServlet2TwoPhase", urlPatterns = { "/ejb3/PingServlet2TwoPhase" }) public class PingServlet2TwoPhase extends HttpServlet { private static final long serialVersionUID = -1563251786527079548L; private static String initTime; private static int hitCount; @EJB(lookup="java:app/daytrader-ee7-ejb/TradeSLSBBean!com.ibm.websphere.samples.daytrader.ejb3.TradeSLSBLocal") private TradeSLSBBean tradeSLSBLocal; @Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doGet(req, res); } @Override public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { res.setContentType("text/html"); java.io.PrintWriter out = res.getWriter(); String symbol = null; QuoteDataBean quoteData = null; StringBuffer output = new StringBuffer(100); output.append("<html><head><title>PingServlet2TwoPhase</title></head>" + "<body><HR><FONT size=\"+2\" color=\"#000066\">PingServlet2TwoPhase<BR></FONT>" + "<FONT size=\"-1\" color=\"#000066\">" + "PingServlet2TwoPhase tests the path of a Servlet calling a Session EJB " + "which in turn calls an Entity EJB to read a DB row (quote). The Session EJB " + "then posts a message to a JMS Queue. " + "<BR> These operations are wrapped in a 2-phase commit<BR>"); try { try { int iter = TradeConfig.getPrimIterations(); for (int ii = 0; ii < iter; ii++) { symbol = TradeConfig.rndSymbol(); // getQuote will call findQuote which will instaniate the // Quote Entity Bean // and then will return a QuoteObject quoteData = tradeSLSBLocal.pingTwoPhase(symbol); } } catch (Exception ne) { Log.error(ne, "PingServlet2TwoPhase.goGet(...): exception getting QuoteData through Trade"); throw ne; } output.append("<HR>initTime: " + initTime).append("<BR>Hit Count: " + hitCount++); output.append("<HR>Two phase ping selected a quote and sent a message to TradeBrokerQueue JMS queue<BR>Quote Information<BR><BR>" + quoteData.toHTML()); out.println(output.toString()); } catch (Exception e) { Log.error(e, "PingServlet2TwoPhase.doGet(...): General Exception caught"); res.sendError(500, "General Exception caught, " + e.toString()); } } @Override public String getServletInfo() { return "web primitive, tests Servlet to Session to Entity EJB and JMS -- 2-phase commit path"; } @Override public void init(ServletConfig config) throws ServletException { super.init(config); hitCount = 0; initTime = new java.util.Date().toString(); } }
4,510
38.920354
141
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/websocket/ActionDecoder.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.websocket; import javax.websocket.DecodeException; import javax.websocket.Decoder; import javax.websocket.EndpointConfig; import com.ibm.websphere.samples.daytrader.util.Log; // This is coded to be a Text type decoder expecting JSON format. // It will decode incoming messages into object of type String public class ActionDecoder implements Decoder.Text<ActionMessage> { public ActionDecoder() { } @Override public void destroy() { } @Override public void init(EndpointConfig config) { } @Override public ActionMessage decode(String jsonText) throws DecodeException { if (Log.doTrace()) { Log.trace("ActionDecoder:decode -- received -->" + jsonText + "<--"); } ActionMessage actionMessage = new ActionMessage(); actionMessage.doDecoding(jsonText); return actionMessage; } @Override public boolean willDecode(String s) { return true; } }
1,627
27.068966
81
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/websocket/ActionMessage.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.websocket; import java.io.StringReader; import javax.json.Json; import javax.json.stream.JsonParser; import com.ibm.websphere.samples.daytrader.util.Log; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class ActionMessage { String decodedAction = null; public ActionMessage() { } public void doDecoding(String jsonText) { String keyName = null; try { // JSON parse JsonParser parser = Json.createParser(new StringReader(jsonText)); while (parser.hasNext()) { JsonParser.Event event = parser.next(); switch(event) { case KEY_NAME: keyName=parser.getString(); break; case VALUE_STRING: if (keyName != null && keyName.equals("action")) { decodedAction=parser.getString(); } break; default: break; } } } catch (Exception e) { Log.error("ActionMessage:doDecoding(" + jsonText + ") --> failed", e); } if (Log.doTrace()) { if (decodedAction != null ) { Log.trace("ActionMessage:doDecoding -- decoded action -->" + decodedAction + "<--"); } else { Log.trace("ActionMessage:doDecoding -- decoded action -->null<--"); } } } public String getDecodedAction() { return decodedAction; } }
3,023
32.6
100
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/websocket/JsonDecoder.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.websocket; import java.io.StringReader; import javax.json.Json; import javax.json.JsonObject; import javax.websocket.DecodeException; import javax.websocket.Decoder; import javax.websocket.EndpointConfig; public class JsonDecoder implements Decoder.Text<JsonMessage> { @Override public void destroy() { } @Override public void init(EndpointConfig ec) { } @Override public JsonMessage decode(String json) throws DecodeException { JsonObject jsonObject = Json.createReader(new StringReader(json)).readObject(); JsonMessage message = new JsonMessage(); message.setKey(jsonObject.getString("key")); message.setValue(jsonObject.getString("value")); return message; } @Override public boolean willDecode(String json) { try { Json.createReader(new StringReader(json)).readObject(); return true; } catch (Exception e) { return false; } } }
1,659
27.62069
87
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/websocket/JsonEncoder.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.websocket; import javax.json.Json; import javax.json.JsonObject; import javax.websocket.EncodeException; import javax.websocket.Encoder; import javax.websocket.EndpointConfig; public class JsonEncoder implements Encoder.Text<JsonMessage>{ @Override public void destroy() { } @Override public void init(EndpointConfig ec) { } @Override public String encode(JsonMessage message) throws EncodeException { JsonObject jsonObject = Json.createObjectBuilder() .add("key", message.getKey()) .add("value", message.getValue()).build(); return jsonObject.toString(); } }
1,314
26.978723
75
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/websocket/JsonMessage.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.websocket; public class JsonMessage { private String key; private String value; public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
999
23.390244
75
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/websocket/MarketSummaryWebSocket.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.websocket; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.concurrent.CountDownLatch; import javax.enterprise.event.Observes; import javax.jms.Message; import javax.json.Json; import javax.json.JsonObject; import javax.json.JsonObjectBuilder; import javax.json.JsonValue; import javax.websocket.CloseReason; import javax.websocket.EndpointConfig; import javax.websocket.OnClose; import javax.websocket.OnError; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; import com.ibm.websphere.samples.daytrader.TradeAction; import com.ibm.websphere.samples.daytrader.util.Log; import com.ibm.websphere.samples.daytrader.util.WebSocketJMSMessage; /** This class is a WebSocket EndPoint that sends the Market Summary in JSON form when requested * and sends stock price changes when received from an MDB through a CDI event * */ @ServerEndpoint(value = "/marketsummary",decoders=ActionDecoder.class) public class MarketSummaryWebSocket { private static final Set<Session> sessions = Collections.synchronizedSet(new HashSet<Session>()); private final CountDownLatch latch = new CountDownLatch(1); @OnOpen public void onOpen(final Session session, EndpointConfig ec) { if (Log.doTrace()) { Log.trace("MarketSummaryWebSocket:onOpen -- session -->" + session + "<--"); } sessions.add(session); latch.countDown(); } @OnMessage public void sendMarketSummary(ActionMessage message, Session currentSession) { String action = message.getDecodedAction(); if (Log.doTrace()) { if (action != null ) { Log.trace("MarketSummaryWebSocket:sendMarketSummary -- received -->" + action + "<--"); } else { Log.trace("MarketSummaryWebSocket:sendMarketSummary -- received -->null<--"); } } if (action != null && action.equals("update")) { TradeAction tAction = new TradeAction(); try { JsonObject mkSummary = tAction.getMarketSummary().toJSON(); if (Log.doTrace()) { Log.trace("MarketSummaryWebSocket:sendMarketSummary -- sending -->" + mkSummary + "<--"); } // Make sure onopen is finished latch.await(); if (RecentStockChangeList.isEmpty()) { currentSession.getAsyncRemote().sendText(mkSummary.toString()); } else { // Merge Objects JsonObject recentChangeList = RecentStockChangeList.stockChangesInJSON(); currentSession.getAsyncRemote().sendText(mergeJsonObjects(mkSummary,recentChangeList).toString()); } } catch (Exception e) { e.printStackTrace(); } } } @OnError public void onError(Throwable t, Session currentSession) { if (Log.doTrace()) { Log.trace("MarketSummaryWebSocket:onError -- session -->" + currentSession + "<--"); } t.printStackTrace(); } @OnClose public void onClose(Session session, CloseReason reason) { if (Log.doTrace()) { Log.trace("MarketSummaryWebSocket:onClose -- session -->" + session + "<--"); } sessions.remove(session); } public static void onJMSMessage(@Observes @WebSocketJMSMessage Message message) { if (Log.doTrace()) { Log.trace("MarketSummaryWebSocket:onJMSMessage"); } RecentStockChangeList.addStockChange(message); JsonObject stockChangeJson = RecentStockChangeList.stockChangesInJSON(); synchronized(sessions) { for (Session s : sessions) { if (s.isOpen()) { s.getAsyncRemote().sendText(stockChangeJson.toString()); } } } } private JsonObject mergeJsonObjects(JsonObject obj1, JsonObject obj2) { JsonObjectBuilder jObjectBuilder = Json.createObjectBuilder(); Set<String> keys1 = obj1.keySet(); Iterator<String> iter1 = keys1.iterator(); while(iter1.hasNext()) { String key = (String)iter1.next(); JsonValue value = obj1.get(key); jObjectBuilder.add(key, value); } Set<String> keys2 = obj2.keySet(); Iterator<String> iter2 = keys2.iterator(); while(iter2.hasNext()) { String key = (String)iter2.next(); JsonValue value = obj2.get(key); jObjectBuilder.add(key, value); } return jObjectBuilder.build(); } }
5,681
31.843931
118
java
sample.daytrader7
sample.daytrader7-master/daytrader-ee7-web/src/main/java/com/ibm/websphere/samples/daytrader/web/websocket/RecentStockChangeList.java
/** * (C) Copyright IBM Corporation 2015. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ibm.websphere.samples.daytrader.web.websocket; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import javax.jms.Message; import javax.json.Json; import javax.json.JsonObject; import javax.json.JsonObjectBuilder; /** This class is a holds the last 5 stock changes, used by the MarketSummary WebSocket * */ public class RecentStockChangeList { private static List<Message> stockChanges = Collections.synchronizedList(new LinkedList<Message>()); public static void addStockChange(Message message) { stockChanges.add(0, message); // Add stock, remove if needed if(stockChanges.size() > 5) { stockChanges.remove(5); } } public static JsonObject stockChangesInJSON() { JsonObjectBuilder jObjectBuilder = Json.createObjectBuilder(); try { int i = 1; List<Message> temp = new LinkedList<Message>(stockChanges); for (Iterator<Message> iterator = temp.iterator(); iterator.hasNext();) { Message message = iterator.next(); jObjectBuilder.add("change" + i + "_stock", message.getStringProperty("symbol")); jObjectBuilder.add("change" + i + "_price","$" + message.getStringProperty("price")); BigDecimal change = new BigDecimal(message.getStringProperty("price")).subtract(new BigDecimal(message.getStringProperty("oldPrice"))); change.setScale(2, RoundingMode.HALF_UP); jObjectBuilder.add("change" + i + "_change", change.toString()); i++; } } catch (Exception e) { e.printStackTrace(); } return jObjectBuilder.build(); } public static boolean isEmpty() { return stockChanges.isEmpty(); } }
2,732
31.927711
151
java
SuSi
SuSi-master/SourceCode/src/de/ecspride/sourcesinkfinder/CutoffClassifier.java
package de.ecspride.sourcesinkfinder; import weka.classifiers.Classifier; import weka.core.Instance; import weka.core.Instances; public class CutoffClassifier extends Classifier { /** * */ private static final long serialVersionUID = -2903136632626071812L; private final Classifier baseClassifier; private final double threshold; private final int fallbackCategory; public CutoffClassifier(Classifier baseClassifier, double threshold, int fallbackCategory) { super(); this.baseClassifier = baseClassifier; this.threshold = threshold; this.fallbackCategory = fallbackCategory; } @Override public double[] distributionForInstance(Instance instance) throws Exception { double[] orgDist = baseClassifier.distributionForInstance(instance); for (double d : orgDist) if (Math.abs(d) > threshold) return orgDist; double[] newDist = new double[orgDist.length]; for (int i = 0; i < newDist.length; i++) if (i == fallbackCategory) newDist[i] = 1.0; else newDist[i] = 0.0; return newDist; } @Override public void buildClassifier(Instances data) throws Exception { baseClassifier.buildClassifier(data); } public Classifier getBaseClassifier() { return baseClassifier; } }
1,236
23.74
78
java
SuSi
SuSi-master/SourceCode/src/de/ecspride/sourcesinkfinder/IFeature.java
package de.ecspride.sourcesinkfinder; import soot.jimple.infoflow.android.data.AndroidMethod; /** * Common interface for all features in the probabilistic model * * @author Steven Arzt * */ public interface IFeature { enum Type{TRUE, FALSE, NOT_SUPPORTED} Type applies(AndroidMethod method); String toString(); }
331
15.6
63
java
SuSi
SuSi-master/SourceCode/src/de/ecspride/sourcesinkfinder/SourceSinkFinder.java
package de.ecspride.sourcesinkfinder; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import java.util.Set; import soot.Scene; import soot.SootClass; import soot.SootMethod; import soot.jimple.infoflow.android.data.AndroidMethod; import soot.jimple.infoflow.android.data.AndroidMethodCategoryComparator; import soot.jimple.infoflow.android.data.parsers.CSVPermissionMethodParser; import soot.jimple.infoflow.android.data.parsers.IPermissionMethodParser; import soot.jimple.infoflow.android.data.parsers.PScoutPermissionMethodParser; import soot.jimple.infoflow.android.data.parsers.PermissionMethodParser; import weka.classifiers.Classifier; import weka.classifiers.Evaluation; import weka.classifiers.bayes.BayesNet; import weka.classifiers.bayes.NaiveBayes; import weka.classifiers.functions.SMO; import weka.classifiers.rules.JRip; import weka.classifiers.trees.J48; import weka.core.Attribute; import weka.core.FastVector; import weka.core.Instance; import weka.core.Instances; import weka.core.Range; import weka.core.converters.ArffSaver; import de.ecspride.sourcesinkfinder.IFeature.Type; import de.ecspride.sourcesinkfinder.features.AbstractSootFeature; import de.ecspride.sourcesinkfinder.features.BaseNameOfClassPackageName; import de.ecspride.sourcesinkfinder.features.IsThreadRunFeature; import de.ecspride.sourcesinkfinder.features.MethodAnonymousClassFeature; import de.ecspride.sourcesinkfinder.features.MethodBodyContainsObjectFeature; import de.ecspride.sourcesinkfinder.features.MethodCallsMethodFeature; import de.ecspride.sourcesinkfinder.features.MethodClassConcreteNameFeature; import de.ecspride.sourcesinkfinder.features.MethodClassContainsNameFeature; import de.ecspride.sourcesinkfinder.features.MethodClassEndsWithNameFeature; import de.ecspride.sourcesinkfinder.features.MethodClassModifierFeature; import de.ecspride.sourcesinkfinder.features.MethodClassModifierFeature.ClassModifier; import de.ecspride.sourcesinkfinder.features.MethodHasParametersFeature; import de.ecspride.sourcesinkfinder.features.MethodIsRealSetterFeature; import de.ecspride.sourcesinkfinder.features.MethodModifierFeature; import de.ecspride.sourcesinkfinder.features.MethodModifierFeature.Modifier; import de.ecspride.sourcesinkfinder.features.MethodNameContainsFeature; import de.ecspride.sourcesinkfinder.features.MethodNameEndsWithFeature; import de.ecspride.sourcesinkfinder.features.MethodNameStartsWithFeature; import de.ecspride.sourcesinkfinder.features.MethodReturnsConstantFeature; import de.ecspride.sourcesinkfinder.features.ParameterContainsTypeOrNameFeature; import de.ecspride.sourcesinkfinder.features.ParameterInCallFeature; import de.ecspride.sourcesinkfinder.features.ParameterInCallFeature.CheckType; import de.ecspride.sourcesinkfinder.features.ParameterIsInterfaceFeature; import de.ecspride.sourcesinkfinder.features.PermissionNameFeature; import de.ecspride.sourcesinkfinder.features.ReturnTypeFeature; import de.ecspride.sourcesinkfinder.features.VoidOnMethodFeature; /** * Finds possible sources and sinks in a given set of Android system methods using * a probabilistic algorithm trained on a previously annotated sample set. * * @author Steven Arzt * */ public class SourceSinkFinder { private final static boolean USE_WEKA = true; private final static boolean DETAILED_INFORMATION = false; private final static boolean ENABLE_PERMISSION = true; private final static boolean LOAD_ANDROID = false; private final static boolean DIFF = false; private final static boolean CLASSIFY_CATEGORY = true; private final static float MIN_PROB = 0.0001f; private final Set<IFeature> featuresSourceSink = initializeFeaturesSourceSink(); private final Set<IFeature> featuresCategories = initializeFeaturesCategories(); private static String ANDROID; private static String MAPS; private static final HashSet<AndroidMethod> methodsWithPermissions = new HashSet<AndroidMethod>(); private final static String WEKA_LEARNER_ALL = "SMO"; private final static String WEKA_LEARNER_CATEGORIES = "SMO"; // private final static double THRESHOLD = 0.1; private final static double THRESHOLD = 0.0; private long startSourceSinkAnalysisTime; private long sourceSinkAnalysisTime; private long startCatSourcesTime; private long catSourcesTime; private long startCatSinksTime; private long catSinksTime; /** * @param args *First parameter: ANDROID platform jar path * *Second parameter: MAPS jar path * *Third - x parameter: names of input * *Last parameter: file name of output */ public static void main(String[] args) { try { if (args.length < 4) { System.out.println("Usage: java de.ecspride.sourcesinkfinder.SourceSinkFinder " + "<androidJAR> <mapsJAR> <input1>...<inputN> <outputFile>"); return; } String[] inputs = Arrays.copyOfRange(args, 2, args.length-1); //set Android paths ANDROID = args[0]; MAPS = args[1]; SourceSinkFinder sourceSinkFinder = new SourceSinkFinder(); sourceSinkFinder.run(inputs, args[args.length - 1]); } catch (IOException e) { e.printStackTrace(); } } public void run(String[] inputFiles, String outputFile) throws IOException { Set<AndroidMethod> methods = loadMethodsFromFile(inputFiles); // Prefilter the interfaces methods = PrefilterInterfaces(methods); // Create the custom annotations for derived methods createSubclassAnnotations(methods); if (LOAD_ANDROID) { Set<AndroidMethod> newMethods = new HashSet<AndroidMethod>(); for (AndroidMethod am : methods) if (am.isAnnotated() || am.getCategory() != null) newMethods.add(am); methods = newMethods; // Load the Android stuff loadMethodsFromAndroid(methods); createSubclassAnnotations(methods); } // Classify the methods into sources, sinks and neither-nor entries if (USE_WEKA){ startSourceSinkAnalysisTime = System.currentTimeMillis(); analyzeSourceSinkWeka(methods, outputFile); sourceSinkAnalysisTime = System.currentTimeMillis() - startSourceSinkAnalysisTime; System.out.println("Time to classify sources/sinks/neither: " + sourceSinkAnalysisTime + " ms"); } else{ startSourceSinkAnalysisTime = System.currentTimeMillis(); analyzeSourceSinkBayes(methods, outputFile); sourceSinkAnalysisTime = System.currentTimeMillis() - startSourceSinkAnalysisTime; System.out.println("Time to classify sources/sinks/neither: " + sourceSinkAnalysisTime + " ms"); } // Classify the categories if(CLASSIFY_CATEGORY){ //source startCatSourcesTime = System.currentTimeMillis(); analyzeCategories(methods, outputFile, true, false); catSourcesTime = System.currentTimeMillis() - startCatSourcesTime; System.out.println("Time to categorize sources: " + catSourcesTime + " ms"); //sink startCatSinksTime = System.currentTimeMillis(); analyzeCategories(methods, outputFile, false, true); catSinksTime = System.currentTimeMillis() - startCatSinksTime; System.out.println("Time to categorize sinks: " + catSinksTime + " ms"); } } /** * Uses a custom NaiveBayes implementation for classifying Android methods * as sources, sinks, or neither-nor entries. * @param sourceFileName * @param targetFileName * @throws IOException */ private void analyzeSourceSinkBayes(Set<AndroidMethod> methods, String targetFileName) throws IOException { Map<IFeature, Double> sourceProps = new HashMap<IFeature, Double>(); Map<IFeature, Double> sinkProps = new HashMap<IFeature, Double>(); Map<IFeature, Double> neitherNorProps = new HashMap<IFeature, Double>(); // Train the classifier List<AndroidMethod> sources = new ArrayList<AndroidMethod>(); List<AndroidMethod> sinks = new ArrayList<AndroidMethod>(); List<AndroidMethod> neitherNor = new ArrayList<AndroidMethod>(); long trainingSetSize = 0; for (AndroidMethod method : methods) { if (method.isSource()) sources.add(method); if (method.isSink()) sinks.add(method); if (method.isNeitherNor()) neitherNor.add(method); if (method.isSource() || method.isSink() || method.isNeitherNor()) trainingSetSize++; } if(DETAILED_INFORMATION) analyseFeatureSpreading(featuresSourceSink, methods, sources, sinks, neitherNor); System.out.println("Training set of " + trainingSetSize + " entries, that is " + trainingSetSize / (float) methods.size() * 100 + "% of all data"); System.out.println("We have " + sources.size() + " sources, " + sinks.size() + " sinks and " + neitherNor.size() + " neither/nor entries"); for (IFeature feature : featuresSourceSink) { int sourceCount = 0; int sinkCount = 0; int neitherNorCount = 0; for (AndroidMethod method : sources) if (feature.applies(method) == Type.TRUE) sourceCount++; for (AndroidMethod method : sinks) if (feature.applies(method) == Type.TRUE) sinkCount++; for (AndroidMethod method : neitherNor) if (feature.applies(method) == Type.TRUE) neitherNorCount++; if (sourceCount == 0 && sinkCount == 0 && neitherNorCount == 0) { System.err.println("Feature " + feature + " never applies in training set"); continue; } double sourceProb = (double) sourceCount / sources.size(); double sinkProb = (double) sinkCount / sinks.size(); double neitherNorProb = (double) neitherNorCount / neitherNor.size(); sourceProps.put(feature, Math.max(sourceProb, MIN_PROB)); sinkProps.put(feature, Math.max(sinkProb, MIN_PROB)); neitherNorProps.put(feature, Math.max(neitherNorProb, MIN_PROB)); } System.out.println("Source conditional probabilities:"); for (Map.Entry<IFeature, Double> cell : sourceProps.entrySet()) System.out.println("\t" + cell.getKey() + "\t" + cell.getValue()); System.out.println("Sink conditional probabilities:"); for (Map.Entry<IFeature, Double> cell : sinkProps.entrySet()) System.out.println("\t" + cell.getKey() + "\t" + cell.getValue()); System.out.println("Neither/nor conditional probabilities:"); for (Map.Entry<IFeature, Double> cell : neitherNorProps.entrySet()) System.out.println("\t" + cell.getKey() + "\t" + cell.getValue()); double sourcePrior = (double) sources.size() / trainingSetSize; double sinkPrior = (double) sinks.size() / trainingSetSize; double neitherNorPrior = (double) neitherNor.size() / trainingSetSize; System.out.println("Source prior is " + sourcePrior + ", sink prior is " + sinkPrior + ", neither/nor prior is " + neitherNorPrior); // Classify 'em all! long classifiedSource = 0; long classifiedSink = 0; long classifiedNeitherNor = 0; for (AndroidMethod method : methods) { // Don't classify stuff from our training set if (method.isSource() || method.isSink() || method.isNeitherNor()) continue; // Bayes double pSource = sourcePrior; double pSink = sinkPrior; double pNeitherNor = neitherNorPrior; for (IFeature feature : featuresSourceSink) { if (!sourceProps.containsKey(feature) && !sinkProps.containsKey(feature) && !neitherNorProps.containsKey(feature)) continue; if (feature.applies(method) == Type.TRUE) { pSource *= sourceProps.get(feature); pSink *= sinkProps.get(feature); pNeitherNor *= neitherNorProps.get(feature); } else { pSource *= 1 - sourceProps.get(feature); pSink *= 1 - sinkProps.get(feature); pNeitherNor *= 1 - neitherNorProps.get(feature); } } if (pNeitherNor >= pSink && pNeitherNor >= pSource) { method.setNeitherNor(true); classifiedNeitherNor++; } else if (pSource >= pSink && pSource >= pNeitherNor) { method.setSource(true); classifiedSource++; } else if (pSink >= pSource && pSink >= pNeitherNor) { method.setSink(true); classifiedSink++; } } System.out.println("We have found " + classifiedSource + " sources, " + classifiedSink + " sinks, and " + classifiedNeitherNor + " neither/nor entries"); writeCategoriesToFiles(targetFileName, methods); } private void writeResultsToFiles(String targetFileName, Set<AndroidMethod> methods, boolean diff) throws IOException { // Dump the stuff BufferedWriter wr = null; try { wr = new BufferedWriter(new FileWriter(targetFileName)); for (AndroidMethod am : methods) wr.write(am.toString() + "\n"); wr.flush(); wr.close(); wr = new BufferedWriter(new FileWriter(appendFileName(targetFileName, "_Sources"))); for (AndroidMethod am : methods) if (am.isSource()){ if(diff && !methodsWithPermissions.contains(am)) wr.write(am.toString() + "\n"); else if(!diff) wr.write(am.toString() + "\n"); } wr.flush(); wr.close(); wr = new BufferedWriter(new FileWriter(appendFileName(targetFileName, "_Sinks"))); for (AndroidMethod am : methods) if (am.isSink()){ if(diff && !methodsWithPermissions.contains(am)) wr.write(am.toString() + "\n"); else if(!diff) wr.write(am.toString() + "\n"); } wr.flush(); wr.close(); wr = new BufferedWriter(new FileWriter(appendFileName(targetFileName, "_NeitherNor"))); for (AndroidMethod am : methods) if (am.isNeitherNor()){ if(diff && !methodsWithPermissions.contains(am)) wr.write(am.toString() + "\n"); else if(!diff) wr.write(am.toString() + "\n"); } wr.flush(); wr.close(); } finally { if (wr != null) wr.close(); } } private void writeCategoryResultsToFiles(String targetFileName, Set<AndroidMethod> methods, boolean source, boolean sink, boolean diff) throws IOException { // Dump the stuff BufferedWriter wr = null; ArrayList<AndroidMethod> methodsAsList = new ArrayList<AndroidMethod>(methods); Comparator<AndroidMethod> catComparator = new AndroidMethodCategoryComparator(); Collections.sort(methodsAsList, catComparator); try { if(source && !sink){ wr = new BufferedWriter(new FileWriter(appendFileName(targetFileName, "_CatSources"))); AndroidMethod.CATEGORY currentCat = null; for (AndroidMethod am : methodsAsList){ if (am.isSource()){ if(currentCat == null || currentCat != am.getCategory()){ currentCat = am.getCategory(); wr.write("\n" + currentCat.toString() + ":\n"); } if(diff && !methodsWithPermissions.contains(am)) wr.write(am.getSignatureAndPermissions() + " (" + currentCat.toString() + ")\n"); else if(!diff) wr.write(am.getSignatureAndPermissions() + " (" + currentCat.toString() + ")\n"); } } wr.flush(); wr.close(); } else if(sink && !source){ wr = new BufferedWriter(new FileWriter(appendFileName(targetFileName, "_CatSinks"))); AndroidMethod.CATEGORY currentCat = null; for (AndroidMethod am : methodsAsList){ if (am.isSink()){ if(currentCat == null || currentCat != am.getCategory()){ currentCat = am.getCategory(); wr.write("\n" + currentCat.toString() + ":\n"); } if(diff && !methodsWithPermissions.contains(am)) wr.write(am.getSignatureAndPermissions() + " (" + currentCat.toString() + ")\n"); else if(!diff) wr.write(am.getSignatureAndPermissions() + " (" + currentCat.toString() + ")\n"); } } wr.flush(); wr.close(); } else throw new RuntimeException("Woops, wrong settings"); } finally { if (wr != null) wr.close(); } } private void writeCategoriesToFiles(String targetFileName, Set<AndroidMethod> methods) throws IOException { // Dump the stuff BufferedWriter wr = null; try { wr = new BufferedWriter(new FileWriter(appendFileName(targetFileName, "_Catgories"))); for (AndroidMethod am : methods) wr.write(am.toString() + "\n"); wr.flush(); wr.close(); } finally { if (wr != null) wr.close(); } } private Set<AndroidMethod> loadMethodsFromFile(String[] sourceFileName) throws IOException { // Read in the source file Set<AndroidMethod> methods = new HashSet<AndroidMethod>(); for (String fileName : sourceFileName) { IPermissionMethodParser pmp = createParser(fileName); Set<AndroidMethod> meths = pmp.parse(); for (AndroidMethod am : meths) { if (methods.contains(am)) { // Merge the methods for (AndroidMethod amOrig : methods) if (am.equals(amOrig)) { // Merge the classification if (am.isSource()) amOrig.setSource(true); if (am.isSource()) amOrig.setSink(true); if (am.isNeitherNor()) amOrig.setNeitherNor(true); // Merge the permissions and parameters amOrig.getPermissions().addAll(am.getPermissions()); amOrig.getParameters().addAll(am.getParameters()); break; } } else{ methods.add(am); if(fileName.endsWith(".pscout")) methodsWithPermissions.add(am); } } } // Create features for the permissions if(ENABLE_PERMISSION){ createPermissionFeatures(methods, this.featuresSourceSink); createPermissionFeatures(methods, this.featuresCategories); } System.out.println("Running with " + featuresSourceSink.size() + " features on " + methods.size() + " methods"); return methods; } private void analyzeSourceSinkWeka(Set<AndroidMethod> methods, String targetFileName) throws IOException { FastVector ordinal = new FastVector(); ordinal.addElement("true"); ordinal.addElement("false"); FastVector classes = new FastVector(); classes.addElement("source"); classes.addElement("sink"); classes.addElement("neithernor"); // Collect all attributes and create the instance set Map<IFeature, Attribute> featureAttribs = new HashMap<IFeature, Attribute>(this.featuresSourceSink.size()); FastVector attributes = new FastVector(); for (IFeature f : this.featuresSourceSink) { Attribute attr = new Attribute(f.toString(), ordinal); featureAttribs.put(f, attr); attributes.addElement(attr); } Attribute classAttr = new Attribute("class", classes); FastVector methodStrings = new FastVector(); for (AndroidMethod am : methods) methodStrings.addElement(am.getSignature()); attributes.addElement(classAttr); Attribute idAttr = new Attribute("id", methodStrings); attributes.addElement(idAttr); Instances trainInstances = new Instances("trainingmethods", attributes, 0); Instances testInstances = new Instances("allmethods", attributes, 0); trainInstances.setClass(classAttr); testInstances.setClass(classAttr); // Create one instance object per data row int sourceTraining = 0; int sinkTraining = 0; int nnTraining = 0; int instanceId = 0; Map<String, AndroidMethod> instanceMethods = new HashMap<String, AndroidMethod>(methods.size()); Map<Integer, AndroidMethod> instanceIndices = new HashMap<Integer, AndroidMethod>(methods.size()); for (AndroidMethod am : methods) { Instance inst = new Instance(attributes.size()); inst.setDataset(trainInstances); for (Entry<IFeature, Attribute> entry : featureAttribs.entrySet()){ switch(entry.getKey().applies(am)){ case TRUE: inst.setValue(entry.getValue(), "true"); break; case FALSE: inst.setValue(entry.getValue(), "false"); break; default: inst.setMissing(entry.getValue()); } } inst.setValue(idAttr, am.getSignature()); instanceMethods.put(am.getSignature(), am); instanceIndices.put(instanceId++, am); // Set the known classifications if (am.isSource()) { inst.setClassValue("source"); sourceTraining++; } else if (am.isSink()) { inst.setClassValue("sink"); sinkTraining++; } else if (am.isNeitherNor()) { inst.setClassValue("neithernor"); nnTraining++; } else inst.setClassMissing(); if (am.isAnnotated()) trainInstances.add(inst); else testInstances.add(inst); } try { // instances.randomize(new Random(1337)); Classifier classifier = null; if(WEKA_LEARNER_ALL.equals("BayesNet")) // (IBK / kNN) vs. SMO vs. (J48 vs. JRIP) vs. NaiveBayes // MultiClassClassifier fr ClassifierPerformanceEvaluator classifier = new BayesNet(); else if(WEKA_LEARNER_ALL.equals("NaiveBayes")) classifier = new NaiveBayes(); else if(WEKA_LEARNER_ALL.equals("J48")) classifier = new J48(); else if(WEKA_LEARNER_ALL.equals("SMO")) classifier = new SMO(); else if(WEKA_LEARNER_ALL.equals("JRip")) classifier = new JRip(); else throw new Exception("Wrong WEKA learner!"); ArffSaver saver = new ArffSaver(); saver.setInstances(trainInstances); saver.setFile(new File("SourcesSinks_Train.arff")); saver.writeBatch(); Evaluation eval = new Evaluation(trainInstances); StringBuffer sb = new StringBuffer(); eval.crossValidateModel(classifier, trainInstances, 10, new Random(1337), sb, new Range(attributes.indexOf(idAttr) + 1 + ""/* "1-" + (attributes.size() - 1)*/), true); System.out.println(sb.toString()); System.out.println("Class details: " + eval.toClassDetailsString()); System.out.println("Ran on a training set of " + sourceTraining + " sources, " + sinkTraining + " sinks, and " + nnTraining + " neither-nors"); classifier.buildClassifier(trainInstances); if(WEKA_LEARNER_ALL.equals("J48")){ System.out.println(((J48)(classifier)).graph()); } for (int instIdx = 0; instIdx < testInstances.numInstances(); instIdx++) { Instance inst = testInstances.instance(instIdx); assert inst.classIsMissing(); AndroidMethod meth = instanceMethods.get(inst.stringValue(idAttr)); double d = classifier.classifyInstance(inst); String cName = testInstances.classAttribute().value((int) d); if (cName.equals("source")) { inst.setClassValue("source"); meth.setSource(true); } else if (cName.equals("sink")) { inst.setClassValue("sink"); meth.setSink(true); } else if (cName.equals("neithernor")) { inst.setClassValue("neithernor"); meth.setNeitherNor(true); } else System.err.println("Unknown class name"); } } catch (Exception ex) { System.err.println("Something went all wonky: " + ex); ex.printStackTrace(); } if(DIFF) writeResultsToFiles(targetFileName, methods, true); else writeResultsToFiles(targetFileName, methods, false); Runtime.getRuntime().gc(); } private void analyzeCategories(Set<AndroidMethod> methods, String targetFileName, boolean sources, boolean sinks) throws IOException { FastVector ordinal = new FastVector(); ordinal.addElement("true"); ordinal.addElement("false"); // We are only interested in sources and sinks { Set<AndroidMethod> newMethods = new HashSet<AndroidMethod>(methods.size()); for (AndroidMethod am : methods) { // Make sure that we run after source/sink classification assert am.isAnnotated(); if (am.isSink() == sinks && am.isSource() == sources) newMethods.add(am); } methods = newMethods; } System.out.println("We have a set of " + methods.size() + " sources and sinks."); // Build the class attribute, one possibility for every category FastVector classes = new FastVector(); for (AndroidMethod.CATEGORY cat : AndroidMethod.CATEGORY.values()) { // Only add the class if it is actually used for (AndroidMethod am : methods) if (am.isSource() == sources && am.isSink() == sinks && am.getCategory() == cat) { classes.addElement(cat.toString()); break; } } // Collect all attributes and create the instance set Map<IFeature, Attribute> featureAttribs = new HashMap<IFeature, Attribute>(this.featuresCategories.size()); FastVector attributes = new FastVector(); for (IFeature f : this.featuresCategories) { Attribute attr = new Attribute(f.toString(), ordinal); featureAttribs.put(f, attr); attributes.addElement(attr); } Attribute classAttr = new Attribute("class", classes); FastVector methodStrings = new FastVector(); for (AndroidMethod am : methods) methodStrings.addElement(am.getSignature()); attributes.addElement(classAttr); Attribute idAttr = new Attribute("id", methodStrings); attributes.addElement(idAttr); Instances trainInstances = new Instances("trainingmethodsCat", attributes, 0); Instances testInstances = new Instances("allmethodsCat", attributes, 0); trainInstances.setClass(classAttr); testInstances.setClass(classAttr); // Create one instance object per data row int instanceId = 0; Map<String, AndroidMethod> instanceMethods = new HashMap<String, AndroidMethod>(methods.size()); Map<Integer, AndroidMethod> instanceIndices = new HashMap<Integer, AndroidMethod>(methods.size()); for (AndroidMethod am : methods) { Instance inst = new Instance(attributes.size()); inst.setDataset(trainInstances); for (Entry<IFeature, Attribute> entry : featureAttribs.entrySet()){ switch(entry.getKey().applies(am)){ case TRUE: inst.setValue(entry.getValue(), "true"); break; case FALSE: inst.setValue(entry.getValue(), "false"); break; default: inst.setMissing(entry.getValue()); } } inst.setValue(idAttr, am.getSignature()); instanceMethods.put(am.getSignature(), am); instanceIndices.put(instanceId++, am); // Set the known classifications if (am.getCategory() == null) { inst.setClassMissing(); testInstances.add(inst); } else { inst.setClassValue(am.getCategory().toString()); trainInstances.add(inst); } } System.out.println("Running category classifier on " + trainInstances.numInstances() + " instances with " + attributes.size() + " attributes..."); ArffSaver saver = new ArffSaver(); saver.setInstances(trainInstances); if (sources) saver.setFile(new File("CategoriesSources_Train.arff")); else saver.setFile(new File("CategoriesSinks_Train.arff")); saver.writeBatch(); try { // instances.randomize(new Random(1337)); int noCatIdx = classes.indexOf("NO_CATEGORY"); if (noCatIdx < 0) throw new RuntimeException("Could not find NO_CATEGORY index"); Classifier classifier = null; if(WEKA_LEARNER_CATEGORIES.equals("BayesNet")) // (IBK / kNN) vs. SMO vs. (J48 vs. JRIP) vs. NaiveBayes // MultiClassClassifier fr ClassifierPerformanceEvaluator classifier = new CutoffClassifier(new BayesNet(), THRESHOLD, noCatIdx); else if(WEKA_LEARNER_CATEGORIES.equals("NaiveBayes")) classifier = new CutoffClassifier(new NaiveBayes(), THRESHOLD, noCatIdx); else if(WEKA_LEARNER_CATEGORIES.equals("J48")) classifier = new CutoffClassifier(new J48(), THRESHOLD, noCatIdx); else if(WEKA_LEARNER_CATEGORIES.equals("SMO")) // classifier = new CutoffClassifier(new SMO(), THRESHOLD, noCatIdx); classifier = new SMO(); else if(WEKA_LEARNER_CATEGORIES.equals("JRip")) classifier = new CutoffClassifier(new JRip(), THRESHOLD, noCatIdx); else throw new Exception("Wrong WEKA learner!"); Evaluation eval = new Evaluation(trainInstances); /*for (int foldNum = 0; foldNum < 10; foldNum++) { Instances train = trainInstances.trainCV(10, foldNum, new Random(1337)); Instances test = trainInstances.testCV(10, foldNum); Classifier clsCopy = Classifier.makeCopy(classifier); clsCopy.buildClassifier(train); eval.evaluateModel(clsCopy, test); }*/ StringBuffer sb = new StringBuffer(); eval.crossValidateModel(classifier, trainInstances, 10, new Random(1337), sb, new Range(attributes.indexOf(idAttr) + 1 + ""), true); System.out.println(sb.toString()); System.out.println("Class details: " + eval.toClassDetailsString()); classifier.buildClassifier(trainInstances); if(WEKA_LEARNER_CATEGORIES.equals("J48")){ Classifier baseClassifier = ((CutoffClassifier)classifier).getBaseClassifier(); System.out.println(((J48)(baseClassifier)).graph()); } System.out.println("Record\tSource\tSink\tNN"); for (int instNum = 0; instNum < testInstances.numInstances(); instNum++) { Instance inst = testInstances.instance(instNum); assert inst.classIsMissing(); AndroidMethod meth = instanceMethods.get(inst.stringValue(idAttr)); double d = classifier.classifyInstance(inst); String cName = trainInstances.classAttribute().value((int) d); meth.setCategory(AndroidMethod.CATEGORY.valueOf(cName)); } } catch (Exception ex) { System.err.println("Something went all wonky: " + ex); ex.printStackTrace(); } if(DIFF) writeCategoryResultsToFiles(targetFileName, methods, sources, sinks, true); else writeCategoryResultsToFiles(targetFileName, methods, sources, sinks, false); } private void loadMethodsFromAndroid(final Set<AndroidMethod> methods) { int methodCount = methods.size(); new AbstractSootFeature(MAPS, ANDROID) { @Override public Type appliesInternal(AndroidMethod method) { for (SootClass sc : Scene.v().getClasses()) if (!sc.isInterface() && !sc.isPrivate()) // && sc.getName().startsWith("android.") // && sc.getName().startsWith("com.")) for (SootMethod sm : sc.getMethods()) if (sm.isConcrete() && !sm.isPrivate()) { AndroidMethod newMethod = new AndroidMethod(sm); methods.add(newMethod); } return Type.NOT_SUPPORTED; } }.applies(new AndroidMethod("a", "void", "x.y")); System.out.println("Loaded " + (methods.size() - methodCount) + " methods from Android JAR"); } /** * Creates artificial annotations for non-overridden methods in subclasses. * If the class A implements some method foo() which is marked as e.g. a * source and class B extends A, but does not overwrite foo(), B.foo() * must also be a source. * @param methods The list of method for which to create subclass * annotations */ private void createSubclassAnnotations(final Set<AndroidMethod> methods) { int copyCount = -1; int totalCopyCount = 0; while (copyCount != 0) copyCount = 0; for (AndroidMethod am : methods) { // Check whether one of the parent classes is already annotated AbstractSootFeature asf = new AbstractSootFeature(MAPS, ANDROID) { @Override public Type appliesInternal(AndroidMethod method) { // This already searches up the class hierarchy until we // find a match for the requested method. SootMethod parentMethod = getSootMethod(method); if (parentMethod == null) return Type.NOT_SUPPORTED; // If we have found the method in a base class and not in // the current one, we can copy our current method's // annotation to this base class. (copy-down) boolean copied = false; if (!parentMethod.getDeclaringClass().getName().equals(method.getClassName())) { // Get the data object for the parent method AndroidMethod parentMethodData = findAndroidMethod(parentMethod); if (parentMethodData == null) return Type.NOT_SUPPORTED; // If we have annotations for both methods, they must match if (parentMethodData.isAnnotated() && method.isAnnotated()) if (parentMethodData.isSource() != method.isSource() || parentMethodData.isSink() != method.isSink() || parentMethodData.isNeitherNor() != method.isNeitherNor()) throw new RuntimeException("Annotation mismatch for " + parentMethodData + " and " + method); if (parentMethodData.getCategory() != null && method.getCategory() != null) if (parentMethodData.getCategory() != method.getCategory()) throw new RuntimeException("Category mismatch for " + parentMethod + " and " + method); // If we only have annotations for the parent method, but not for // the current one, we copy it down if (parentMethodData.isAnnotated() && !method.isAnnotated()) { method.setSource(parentMethodData.isSource()); method.setSink(parentMethodData.isSink()); method.setNeitherNor(parentMethodData.isNeitherNor()); copied = true; } if (parentMethodData.getCategory() != null && method.getCategory() == null) method.setCategory(parentMethodData.getCategory()); // If we only have annotations for the current method, but not for // the parent one, we can copy it up if (!parentMethodData.isAnnotated() && method.isAnnotated()) { parentMethodData.setSource(method.isSource()); parentMethodData.setSink(method.isSink()); parentMethodData.setNeitherNor(method.isNeitherNor()); copied = true; } if (parentMethodData.getCategory() == null && method.getCategory() != null) parentMethodData.setCategory(method.getCategory()); } return copied ? Type.TRUE : Type.FALSE; } private AndroidMethod findAndroidMethod(SootMethod sm) { AndroidMethod smData = new AndroidMethod(sm); for (AndroidMethod am : methods) if (am.equals(smData)) return am; return null; } }; if (asf.applies(am) == Type.TRUE) { copyCount++; totalCopyCount++; } } System.out.println("Created automatic annotations starting from " + totalCopyCount + " methods"); } /** * Removes all interfaces from the given set of methods and returns the * purged set. * @param methods The set of methods from which to remove the interfaces. * @return The purged set of methods. */ private Set<AndroidMethod> PrefilterInterfaces(Set<AndroidMethod> methods) { Set<AndroidMethod> purgedMethods = new HashSet<AndroidMethod>(methods.size()); for (AndroidMethod am : methods) { AbstractSootFeature asf = new AbstractSootFeature(MAPS, ANDROID) { @Override public Type appliesInternal(AndroidMethod method) { SootMethod sm = getSootMethod(method); if (sm == null) return Type.NOT_SUPPORTED; if (sm.isAbstract() || sm.getDeclaringClass().isInterface() || sm.isPrivate()) return Type.FALSE; else return Type.TRUE; } }; if (asf.applies(am) == Type.TRUE) purgedMethods.add(am); } System.out.println(methods.size() + " methods purged down to " + purgedMethods.size()); return purgedMethods; } /** * Creates one feature for every unique permission required by a method * @param methods The list of methods and permissions */ private void createPermissionFeatures(Set<AndroidMethod> methods, Set<IFeature> featureSet) { for (AndroidMethod am : methods) for (String perm : am.getPermissions()) featureSet.add(new PermissionNameFeature(perm)); } private String appendFileName(String targetFileName, String string) { int pos = targetFileName.lastIndexOf("."); return targetFileName.substring(0, pos) + string + targetFileName.substring(pos); } private IPermissionMethodParser createParser(String fileName) throws IOException { String fileExt = fileName.substring(fileName.lastIndexOf(".")); if (fileExt.equalsIgnoreCase(".txt")) return PermissionMethodParser.fromFile(fileName); if (fileExt.equalsIgnoreCase(".csv")) return new CSVPermissionMethodParser(fileName); if (fileExt.equalsIgnoreCase(".pscout")) return new PScoutPermissionMethodParser(fileName); throw new RuntimeException("Unknown source file format"); } private void analyseFeatureSpreading(Set<IFeature> features, Set<AndroidMethod> methods, List<AndroidMethod> sources, List<AndroidMethod> sinks, List<AndroidMethod> neitherNor){ Map<IFeature, Set<AndroidMethod>> featureMethodMap = new HashMap<IFeature, Set<AndroidMethod>>(); for(AndroidMethod method : methods){ for(IFeature feature : features){ if(feature.applies(method) == Type.TRUE){ if(featureMethodMap.containsKey(feature)){ Set<AndroidMethod> methodList = featureMethodMap.get(feature); methodList.add(method); } else{ Set<AndroidMethod> newMethodList = new HashSet<AndroidMethod>(); newMethodList.add(method); featureMethodMap.put(feature, newMethodList); } } } } for(IFeature feature : features) if(!featureMethodMap.keySet().contains(feature)) featureMethodMap.put(feature, null); //############## Print feature spreading: ############## System.out.println("############## Print feature spreading: ##############"); for(Map.Entry<IFeature, Set<AndroidMethod>> entry : featureMethodMap.entrySet()){ if(entry.getValue() != null) System.out.println(entry.getKey() + "\t" + entry.getValue().size()); else System.out.println(entry.getKey() + "\t0"); } System.out.println("######################################################"); //############## Print feature spreading based on trainings-set: ############## System.out.println("############## Print feature spreading based on trainings-set: ##############"); System.out.println("Feature:\tSources \\%\tSinks: \\%\tNeitherNor:"); for(Map.Entry<IFeature, Set<AndroidMethod>> entry : featureMethodMap.entrySet()){ if(entry.getValue() != null){ int sourcesCounter = 0, sinkCounter = 0, neitherNorCounter = 0; for(AndroidMethod method : entry.getValue()){ //sources if(sources.contains(method)) sourcesCounter++; //sinks else if(sinks.contains(method)) sinkCounter++; //neither nor else if(neitherNor.contains(method)) neitherNorCounter++; } System.out.print(entry.getKey()); System.out.print("\t" + sourcesCounter*100/sources.size()); System.out.print("\t" + sinkCounter*100/sinks.size()); System.out.print("\t" + neitherNorCounter*100/neitherNor.size() + "\n"); } else{ System.out.print(entry.getKey()); System.out.print("\t-\t-\t-\n"); } } System.out.println("######################################################"); } /** * Initializes the set of features for classifying methods as sources, * sinks or neither-nor entries. * @return The generated feature set. */ private Set<IFeature> initializeFeaturesSourceSink() { Set<IFeature> features = new HashSet<IFeature>(); /* Method name indications */ IFeature nameStartsWithGet = new MethodNameStartsWithFeature("get", 0.2f); features.add(nameStartsWithGet); IFeature nameStartsWithDo = new MethodNameStartsWithFeature("do", 0.2f); features.add(nameStartsWithDo); IFeature nameStartsWithNotify = new MethodNameStartsWithFeature("notify", 0.2f); features.add(nameStartsWithNotify); IFeature nameStartsWithUpdate = new MethodNameStartsWithFeature("update", 0.2f); features.add(nameStartsWithUpdate); IFeature nameStartsWithIs = new MethodNameStartsWithFeature("is", 0.2f); features.add(nameStartsWithIs); IFeature nameStartsWithSend = new MethodNameStartsWithFeature("send", 0.1f); features.add(nameStartsWithSend); IFeature nameStartsWithSet = new MethodNameStartsWithFeature("set", 0.2f); features.add(nameStartsWithSet); IFeature nameStartsWithFinish = new MethodNameStartsWithFeature("finish", 0.1f); features.add(nameStartsWithFinish); IFeature nameStartsWithStart = new MethodNameStartsWithFeature("start", 0.1f); features.add(nameStartsWithStart); IFeature nameStartsWithHandle = new MethodNameStartsWithFeature("handle", 0.1f); features.add(nameStartsWithHandle); IFeature nameStartsWithClear = new MethodNameStartsWithFeature("clear", 0.3f); features.add(nameStartsWithClear); /* Does not change anything IFeature nameStartsWithShow = new MethodNameStartsWithFeature("show", 0.2f); features.add(nameStartsWithShow); IFeature nameStartsWithMove = new MethodNameStartsWithFeature("move", 0.1f); features.add(nameStartsWithMove); IFeature nameStartsWithConnect = new MethodNameStartsWithFeature("connect", 0.1f); features.add(nameStartsWithConnect); IFeature nameStartsWithEnforce = new MethodNameStartsWithFeature("enforce", 0.1f); features.add(nameStartsWithEnforce); IFeature nameStartsWithDisplay = new MethodNameStartsWithFeature("display", 0.1f); features.add(nameStartsWithDisplay); IFeature nameStartsWithPull = new MethodNameStartsWithFeature("pull", 0.1f); features.add(nameStartsWithPull); IFeature nameStartsWithPresent = new MethodNameStartsWithFeature("present", 0.1f); features.add(nameStartsWithPresent); IFeature nameStartsWithSave = new MethodNameStartsWithFeature("save", 0.3f); features.add(nameStartsWithSave); IFeature nameStartsWithWrite = new MethodNameStartsWithFeature("write", 0.3f); features.add(nameStartsWithWrite); IFeature nameStartsWithBroadcast = new MethodNameStartsWithFeature("broadcast", 0.1f); features.add(nameStartsWithBroadcast); IFeature nameEndsWithUpdated = new MethodNameEndsWithFeature("Updated"); features.add(nameEndsWithUpdated); */ IFeature nameStartsWithRemove = new MethodNameStartsWithFeature("remove", 0.3f); features.add(nameStartsWithRemove); IFeature nameStartsWithRelease = new MethodNameStartsWithFeature("release", 0.3f); features.add(nameStartsWithRelease); IFeature nameStartsWithNote = new MethodNameStartsWithFeature("note", 0.1f); features.add(nameStartsWithNote); IFeature nameStartsWithUnregister = new MethodNameStartsWithFeature("unregister", 0.1f); features.add(nameStartsWithUnregister); IFeature nameStartsWithRegister = new MethodNameStartsWithFeature("register", 0.1f); features.add(nameStartsWithRegister); IFeature nameStartsWithPut = new MethodNameStartsWithFeature("put", 0.3f); features.add(nameStartsWithPut); IFeature nameStartsWithAdd = new MethodNameStartsWithFeature("add", 0.3f); features.add(nameStartsWithAdd); IFeature nameStartsWithSupply = new MethodNameStartsWithFeature("supply", 0.1f); features.add(nameStartsWithSupply); IFeature nameStartsWithDelete = new MethodNameStartsWithFeature("delete", 0.3f); features.add(nameStartsWithDelete); IFeature nameStartsWithInit = new MethodNameStartsWithFeature("<init>", 0.1f); features.add(nameStartsWithInit); IFeature nameStartsWithOpen = new MethodNameStartsWithFeature("open", 0.1f); features.add(nameStartsWithOpen); IFeature nameStartsWithClose = new MethodNameStartsWithFeature("close", 0.1f); features.add(nameStartsWithClose); IFeature nameStartsWithEnable = new MethodNameStartsWithFeature("enable", 0.1f); features.add(nameStartsWithEnable); IFeature nameStartsWithDisable = new MethodNameStartsWithFeature("disable", 0.1f); features.add(nameStartsWithDisable); IFeature nameStartsWithQuery = new MethodNameStartsWithFeature("query", 0.1f); features.add(nameStartsWithQuery); IFeature nameStartsWithProcess = new MethodNameStartsWithFeature("process", 0.1f); features.add(nameStartsWithProcess); IFeature nameStartsWithRun = new MethodNameStartsWithFeature("run", 0.1f); features.add(nameStartsWithRun); IFeature nameStartsWithPerform = new MethodNameStartsWithFeature("perform", 0.1f); features.add(nameStartsWithPerform); IFeature nameStartsWithToggle = new MethodNameStartsWithFeature("toggle", 0.1f); features.add(nameStartsWithToggle); IFeature nameStartsWithBind = new MethodNameStartsWithFeature("bind", 0.1f); features.add(nameStartsWithBind); IFeature nameStartsWithDispatch = new MethodNameStartsWithFeature("dispatch", 0.1f); features.add(nameStartsWithDispatch); IFeature nameStartsWithApply = new MethodNameStartsWithFeature("apply", 0.1f); features.add(nameStartsWithApply); IFeature nameStartsWithLoad = new MethodNameStartsWithFeature("load", 0.1f); features.add(nameStartsWithLoad); IFeature nameStartsWithDump = new MethodNameStartsWithFeature("dump", 0.1f); features.add(nameStartsWithDump); IFeature nameStartsWithRequest = new MethodNameStartsWithFeature("request", 0.1f); features.add(nameStartsWithRequest); IFeature nameStartsWithRestore = new MethodNameStartsWithFeature("restore", 0.1f); features.add(nameStartsWithRestore); IFeature nameStartsWithInsert = new MethodNameStartsWithFeature("insert", 0.1f); features.add(nameStartsWithInsert); IFeature nameStartsWithOnClick = new MethodNameStartsWithFeature("onClick", 0.1f); features.add(nameStartsWithOnClick); IFeature nameEndWithMessenger = new MethodNameEndsWithFeature("Messenger"); features.add(nameEndWithMessenger); IFeature parameterStartsWithJavaIo = new ParameterContainsTypeOrNameFeature("java.io."); features.add(parameterStartsWithJavaIo); IFeature parameterStartsWithCursor = new ParameterContainsTypeOrNameFeature("android.database.Cursor"); features.add(parameterStartsWithCursor); IFeature parameterStartsWithContenResolver = new ParameterContainsTypeOrNameFeature("android.content.ContentResolver"); features.add(parameterStartsWithContenResolver); IFeature parameterTypeURI = new ParameterContainsTypeOrNameFeature("android.net.Uri"); features.add(parameterTypeURI); IFeature parameterTypeHasGoogleIO = new ParameterContainsTypeOrNameFeature("com.google.common.io"); features.add(parameterTypeHasGoogleIO); IFeature parameterTypeHasContext = new ParameterContainsTypeOrNameFeature("android.content.Context"); features.add(parameterTypeHasContext); IFeature parameterEndsWithObserver = new ParameterContainsTypeOrNameFeature("Observer"); features.add(parameterEndsWithObserver); IFeature parameterTypeHasWriter = new ParameterContainsTypeOrNameFeature("Writer"); features.add(parameterTypeHasWriter); IFeature parameterTypeHasEvent = new ParameterContainsTypeOrNameFeature("Event"); features.add(parameterTypeHasEvent); // IFeature parameterTypeHasOutputStream = new ParameterHasTypeFeature("OutputStream", 0.2f); // features.add(parameterTypeHasOutputStream); // // IFeature parameterTypeHasInputStream = new ParameterHasTypeFeature("InputStream", 0.2f); // features.add(parameterTypeHasInputStream); /* DOES NOT CHANGE ANYTHING */ // (unfortunately there are also some neithernors that contains an IBinder!!) /* IFeature parameterTypeHasIBinder = new ParameterContainsTypeOrNameFeature("android.os.IBinder", 0.2f); features.add(parameterTypeHasIBinder); */ IFeature parameterTypeHasKey = new ParameterContainsTypeOrNameFeature("com.android.inputmethod.keyboard.Key"); features.add(parameterTypeHasKey); IFeature parameterTypeHasIntend = new ParameterContainsTypeOrNameFeature("android.content.Intent"); features.add(parameterTypeHasIntend); IFeature parameterTypeHasFileDescriptor = new ParameterContainsTypeOrNameFeature("java.io.FileDescriptor"); features.add(parameterTypeHasFileDescriptor); IFeature parameterTypeHasFilterContext = new ParameterContainsTypeOrNameFeature("android.filterfw.core.FilterContext"); features.add(parameterTypeHasFilterContext); IFeature parameterTypeHasString = new ParameterContainsTypeOrNameFeature("java.lang.String"); features.add(parameterTypeHasString); IFeature voidReturnType = new ReturnTypeFeature(MAPS, ANDROID, "void"); features.add(voidReturnType); IFeature booleanReturnType = new ReturnTypeFeature(MAPS, ANDROID, "boolean"); features.add(booleanReturnType); IFeature intReturnType = new ReturnTypeFeature(MAPS, ANDROID, "int"); features.add(intReturnType); IFeature byteArrayReturnType = new ReturnTypeFeature(MAPS, ANDROID, "byte[]"); features.add(byteArrayReturnType); IFeature cursorReturnType = new ReturnTypeFeature(MAPS, ANDROID, "android.database.Cursor"); features.add(cursorReturnType); /* Does not change anything IFeature mergeCursorReturnType = new ReturnTypeFeature(MAPS, ANDROID, "android.database.MergeCursor"); features.add(mergeCursorReturnType); IFeature webviewReturnType = new ReturnTypeFeature(MAPS, ANDROID, "android.webkit.WebView"); features.add(webviewReturnType); */ IFeature uriReturnType = new ReturnTypeFeature(MAPS, ANDROID, "android.net.Uri"); features.add(uriReturnType); IFeature connectionReturnType = new ReturnTypeFeature(MAPS, ANDROID, "com.android.internal.telephony.Connection"); features.add(connectionReturnType); IFeature returnTypeImplementsInterfaceList = new ReturnTypeFeature(MAPS, ANDROID, "java.util.List"); features.add(returnTypeImplementsInterfaceList); IFeature returnTypeImplementsInterfaceMap = new ReturnTypeFeature(MAPS, ANDROID, "java.util.Map"); features.add(returnTypeImplementsInterfaceMap); IFeature returnTypeImplementsInterfaceParcelable = new ReturnTypeFeature(MAPS, ANDROID, "android.os.Parcelable"); features.add(returnTypeImplementsInterfaceParcelable); IFeature hasParamsPerm = new MethodHasParametersFeature(0.2f); features.add(hasParamsPerm); IFeature voidOnMethod = new VoidOnMethodFeature(); features.add(voidOnMethod); /* Method modifiers */ IFeature isStaticMethod = new MethodModifierFeature(MAPS, ANDROID, Modifier.STATIC); features.add(isStaticMethod); IFeature isPublicMethod = new MethodModifierFeature(MAPS, ANDROID, Modifier.PUBLIC); features.add(isPublicMethod); /* Does not change anything IFeature isNativeMethod = new MethodModifierFeature(MAPS, ANDROID, Modifier.NATIVE); features.add(isNativeMethod); IFeature isAbstraceMethod = new MethodModifierFeature(MAPS, ANDROID, Modifier.ABSTRACT); features.add(isAbstraceMethod); IFeature isPrivateMethod = new MethodModifierFeature(MAPS, ANDROID, Modifier.PRIVATE); features.add(isPrivateMethod); */ IFeature isProtectedMethod = new MethodModifierFeature(MAPS, ANDROID, Modifier.PROTECTED); features.add(isProtectedMethod); IFeature isFinalMethod = new MethodModifierFeature(MAPS, ANDROID, Modifier.FINAL); features.add(isFinalMethod); /* Class modifiers */ IFeature isPrivateClassOfMethod = new MethodClassModifierFeature(MAPS, ANDROID, ClassModifier.PRIVATE); features.add(isPrivateClassOfMethod); IFeature isPublicClassOfMethod = new MethodClassModifierFeature(MAPS, ANDROID, ClassModifier.PUBLIC); features.add(isPublicClassOfMethod); IFeature isProtectedClassOfMethod = new MethodClassModifierFeature(MAPS, ANDROID, ClassModifier.PROTECTED); features.add(isProtectedClassOfMethod); IFeature isStaticClassOfMethod = new MethodClassModifierFeature(MAPS, ANDROID, ClassModifier.STATIC); features.add(isStaticClassOfMethod); IFeature isFinalClassOfMethod = new MethodClassModifierFeature(MAPS, ANDROID, ClassModifier.FINAL); features.add(isFinalClassOfMethod); IFeature isAbstractClassOfMethod = new MethodClassModifierFeature(MAPS, ANDROID, ClassModifier.ABSTRACT); features.add(isAbstractClassOfMethod); /* Specific class properties */ /* Does not change anything IFeature isInnerClassOfMethod = new MethodInnerClassFeature(MAPS, ANDROID, true); features.add(isInnerClassOfMethod); */ IFeature isAnonymousClassOfMethod = new MethodAnonymousClassFeature(true); features.add(isAnonymousClassOfMethod); // IFeature connectivityManagerClass = new MethodClassConcreteNameFeature("android.net.ConnectivityManager", 0.2f); // features.add(connectivityManagerClass); // // IFeature telephonyManagerClass = new MethodClassConcreteNameFeature("android.telephony.TelephonyManager", 0.4f); // features.add(telephonyManagerClass); // // IFeature locationManagerClass = new MethodClassConcreteNameFeature("android.location.LocationManager", 0.3f); // features.add(locationManagerClass); // // IFeature accountManagerClass = new MethodClassConcreteNameFeature("android.accounts.AccountManager", 0.3f); // features.add(accountManagerClass); // // IFeature smsManagerClass = new MethodClassConcreteNameFeature("android.telephony.gsm.SmsManager", 0.4f); // features.add(smsManagerClass); /* Class name ends with - gives a hint about the type of operation handled in the class */ IFeature managerClasses = new MethodClassEndsWithNameFeature("Manager"); features.add(managerClasses); IFeature factoryClasses = new MethodClassEndsWithNameFeature("Factory"); features.add(factoryClasses); IFeature serviceClasses = new MethodClassEndsWithNameFeature("Service"); features.add(serviceClasses); IFeature viewClasses = new MethodClassEndsWithNameFeature("View"); features.add(viewClasses); IFeature ioClasses = new MethodClassContainsNameFeature("java.io."); features.add(ioClasses); IFeature loaderClasses = new MethodClassEndsWithNameFeature("Loader"); features.add(loaderClasses); IFeature handlerClasses = new MethodClassEndsWithNameFeature("Handler"); features.add(handlerClasses); IFeature contextClasses = new MethodClassEndsWithNameFeature("Context"); features.add(contextClasses); /* SLIGHTLY INCREASES FP FOR SINKS */ /* IFeature providerClasses = new MethodClassEndsWithNameFeature("Provider", 0.4f); features.add(providerClasses); */ IFeature googleIOClasses = new MethodClassContainsNameFeature("com.google.common.io"); features.add(googleIOClasses); IFeature contentResolverClass = new MethodClassConcreteNameFeature("android.content.ContentResolver"); features.add(contentResolverClass); IFeature contextClass = new MethodClassConcreteNameFeature("android.content.Context"); features.add(contextClass); IFeature activityClass = new MethodClassConcreteNameFeature("android.app.Activity"); features.add(activityClass); IFeature serviceClass = new MethodClassConcreteNameFeature("android.app.Service"); features.add(serviceClass); IFeature contentProviderClass = new MethodClassConcreteNameFeature("android.app.ContentProvider"); features.add(contentProviderClass); IFeature broadcastReceiverClass = new MethodClassConcreteNameFeature("android.app.BroadcastReceiver"); features.add(broadcastReceiverClass); //not in Testcase! // IFeature locationListenerClass = new MethodClassConcreteNameFeature("android.location.LocationListener", 0.2f); // features.add(locationListenerClass); //not in Testcase! // IFeature phoneStateListenerClass = new MethodClassConcreteNameFeature("android.telephony.PhoneStateListener", 0.2f); // features.add(phoneStateListenerClass); // IFeature dataFlowQuerySource = new DataFlowSourceFeature(ANDROID, "query", 0.6f); // features.add(dataFlowQuerySource); // // IFeature dataFlowCreateTypedArrayListSource = new DataFlowSourceFeature(ANDROID, "createTypedArrayList", 0.6f); // features.add(dataFlowCreateTypedArrayListSource); // IFeature parameterInSink = new ParameterInCallFeature(MAPS, ANDROID, "", CheckType.CheckSink); // features.add(parameterInSink); IFeature parameterInRemove = new ParameterInCallFeature(MAPS, ANDROID, "remove", CheckType.CheckSink); features.add(parameterInRemove); IFeature parameterInSync = new ParameterInCallFeature(MAPS, ANDROID, "sync", CheckType.CheckSink); features.add(parameterInSync); IFeature parameterInClear = new ParameterInCallFeature(MAPS, ANDROID, "clear", CheckType.CheckSink); features.add(parameterInClear); IFeature parameterInOnCreate = new ParameterInCallFeature(MAPS, ANDROID, "onCreate", CheckType.CheckSink); features.add(parameterInOnCreate); IFeature parameterInDelete = new ParameterInCallFeature(MAPS, ANDROID, "delete", CheckType.CheckSink); features.add(parameterInDelete); IFeature parameterInSet = new ParameterInCallFeature(MAPS, ANDROID, "set", -1, false /*true*/, CheckType.CheckSink); features.add(parameterInSet); IFeature parameterInEnable = new ParameterInCallFeature(MAPS, ANDROID, "enable", CheckType.CheckSink); features.add(parameterInEnable); IFeature parameterInDisable = new ParameterInCallFeature(MAPS, ANDROID, "disable", CheckType.CheckSink); features.add(parameterInDisable); IFeature parameterInPut = new ParameterInCallFeature(MAPS, ANDROID, "put", -1, false /*true*/, CheckType.CheckSink); features.add(parameterInPut); IFeature parameterInStart = new ParameterInCallFeature(MAPS, ANDROID, "start", CheckType.CheckSink); features.add(parameterInStart); IFeature parameterInSave = new ParameterInCallFeature(MAPS, ANDROID, "save", CheckType.CheckSink); features.add(parameterInSave); IFeature parameterInSend = new ParameterInCallFeature(MAPS, ANDROID, "send", CheckType.CheckSink); features.add(parameterInSend); IFeature parameterInDump = new ParameterInCallFeature(MAPS, ANDROID, "dump", CheckType.CheckSink); features.add(parameterInDump); IFeature parameterInDial = new ParameterInCallFeature(MAPS, ANDROID, "dial", CheckType.CheckSink); features.add(parameterInDial); IFeature parameterInBroadcast = new ParameterInCallFeature(MAPS, ANDROID, "broadcast", CheckType.CheckSink); features.add(parameterInBroadcast); IFeature parameterInBind = new ParameterInCallFeature(MAPS, ANDROID, "bind", CheckType.CheckSink); features.add(parameterInBind); IFeature parameterInTransact = new ParameterInCallFeature(MAPS, ANDROID, "transact", CheckType.CheckSink); features.add(parameterInTransact); IFeature parameterInWrite = new ParameterInCallFeature(MAPS, ANDROID, "write", CheckType.CheckSink); features.add(parameterInWrite); IFeature parameterInUpdate = new ParameterInCallFeature(MAPS, ANDROID, "update", CheckType.CheckSink); features.add(parameterInUpdate); IFeature parameterInPerform = new ParameterInCallFeature(MAPS, ANDROID, "perform", CheckType.CheckSink); features.add(parameterInPerform); IFeature parameterInNotify = new ParameterInCallFeature(MAPS, ANDROID, "notify", CheckType.CheckSink); features.add(parameterInNotify); IFeature parameterInInsert = new ParameterInCallFeature(MAPS, ANDROID, "insert", CheckType.CheckSink); features.add(parameterInInsert); IFeature parameterInEnqueue = new ParameterInCallFeature(MAPS, ANDROID, "enqueue", CheckType.CheckSink); features.add(parameterInEnqueue); IFeature parameterInReplace = new ParameterInCallFeature(MAPS, ANDROID, "replace", CheckType.CheckSink); features.add(parameterInReplace); IFeature parameterInShow = new ParameterInCallFeature(MAPS, ANDROID, "show", CheckType.CheckSink); features.add(parameterInShow); IFeature parameterInDispatch = new ParameterInCallFeature(MAPS, ANDROID, "dispatch", CheckType.CheckSink); features.add(parameterInDispatch); /* Does not change anything IFeature parameterInPrint = new ParameterInCallFeature(MAPS, ANDROID, "print", CheckType.CheckSink); features.add(parameterInPrint); */ IFeature parameterInPrintln = new ParameterInCallFeature(MAPS, ANDROID, "println", CheckType.CheckSink); features.add(parameterInPrintln); IFeature parameterInCreate = new ParameterInCallFeature(MAPS, ANDROID, "create", CheckType.CheckSink); features.add(parameterInCreate); IFeature parameterInAdjust = new ParameterInCallFeature(MAPS, ANDROID, "adjust", CheckType.CheckSink); features.add(parameterInAdjust); IFeature parameterInSetup = new ParameterInCallFeature(MAPS, ANDROID, "setup", CheckType.CheckSink); features.add(parameterInSetup); IFeature parameterInRestore = new ParameterInCallFeature(MAPS, ANDROID, "restore", CheckType.CheckSink); features.add(parameterInRestore); IFeature parameterInConnect = new ParameterInCallFeature(MAPS, ANDROID, "connect", CheckType.CheckSink); features.add(parameterInConnect); IFeature parameterInAbstract = new ParameterInCallFeature(MAPS, ANDROID, "", CheckType.CheckSinkInAbstract); features.add(parameterInAbstract); IFeature parameterInCI = new ParameterInCallFeature(MAPS, ANDROID, "com.android.internal.telephony.CommandsInterface", CheckType.CheckSink); features.add(parameterInCI); IFeature getInReturn = new ParameterInCallFeature(MAPS, ANDROID, "get", CheckType.CheckSource); features.add(getInReturn); IFeature queryInReturn = new ParameterInCallFeature(MAPS, ANDROID, "query", CheckType.CheckSource); features.add(queryInReturn); // IFeature ctalInReturn = new ParameterInCallFeature("createTypedArrayList", CheckType.CheckSource); // features.add(ctalInReturn); IFeature createInReturn = new ParameterInCallFeature(MAPS, ANDROID, "create", CheckType.CheckSource); features.add(createInReturn); IFeature obtainMessageInReturn = new ParameterInCallFeature(MAPS, ANDROID, "obtainMessage", CheckType.CheckSource); features.add(obtainMessageInReturn); IFeature isInReturn = new ParameterInCallFeature(MAPS, ANDROID, "is", CheckType.CheckSource); features.add(isInReturn); IFeature parameterInNative = new ParameterInCallFeature(MAPS, ANDROID, "", CheckType.CheckFromParamToNative); features.add(parameterInNative); // IFeature parameterInNative = new ParameterInCallFeature(MAPS, ANDROID, "", CheckType.CheckFromParamToInterface); // features.add(parameterInNative); /* Does not change anything IFeature transactArgument2InReturn = new ParameterInCallFeature(MAPS, ANDROID, "transact", 2, false, CheckType.CheckSource); features.add(transactArgument2InReturn); */ IFeature wtParcelArgument1InReturn = new ParameterInCallFeature(MAPS, ANDROID, "writeToParcel", 0, false, CheckType.CheckSource); features.add(wtParcelArgument1InReturn); IFeature getToSink = new ParameterInCallFeature(MAPS, ANDROID, "get", CheckType.CheckFromMethodToSink); features.add(getToSink); IFeature threadRun = new IsThreadRunFeature(MAPS, ANDROID); features.add(threadRun); IFeature methodReturnsConstant = new MethodReturnsConstantFeature(MAPS, ANDROID); features.add(methodReturnsConstant); //sink feature // IFeature parameterFlowsToSpecificMethod = new DataFlowFromParameterToSpecificMethodFeature(ANDROID, WRAPPER_FILE, 0.2f); // features.add(parameterFlowsToSpecificMethod); IFeature classNameContainsTelephony = new BaseNameOfClassPackageName("telephony"); features.add(classNameContainsTelephony); IFeature classNameContainsIO = new BaseNameOfClassPackageName("io"); features.add(classNameContainsIO); IFeature classNameContainsAccounts = new BaseNameOfClassPackageName("accounts"); features.add(classNameContainsAccounts); IFeature classNameContainsWebkit = new BaseNameOfClassPackageName("webkit"); features.add(classNameContainsWebkit); IFeature classNameContainsMusik = new BaseNameOfClassPackageName("music"); features.add(classNameContainsMusik); // IFeature notifyCalled = new MethodCallsMethodFeature(MAPS, ANDROID, "notify"); // features.add(notifyCalled); IFeature notifyCalled = new MethodCallsMethodFeature(MAPS, ANDROID, "android.database.sqlite.SQLiteDatabase", "insert"); features.add(notifyCalled); IFeature interfaceParameter = new ParameterIsInterfaceFeature(MAPS, ANDROID); features.add(interfaceParameter); /* Does not change anything IFeature binderCalled = new MethodCallsMethodFeature(MAPS, ANDROID, "android.os.IBinder", "transact"); features.add(binderCalled); */ IFeature isSetter = new MethodIsRealSetterFeature(MAPS, ANDROID); features.add(isSetter); // IFeature invokeAdd = new MethodInvocationOnParameterFeature(MAPS, "ANDROID", "add"); // features.add(invokeAdd); return features; } /** * Initializes the set of features for classifying sources and sinks into * categories. * @return The generated feature set. */ private Set<IFeature> initializeFeaturesCategories() { Set<IFeature> features = new HashSet<IFeature>(); IFeature nameContainsProvider = new MethodNameContainsFeature("Provider"); features.add(nameContainsProvider); IFeature nameContainsPreferred = new MethodNameContainsFeature("Preferred"); features.add(nameContainsPreferred); IFeature nameContainsType = new MethodNameContainsFeature("Type"); features.add(nameContainsType); IFeature nameContainsPreference = new MethodNameContainsFeature("Preference"); features.add(nameContainsPreference); IFeature nameContainsNdef = new MethodNameContainsFeature("ndef"); features.add(nameContainsNdef); IFeature nameContainsRoute = new MethodNameContainsFeature("Route"); features.add(nameContainsRoute); IFeature nameContainsDtmf = new MethodNameContainsFeature("dtmf"); features.add(nameContainsDtmf); IFeature nameContainsConnect = new MethodNameContainsFeature("connect"); features.add(nameContainsConnect); IFeature nameContainsMobile = new MethodNameContainsFeature("mobile"); features.add(nameContainsMobile); IFeature nameContainsNotify = new MethodNameContainsFeature("notify"); features.add(nameContainsNotify); IFeature nameContainsConfiguration = new MethodNameContainsFeature("Configuration"); features.add(nameContainsConfiguration); IFeature nameContainsConnectivity = new MethodNameContainsFeature("Connectivity"); features.add(nameContainsConnectivity); IFeature nameContainsMailbox = new MethodNameContainsFeature("Mailbox"); features.add(nameContainsMailbox); IFeature nameContainsSubmit = new MethodNameContainsFeature("submit"); features.add(nameContainsSubmit); IFeature nameContainsSend = new MethodNameContainsFeature("send"); features.add(nameContainsSend); IFeature nameContainsAuth = new MethodNameContainsFeature("auth"); features.add(nameContainsAuth); IFeature nameContainsToken = new MethodNameContainsFeature("token"); features.add(nameContainsToken); IFeature nameContainsSync = new MethodNameContainsFeature("sync"); features.add(nameContainsSync); IFeature nameContainsPassword = new MethodNameContainsFeature("password"); features.add(nameContainsPassword); IFeature nameContainsTethering = new MethodNameContainsFeature("Tethering"); features.add(nameContainsTethering); IFeature nameContainsConnection = new MethodNameContainsFeature("Connection"); features.add(nameContainsConnection); IFeature nameContainsUrl = new MethodNameContainsFeature("url"); features.add(nameContainsUrl); IFeature nameContainsUri = new MethodNameContainsFeature("uri"); features.add(nameContainsUri); IFeature nameContainsCell = new MethodNameContainsFeature("cell"); features.add(nameContainsCell); IFeature mnameContainsLocation = new MethodNameContainsFeature("Location"); features.add(mnameContainsLocation); IFeature mnameContainsSyncable = new MethodNameContainsFeature("syncable"); features.add(mnameContainsSyncable); IFeature mnameContainsFile = new MethodNameContainsFeature("file"); features.add(mnameContainsFile); IFeature mnameContainsSim = new MethodNameContainsFeature("sim"); features.add(mnameContainsSim); IFeature mnameContainsId = new MethodNameContainsFeature("id"); features.add(mnameContainsId); IFeature mnameContainsSerial = new MethodNameContainsFeature("serial"); features.add(mnameContainsSerial); IFeature mnameContainsNumber = new MethodNameContainsFeature("number"); features.add(mnameContainsNumber); IFeature mnameContainsDump = new MethodNameContainsFeature("dump"); features.add(mnameContainsDump); IFeature mnameContainsSystem = new MethodNameContainsFeature("system"); features.add(mnameContainsSystem); IFeature mnameContainsNeighbor = new MethodNameContainsFeature("Neighbor"); features.add(mnameContainsNeighbor); IFeature mnameContainsFeature = new MethodNameContainsFeature("feature"); features.add(mnameContainsFeature); IFeature mnameContainsUsing = new MethodNameContainsFeature("using"); features.add(mnameContainsUsing); IFeature mnameContainsGSM = new MethodNameContainsFeature("GSM"); features.add(mnameContainsGSM); IFeature mnameContainsNetwork = new MethodNameContainsFeature("Network"); features.add(mnameContainsNetwork); IFeature mnameContainsIcc = new MethodNameContainsFeature("Icc"); features.add(mnameContainsIcc); IFeature mnameContainsBluetooth = new MethodNameContainsFeature("bluetooth"); features.add(mnameContainsBluetooth); IFeature mnameContainsUser = new MethodNameContainsFeature("user"); features.add(mnameContainsUser); IFeature mnameContainsDial = new MethodNameContainsFeature("dial"); features.add(mnameContainsDial); IFeature mnameContainsPolicy = new MethodNameContainsFeature("Policy"); features.add(mnameContainsPolicy); IFeature mnameContainsAccount = new MethodNameContainsFeature("Account"); features.add(mnameContainsAccount); IFeature mnameContainsWidth = new MethodNameContainsFeature("width"); //no-category features.add(mnameContainsWidth); IFeature mnameContainsHeight = new MethodNameContainsFeature("heigth"); //no-category features.add(mnameContainsHeight); features.add(mnameContainsWidth); IFeature mnameContainsHost = new MethodNameContainsFeature("host"); //network-information features.add(mnameContainsHost); IFeature mnameContainsString = new MethodNameContainsFeature("string"); //network-information features.add(mnameContainsString); IFeature mnameContainsImei = new MethodNameContainsFeature("imei"); //unique-identifier features.add(mnameContainsImei); IFeature mnameContainsLog = new MethodNameContainsFeature("log"); features.add(mnameContainsLog); IFeature mnameContainsWrite = new MethodNameContainsFeature("write"); features.add(mnameContainsWrite); IFeature mnameContainsBattery = new MethodNameContainsFeature("battery"); features.add(mnameContainsBattery); IFeature mnameContainsOpen = new MethodNameContainsFeature("open"); features.add(mnameContainsOpen); IFeature mnameContainsImage = new MethodNameContainsFeature("image"); features.add(mnameContainsImage); IFeature mnameContainsBitmap = new MethodNameContainsFeature("bitmap"); features.add(mnameContainsBitmap); IFeature mnameContainsTimeZone = new MethodNameContainsFeature("TimeZone"); features.add(mnameContainsTimeZone); IFeature mnameContainsEnabled = new MethodNameContainsFeature("Enabled"); features.add(mnameContainsEnabled); IFeature mnameContainsDisabled = new MethodNameContainsFeature("Disabled"); features.add(mnameContainsDisabled); IFeature nameContainsService = new MethodClassContainsNameFeature("Service"); features.add(nameContainsService); IFeature nameContainsLocation = new MethodClassContainsNameFeature("Location"); features.add(nameContainsLocation); IFeature nameContainsNfc = new MethodClassContainsNameFeature("Nfc"); features.add(nameContainsNfc); IFeature nameContainsTelephony = new MethodClassContainsNameFeature("Telephony"); features.add(nameContainsTelephony); IFeature nameContainsDcma = new MethodClassContainsNameFeature("dcma"); features.add(nameContainsDcma); IFeature nameContainsPhone = new MethodClassContainsNameFeature("Phone"); features.add(nameContainsPhone); IFeature nameContainsPhoneBase = new MethodClassContainsNameFeature("PhoneBase"); features.add(nameContainsPhoneBase); IFeature nameContainsGSM = new MethodClassContainsNameFeature("GSM"); features.add(nameContainsGSM); IFeature cnameContainsConnection = new MethodClassContainsNameFeature("Connection"); features.add(cnameContainsConnection); IFeature nameContainsData = new MethodClassContainsNameFeature("Data"); features.add(nameContainsData); IFeature cnameContainsTethering = new MethodClassContainsNameFeature("Tethering"); features.add(cnameContainsTethering); IFeature cnameContainsConnectivity = new MethodClassContainsNameFeature("Connectivity"); features.add(cnameContainsConnectivity); IFeature nameContainsSip = new MethodClassContainsNameFeature("Sip"); features.add(nameContainsSip); IFeature nameContainsSystem = new MethodClassContainsNameFeature("System"); features.add(nameContainsSystem); IFeature nameContainsSettings = new MethodClassContainsNameFeature("Settings"); features.add(nameContainsSettings); IFeature nameContainsMail = new MethodClassContainsNameFeature("Mail"); features.add(nameContainsMail); IFeature nameContainsMMS = new MethodClassContainsNameFeature("MMS"); features.add(nameContainsMMS); IFeature nameContainsSMS = new MethodClassContainsNameFeature("SMS"); features.add(nameContainsSMS); IFeature nameContainsCalendar = new MethodClassContainsNameFeature("Calendar"); features.add(nameContainsCalendar); IFeature nameContainsAccount = new MethodClassContainsNameFeature("Account"); features.add(nameContainsAccount); IFeature nameContainsManager = new MethodClassContainsNameFeature("Manager"); features.add(nameContainsManager); IFeature nameContainsAudio = new MethodClassContainsNameFeature("Audio"); features.add(nameContainsAudio); IFeature nameContainsVideo = new MethodClassContainsNameFeature("Video"); features.add(nameContainsVideo); IFeature nameContainsMedia = new MethodClassContainsNameFeature("Media"); features.add(nameContainsMedia); IFeature nameContainsEncoder = new MethodClassContainsNameFeature("Encoder"); features.add(nameContainsEncoder); IFeature nameContainsDevice = new MethodClassContainsNameFeature("Device"); features.add(nameContainsDevice); IFeature nameContainsBluetooth = new MethodClassContainsNameFeature("Bluetooth"); features.add(nameContainsBluetooth); IFeature nameContainsWifi = new MethodClassContainsNameFeature("Wifi"); features.add(nameContainsWifi); IFeature cnameContainsSync = new MethodClassContainsNameFeature("Sync"); features.add(cnameContainsSync); IFeature cnameContainsContact = new MethodClassContainsNameFeature("Contact"); features.add(cnameContainsContact); IFeature cnameContainsBrowser = new MethodClassContainsNameFeature("Browser"); features.add(cnameContainsBrowser); IFeature cnameContainsBookmarks = new MethodClassContainsNameFeature("Bookmarks"); features.add(cnameContainsBookmarks); IFeature cnameContainsProfile = new MethodClassContainsNameFeature("Profile"); features.add(cnameContainsProfile); IFeature cnameContainsVcard = new MethodClassContainsNameFeature("VCard"); features.add(cnameContainsVcard); IFeature cnameContainsGallery = new MethodClassContainsNameFeature("Gallery"); features.add(cnameContainsGallery); IFeature cnameContainsLayout = new MethodClassContainsNameFeature("layout"); //no-category features.add(cnameContainsLayout); IFeature packageNameSignal = new MethodClassContainsNameFeature("Signal"); //network-information features.add(packageNameSignal); IFeature packageNameCdma = new MethodClassContainsNameFeature("cdma"); //network-information features.add(packageNameCdma); IFeature packageNamePaint = new MethodClassContainsNameFeature("paint"); //image features.add(packageNamePaint); IFeature packageNameSSL = new MethodClassContainsNameFeature("ssl"); //network-information features.add(packageNameSSL); IFeature packageNameScroll = new MethodClassContainsNameFeature("scroll"); //no-category features.add(packageNameScroll); //IFeature packageNameVideo = new MethodClassContainsNameFeature("video"); //video (duplicate) //features.add(packageNameVideo); IFeature packageNameBattery = new MethodClassContainsNameFeature("battery"); //system-settings features.add(packageNameBattery); IFeature packageNameNetwork = new MethodClassContainsNameFeature("network"); //system-settings features.add(packageNameNetwork); /* IFeature cnameContainsInternal = new MethodClassContainsNameFeature("internal"); features.add(cnameContainsInternal); */ IFeature cnameContainsContactsContract = new MethodClassContainsNameFeature("ContactsContract"); features.add(cnameContainsContactsContract); IFeature cnameContainsEmail = new MethodClassContainsNameFeature("Email"); features.add(cnameContainsEmail); IFeature cnameContainsThrottle = new MethodClassContainsNameFeature("Throttle"); features.add(cnameContainsThrottle); IFeature cnameContainsTab = new MethodClassContainsNameFeature("Tab"); features.add(cnameContainsTab); IFeature cnameContainsPassword = new MethodClassContainsNameFeature("Password"); features.add(cnameContainsPassword); IFeature cnameContainsPhoneBook = new MethodClassContainsNameFeature("PhoneBook"); features.add(cnameContainsPhoneBook); IFeature cNameContainsFactory = new MethodClassEndsWithNameFeature("Factory"); features.add(cNameContainsFactory); IFeature packageNameTelephony = new MethodClassContainsNameFeature("android.telephony."); features.add(packageNameTelephony); IFeature packageNameIntTelephony = new MethodClassContainsNameFeature("android.internal.telephony."); features.add(packageNameIntTelephony); IFeature packageNameLocation = new MethodClassContainsNameFeature("android.location"); features.add(packageNameLocation); IFeature packageNameLocationManager = new MethodClassContainsNameFeature("android.location.LocationManager"); features.add(packageNameLocationManager); IFeature packageNameAccounts = new MethodClassContainsNameFeature("android.accounts"); features.add(packageNameAccounts); IFeature packageNameNet = new MethodClassContainsNameFeature("android.net"); features.add(packageNameNet); IFeature packageNameOs = new MethodClassContainsNameFeature("android.os"); features.add(packageNameOs); IFeature nameContainsAndroidBluetooth = new MethodClassContainsNameFeature("android.bluetooth"); features.add(nameContainsAndroidBluetooth); IFeature nameContainsAndroidNFC = new MethodClassContainsNameFeature("android.nfc."); features.add(nameContainsAndroidNFC); IFeature packageNameExchange = new MethodClassContainsNameFeature("com.android.exchange."); features.add(packageNameExchange); IFeature packageNameJavaString = new MethodClassContainsNameFeature("java.lang.String"); features.add(packageNameJavaString); IFeature packageNameApacheHttp = new MethodClassContainsNameFeature("org.apache.http"); features.add(packageNameApacheHttp); IFeature packageNameLauncher = new MethodClassContainsNameFeature("com.android.launcher2"); features.add(packageNameLauncher); IFeature packageNameDatabase = new MethodClassContainsNameFeature("android.database"); features.add(packageNameDatabase); IFeature packageNameCrypto = new MethodClassContainsNameFeature("javax.crypto"); features.add(packageNameCrypto); IFeature packageNameXML = new MethodClassContainsNameFeature("org.apache.harmony.xml"); features.add(packageNameXML); IFeature packageNameNIO = new MethodClassContainsNameFeature("java.nio"); features.add(packageNameNIO); IFeature packageNameLog = new MethodClassContainsNameFeature("android.util.Log"); features.add(packageNameLog); IFeature packageNameURL = new MethodClassContainsNameFeature("java.net.URL"); features.add(packageNameURL); IFeature packageNameSip = new MethodClassContainsNameFeature("com.android.internal.telephony.sip"); features.add(packageNameSip); IFeature packageNameServerLocation = new MethodClassContainsNameFeature("com.android.server.location"); features.add(packageNameServerLocation); IFeature packageNameServerNet = new MethodClassContainsNameFeature("com.android.server.net"); features.add(packageNameServerNet); IFeature packageNameServerConnectivity = new MethodClassContainsNameFeature("com.android.server.connectivity"); features.add(packageNameServerConnectivity); IFeature packageNameServerSip = new MethodClassContainsNameFeature("com.android.server.sip"); features.add(packageNameServerSip); IFeature packageNameServerUSB = new MethodClassContainsNameFeature("com.android.server.usb"); features.add(packageNameServerUSB); IFeature packageNameServerDisplay = new MethodClassContainsNameFeature("com.android.server.display"); features.add(packageNameServerDisplay); IFeature packageNameServerPower = new MethodClassContainsNameFeature("com.android.server.power"); features.add(packageNameServerPower); IFeature packageNameInternalOs = new MethodClassContainsNameFeature("com.android.internal.os"); features.add(packageNameInternalOs); IFeature packageNameAndroidContacts = new MethodClassContainsNameFeature("com.android.contacts"); features.add(packageNameAndroidContacts); IFeature packageNameTelephonyManager = new MethodClassContainsNameFeature("android.telephony.TelephonyManager"); features.add(packageNameTelephonyManager); IFeature packageNameNfc = new MethodClassContainsNameFeature("com.android.nfc"); features.add(packageNameNfc); IFeature packageNameBrowser = new MethodClassContainsNameFeature("com.android.browser"); features.add(packageNameBrowser); IFeature packageNameMMS = new MethodClassContainsNameFeature("com.android.mms"); features.add(packageNameMMS); IFeature packageNameEmail = new MethodClassContainsNameFeature("com.android.email"); features.add(packageNameEmail); IFeature packageNameWifiService = new MethodClassContainsNameFeature("com.android.server.WifiService"); features.add(packageNameWifiService); IFeature packageNameWifi = new MethodClassContainsNameFeature("android.net.wifi"); features.add(packageNameWifi); IFeature packageNameHardwareInput = new MethodClassContainsNameFeature("android.hardware.input"); features.add(packageNameHardwareInput); IFeature packageNameInternalWidget = new MethodClassContainsNameFeature("com.android.internal.widget"); features.add(packageNameInternalWidget); IFeature packageNameGraphics = new MethodClassContainsNameFeature("android.graphics"); features.add(packageNameGraphics); IFeature packageNameParcel = new MethodClassContainsNameFeature("android.os.Parcel"); features.add(packageNameParcel); IFeature packageNameCalendar = new MethodClassContainsNameFeature("com.android.calendar"); features.add(packageNameCalendar); IFeature packageNameServerAm = new MethodClassContainsNameFeature("com.android.server.am"); features.add(packageNameServerAm); IFeature packageNameSyncManager = new MethodClassContainsNameFeature("android.content.SyncManager"); features.add(packageNameSyncManager); IFeature paramNdefMessage = new ParameterContainsTypeOrNameFeature("android.nfc.NdefMessage"); features.add(paramNdefMessage); IFeature paramOSMessage = new ParameterContainsTypeOrNameFeature("android.os.Message"); features.add(paramOSMessage); IFeature paramConfiguration = new ParameterContainsTypeOrNameFeature("android.content.res.Configuration"); features.add(paramConfiguration); IFeature paramAccount = new ParameterContainsTypeOrNameFeature("android.accounts.Account"); features.add(paramAccount); IFeature paramContentValues = new ParameterContainsTypeOrNameFeature("android.content.ContentValues"); features.add(paramContentValues); IFeature paramBluetooth = new ParameterContainsTypeOrNameFeature("android.bluetooth.BluetoothDevice"); features.add(paramBluetooth); IFeature paramSip = new ParameterContainsTypeOrNameFeature(".Sip"); features.add(paramSip); IFeature parameterInDial = new ParameterInCallFeature(MAPS, ANDROID, "dial", CheckType.CheckSink); features.add(parameterInDial); IFeature parameterInSend = new ParameterInCallFeature(MAPS, ANDROID, "send", CheckType.CheckSink); features.add(parameterInSend); IFeature parameterInBroadcast = new ParameterInCallFeature(MAPS, ANDROID, "broadcast", CheckType.CheckSink); features.add(parameterInBroadcast); IFeature returnTypeCellLocation = new ReturnTypeFeature(MAPS, ANDROID, "android.telephony.CellLocation"); features.add(returnTypeCellLocation); IFeature returnTypeCountry = new ReturnTypeFeature(MAPS, ANDROID, "android.location.Country"); features.add(returnTypeCountry); IFeature returnTypeString = new ReturnTypeFeature(MAPS, ANDROID, "java.lang.String"); features.add(returnTypeString); IFeature returnTypeBitmap = new ReturnTypeFeature(MAPS, ANDROID, "android.graphics.Bitmap"); features.add(returnTypeBitmap); IFeature returnTypeAccountArray = new ReturnTypeFeature(MAPS, ANDROID, "android.accounts.Account[]"); features.add(returnTypeAccountArray); IFeature returnTypeIterator = new ReturnTypeFeature(MAPS, ANDROID, "java.util.Iterator"); features.add(returnTypeIterator); IFeature returnTypeDrawable = new ReturnTypeFeature(MAPS, ANDROID, "android.graphics.drawable.Drawable"); features.add(returnTypeDrawable); IFeature returnTypeNFCTag = new ReturnTypeFeature(MAPS, ANDROID, "android.nfc.Tag"); features.add(returnTypeNFCTag); IFeature returnTypeSIPHeader = new ReturnTypeFeature(MAPS, ANDROID, "gov.nist.javax.sip.header.SIPHeader"); features.add(returnTypeSIPHeader); IFeature returnTypeSocket = new ReturnTypeFeature(MAPS, ANDROID, "java.net.Socket"); features.add(returnTypeSocket); IFeature returnTypeURL = new ReturnTypeFeature(MAPS, ANDROID, "java.net.URLConnection"); features.add(returnTypeURL); IFeature parameterTypeHasFileDescriptor = new ParameterContainsTypeOrNameFeature("java.io.FileDescriptor"); features.add(parameterTypeHasFileDescriptor); IFeature callsMessageMethod = new MethodCallsMethodFeature(MAPS, ANDROID, "", "Icc", true); features.add(callsMessageMethod); IFeature callsSystemProperties = new MethodCallsMethodFeature(MAPS, ANDROID, "android.os.SystemProperties", "get"); features.add(callsSystemProperties); IFeature callsSystemSettings = new MethodCallsMethodFeature(MAPS, ANDROID, "android.provider.Settings", "put"); features.add(callsSystemSettings); IFeature callsCellLocation = new MethodCallsMethodFeature(MAPS, ANDROID, "", "getCellLocation"); features.add(callsCellLocation); IFeature methodBodyContainsAccounts = new MethodBodyContainsObjectFeature(MAPS, ANDROID, "android.accounts.Account"); features.add(methodBodyContainsAccounts); IFeature methodBodyContainsAccountManger = new MethodBodyContainsObjectFeature(MAPS, ANDROID, "android.accounts.AccountManager"); features.add(methodBodyContainsAccountManger); IFeature methodBodyContainsPhoneSubInfo = new MethodBodyContainsObjectFeature(MAPS, ANDROID, "com.android.internal.telephony.IPhoneSubInfo"); features.add(methodBodyContainsPhoneSubInfo); IFeature methodBodyContainsPhone = new MethodBodyContainsObjectFeature(MAPS, ANDROID, "com.android.internal.telephony.Phone"); features.add(methodBodyContainsPhone); IFeature methodBodyContainsSMSManager = new MethodBodyContainsObjectFeature(MAPS, ANDROID, "android.telephony.SmsManager"); features.add(methodBodyContainsSMSManager); IFeature methodBodyContainsILocationManager = new MethodBodyContainsObjectFeature(MAPS, ANDROID, "android.location.ILocationManager"); features.add(methodBodyContainsILocationManager); IFeature methodBodyContainsLocationRequest = new MethodBodyContainsObjectFeature(MAPS, ANDROID, "android.location.LocationRequest"); features.add(methodBodyContainsLocationRequest); IFeature methodBodyContainsLocationListener = new MethodBodyContainsObjectFeature(MAPS, ANDROID, "android.location.LocationListener"); features.add(methodBodyContainsLocationListener); IFeature methodBodyContainsCellLocation = new MethodBodyContainsObjectFeature(MAPS, ANDROID, "android.telephony.CellLocation"); features.add(methodBodyContainsCellLocation); IFeature methodBodyContainsBitmap = new MethodBodyContainsObjectFeature(MAPS, ANDROID, "android.graphics.Bitmap"); features.add(methodBodyContainsBitmap); IFeature methodBodyContainsMediaSet = new MethodBodyContainsObjectFeature(MAPS, ANDROID, "com.android.gallery3d.data.MediaSet"); features.add(methodBodyContainsMediaSet); IFeature methodBodyContainsISMS = new MethodBodyContainsObjectFeature(MAPS, ANDROID, "com.android.internal.telephony.ISms"); features.add(methodBodyContainsISMS); IFeature methodBodyContainsSmsRawData = new MethodBodyContainsObjectFeature(MAPS, ANDROID, "com.android.internal.telephony.SmsRawData"); features.add(methodBodyContainsSmsRawData); IFeature methodBodyContainsView = new MethodBodyContainsObjectFeature(MAPS, ANDROID, "android.view.View"); features.add(methodBodyContainsView); IFeature methodBodyContainsViewGroup = new MethodBodyContainsObjectFeature(MAPS, ANDROID, "android.view.ViewGroup"); features.add(methodBodyContainsViewGroup); IFeature methodBodyContainsSnapshotProvider = new MethodBodyContainsObjectFeature(MAPS, ANDROID, "com.android.browser.provider.SnapshotProvider"); features.add(methodBodyContainsSnapshotProvider); IFeature methodBodyContainsFileWriter = new MethodBodyContainsObjectFeature(MAPS, ANDROID, "java.io.FileWriter"); features.add(methodBodyContainsFileWriter); IFeature methodBodyContainsFileDescriptor = new MethodBodyContainsObjectFeature(MAPS, ANDROID, "java.io.FileDescriptor"); features.add(methodBodyContainsFileDescriptor); IFeature methodBodyContainsFile = new MethodBodyContainsObjectFeature(MAPS, ANDROID, "java.io.File"); features.add(methodBodyContainsFile); IFeature methodBodyContainsLog = new MethodBodyContainsObjectFeature(MAPS, ANDROID, "android.util.Log"); features.add(methodBodyContainsLog); IFeature methodBodyContainsBattery = new MethodBodyContainsObjectFeature(MAPS, ANDROID, "com.android.internal.os.BatteryStatsImpl"); features.add(methodBodyContainsBattery); return features; } }
88,908
45.476215
179
java
SuSi
SuSi-master/SourceCode/src/de/ecspride/sourcesinkfinder/analysis/InitializeSoot.java
package de.ecspride.sourcesinkfinder.analysis; import soot.Scene; import soot.options.Options; public class InitializeSoot { public InitializeSoot(){ } private String[] buildArgs(String path){ String[] result = { "-w", "-no-bodies-for-excluded", "-include-all", "-p", "cg.spark", "on", "-cp", path, "-p", "jb", "use-original-names:true", "-f", "n", //do not merge variables (causes problems with PointsToSets) "-p", "jb.ulp", "off" }; return result; } public void initialize(String path){ String[] args = buildArgs(path); Options.v().set_allow_phantom_refs(true); Options.v().set_prepend_classpath(true); Options.v().set_output_format(Options.output_format_none); Options.v().parse(args); Options.v().set_whole_program(true); Scene.v().addBasicClass(Object.class.getName()); Scene.v().loadNecessaryClasses(); } }
911
17.24
63
java
SuSi
SuSi-master/SourceCode/src/de/ecspride/sourcesinkfinder/features/AbstractSootFeature.java
package de.ecspride.sourcesinkfinder.features; import java.io.File; import java.util.HashMap; import java.util.List; import java.util.Map; import soot.G; import soot.Hierarchy; import soot.RefType; import soot.Scene; import soot.SootClass; import soot.SootMethod; import soot.jimple.infoflow.android.data.AndroidMethod; import soot.options.Options; import de.ecspride.sourcesinkfinder.IFeature; public abstract class AbstractSootFeature implements IFeature { private static boolean SOOT_INITIALIZED = false; private Map<AndroidMethod, Type> resultCache = new HashMap<AndroidMethod, Type>(); private String mapsJAR; private String androidJAR; public AbstractSootFeature(String mapsJAR, String androidJAR) { this.mapsJAR = mapsJAR; this.androidJAR = androidJAR; initializeSoot(); } private void initializeSoot() { if (SOOT_INITIALIZED) return; G.reset(); Options.v().set_allow_phantom_refs(true); Options.v().set_prepend_classpath(false); Options.v().set_soot_classpath(mapsJAR + File.pathSeparator + androidJAR); // Options.v().set_soot_classpath(androidJAR); Options.v().set_whole_program(true); Options.v().set_include_all(true); Scene.v().loadNecessaryClasses(); SOOT_INITIALIZED = true; } protected SootMethod getSootMethod(AndroidMethod method) { return getSootMethod(method, true); } protected SootMethod getSootMethod(AndroidMethod method, boolean lookInHierarchy) { SootClass c = Scene.v().forceResolve(method.getClassName(), SootClass.BODIES); if (c == null || c.isPhantom()) { System.err.println("Class " + method.getClassName() + " not found"); return null; } c.setApplicationClass(); if (c.isInterface()) return null; while (c != null) { // Does the current class declare the method we are looking for? if (method.getReturnType().isEmpty()) { if (c.declaresMethodByName(method.getMethodName())) return c.getMethodByName(method.getMethodName()); } else{ if (c.declaresMethod(method.getSubSignature())) return c.getMethod(method.getSubSignature()); } // Continue our search up the class hierarchy if (lookInHierarchy && c.hasSuperclass()) c = c.getSuperclass(); else c = null; } return null; } protected boolean isOfType(soot.Type type, String typeName) { if(!(type instanceof RefType)) return false; // Check for a direct match RefType refType = (RefType) type; if(refType.getSootClass().getName().equals(typeName)) return true; //interface treatment if(refType.getSootClass().isInterface()) return false; //class treatment Hierarchy h = Scene.v().getActiveHierarchy(); List<SootClass> ancestors = h.getSuperclassesOf(refType.getSootClass()); for(SootClass ancestor : ancestors) { if(ancestor.getName().equals(typeName)) return true; for (SootClass sc : ancestor.getInterfaces()) if (sc.getName().equals(typeName)) return true; } return false; } @Override public Type applies(AndroidMethod method) { if (this.resultCache.containsKey(method)) return this.resultCache.get(method); else { Type tp = this.appliesInternal(method); this.resultCache.put(method, tp); return tp; } } public abstract Type appliesInternal(AndroidMethod method); }
3,283
25.699187
84
java
SuSi
SuSi-master/SourceCode/src/de/ecspride/sourcesinkfinder/features/BaseNameOfClassPackageName.java
package de.ecspride.sourcesinkfinder.features; import soot.jimple.infoflow.android.data.AndroidMethod; import de.ecspride.sourcesinkfinder.IFeature; /** * This feature checks the name of the package * @author Siegfried Rasthofer */ public class BaseNameOfClassPackageName implements IFeature { private final String baseNameOfClassPackageName; public BaseNameOfClassPackageName(String baseNameOfClassPackageName){ this.baseNameOfClassPackageName = baseNameOfClassPackageName; } @Override public Type applies(AndroidMethod method) { String[] classNameParts = method.getClassName().split("\\."); String otherBaseNameOfClassPackageName = classNameParts[classNameParts.length -2]; return (otherBaseNameOfClassPackageName.equals(baseNameOfClassPackageName) ? Type.TRUE : Type.FALSE); } @Override public String toString() { return "<Base name of class package name: " + baseNameOfClassPackageName + ">"; } }
934
30.166667
103
java
SuSi
SuSi-master/SourceCode/src/de/ecspride/sourcesinkfinder/features/IsThreadRunFeature.java
package de.ecspride.sourcesinkfinder.features; import soot.SootMethod; import soot.jimple.infoflow.android.data.AndroidMethod; /** * Feature that checks whether the current method is the run method of a thread * * @author Steven Arzt, Siegfried Rasthofer * */ public class IsThreadRunFeature extends AbstractSootFeature { public IsThreadRunFeature(String mapsJAR, String androidJAR) { super(mapsJAR, androidJAR); } @Override public Type appliesInternal(AndroidMethod method) { if (!method.getMethodName().equals("run")) return Type.FALSE; SootMethod sm = getSootMethod(method); if (sm == null) return Type.NOT_SUPPORTED; try { if (this.isOfType(sm.getDeclaringClass().getType(), "java.lang.Runnable")) return Type.TRUE; else return Type.FALSE; }catch (Exception ex) { System.err.println("Something went wrong:"); ex.printStackTrace(); return Type.NOT_SUPPORTED; } } @Override public String toString() { return "<Method is thread runner>"; } }
1,014
22.068182
79
java
SuSi
SuSi-master/SourceCode/src/de/ecspride/sourcesinkfinder/features/MethodAnonymousClassFeature.java
package de.ecspride.sourcesinkfinder.features; import java.util.regex.Pattern; import soot.jimple.infoflow.android.data.AndroidMethod; import de.ecspride.sourcesinkfinder.IFeature; /** * This feature checks wether the method is part of an anonymous class or not. * * @author Siegfried Rasthofer * */ public class MethodAnonymousClassFeature implements IFeature { private final boolean anonymousClass; public MethodAnonymousClassFeature(boolean anonymousClass){ this.anonymousClass = anonymousClass; } @Override public Type applies(AndroidMethod method) { int index = method.getClassName().lastIndexOf("$"); if(index != -1){ String subclassName = method.getClassName().substring(index+1); return (Pattern.matches("^\\d+$", subclassName)? Type.TRUE : Type.FALSE); } return Type.FALSE; } @Override public String toString() { return "<Method is part of a" + (anonymousClass ? "n anonymous" : " non-anonymous") +" class>"; } }
966
23.794872
97
java
SuSi
SuSi-master/SourceCode/src/de/ecspride/sourcesinkfinder/features/MethodBodyContainsObjectFeature.java
package de.ecspride.sourcesinkfinder.features; import soot.Body; import soot.SootMethod; import soot.jimple.infoflow.android.data.AndroidMethod; /** * Feature that checks if the body of a method contains a specific object. * * @author Siegfried Rasthofer * */ public class MethodBodyContainsObjectFeature extends AbstractSootFeature { private final String objectName; public MethodBodyContainsObjectFeature(String mapsJAR, String androidJAR, String objectName){ super(mapsJAR, androidJAR); this.objectName = objectName.trim().toLowerCase(); } @Override public Type appliesInternal(AndroidMethod method) { try { SootMethod sm = getSootMethod(method); if (sm == null) { System.err.println("Method not declared: " + method); return Type.NOT_SUPPORTED; } if (!sm.isConcrete()) return Type.NOT_SUPPORTED; Body body = null; try{ body = sm.retrieveActiveBody(); }catch(Exception ex){ return Type.NOT_SUPPORTED; } if(body.toString().toLowerCase().contains(objectName)) return Type.TRUE; // for(Local local : sm.getActiveBody().getLocals()) // if(local.getType().toString().trim().toLowerCase().contains(objectName)){ // if(objectName.equals("android.location.LocationListener")) // System.out.println(); // return Type.TRUE; // } return Type.FALSE; }catch (Exception ex) { System.err.println("Something went wrong:"); ex.printStackTrace(); return Type.NOT_SUPPORTED; } } @Override public String toString() { return "Method-Body contains object '" + this.objectName; } }
1,597
24.774194
94
java
SuSi
SuSi-master/SourceCode/src/de/ecspride/sourcesinkfinder/features/MethodCallsMethodFeature.java
package de.ecspride.sourcesinkfinder.features; import java.util.ArrayList; import java.util.List; import soot.Body; import soot.SootMethod; import soot.Unit; import soot.jimple.InvokeExpr; import soot.jimple.Stmt; import soot.jimple.infoflow.android.data.AndroidMethod; /** * Feature which checks whether the current method (indirectly) calls another * one * * @author Steven Arzt, Siegfried Rasthofer * */ public class MethodCallsMethodFeature extends AbstractSootFeature { private final String className; private final String methodName; private final boolean substringMatch; public MethodCallsMethodFeature(String mapsJAR, String androidJAR, String methodName) { this(mapsJAR, androidJAR, "", methodName); } public MethodCallsMethodFeature(String mapsJAR, String androidJAR, String className, String methodName) { this(mapsJAR, androidJAR, className, methodName, false); } public MethodCallsMethodFeature(String mapsJAR, String androidJAR, String className, String methodName, boolean substringMatch) { super(mapsJAR, androidJAR); this.className = className; this.methodName = methodName; this.substringMatch = substringMatch; } @Override public Type appliesInternal(AndroidMethod method) { try { SootMethod sm = getSootMethod(method); if (sm == null) { System.err.println("Method not declared: " + method); return Type.NOT_SUPPORTED; } return checkMethod(sm, new ArrayList<SootMethod>()); }catch (Exception ex) { System.err.println("Something went wrong:"); ex.printStackTrace(); return Type.NOT_SUPPORTED; } } public Type checkMethod(SootMethod method, List<SootMethod> doneList) { if (doneList.contains(method)) return Type.NOT_SUPPORTED; if (!method.isConcrete()) return Type.NOT_SUPPORTED; doneList.add(method); try { Body body = null; try{ body = method.retrieveActiveBody(); }catch(Exception ex){ return Type.NOT_SUPPORTED; } for (Unit u : body.getUnits()) { if (!(u instanceof Stmt)) continue; Stmt stmt = (Stmt) u; if (!stmt.containsInvokeExpr()) continue; InvokeExpr inv = stmt.getInvokeExpr(); if ((substringMatch && inv.getMethod().getName().contains(this.methodName)) || inv.getMethod().getName().startsWith(this.methodName)) { if (this.className.isEmpty() || this.className.equals (inv.getMethod().getDeclaringClass().getName())) return Type.TRUE; } else if (checkMethod(inv.getMethod(), doneList) == Type.TRUE) return Type.TRUE; } return Type.FALSE; } catch (Exception ex) { System.err.println("Oops: " + ex); return Type.NOT_SUPPORTED; } } @Override public String toString() { return "Method starting with '" + this.methodName + "' invoked"; } }
2,801
24.944444
80
java
SuSi
SuSi-master/SourceCode/src/de/ecspride/sourcesinkfinder/features/MethodClassConcreteNameFeature.java
package de.ecspride.sourcesinkfinder.features; import soot.jimple.infoflow.android.data.AndroidMethod; import de.ecspride.sourcesinkfinder.IFeature; public class MethodClassConcreteNameFeature implements IFeature { private final String className; public MethodClassConcreteNameFeature(String className){ this.className = className; } @Override public Type applies(AndroidMethod method) { return (method.getClassName().equals(className)? Type.TRUE : Type.FALSE); } @Override public String toString() { return "<Method is part of class " + className + ">"; } }
583
22.36
75
java
SuSi
SuSi-master/SourceCode/src/de/ecspride/sourcesinkfinder/features/MethodClassContainsNameFeature.java
package de.ecspride.sourcesinkfinder.features; import soot.jimple.infoflow.android.data.AndroidMethod; import de.ecspride.sourcesinkfinder.IFeature; public class MethodClassContainsNameFeature implements IFeature { private final String partOfName; public MethodClassContainsNameFeature(String partOfName){ this.partOfName = partOfName.toLowerCase(); } @Override public Type applies(AndroidMethod method) { return (method.getClassName().toLowerCase().contains(partOfName)? Type.TRUE : Type.FALSE); } @Override public String toString() { return "<Method is part of class that contains the name " + partOfName + ">"; } }
641
25.75
92
java
SuSi
SuSi-master/SourceCode/src/de/ecspride/sourcesinkfinder/features/MethodClassEndsWithNameFeature.java
package de.ecspride.sourcesinkfinder.features; import soot.jimple.infoflow.android.data.AndroidMethod; import de.ecspride.sourcesinkfinder.IFeature; public class MethodClassEndsWithNameFeature implements IFeature { private final String partOfName; public MethodClassEndsWithNameFeature(String partOfName){ this.partOfName = partOfName; } @Override public Type applies(AndroidMethod method) { return (method.getClassName().endsWith(partOfName)? Type.TRUE : Type.FALSE); } @Override public String toString() { return "<Method is part of class that ends with " + partOfName + ">"; } }
606
24.291667
78
java
SuSi
SuSi-master/SourceCode/src/de/ecspride/sourcesinkfinder/features/MethodClassModifierFeature.java
package de.ecspride.sourcesinkfinder.features; import soot.Modifier; import soot.SootClass; import soot.SootMethod; import soot.jimple.infoflow.android.data.AndroidMethod; /** * This feature checks the modifier of the class where the method is part of. * * @author Siegfried Rasthofer * */ public class MethodClassModifierFeature extends AbstractSootFeature { public enum ClassModifier{ABSTRACT, FINAL, PRIVATE, PROTECTED, PUBLIC, STATIC}; private final ClassModifier classModifier; public MethodClassModifierFeature(String mapsJAR, String androidJAR, ClassModifier classModifier){ super(mapsJAR, androidJAR); this.classModifier = classModifier; } @Override public Type appliesInternal(AndroidMethod method) { try { SootMethod sm = getSootMethod(method); if (sm == null) return Type.NOT_SUPPORTED; SootClass sClass = sm.getDeclaringClass(); switch(classModifier){ case ABSTRACT : return (sClass.isAbstract()? Type.TRUE : Type.FALSE); case FINAL : return (Modifier.isFinal(sClass.getModifiers())? Type.TRUE : Type.FALSE); case PRIVATE : return (sClass.isPrivate()? Type.TRUE : Type.FALSE); case PROTECTED : return (sClass.isProtected()? Type.TRUE : Type.FALSE); case PUBLIC : return (sClass.isPublic()? Type.TRUE : Type.FALSE); case STATIC : return (Modifier.isStatic(sClass.getModifiers())? Type.TRUE : Type.FALSE); } throw new Exception("Modifier not declared!"); }catch (Exception ex) { System.err.println("Something went wrong: " + ex.getMessage()); return Type.NOT_SUPPORTED; } } @Override public String toString() { return "<Method is part of a " + classModifier.name() + " class>"; } }
1,690
30.90566
92
java
SuSi
SuSi-master/SourceCode/src/de/ecspride/sourcesinkfinder/features/MethodHasParametersFeature.java
package de.ecspride.sourcesinkfinder.features; import soot.jimple.infoflow.android.data.AndroidMethod; import de.ecspride.sourcesinkfinder.IFeature; public class MethodHasParametersFeature implements IFeature { public MethodHasParametersFeature(float weight) { } @Override public Type applies(AndroidMethod method) { return (method.getParameters().size() > 0 ? Type.TRUE : Type.FALSE); } @Override public String toString() { return "<Method has parameters>"; } }
483
21
70
java
SuSi
SuSi-master/SourceCode/src/de/ecspride/sourcesinkfinder/features/MethodInnerClassFeature.java
package de.ecspride.sourcesinkfinder.features; import soot.SootMethod; import soot.jimple.infoflow.android.data.AndroidMethod; public class MethodInnerClassFeature extends AbstractSootFeature { private final boolean innerClass; public MethodInnerClassFeature(String mapsJAR, String androidJAR, boolean innerClass) { super(mapsJAR, androidJAR); this.innerClass = innerClass; } @Override public Type appliesInternal(AndroidMethod method) { SootMethod sm = getSootMethod(method); if (sm == null) return Type.NOT_SUPPORTED; try { if(sm.getDeclaringClass().hasOuterClass() && innerClass) return Type.TRUE; else if(innerClass && !sm.getDeclaringClass().hasOuterClass()) return Type.FALSE; else if(!innerClass && sm.getDeclaringClass().hasOuterClass()) return Type.FALSE; else return Type.TRUE; }catch(Exception ex){ System.err.println("Something went wrong: " + ex.getMessage()); return Type.NOT_SUPPORTED; } } public String toString() { return "<Method is " + (innerClass ? "" : "not ") + "part of inner class>"; } }
1,085
25.487805
88
java
SuSi
SuSi-master/SourceCode/src/de/ecspride/sourcesinkfinder/features/MethodInvocationOnParameterFeature.java
package de.ecspride.sourcesinkfinder.features; import java.util.HashSet; import java.util.Set; import soot.SootMethod; import soot.Unit; import soot.Value; import soot.jimple.IdentityStmt; import soot.jimple.InstanceInvokeExpr; import soot.jimple.ParameterRef; import soot.jimple.Stmt; import soot.jimple.infoflow.android.data.AndroidMethod; /** * Feature that checks whether a method starting with a specific string is * invoked on one of the parameters * * @author Steven Arzt, Siegfried Rasthofer * */ public class MethodInvocationOnParameterFeature extends AbstractSootFeature { private final String methodName; public MethodInvocationOnParameterFeature(String mapsJAR, String androidJAR, String methodName) { super(mapsJAR, androidJAR); this.methodName = methodName; } @Override public Type appliesInternal(AndroidMethod method) { SootMethod sm = getSootMethod(method); if (sm == null) { System.err.println("Method not declared: " + method); return Type.NOT_SUPPORTED; } // We are only interested in setters if (!sm.isConcrete()) return Type.NOT_SUPPORTED; try { Set<Value> paramVals = new HashSet<Value>(); for (Unit u : sm.retrieveActiveBody().getUnits()) { // Collect the parameters if (u instanceof IdentityStmt) { IdentityStmt id = (IdentityStmt) u; if (id.getRightOp() instanceof ParameterRef) paramVals.add(id.getLeftOp()); } // Check for invocations if (u instanceof Stmt) { Stmt stmt = (Stmt) u; if (stmt.containsInvokeExpr()) if (stmt.getInvokeExpr() instanceof InstanceInvokeExpr) { InstanceInvokeExpr iinv = (InstanceInvokeExpr) stmt.getInvokeExpr(); if (paramVals.contains(iinv.getBase())) if (iinv.getMethod().getName().startsWith(methodName)) return Type.TRUE; } } } return Type.FALSE; }catch (Exception ex) { System.err.println("Something went wrong:"); ex.printStackTrace(); return Type.NOT_SUPPORTED; } } @Override public String toString() { return "<Method " + methodName + "invoked on parameter object>"; } }
2,117
25.475
98
java