index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/aries/samples/ariestrader/modules/ariestrader-util/src/main/java/org/apache/aries/samples/ariestrader
Create_ds/aries/samples/ariestrader/modules/ariestrader-util/src/main/java/org/apache/aries/samples/ariestrader/util/Log.java
/** * 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. */ package org.apache.aries.samples.ariestrader.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collection; import java.util.Iterator; public class Log { private final static Logger log = LoggerFactory.getLogger(Log.class); //A general purpose, high performance logging, tracing, statistic service public static void log(String message) { log.debug("AriesTrader Log:" + new java.util.Date() + "------\n\t "); log.debug(message); } public static void log(String msg1, String msg2) { log(msg1+msg2); } public static void log(String msg1, String msg2, String msg3) { log(msg1+msg2+msg3); } public static void error(String message) { message = "Error: " + message; log.error(message); } public static void error(String message, Throwable e) { error(message+"\n\t"+e.toString()); e.printStackTrace(System.out); } public static void error(String msg1, String msg2, Throwable e) { error(msg1+"\n"+msg2+"\n\t", e); } public static void error(String msg1, String msg2, String msg3, Throwable e) { error(msg1+"\n"+msg2+"\n"+msg3+"\n\t", e); } public static void error(Throwable e, String message) { error(message+"\n\t",e); e.printStackTrace(System.out); } public static void error(Throwable e, String msg1, String msg2) { error(msg1+"\n"+msg2+"\n\t",e); } public static void error(Throwable e, String msg1, String msg2, String msg3) { error(msg1+"\n"+msg2+"\n"+msg3+"\n\t", e); } public static void trace(String message) { log.trace(message + " threadID="+ Thread.currentThread()); } public static void trace(String message, Object parm1) { trace(message+"("+parm1+")"); } public static void trace(String message, Object parm1, Object parm2) { trace(message+"("+parm1+", "+parm2+")"); } public static void trace(String message, Object parm1, Object parm2, Object parm3) { trace(message+"("+parm1+", "+parm2+", "+parm3+")"); } public static void trace(String message, Object parm1, Object parm2, Object parm3, Object parm4) { trace(message+"("+parm1+", "+parm2+", "+parm3+")"+", "+parm4); } public static void trace(String message, Object parm1, Object parm2, Object parm3, Object parm4, Object parm5) { trace(message+"("+parm1+", "+parm2+", "+parm3+")"+", "+parm4+", "+parm5); } public static void trace(String message, Object parm1, Object parm2, Object parm3, Object parm4, Object parm5, Object parm6) { trace(message+"("+parm1+", "+parm2+", "+parm3+")"+", "+parm4+", "+parm5+", "+parm6); } public static void trace(String message, Object parm1, Object parm2, Object parm3, Object parm4, Object parm5, Object parm6, Object parm7) { trace(message+"("+parm1+", "+parm2+", "+parm3+")"+", "+parm4+", "+parm5+", "+parm6+", "+parm7); } public static void traceEnter(String message) { log.trace("Method enter --" + message); } public static void traceExit(String message) { log.trace("Method exit --" + message); } public static void stat(String message) { log(message); } public static void debug(String message) { log.debug(message); } public static void print(String message) { log(message); } public static void printObject(Object o) { log("\t"+o.toString()); } public static void printCollection(Collection c) { log("\t---Log.printCollection -- collection size=" + c.size()); Iterator it = c.iterator(); while ( it.hasNext() ) { log("\t\t"+it.next().toString()); } log("\t---Log.printCollection -- complete"); } public static void printCollection(String message, Collection c) { log(message); printCollection(c); } public static boolean doActionTrace() { return getTrace() || getActionTrace(); } public static boolean doTrace() { return getTrace(); } public static boolean doDebug() { return true; } public static boolean doStat() { return true; } /** * Gets the trace * @return Returns a boolean */ public static boolean getTrace() { return TradeConfig.getTrace(); } /** * Gets the trace value for Trade actions only * @return Returns a boolean */ public static boolean getActionTrace() { return TradeConfig.getActionTrace(); } /** * Sets the trace * @param traceValue The trace to set */ public static void setTrace(boolean traceValue) { TradeConfig.setTrace(traceValue); } /** * Sets the trace value for Trade actions only * @param traceValue The trace to set */ public static void setActionTrace(boolean traceValue) { TradeConfig.setActionTrace(traceValue); } }
8,200
0
Create_ds/aries/samples/ariestrader/modules/ariestrader-util/src/main/java/org/apache/aries/samples/ariestrader
Create_ds/aries/samples/ariestrader/modules/ariestrader-util/src/main/java/org/apache/aries/samples/ariestrader/util/TradeConfig.java
/** * 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. */ package org.apache.aries.samples.ariestrader.util; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Random; /** * TradeConfig is a JavaBean holding all configuration and runtime parameters for the Trade application * TradeConfig sets runtime parameters such as the RunTimeMode (EJB3, DIRECT, SESSION3, JDBC, JPA) * */ public class TradeConfig { /* Trade Runtime Configuration Parameters */ /* Trade Runtime Mode parameters */ public static String[] runTimeModeNames = { "JDBC", "JPA App Managed", "JPA Container Managed"}; public static enum ModeType{JDBC,JPA_AM,JPA_CM} public static ModeType runTimeMode = ModeType.JDBC; /* Trade JPA Layer parameters */ public static String[] jpaLayerNames = {"OpenJPA", "Hibernate"}; public static final int OPENJPA = 0; public static final int HIBERNATE = 1; public static int jpaLayer = OPENJPA; public static String[] orderProcessingModeNames = { "Synchronous", "Asynchronous_2-Phase" }; public static final int SYNCH = 0; public static final int ASYNCH_2PHASE = 1; public static int orderProcessingMode = SYNCH; public static String[] accessModeNames = { "Standard", "WebServices" }; public static final int STANDARD = 0; public static final int WEBSERVICES = 1; private static int accessMode = STANDARD; /* Trade Scenario Workload parameters */ public static String[] workloadMixNames = { "Standard", "High-Volume", }; public final static int SCENARIOMIX_STANDARD = 0; public final static int SCENARIOMIX_HIGHVOLUME = 1; public static int workloadMix = SCENARIOMIX_STANDARD; /* Trade Web Interface parameters */ public static String[] webInterfaceNames = { "JSP", "JSP-Images" }; public static final int JSP = 0; public static final int JSP_Images = 1; public static int webInterface = JSP; /* Trade Caching Type parameters */ public static String[] cachingTypeNames = { "DistributedMap", "Command Caching", "No Caching" }; public static final int DISTRIBUTEDMAP = 0; public static final int COMMAND_CACHING = 1; public static final int NO_CACHING = 2; public static int cachingType = NO_CACHING; /* Trade Database Scaling parameters*/ private static int MAX_USERS = 200; private static int MAX_QUOTES = 400; /* Trade Database specific parameters */ public static String JDBC_UID = null; public static String JDBC_PWD = null; /* OSGi specific parameters */ public static String OSGI_SERVICE_PREFIX = "osgi:service/"; public static String OSGI_DS_NAME_FILTER = "(osgi.jndi.service.name=jdbc/NoTxTradeDataSource)"; /*Trade SOAP specific parameters */ private static String SoapURL = "http://localhost:8080/ariestrader/services/TradeWSServices"; /*Trade XA Datasource specific parameters */ public static boolean JDBCDriverNeedsGlobalTransaction = false; /* Trade Config Miscellaneous items */ public static int KEYBLOCKSIZE = 1000; public static int QUOTES_PER_PAGE = 10; public static boolean RND_USER = true; private static int MAX_HOLDINGS = 10; private static int count = 0; private static Object userID_count_semaphore = new Object(); private static int userID_count = 0; private static String hostName = null; private static Random r0 = new Random(System.currentTimeMillis()); private static Random randomNumberGenerator = r0; public static final String newUserPrefix = "ru:"; public static final int verifyPercent = 5; private static boolean trace = false; private static boolean actionTrace = false; private static boolean updateQuotePrices = true; private static int primIterations = 1; private static boolean longRun = true; private static boolean publishQuotePriceChange = false; /** * -1 means every operation * 0 means never perform a market summary * > 0 means number of seconds between summaries. These will be * synchronized so only one transaction in this period will create a summary and * will cache its results. */ private static int marketSummaryInterval = 20; /* * Penny stocks is a problem where the random price change factor gets a stock * down to $.01. In this case trade jumpstarts the price back to $6.00 to * keep the math interesting. */ public static BigDecimal PENNY_STOCK_PRICE; public static BigDecimal PENNY_STOCK_RECOVERY_MIRACLE_MULTIPLIER; static { PENNY_STOCK_PRICE = new BigDecimal(0.01); PENNY_STOCK_PRICE = PENNY_STOCK_PRICE.setScale(2, BigDecimal.ROUND_HALF_UP); PENNY_STOCK_RECOVERY_MIRACLE_MULTIPLIER = new BigDecimal(600.0); PENNY_STOCK_RECOVERY_MIRACLE_MULTIPLIER.setScale( 2, BigDecimal.ROUND_HALF_UP); } /* CJB (DAYTRADER-25) - Also need to impose a ceiling on the quote price to ensure * prevent account and holding balances from exceeding the databases decimal precision. * At some point, this maximum value can be used to trigger a stock split. */ public static BigDecimal MAXIMUM_STOCK_PRICE; public static BigDecimal MAXIMUM_STOCK_SPLIT_MULTIPLIER; static { MAXIMUM_STOCK_PRICE = new BigDecimal(400); MAXIMUM_STOCK_PRICE.setScale(2, BigDecimal.ROUND_HALF_UP); MAXIMUM_STOCK_SPLIT_MULTIPLIER = new BigDecimal(0.5); MAXIMUM_STOCK_SPLIT_MULTIPLIER.setScale(2, BigDecimal.ROUND_HALF_UP); } /* Trade Scenario actions mixes. Each of the array rows represents a specific Trade Scenario Mix. The columns give the percentages for each action in the column header. Note: "login" is always 0. logout represents both login and logout (because each logout operation will cause a new login when the user context attempts the next action. */ /* Trade Scenario Workload parameters */ public final static int HOME_OP = 0; public final static int QUOTE_OP = 1; public final static int LOGIN_OP = 2; public final static int LOGOUT_OP = 3; public final static int REGISTER_OP = 4; public final static int ACCOUNT_OP = 5; public final static int PORTFOLIO_OP = 6; public final static int BUY_OP = 7; public final static int SELL_OP = 8; public final static int UPDATEACCOUNT_OP = 9; private static int scenarioMixes[][] = { // h q l o r a p b s u { 20, 40, 0, 4, 2, 10, 12, 4, 4, 4 }, //STANDARD { 20, 40, 0, 4, 2, 7, 7, 7, 7, 6 }, //High Volume }; private static char actions[] = { 'h', 'q', 'l', 'o', 'r', 'a', 'p', 'b', 's', 'u' }; private static int sellDeficit = 0; //Tracks the number of buys over sell when a users portfolio is empty // Used to maintain the correct ratio of buys/sells /* JSP pages for all Trade Actions */ public final static int WELCOME_PAGE = 0; public final static int REGISTER_PAGE = 1; public final static int PORTFOLIO_PAGE = 2; public final static int QUOTE_PAGE = 3; public final static int HOME_PAGE = 4; public final static int ACCOUNT_PAGE = 5; public final static int ORDER_PAGE = 6; public final static int CONFIG_PAGE = 7; public final static int STATS_PAGE = 8; //FUTURE Add XML/XSL View public static String webUI[][] = { { "/welcome.jsp", "/register.jsp", "/portfolio.jsp", "/quote.jsp", "/tradehome.jsp", "/account.jsp", "/order.jsp", "/config.jsp", "/runStats.jsp" }, //JSP Interface { "/welcomeImg.jsp", "/registerImg.jsp", "/portfolioImg.jsp", "/quoteImg.jsp", "/tradehomeImg.jsp", "/accountImg.jsp", "/orderImg.jsp", "/config.jsp", "/runStats.jsp" }, //JSP Interface }; /** * Return the hostname for this system * Creation date: (2/16/2000 9:02:25 PM) */ private static String getHostname() { try { if (hostName == null) { hostName = java.net.InetAddress.getLocalHost().getHostName(); //Strip of fully qualified domain if necessary try { hostName = hostName.substring(0, hostName.indexOf('.')); } catch (Exception e) { } } } catch (Exception e) { Log.error( "Exception getting local host name using 'localhost' - ", e); hostName = "localhost"; } return hostName; } /** * Return a Trade UI Web page based on the current configuration * This may return a JSP page or a Servlet page * Creation date: (3/14/2000 9:08:34 PM) */ public static String getPage(int pageNumber) { return webUI[webInterface][pageNumber]; } /** * Return the list of run time mode names * Creation date: (3/8/2000 5:58:34 PM) * @return java.lang.String[] */ public static java.lang.String[] getRunTimeModeNames() { return runTimeModeNames; } private static int scenarioCount = 0; /** * Return a Trade Scenario Operation based on the setting of the current mix (TradeScenarioMix) * Creation date: (2/10/2000 9:08:34 PM) */ public static char getScenarioAction(boolean newUser) { int r = rndInt(100); //0 to 99 = 100 int i = 0; int sum = scenarioMixes[workloadMix][i]; while (sum <= r) { i++; sum += scenarioMixes[workloadMix][i]; } incrementScenarioCount(); /* In TradeScenarioServlet, if a sell action is selected, but the users portfolio is empty, * a buy is executed instead and sellDefecit is incremented. This allows the number of buy/sell * operations to stay in sync w/ the given Trade mix. */ if ((!newUser) && (actions[i] == 'b')) { synchronized (TradeConfig.class) { if (sellDeficit > 0) { sellDeficit--; return 's'; //Special case for TradeScenarioServlet to note this is a buy switched to a sell to fix sellDeficit } } } return actions[i]; } public static String getUserID() { String userID; if (RND_USER) { userID = rndUserID(); } else { userID = nextUserID(); } return userID; } private static final BigDecimal orderFee = new BigDecimal("24.95"); private static final BigDecimal cashFee = new BigDecimal("0.0"); public static BigDecimal getOrderFee(String orderType) { if ((orderType.compareToIgnoreCase("BUY") == 0) || (orderType.compareToIgnoreCase("SELL") == 0)) return orderFee; return cashFee; } /** * Increment the sell deficit counter * Creation date: (6/21/2000 11:33:45 AM) */ public synchronized static void incrementSellDeficit() { sellDeficit++; } public static String nextUserID() { String userID; synchronized (userID_count_semaphore) { userID = "uid:" + userID_count; userID_count++; if (userID_count % MAX_USERS == 0) { userID_count = 0; } } return userID; } public static double random() { return randomNumberGenerator.nextDouble(); } public static String rndAddress() { return rndInt(1000) + " Oak St."; } public static String rndBalance() { //Give all new users a cool mill in which to trade return "1000000"; } public static String rndCreditCard() { return rndInt(100) + "-" + rndInt(1000) + "-" + rndInt(1000) + "-" + rndInt(1000); } public static String rndEmail(String userID) { return userID + "@" + rndInt(100) + ".com"; } public static String rndFullName() { return "first:" + rndInt(1000) + " last:" + rndInt(5000); } public static int rndInt(int i) { return (new Float(random() * i)).intValue(); } public static float rndFloat(int i) { return (new Float(random() * i)).floatValue(); } public static BigDecimal rndBigDecimal(float f) { return (new BigDecimal(random() * f)).setScale( 2, BigDecimal.ROUND_HALF_UP); } public static boolean rndBoolean() { return randomNumberGenerator.nextBoolean(); } /** * Returns a new Trade user * Creation date: (2/16/2000 8:50:35 PM) */ public synchronized static String rndNewUserID() { return newUserPrefix + getHostname() + System.currentTimeMillis() + count++; } public static float rndPrice() { return ((new Integer(rndInt(200))).floatValue()) + 1.0f; } private final static BigDecimal ONE = new BigDecimal(1.0); public static BigDecimal getRandomPriceChangeFactor() { double percentGain = rndFloat(1) * 0.2; if (random() < .5) percentGain *= -1; percentGain += 1; // change factor is between +/- 20% BigDecimal percentGainBD = (new BigDecimal(percentGain)).setScale(2, BigDecimal.ROUND_HALF_UP); if (percentGainBD.doubleValue() <= 0.0) percentGainBD = ONE; return percentGainBD; } public static float rndQuantity() { return ((new Integer(rndInt(200))).floatValue()) + 1.0f; } public static String rndSymbol() { return "s:" + rndInt(MAX_QUOTES - 1); } public static String rndSymbols() { String symbols = ""; int num_symbols = rndInt(QUOTES_PER_PAGE); for (int i = 0; i <= num_symbols; i++) { symbols += "s:" + rndInt(MAX_QUOTES - 1); if (i < num_symbols) symbols += ","; } return symbols; } public static String rndUserID() { String nextUser = getNextUserIDFromDeck(); if (Log.doTrace()) Log.trace("TradeConfig:rndUserID -- new trader = " + nextUser); return nextUser; } private static synchronized String getNextUserIDFromDeck() { int numUsers = getMAX_USERS(); if (deck == null) { deck = new ArrayList(numUsers); for (int i = 0; i < numUsers; i++) deck.add(i, new Integer(i)); java.util.Collections.shuffle(deck, r0); } if (card >= numUsers) card = 0; return "uid:" + deck.get(card++); } //Trade implements a card deck approach to selecting // users for trading with tradescenarioservlet private static ArrayList deck = null; private static int card = 0; /** * Set the list of run time mode names * Creation date: (3/8/2000 5:58:34 PM) * @param newRunTimeModeNames java.lang.String[] */ public static void setRunTimeModeNames( java.lang.String[] newRunTimeModeNames) { runTimeModeNames = newRunTimeModeNames; } /** * This is a convenience method for servlets to set Trade configuration parameters * from servlet initialization parameters. The servlet provides the init param and its * value as strings. This method then parses the parameter, converts the value to the * correct type and sets the corresponding TradeConfig parameter to the converted value * */ public static void setConfigParam(String parm, String value) { Log.log("TradeConfig setting parameter: " + parm + "=" + value); // Compare the parm value to valid TradeConfig parameters that can be set // by servlet initialization // First check the proposed new parm and value - if empty or null ignore it if (parm == null) return; parm = parm.trim(); if (parm.length() <= 0) return; if (value == null) return; value = value.trim(); if (parm.equalsIgnoreCase("runTimeMode")) { try { for (int i = 0; i < runTimeModeNames.length; i++) { if (value.equalsIgnoreCase(runTimeModeNames[i])) { setRunTimeMode(ModeType.values()[i]); break; } } } catch (Exception e) { Log.error( "TradeConfig.setConfigParm(..): minor exception caught" + "trying to set runtimemode to " + value + "reverting to current value: " + runTimeModeNames[getRunTimeMode().ordinal()], e); } // If the value is bad, simply revert to current } else if (parm.equalsIgnoreCase("orderProcessingMode")) { try { for (int i = 0; i < orderProcessingModeNames.length; i++) { if (value.equalsIgnoreCase(orderProcessingModeNames[i])) { orderProcessingMode = i; break; } } } catch (Exception e) { Log.error( "TradeConfig.setConfigParm(..): minor exception caught" + "trying to set orderProcessingMode to " + value + "reverting to current value: " + orderProcessingModeNames[orderProcessingMode], e); } // If the value is bad, simply revert to current } else if (parm.equalsIgnoreCase("accessMode")) { try { for (int i = 0; i < accessModeNames.length; i++) { if (value.equalsIgnoreCase(accessModeNames[i])) { accessMode = i; break; } } } catch (Exception e) { Log.error( "TradeConfig.setConfigParm(..): minor exception caught" + "trying to set accessMode to " + value + "reverting to current value: " + accessModeNames[accessMode], e); } } else if (parm.equalsIgnoreCase("webServicesEndpoint")) { try { setSoapURL(value); } catch (Exception e) { Log.error( "TradeConfig.setConfigParm(..): minor exception caught" + "Setting web services endpoint", e); } //On error, revert to saved } else if (parm.equalsIgnoreCase("workloadMix")) { try { for (int i = 0; i < workloadMixNames.length; i++) { if (value.equalsIgnoreCase(workloadMixNames[i])) { workloadMix = i; break; } } } catch (Exception e) { Log.error( "TradeConfig.setConfigParm(..): minor exception caught" + "trying to set workloadMix to " + value + "reverting to current value: " + workloadMixNames[workloadMix], e); } // If the value is bad, simply revert to current } else if (parm.equalsIgnoreCase("WebInterface")) { try { for (int i = 0; i < webInterfaceNames.length; i++) { if (value.equalsIgnoreCase(webInterfaceNames[i])) { webInterface = i; break; } } } catch (Exception e) { Log.error( "TradeConfig.setConfigParm(..): minor exception caught" + "trying to set WebInterface to " + value + "reverting to current value: " + webInterfaceNames[webInterface], e); } // If the value is bad, simply revert to current } else if (parm.equalsIgnoreCase("CachingType")) { try { for (int i = 0; i < cachingTypeNames.length; i++) { if (value.equalsIgnoreCase(cachingTypeNames[i])) { cachingType = i; break; } } } catch (Exception e) { Log.error( "TradeConfig.setConfigParm(..): minor exception caught" + "trying to set CachingType to " + value + "reverting to current value: " + cachingTypeNames[cachingType], e); } // If the value is bad, simply revert to current } else if (parm.equalsIgnoreCase("maxUsers")) { try { MAX_USERS = Integer.parseInt(value); } catch (Exception e) { Log.error( "TradeConfig.setConfigParm(..): minor exception caught" + "Setting maxusers, error parsing string to int:" + value + "revering to current value: " + MAX_USERS, e); } //On error, revert to saved } else if (parm.equalsIgnoreCase("maxQuotes")) { try { MAX_QUOTES = Integer.parseInt(value); } catch (Exception e) { Log.error( "TradeConfig.setConfigParm(...) minor exception caught" + "Setting max_quotes, error parsing string to int " + value + "reverting to current value: " + MAX_QUOTES, e); } //On error, revert to saved } else if (parm.equalsIgnoreCase("primIterations")) { try { primIterations = Integer.parseInt(value); } catch (Exception e) { Log.error( "TradeConfig.setConfigParm(..): minor exception caught" + "Setting primIterations, error parsing string to int:" + value + "revering to current value: " + primIterations, e); } //On error, revert to saved } } /** * Gets the orderProcessingModeNames * @return Returns a String[] */ public static String[] getOrderProcessingModeNames() { return orderProcessingModeNames; } /** * Gets the workloadMixNames * @return Returns a String[] */ public static String[] getWorkloadMixNames() { return workloadMixNames; } /** * Gets the webInterfaceNames * @return Returns a String[] */ public static String[] getWebInterfaceNames() { return webInterfaceNames; } /** * Gets the webInterfaceNames * @return Returns a String[] */ public static String[] getCachingTypeNames() { return cachingTypeNames; } /** * Gets the scenarioMixes * @return Returns a int[][] */ public static int[][] getScenarioMixes() { return scenarioMixes; } /** * Gets the trace * @return Returns a boolean */ public static boolean getTrace() { return trace; } /** * Sets the trace * @param trace The trace to set */ public static void setTrace(boolean traceValue) { trace = traceValue; } /** * Gets the mAX_USERS. * @return Returns a int */ public static int getMAX_USERS() { return MAX_USERS; } /** * Sets the mAX_USERS. * @param mAX_USERS The mAX_USERS to set */ public static void setMAX_USERS(int mAX_USERS) { MAX_USERS = mAX_USERS; deck = null; // reset the card deck for selecting users } /** * Gets the mAX_QUOTES. * @return Returns a int */ public static int getMAX_QUOTES() { return MAX_QUOTES; } /** * Sets the mAX_QUOTES. * @param mAX_QUOTES The mAX_QUOTES to set */ public static void setMAX_QUOTES(int mAX_QUOTES) { MAX_QUOTES = mAX_QUOTES; } /** * Gets the mAX_HOLDINGS. * @return Returns a int */ public static int getMAX_HOLDINGS() { return MAX_HOLDINGS; } /** * Sets the mAX_HOLDINGS. * @param mAX_HOLDINGS The mAX_HOLDINGS to set */ public static void setMAX_HOLDINGS(int mAX_HOLDINGS) { MAX_HOLDINGS = mAX_HOLDINGS; } /** * Gets the actionTrace. * @return Returns a boolean */ public static boolean getActionTrace() { return actionTrace; } /** * Sets the actionTrace. * @param actionTrace The actionTrace to set */ public static void setActionTrace(boolean actionTrace) { TradeConfig.actionTrace = actionTrace; } /** * Gets the scenarioCount. * @return Returns a int */ public static int getScenarioCount() { return scenarioCount; } /** * Sets the scenarioCount. * @param scenarioCount The scenarioCount to set */ public static void setScenarioCount(int scenarioCount) { TradeConfig.scenarioCount = scenarioCount; } public static synchronized void incrementScenarioCount() { scenarioCount++; } /** * Gets the jdbc driver needs global transaction * Some XA Drivers require a global transaction to be started * for all SQL calls. To work around this, set this to true * to cause the direct mode to start a user transaction. * @return Returns a boolean */ public static boolean getJDBCDriverNeedsGlobalTransaction() { return JDBCDriverNeedsGlobalTransaction; } /** * Sets the jdbc driver needs global transaction * @param JDBCDriverNeedsGlobalTransactionVal the value */ public static void setJDBCDriverNeedsGlobalTransaction(boolean JDBCDriverNeedsGlobalTransactionVal) { JDBCDriverNeedsGlobalTransaction = JDBCDriverNeedsGlobalTransactionVal; } /** * Gets the updateQuotePrices. * @return Returns a boolean */ public static boolean getUpdateQuotePrices() { return updateQuotePrices; } /** * Sets the updateQuotePrices. * @param updateQuotePrices The updateQuotePrices to set */ public static void setUpdateQuotePrices(boolean updateQuotePrices) { TradeConfig.updateQuotePrices = updateQuotePrices; } public static String getSoapURL() { return SoapURL; } public static void setSoapURL(String value) { SoapURL = value; } public static int getAccessMode() { return accessMode; } public static void setAccessMode(int value) { accessMode = value; } public static ModeType getRunTimeMode() { return runTimeMode; } public static void setRunTimeMode(ModeType value) { runTimeMode = value; } public static int getPrimIterations() { return primIterations; } public static void setPrimIterations(int iter) { primIterations = iter; } public static boolean getLongRun() { return longRun; } public static void setLongRun(boolean longRun) { TradeConfig.longRun = longRun; } public static void setPublishQuotePriceChange(boolean publishQuotePriceChange) { TradeConfig.publishQuotePriceChange = publishQuotePriceChange; } public static boolean getPublishQuotePriceChange() { return publishQuotePriceChange; } public static void setMarketSummaryInterval(int seconds) { TradeConfig.marketSummaryInterval = seconds; } public static int getMarketSummaryInterval() { return TradeConfig.marketSummaryInterval; } /** * Return the list of JPA Layer names * Creation date: (01/10/2009) * @return java.lang.String[] */ public static java.lang.String[] getJPALayerNames() { return jpaLayerNames; } }
8,201
0
Create_ds/aries/samples/ariestrader/modules/ariestrader-util/src/main/java/org/apache/aries/samples/ariestrader
Create_ds/aries/samples/ariestrader/modules/ariestrader-util/src/main/java/org/apache/aries/samples/ariestrader/util/KeyBlock.java
/** * 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. */ package org.apache.aries.samples.ariestrader.util; import java.util.AbstractSequentialList; import java.util.ListIterator; public class KeyBlock extends AbstractSequentialList { // min and max provide range of valid primary keys for this KeyBlock private int min = 0; private int max = 0; private int index = 0; /** * Constructor for KeyBlock */ public KeyBlock() { super(); min = 0; max = 0; index = min; } /** * Constructor for KeyBlock */ public KeyBlock(int min, int max) { super(); this.min = min; this.max = max; index = min; } /** * @see AbstractCollection#size() */ public int size() { return (max - min) + 1; } /** * @see AbstractSequentialList#listIterator(int) */ public ListIterator listIterator(int arg0) { return new KeyBlockIterator(); } class KeyBlockIterator implements ListIterator { /** * @see ListIterator#hasNext() */ public boolean hasNext() { return index <= max; } /** * @see ListIterator#next() */ public synchronized Object next() { if (index > max) throw new java.lang.RuntimeException("KeyBlock:next() -- Error KeyBlock depleted"); return new Integer(index++); } /** * @see ListIterator#hasPrevious() */ public boolean hasPrevious() { return index > min; } /** * @see ListIterator#previous() */ public Object previous() { return new Integer(--index); } /** * @see ListIterator#nextIndex() */ public int nextIndex() { return index-min; } /** * @see ListIterator#previousIndex() */ public int previousIndex() { throw new UnsupportedOperationException("KeyBlock: previousIndex() not supported"); } /** * @see ListIterator#add() */ public void add(Object o) { throw new UnsupportedOperationException("KeyBlock: add() not supported"); } /** * @see ListIterator#remove() */ public void remove() { throw new UnsupportedOperationException("KeyBlock: remove() not supported"); } /** * @see ListIterator#set(Object) */ public void set(Object arg0) { } } }
8,202
0
Create_ds/aries/samples/ariestrader/modules/ariestrader-entities/src/main/java/org/apache/aries/samples/ariestrader
Create_ds/aries/samples/ariestrader/modules/ariestrader-entities/src/main/java/org/apache/aries/samples/ariestrader/entities/AccountDataBeanImpl.java
/** * 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. */ package org.apache.aries.samples.ariestrader.entities; import java.io.Serializable; import java.math.BigDecimal; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.persistence.TableGenerator; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; import org.apache.aries.samples.ariestrader.util.Log; import org.apache.aries.samples.ariestrader.util.TradeConfig; import org.apache.aries.samples.ariestrader.api.persistence.AccountDataBean; import org.apache.aries.samples.ariestrader.api.persistence.AccountProfileDataBean; import org.apache.aries.samples.ariestrader.api.persistence.HoldingDataBean; import org.apache.aries.samples.ariestrader.api.persistence.OrderDataBean; @Entity (name = "accountejb") @Table(name = "accountejb") @NamedQueries( { @NamedQuery(name = "accountejb.findByCreationdate", query = "SELECT a FROM accountejb a WHERE a.creationDate = :creationdate"), @NamedQuery(name = "accountejb.findByOpenbalance", query = "SELECT a FROM accountejb a WHERE a.openBalance = :openbalance"), @NamedQuery(name = "accountejb.findByLogoutcount", query = "SELECT a FROM accountejb a WHERE a.logoutCount = :logoutcount"), @NamedQuery(name = "accountejb.findByBalance", query = "SELECT a FROM accountejb a WHERE a.balance = :balance"), @NamedQuery(name = "accountejb.findByAccountid", query = "SELECT a FROM accountejb a WHERE a.accountID = :accountid"), @NamedQuery(name = "accountejb.findByAccountid_eager", query = "SELECT a FROM accountejb a LEFT JOIN FETCH a.profile WHERE a.accountID = :accountid"), @NamedQuery(name = "accountejb.findByAccountid_eagerholdings", query = "SELECT a FROM accountejb a LEFT JOIN FETCH a.holdings WHERE a.accountID = :accountid"), @NamedQuery(name = "accountejb.findByLastlogin", query = "SELECT a FROM accountejb a WHERE a.lastLogin = :lastlogin"), @NamedQuery(name = "accountejb.findByLogincount", query = "SELECT a FROM accountejb a WHERE a.loginCount = :logincount") }) public class AccountDataBeanImpl implements AccountDataBean, Serializable { /* Accessor methods for persistent fields */ @TableGenerator( name="accountIdGen", table="KEYGENEJB", pkColumnName="KEYNAME", valueColumnName="KEYVAL", pkColumnValue="account", allocationSize=1000) @Id @GeneratedValue(strategy=GenerationType.TABLE, generator="accountIdGen") @Column(name = "ACCOUNTID", nullable = false) private Integer accountID; /* accountID */ @Column(name = "LOGINCOUNT", nullable = false) private int loginCount; /* loginCount */ @Column(name = "LOGOUTCOUNT", nullable = false) private int logoutCount; /* logoutCount */ @Column(name = "LASTLOGIN") @Temporal(TemporalType.TIMESTAMP) private Date lastLogin; /* lastLogin Date */ @Column(name = "CREATIONDATE") @Temporal(TemporalType.TIMESTAMP) private Date creationDate; /* creationDate */ @Column(name = "BALANCE") private BigDecimal balance; /* balance */ @Column(name = "OPENBALANCE") private BigDecimal openBalance; /* open balance */ @OneToMany(mappedBy = "account", fetch=FetchType.LAZY) private Collection<OrderDataBeanImpl> orders; @OneToMany(mappedBy = "account", fetch=FetchType.LAZY) private Collection<HoldingDataBeanImpl> holdings; @OneToOne(fetch=FetchType.LAZY) @JoinColumn(name="PROFILE_USERID", columnDefinition="VARCHAR(255)") private AccountProfileDataBeanImpl profile; /* Accessor methods for relationship fields are only included for the AccountProfile profileID */ @Transient private String profileID; public AccountDataBeanImpl() { } public AccountDataBeanImpl(Integer accountID, int loginCount, int logoutCount, Date lastLogin, Date creationDate, BigDecimal balance, BigDecimal openBalance, String profileID) { setAccountID(accountID); setLoginCount(loginCount); setLogoutCount(logoutCount); setLastLogin(lastLogin); setCreationDate(creationDate); setBalance(balance); setOpenBalance(openBalance); setProfileID(profileID); } public AccountDataBeanImpl(int loginCount, int logoutCount, Date lastLogin, Date creationDate, BigDecimal balance, BigDecimal openBalance, String profileID) { setLoginCount(loginCount); setLogoutCount(logoutCount); setLastLogin(lastLogin); setCreationDate(creationDate); setBalance(balance); setOpenBalance(openBalance); setProfileID(profileID); } public static AccountDataBean getRandomInstance() { return new AccountDataBeanImpl(new Integer(TradeConfig.rndInt(100000)), //accountID TradeConfig.rndInt(10000), //loginCount TradeConfig.rndInt(10000), //logoutCount new java.util.Date(), //lastLogin new java.util.Date(TradeConfig.rndInt(Integer.MAX_VALUE)), //creationDate TradeConfig.rndBigDecimal(1000000.0f), //balance TradeConfig.rndBigDecimal(1000000.0f), //openBalance TradeConfig.rndUserID() //profileID ); } public String toString() { return "\n\tAccount Data for account: " + getAccountID() + "\n\t\t loginCount:" + getLoginCount() + "\n\t\t logoutCount:" + getLogoutCount() + "\n\t\t lastLogin:" + getLastLogin() + "\n\t\t creationDate:" + getCreationDate() + "\n\t\t balance:" + getBalance() + "\n\t\t openBalance:" + getOpenBalance() + "\n\t\t profileID:" + getProfileID() ; } public String toHTML() { return "<BR>Account Data for account: <B>" + getAccountID() + "</B>" + "<LI> loginCount:" + getLoginCount() + "</LI>" + "<LI> logoutCount:" + getLogoutCount() + "</LI>" + "<LI> lastLogin:" + getLastLogin() + "</LI>" + "<LI> creationDate:" + getCreationDate() + "</LI>" + "<LI> balance:" + getBalance() + "</LI>" + "<LI> openBalance:" + getOpenBalance() + "</LI>" + "<LI> profileID:" + getProfileID() + "</LI>" ; } public void print() { Log.log(this.toString()); } public Integer getAccountID() { return accountID; } public void setAccountID(Integer accountID) { this.accountID = accountID; } public int getLoginCount() { return loginCount; } public void setLoginCount(int loginCount) { this.loginCount = loginCount; } public int getLogoutCount() { return logoutCount; } public void setLogoutCount(int logoutCount) { this.logoutCount = logoutCount; } public Date getLastLogin() { return lastLogin; } public void setLastLogin(Date lastLogin) { this.lastLogin = lastLogin; } public Date getCreationDate() { return creationDate; } public void setCreationDate(Date creationDate) { this.creationDate = creationDate; } public BigDecimal getBalance() { return balance; } public void setBalance(BigDecimal balance) { this.balance = balance; } public BigDecimal getOpenBalance() { return openBalance; } public void setOpenBalance(BigDecimal openBalance) { this.openBalance = openBalance; } public String getProfileID() { return profileID; } public void setProfileID(String profileID) { this.profileID = profileID; } public Collection<OrderDataBean> getOrders() { Collection orderDataBeans = new ArrayList(); for (OrderDataBeanImpl o : orders ) { orderDataBeans.add( (OrderDataBean) o); } return orderDataBeans; } public void setOrders(Collection<OrderDataBeanImpl> orders) { this.orders = orders; } public Collection<HoldingDataBean> getHoldings() { Collection holdingDataBeans = new ArrayList(); for (HoldingDataBeanImpl h : holdings ) { holdingDataBeans.add( (HoldingDataBean) h); } return holdingDataBeans; } public void setHoldings(Collection<HoldingDataBeanImpl> holdings) { this.holdings = holdings; } public AccountProfileDataBean getProfile() { return profile; } public void setProfile(AccountProfileDataBean profile) { this.profile = (AccountProfileDataBeanImpl) profile; } public void login(String password) { AccountProfileDataBean profile = getProfile(); if ((profile == null) || (profile.getPassword().equals(password) == false)) { String error = "AccountBean:Login failure for account: " + getAccountID() + ((profile == null) ? "null AccountProfile" : "\n\tIncorrect password-->" + profile.getUserID() + ":" + profile.getPassword()); throw new RuntimeException(error); } setLastLogin(new Timestamp(System.currentTimeMillis())); setLoginCount(getLoginCount() + 1); } public void logout() { setLogoutCount(getLogoutCount() + 1); } @Override public int hashCode() { int hash = 0; hash += (this.accountID != null ? this.accountID.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof AccountDataBeanImpl)) { return false; } AccountDataBeanImpl other = (AccountDataBeanImpl)object; if (this.accountID != other.accountID && (this.accountID == null || !this.accountID.equals(other.accountID))) return false; return true; } }
8,203
0
Create_ds/aries/samples/ariestrader/modules/ariestrader-entities/src/main/java/org/apache/aries/samples/ariestrader
Create_ds/aries/samples/ariestrader/modules/ariestrader-entities/src/main/java/org/apache/aries/samples/ariestrader/entities/AccountProfileDataBeanImpl.java
/** * 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. */ package org.apache.aries.samples.ariestrader.entities; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToOne; import javax.persistence.Table; import org.apache.aries.samples.ariestrader.util.Log; import org.apache.aries.samples.ariestrader.util.TradeConfig; import org.apache.aries.samples.ariestrader.api.persistence.AccountDataBean; import org.apache.aries.samples.ariestrader.api.persistence.AccountProfileDataBean; @Entity(name = "accountprofileejb") @Table(name = "accountprofileejb") @NamedQueries( { @NamedQuery(name = "accountprofileejb.findByAddress", query = "SELECT a FROM accountprofileejb a WHERE a.address = :address"), @NamedQuery(name = "accountprofileejb.findByPasswd", query = "SELECT a FROM accountprofileejb a WHERE a.passwd = :passwd"), @NamedQuery(name = "accountprofileejb.findByUserid", query = "SELECT a FROM accountprofileejb a WHERE a.userID = :userid"), @NamedQuery(name = "accountprofileejb.findByEmail", query = "SELECT a FROM accountprofileejb a WHERE a.email = :email"), @NamedQuery(name = "accountprofileejb.findByCreditcard", query = "SELECT a FROM accountprofileejb a WHERE a.creditCard = :creditcard"), @NamedQuery(name = "accountprofileejb.findByFullname", query = "SELECT a FROM accountprofileejb a WHERE a.fullName = :fullname") }) public class AccountProfileDataBeanImpl implements AccountProfileDataBean, java.io.Serializable { @Id @Column(name = "USERID", nullable = false, length = 255) private String userID; /* userID */ @Column(name = "PASSWD", length = 255) private String passwd; /* password */ @Column(name = "FULLNAME", length = 255) private String fullName; /* fullName */ @Column(name = "ADDRESS", length = 255) private String address; /* address */ @Column(name = "email", length = 255) private String email; /* email */ @Column(name = "creditcard", length = 255) //why was it credit? private String creditCard; /* creditCard */ @OneToOne(mappedBy="profile", fetch=FetchType.LAZY) private AccountDataBeanImpl account; public AccountProfileDataBeanImpl() { } public AccountProfileDataBeanImpl(String userID, String password, String fullName, String address, String email, String creditCard) { setUserID(userID); setPassword(password); setFullName(fullName); setAddress(address); setEmail(email); setCreditCard(creditCard); } public static AccountProfileDataBean getRandomInstance() { return new AccountProfileDataBeanImpl( TradeConfig.rndUserID(), // userID TradeConfig.rndUserID(), // passwd TradeConfig.rndFullName(), // fullname TradeConfig.rndAddress(), // address TradeConfig.rndEmail(TradeConfig.rndUserID()), //email TradeConfig.rndCreditCard() // creditCard ); } public String toString() { return "\n\tAccount Profile Data for userID:" + getUserID() + "\n\t\t passwd:" + getPassword() + "\n\t\t fullName:" + getFullName() + "\n\t\t address:" + getAddress() + "\n\t\t email:" + getEmail() + "\n\t\t creditCard:" + getCreditCard() ; } public String toHTML() { return "<BR>Account Profile Data for userID: <B>" + getUserID() + "</B>" + "<LI> passwd:" + getPassword() + "</LI>" + "<LI> fullName:" + getFullName() + "</LI>" + "<LI> address:" + getAddress() + "</LI>" + "<LI> email:" + getEmail() + "</LI>" + "<LI> creditCard:" + getCreditCard() + "</LI>" ; } public void print() { Log.log(this.toString()); } public String getUserID() { return userID; } public void setUserID(String userID) { this.userID = userID; } public String getPassword() { return passwd; } public void setPassword(String password) { this.passwd = password; } public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } 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 getCreditCard() { return creditCard; } public void setCreditCard(String creditCard) { this.creditCard = creditCard; } public AccountDataBean getAccount() { return account; } public void setAccount(AccountDataBean account) { this.account = (AccountDataBeanImpl) account; } @Override public int hashCode() { int hash = 0; hash += (this.userID != null ? this.userID.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof AccountProfileDataBeanImpl)) { return false; } AccountProfileDataBeanImpl other = (AccountProfileDataBeanImpl)object; if (this.userID != other.userID && (this.userID == null || !this.userID.equals(other.userID))) return false; return true; } }
8,204
0
Create_ds/aries/samples/ariestrader/modules/ariestrader-entities/src/main/java/org/apache/aries/samples/ariestrader
Create_ds/aries/samples/ariestrader/modules/ariestrader-entities/src/main/java/org/apache/aries/samples/ariestrader/entities/HoldingDataBeanImpl.java
/** * 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. */ package org.apache.aries.samples.ariestrader.entities; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.persistence.TableGenerator; import javax.persistence.Transient; import org.apache.aries.samples.ariestrader.util.Log; import org.apache.aries.samples.ariestrader.util.TradeConfig; import org.apache.aries.samples.ariestrader.api.persistence.AccountDataBean; import org.apache.aries.samples.ariestrader.api.persistence.HoldingDataBean; import org.apache.aries.samples.ariestrader.api.persistence.QuoteDataBean; @Entity(name = "holdingejb") @Table(name = "holdingejb") @NamedQueries( { @NamedQuery(name = "holdingejb.findByPurchaseprice", query = "SELECT h FROM holdingejb h WHERE h.purchasePrice = :purchaseprice"), @NamedQuery(name = "holdingejb.findByHoldingid", query = "SELECT h FROM holdingejb h WHERE h.holdingID = :holdingid"), @NamedQuery(name = "holdingejb.findByQuantity", query = "SELECT h FROM holdingejb h WHERE h.quantity = :quantity"), @NamedQuery(name = "holdingejb.findByPurchasedate", query = "SELECT h FROM holdingejb h WHERE h.purchaseDate = :purchasedate"), @NamedQuery(name = "holdingejb.holdingsByUserID", query = "SELECT h FROM holdingejb h where h.account.profile.userID = :userID") }) public class HoldingDataBeanImpl implements HoldingDataBean, Serializable { /* persistent/relationship fields */ @TableGenerator(name = "holdingIdGen", table = "KEYGENEJB", pkColumnName = "KEYNAME", valueColumnName = "KEYVAL", pkColumnValue = "holding", allocationSize = 1000) @Id @GeneratedValue(strategy = GenerationType.TABLE, generator = "holdingIdGen") @Column(name = "HOLDINGID", nullable = false) private Integer holdingID; /* holdingID */ @Column(name = "QUANTITY", nullable = false) private double quantity; /* quantity */ @Column(name = "PURCHASEPRICE") private BigDecimal purchasePrice; /* purchasePrice */ @Column(name = "PURCHASEDATE") private Date purchaseDate; /* purchaseDate */ @Transient private String quoteID; /* Holding() ---> Quote(1) */ @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "ACCOUNT_ACCOUNTID") private AccountDataBeanImpl account; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "QUOTE_SYMBOL", columnDefinition="VARCHAR(255)") private QuoteDataBeanImpl quote; public HoldingDataBeanImpl() { } public HoldingDataBeanImpl(Integer holdingID, double quantity, BigDecimal purchasePrice, Date purchaseDate, String quoteID) { setHoldingID(holdingID); setQuantity(quantity); setPurchasePrice(purchasePrice); setPurchaseDate(purchaseDate); setQuoteID(quoteID); } public HoldingDataBeanImpl(double quantity, BigDecimal purchasePrice, Date purchaseDate, AccountDataBean account, QuoteDataBean quote) { setQuantity(quantity); setPurchasePrice(purchasePrice); setPurchaseDate(purchaseDate); setAccount(account); setQuote(quote); } public static HoldingDataBean getRandomInstance() { return new HoldingDataBeanImpl(new Integer(TradeConfig.rndInt(100000)), // holdingID TradeConfig.rndQuantity(), // quantity TradeConfig.rndBigDecimal(1000.0f), // purchasePrice new java.util.Date(TradeConfig.rndInt(Integer.MAX_VALUE)), // purchaseDate TradeConfig.rndSymbol() // symbol ); } public String toString() { return "\n\tHolding Data for holding: " + getHoldingID() + "\n\t\t quantity:" + getQuantity() + "\n\t\t purchasePrice:" + getPurchasePrice() + "\n\t\t purchaseDate:" + getPurchaseDate() + "\n\t\t quoteID:" + getQuoteID(); } public String toHTML() { return "<BR>Holding Data for holding: " + getHoldingID() + "</B>" + "<LI> quantity:" + getQuantity() + "</LI>" + "<LI> purchasePrice:" + getPurchasePrice() + "</LI>" + "<LI> purchaseDate:" + getPurchaseDate() + "</LI>" + "<LI> quoteID:" + getQuoteID() + "</LI>"; } public void print() { Log.log(this.toString()); } public Integer getHoldingID() { return holdingID; } public void setHoldingID(Integer holdingID) { this.holdingID = holdingID; } public double getQuantity() { return quantity; } public void setQuantity(double quantity) { this.quantity = quantity; } public BigDecimal getPurchasePrice() { return purchasePrice; } public void setPurchasePrice(BigDecimal purchasePrice) { this.purchasePrice = purchasePrice; } public Date getPurchaseDate() { return purchaseDate; } public void setPurchaseDate(Date purchaseDate) { this.purchaseDate = purchaseDate; } public String getQuoteID() { if (quote != null) { return quote.getSymbol(); } return quoteID; } public void setQuoteID(String quoteID) { this.quoteID = quoteID; } public AccountDataBean getAccount() { return account; } public void setAccount(AccountDataBean account) { this.account = (AccountDataBeanImpl) account; } /* * Disabled for D185273 public String getSymbol() { return getQuoteID(); } */ public QuoteDataBean getQuote() { return quote; } public void setQuote(QuoteDataBean quote) { this.quote = (QuoteDataBeanImpl) quote; } @Override public int hashCode() { int hash = 0; hash += (this.holdingID != null ? this.holdingID.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are // not set if (!(object instanceof HoldingDataBeanImpl)) { return false; } HoldingDataBeanImpl other = (HoldingDataBeanImpl) object; if (this.holdingID != other.holdingID && (this.holdingID == null || !this.holdingID .equals(other.holdingID))) return false; return true; } }
8,205
0
Create_ds/aries/samples/ariestrader/modules/ariestrader-entities/src/main/java/org/apache/aries/samples/ariestrader
Create_ds/aries/samples/ariestrader/modules/ariestrader-entities/src/main/java/org/apache/aries/samples/ariestrader/entities/QuoteDataBeanImpl.java
/** * 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. */ package org.apache.aries.samples.ariestrader.entities; import java.io.Serializable; import java.math.BigDecimal; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.NamedNativeQueries; import javax.persistence.NamedNativeQuery; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import org.apache.aries.samples.ariestrader.util.Log; import org.apache.aries.samples.ariestrader.util.TradeConfig; import org.apache.aries.samples.ariestrader.api.persistence.QuoteDataBean; @Entity(name = "quoteejb") @Table(name = "quoteejb") @NamedQueries({ @NamedQuery(name = "quoteejb.allQuotes",query = "SELECT q FROM quoteejb q"), @NamedQuery(name = "quoteejb.quotesByChange",query = "SELECT q FROM quoteejb q WHERE q.symbol LIKE 's:1__' ORDER BY q.change1 DESC"), @NamedQuery(name = "quoteejb.findByLow", query = "SELECT q FROM quoteejb q WHERE q.low = :low"), @NamedQuery(name = "quoteejb.findByOpen1", query = "SELECT q FROM quoteejb q WHERE q.open1 = :open1"), @NamedQuery(name = "quoteejb.findByVolume", query = "SELECT q FROM quoteejb q WHERE q.volume = :volume"), @NamedQuery(name = "quoteejb.findByPrice", query = "SELECT q FROM quoteejb q WHERE q.price = :price"), @NamedQuery(name = "quoteejb.findByHigh", query = "SELECT q FROM quoteejb q WHERE q.high = :high"), @NamedQuery(name = "quoteejb.findByCompanyname", query = "SELECT q FROM quoteejb q WHERE q.companyName = :companyname"), @NamedQuery(name = "quoteejb.findBySymbol", query = "SELECT q FROM quoteejb q WHERE q.symbol = :symbol"), @NamedQuery(name = "quoteejb.findByChange1", query = "SELECT q FROM quoteejb q WHERE q.change1 = :change1") }) @NamedNativeQueries({ @NamedNativeQuery(name="quoteejb.quoteForUpdate", query="select * from quoteejb q where q.symbol=? for update",resultClass=org.apache.aries.samples.ariestrader.entities.QuoteDataBeanImpl.class) }) public class QuoteDataBeanImpl implements QuoteDataBean, Serializable { /** * */ private static final long serialVersionUID = 8476917690278143517L; @Id @Column(name = "SYMBOL", nullable = false, length = 255) private String symbol; /* symbol */ @Column(name = "COMPANYNAME", length = 255) private String companyName; /* companyName */ @Column(name = "VOLUME", nullable = false) private double volume; /* volume */ @Column(name = "PRICE") private BigDecimal price; /* price */ @Column(name = "OPEN1") private BigDecimal open1; /* open1 price */ @Column(name = "LOW") private BigDecimal low; /* low price */ @Column(name = "HIGH") private BigDecimal high; /* high price */ @Column(name = "CHANGE1", nullable = false) private double change1; /* price change */ public QuoteDataBeanImpl() { } public QuoteDataBeanImpl(String symbol, String companyName, double volume, BigDecimal price, BigDecimal open, BigDecimal low, BigDecimal high, double change) { setSymbol(symbol); setCompanyName(companyName); setVolume(volume); setPrice(price); setOpen(open); setLow(low); setHigh(high); setChange(change); } public static QuoteDataBean getRandomInstance() { return new QuoteDataBeanImpl( TradeConfig.rndSymbol(), //symbol TradeConfig.rndSymbol() + " Incorporated", //Company Name TradeConfig.rndFloat(100000), //volume TradeConfig.rndBigDecimal(1000.0f), //price TradeConfig.rndBigDecimal(1000.0f), //open1 TradeConfig.rndBigDecimal(1000.0f), //low TradeConfig.rndBigDecimal(1000.0f), //high TradeConfig.rndFloat(100000) //volume ); } //Create a "zero" value QuoteDataBeanImpl for the given symbol public QuoteDataBeanImpl(String symbol) { setSymbol(symbol); } public String toString() { return "\n\tQuote Data for: " + getSymbol() + "\n\t\t companyName: " + getCompanyName() + "\n\t\t volume: " + getVolume() + "\n\t\t price: " + getPrice() + "\n\t\t open1: " + getOpen() + "\n\t\t low: " + getLow() + "\n\t\t high: " + getHigh() + "\n\t\t change1: " + getChange() ; } public String toHTML() { return "<BR>Quote Data for: " + getSymbol() + "<LI> companyName: " + getCompanyName() + "</LI>" + "<LI> volume: " + getVolume() + "</LI>" + "<LI> price: " + getPrice() + "</LI>" + "<LI> open1: " + getOpen() + "</LI>" + "<LI> low: " + getLow() + "</LI>" + "<LI> high: " + getHigh() + "</LI>" + "<LI> change1: " + getChange() + "</LI>" ; } public void print() { Log.log(this.toString()); } public String getSymbol() { return symbol; } public void setSymbol(String symbol) { this.symbol = symbol; } public String getCompanyName() { return companyName; } public void setCompanyName(String companyName) { this.companyName = companyName; } public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } public BigDecimal getOpen() { return open1; } public void setOpen(BigDecimal open) { this.open1 = open; } public BigDecimal getLow() { return low; } public void setLow(BigDecimal low) { this.low = low; } public BigDecimal getHigh() { return high; } public void setHigh(BigDecimal high) { this.high = high; } public double getChange() { return change1; } public void setChange(double change) { this.change1 = change; } public double getVolume() { return volume; } public void setVolume(double volume) { this.volume = volume; } @Override public int hashCode() { int hash = 0; hash += (this.symbol != null ? this.symbol.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof QuoteDataBeanImpl)) { return false; } QuoteDataBeanImpl other = (QuoteDataBeanImpl)object; if (this.symbol != other.symbol && (this.symbol == null || !this.symbol.equals(other.symbol))) return false; return true; } }
8,206
0
Create_ds/aries/samples/ariestrader/modules/ariestrader-entities/src/main/java/org/apache/aries/samples/ariestrader
Create_ds/aries/samples/ariestrader/modules/ariestrader-entities/src/main/java/org/apache/aries/samples/ariestrader/entities/OrderDataBeanImpl.java
/** * 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. */ package org.apache.aries.samples.ariestrader.entities; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.persistence.TableGenerator; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; import org.apache.aries.samples.ariestrader.util.Log; import org.apache.aries.samples.ariestrader.util.TradeConfig; import org.apache.aries.samples.ariestrader.api.persistence.AccountDataBean; import org.apache.aries.samples.ariestrader.api.persistence.HoldingDataBean; import org.apache.aries.samples.ariestrader.api.persistence.OrderDataBean; import org.apache.aries.samples.ariestrader.api.persistence.QuoteDataBean; @Entity(name = "orderejb") @Table(name = "orderejb") @NamedQueries( { @NamedQuery(name = "orderejb.findByOrderfee", query = "SELECT o FROM orderejb o WHERE o.orderFee = :orderfee"), @NamedQuery(name = "orderejb.findByCompletiondate", query = "SELECT o FROM orderejb o WHERE o.completionDate = :completiondate"), @NamedQuery(name = "orderejb.findByOrdertype", query = "SELECT o FROM orderejb o WHERE o.orderType = :ordertype"), @NamedQuery(name = "orderejb.findByOrderstatus", query = "SELECT o FROM orderejb o WHERE o.orderStatus = :orderstatus"), @NamedQuery(name = "orderejb.findByPrice", query = "SELECT o FROM orderejb o WHERE o.price = :price"), @NamedQuery(name = "orderejb.findByQuantity", query = "SELECT o FROM orderejb o WHERE o.quantity = :quantity"), @NamedQuery(name = "orderejb.findByOpendate", query = "SELECT o FROM orderejb o WHERE o.openDate = :opendate"), @NamedQuery(name = "orderejb.findByOrderid", query = "SELECT o FROM orderejb o WHERE o.orderID = :orderid"), @NamedQuery(name = "orderejb.findByAccountAccountid", query = "SELECT o FROM orderejb o WHERE o.account.accountID = :accountAccountid"), @NamedQuery(name = "orderejb.findByQuoteSymbol", query = "SELECT o FROM orderejb o WHERE o.quote.symbol = :quoteSymbol"), @NamedQuery(name = "orderejb.findByHoldingHoldingid", query = "SELECT o FROM orderejb o WHERE o.holding.holdingID = :holdingHoldingid"), @NamedQuery(name = "orderejb.closedOrders", query = "SELECT o FROM orderejb o WHERE o.orderStatus = 'closed' AND o.account.profile.userID = :userID"), @NamedQuery(name = "orderejb.completeClosedOrders", query = "UPDATE orderejb o SET o.orderStatus = 'completed' WHERE o.orderStatus = 'closed' AND o.account.profile.userID = :userID") }) public class OrderDataBeanImpl implements OrderDataBean, Serializable { @TableGenerator(name = "orderIdGen", table = "KEYGENEJB", pkColumnName = "KEYNAME", valueColumnName = "KEYVAL", pkColumnValue = "order", allocationSize = 1000) @Id @GeneratedValue(strategy = GenerationType.TABLE, generator = "orderIdGen") @Column(name = "ORDERID", nullable = false) private Integer orderID; /* orderID */ @Column(name = "ORDERTYPE", length = 255) private String orderType; /* orderType (buy, sell, etc.) */ @Column(name = "ORDERSTATUS", length = 255) private String orderStatus; /* * orderStatus (open, processing, completed, * closed, canceled) */ @Column(name = "OPENDATE") @Temporal(TemporalType.TIMESTAMP) private Date openDate; /* openDate (when the order was entered) */ @Column(name = "COMPLETIONDATE") @Temporal(TemporalType.TIMESTAMP) private Date completionDate; /* completionDate */ @Column(name = "QUANTITY", nullable = false) private double quantity; /* quantity */ @Column(name = "PRICE") private BigDecimal price; /* price */ @Column(name = "ORDERFEE") private BigDecimal orderFee; /* price */ @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name="ACCOUNT_ACCOUNTID") private AccountDataBeanImpl account; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "QUOTE_SYMBOL", columnDefinition="VARCHAR(255)") private QuoteDataBeanImpl quote; @OneToOne(fetch = FetchType.LAZY) @JoinColumn(name = "HOLDING_HOLDINGID") private HoldingDataBeanImpl holding; @Transient private String symbol; public OrderDataBeanImpl() { } public OrderDataBeanImpl(Integer orderID, String orderType, String orderStatus, Date openDate, Date completionDate, double quantity, BigDecimal price, BigDecimal orderFee, String symbol) { setOrderID(orderID); setOrderType(orderType); setOrderStatus(orderStatus); setOpenDate(openDate); setCompletionDate(completionDate); setQuantity(quantity); setPrice(price); setOrderFee(orderFee); setSymbol(symbol); } public OrderDataBeanImpl(String orderType, String orderStatus, Date openDate, Date completionDate, double quantity, BigDecimal price, BigDecimal orderFee, AccountDataBean account, QuoteDataBean quote, HoldingDataBean holding) { setOrderType(orderType); setOrderStatus(orderStatus); setOpenDate(openDate); setCompletionDate(completionDate); setQuantity(quantity); setPrice(price); setOrderFee(orderFee); setAccount(account); setQuote(quote); setHolding(holding); } public static OrderDataBean getRandomInstance() { return new OrderDataBeanImpl(new Integer(TradeConfig.rndInt(100000)), TradeConfig.rndBoolean() ? "buy" : "sell", "open", new java.util.Date(TradeConfig.rndInt(Integer.MAX_VALUE)), new java.util.Date(TradeConfig.rndInt(Integer.MAX_VALUE)), TradeConfig.rndQuantity(), TradeConfig.rndBigDecimal(1000.0f), TradeConfig.rndBigDecimal(1000.0f), TradeConfig.rndSymbol()); } public String toString() { return "Order " + getOrderID() + "\n\t orderType: " + getOrderType() + "\n\t orderStatus: " + getOrderStatus() + "\n\t openDate: " + getOpenDate() + "\n\t completionDate: " + getCompletionDate() + "\n\t quantity: " + getQuantity() + "\n\t price: " + getPrice() + "\n\t orderFee: " + getOrderFee() + "\n\t symbol: " + getSymbol(); } public String toHTML() { return "<BR>Order <B>" + getOrderID() + "</B>" + "<LI> orderType: " + getOrderType() + "</LI>" + "<LI> orderStatus: " + getOrderStatus() + "</LI>" + "<LI> openDate: " + getOpenDate() + "</LI>" + "<LI> completionDate: " + getCompletionDate() + "</LI>" + "<LI> quantity: " + getQuantity() + "</LI>" + "<LI> price: " + getPrice() + "</LI>" + "<LI> orderFee: " + getOrderFee() + "</LI>" + "<LI> symbol: " + getSymbol() + "</LI>"; } public void print() { Log.log(this.toString()); } public Integer getOrderID() { return orderID; } public void setOrderID(Integer orderID) { this.orderID = orderID; } public String getOrderType() { return orderType; } public void setOrderType(String orderType) { this.orderType = orderType; } public String getOrderStatus() { return orderStatus; } public void setOrderStatus(String orderStatus) { this.orderStatus = orderStatus; } public Date getOpenDate() { return openDate; } public void setOpenDate(Date openDate) { this.openDate = openDate; } public Date getCompletionDate() { return completionDate; } public void setCompletionDate(Date completionDate) { this.completionDate = completionDate; } public double getQuantity() { return quantity; } public void setQuantity(double quantity) { this.quantity = quantity; } public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } public BigDecimal getOrderFee() { return orderFee; } public void setOrderFee(BigDecimal orderFee) { this.orderFee = orderFee; } public String getSymbol() { if (quote != null) { return quote.getSymbol(); } return symbol; } public void setSymbol(String symbol) { this.symbol = symbol; } public AccountDataBean getAccount() { return account; } public void setAccount(AccountDataBean account) { this.account = (AccountDataBeanImpl) account; } public QuoteDataBean getQuote() { return quote; } public void setQuote(QuoteDataBean quote) { this.quote = (QuoteDataBeanImpl) quote; } public HoldingDataBean getHolding() { return holding; } public void setHolding(HoldingDataBean holding) { this.holding = (HoldingDataBeanImpl) holding; } public boolean isBuy() { String orderType = getOrderType(); if (orderType.compareToIgnoreCase("buy") == 0) return true; return false; } public boolean isSell() { String orderType = getOrderType(); if (orderType.compareToIgnoreCase("sell") == 0) return true; return false; } public boolean isOpen() { String orderStatus = getOrderStatus(); if ((orderStatus.compareToIgnoreCase("open") == 0) || (orderStatus.compareToIgnoreCase("processing") == 0)) return true; return false; } public boolean isCompleted() { String orderStatus = getOrderStatus(); if ((orderStatus.compareToIgnoreCase("completed") == 0) || (orderStatus.compareToIgnoreCase("alertcompleted") == 0) || (orderStatus.compareToIgnoreCase("cancelled") == 0)) return true; return false; } public boolean isCancelled() { String orderStatus = getOrderStatus(); if (orderStatus.compareToIgnoreCase("cancelled") == 0) return true; return false; } public void cancel() { setOrderStatus("cancelled"); } @Override public int hashCode() { int hash = 0; hash += (this.orderID != null ? this.orderID.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are // not set if (!(object instanceof OrderDataBeanImpl)) { return false; } OrderDataBeanImpl other = (OrderDataBeanImpl) object; if (this.orderID != other.orderID && (this.orderID == null || !this.orderID.equals(other.orderID))) return false; return true; } }
8,207
0
Create_ds/aries/samples/ariestrader/modules/ariestrader-persist-jpa-am/src/main/java/org/apache/aries/samples/ariestrader/persist/jpa
Create_ds/aries/samples/ariestrader/modules/ariestrader-persist-jpa-am/src/main/java/org/apache/aries/samples/ariestrader/persist/jpa/am/TradeJpaAm.java
/** * 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. */ package org.apache.aries.samples.ariestrader.persist.jpa.am; import java.math.BigDecimal; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Query; import org.apache.aries.samples.ariestrader.api.TradeServices; import org.apache.aries.samples.ariestrader.entities.AccountDataBeanImpl; import org.apache.aries.samples.ariestrader.entities.AccountProfileDataBeanImpl; import org.apache.aries.samples.ariestrader.entities.HoldingDataBeanImpl; import org.apache.aries.samples.ariestrader.entities.OrderDataBeanImpl; import org.apache.aries.samples.ariestrader.entities.QuoteDataBeanImpl; import org.apache.aries.samples.ariestrader.api.persistence.AccountDataBean; import org.apache.aries.samples.ariestrader.api.persistence.AccountProfileDataBean; import org.apache.aries.samples.ariestrader.api.persistence.HoldingDataBean; import org.apache.aries.samples.ariestrader.api.persistence.MarketSummaryDataBean; import org.apache.aries.samples.ariestrader.api.persistence.OrderDataBean; import org.apache.aries.samples.ariestrader.api.persistence.QuoteDataBean; import org.apache.aries.samples.ariestrader.util.FinancialUtils; import org.apache.aries.samples.ariestrader.util.Log; import org.apache.aries.samples.ariestrader.util.TradeConfig; /** * TradeJpaAm uses JPA via a Application Managed (AM) * entity managers to implement the business methods of the * Trade online broker application. These business methods * represent the features and operations that can be performed * by customers of the brokerage such as login, logout, get a * stock quote, buy or sell a stock, etc. and are specified in * the {@link * org.apache.aries.samples.ariestrader.TradeServices} * interface * * @see org.apache.aries.samples.ariestrader.TradeServices * */ public class TradeJpaAm implements TradeServices { // @PersistenceUnit(unitName="ariestrader-am") private static EntityManagerFactory emf; private static boolean initialized = false; /** * Zero arg constructor for TradeJpaAm */ public TradeJpaAm() { } public void setEmf (EntityManagerFactory emf) { this.emf = emf; } public void init() { if (initialized) return; if (Log.doTrace()) Log.trace("TradeJpaAm:init -- *** initializing"); if (Log.doTrace()) Log.trace("TradeJpaAm:init -- +++ initialized"); initialized = true; } public void destroy() { try { if (!initialized) return; Log.trace("TradeJpaAm:destroy"); } catch (Exception e) { Log.error("TradeJpaAm:destroy", e); } } public MarketSummaryDataBean getMarketSummary() { MarketSummaryDataBean marketSummaryData; /* * Creating entiManager */ EntityManager entityManager = emf.createEntityManager(); try { if (Log.doTrace()) Log.trace("TradeJpaAm:getMarketSummary -- getting market summary"); // Find Trade Stock Index Quotes (Top 100 quotes) // ordered by their change in value Collection<QuoteDataBean> quotes; Query query = entityManager.createNamedQuery("quoteejb.quotesByChange"); quotes = query.getResultList(); QuoteDataBean[] quoteArray = (QuoteDataBean[]) quotes.toArray(new QuoteDataBean[quotes.size()]); ArrayList<QuoteDataBean> topGainers = new ArrayList<QuoteDataBean>( 5); ArrayList<QuoteDataBean> topLosers = new ArrayList<QuoteDataBean>(5); BigDecimal TSIA = FinancialUtils.ZERO; BigDecimal openTSIA = FinancialUtils.ZERO; double totalVolume = 0.0; if (quoteArray.length > 5) { for (int i = 0; i < 5; i++) topGainers.add(quoteArray[i]); for (int i = quoteArray.length - 1; i >= quoteArray.length - 5; i--) topLosers.add(quoteArray[i]); for (QuoteDataBean quote : quoteArray) { BigDecimal price = quote.getPrice(); BigDecimal open = quote.getOpen(); double volume = quote.getVolume(); TSIA = TSIA.add(price); openTSIA = openTSIA.add(open); totalVolume += volume; } TSIA = TSIA.divide(new BigDecimal(quoteArray.length), FinancialUtils.ROUND); openTSIA = openTSIA.divide(new BigDecimal(quoteArray.length), FinancialUtils.ROUND); } marketSummaryData = new MarketSummaryDataBean(TSIA, openTSIA, totalVolume, topGainers, topLosers); } catch (Exception e) { Log.error("TradeJpaAm:getMarketSummary", e); throw new RuntimeException("TradeJpaAm:getMarketSummary -- error ", e); } /* * closing entitymanager */ entityManager.close(); return marketSummaryData; } public OrderDataBean buy(String userID, String symbol, double quantity, int orderProcessingMode) { OrderDataBean order = null; BigDecimal total; /* * creating entitymanager */ EntityManager entityManager = emf.createEntityManager(); try { if (Log.doTrace()) Log.trace("TradeJpaAm:buy", userID, symbol, quantity, orderProcessingMode); entityManager.getTransaction().begin(); AccountProfileDataBeanImpl profile = entityManager.find(AccountProfileDataBeanImpl.class, userID); AccountDataBean account = profile.getAccount(); QuoteDataBeanImpl quote = entityManager.find(QuoteDataBeanImpl.class, symbol); HoldingDataBeanImpl holding = null; // The holding will be created by this buy order order = createOrder( account, (QuoteDataBean) quote, (HoldingDataBean) holding, "buy", quantity, entityManager); // order = createOrder(account, quote, holding, "buy", quantity); // UPDATE - account should be credited during completeOrder BigDecimal price = quote.getPrice(); BigDecimal orderFee = order.getOrderFee(); BigDecimal balance = account.getBalance(); total = (new BigDecimal(quantity).multiply(price)).add(orderFee); account.setBalance(balance.subtract(total)); // commit the transaction before calling completeOrder entityManager.getTransaction().commit(); if (orderProcessingMode == TradeConfig.SYNCH) completeOrder(order.getOrderID(), false); else if (orderProcessingMode == TradeConfig.ASYNCH_2PHASE) queueOrder(order.getOrderID(), true); } catch (Exception e) { Log.error("TradeJpaAm:buy(" + userID + "," + symbol + "," + quantity + ") --> failed", e); /* On exception - cancel the order */ // TODO figure out how to do this with JPA if (order != null) order.cancel(); entityManager.getTransaction().rollback(); // throw new EJBException(e); throw new RuntimeException(e); } if (entityManager != null) { entityManager.close(); entityManager = null; } // after the purchase or sale of a stock, update the stocks volume and // price updateQuotePriceVolume(symbol, TradeConfig.getRandomPriceChangeFactor(), quantity); return order; } public OrderDataBean sell(String userID, Integer holdingID, int orderProcessingMode) { EntityManager entityManager = emf.createEntityManager(); OrderDataBean order = null; BigDecimal total; try { entityManager.getTransaction().begin(); if (Log.doTrace()) Log.trace("TradeJpaAm:sell", userID, holdingID, orderProcessingMode); AccountProfileDataBeanImpl profile = entityManager.find(AccountProfileDataBeanImpl.class, userID); AccountDataBean account = profile.getAccount(); HoldingDataBeanImpl holding = entityManager.find(HoldingDataBeanImpl.class, holdingID); if (holding == null) { Log.error("TradeJpaAm:sell User " + userID + " attempted to sell holding " + holdingID + " which has already been sold"); OrderDataBean orderData = new OrderDataBeanImpl(); orderData.setOrderStatus("cancelled"); entityManager.persist(orderData); entityManager.getTransaction().commit(); if (entityManager != null) { entityManager.close(); entityManager = null; } return orderData; } QuoteDataBean quote = holding.getQuote(); double quantity = holding.getQuantity(); order = createOrder(account, quote, holding, "sell", quantity, entityManager); // UPDATE the holding purchase data to signify this holding is // "inflight" to be sold // -- could add a new holdingStatus attribute to holdingEJB holding.setPurchaseDate(new java.sql.Timestamp(0)); // UPDATE - account should be credited during completeOrder BigDecimal price = quote.getPrice(); BigDecimal orderFee = order.getOrderFee(); BigDecimal balance = account.getBalance(); total = (new BigDecimal(quantity).multiply(price)).subtract(orderFee); account.setBalance(balance.add(total)); // commit the transaction before calling completeOrder entityManager.getTransaction().commit(); if (orderProcessingMode == TradeConfig.SYNCH) completeOrder(order.getOrderID(), false); else if (orderProcessingMode == TradeConfig.ASYNCH_2PHASE) queueOrder(order.getOrderID(), true); } catch (Exception e) { Log.error("TradeJpaAm:sell(" + userID + "," + holdingID + ") --> failed", e); // TODO figure out JPA cancel if (order != null) order.cancel(); entityManager.getTransaction().rollback(); throw new RuntimeException("TradeJpaAm:sell(" + userID + "," + holdingID + ")", e); } if (entityManager != null) { entityManager.close(); entityManager = null; } if (!(order.getOrderStatus().equalsIgnoreCase("cancelled"))) //after the purchase or sell of a stock, update the stocks volume and price updateQuotePriceVolume(order.getSymbol(), TradeConfig.getRandomPriceChangeFactor(), order.getQuantity()); return order; } public void queueOrder(Integer orderID, boolean twoPhase) { Log .error("TradeJpaAm:queueOrder() not implemented for this runtime mode"); throw new UnsupportedOperationException( "TradeJpaAm:queueOrder() not implemented for this runtime mode"); } public OrderDataBean completeOrder(Integer orderID, boolean twoPhase) throws Exception { EntityManager entityManager = emf.createEntityManager(); OrderDataBeanImpl order = null; if (Log.doTrace()) Log.trace("TradeJpaAm:completeOrder", orderID + " twoPhase=" + twoPhase); order = entityManager.find(OrderDataBeanImpl.class, orderID); order.getQuote(); if (order == null) { Log.error("TradeJpaAm:completeOrder -- Unable to find Order " + orderID + " FBPK returned " + order); return null; } if (order.isCompleted()) { throw new RuntimeException("Error: attempt to complete Order that is already completed\n" + order); } AccountDataBean account = order.getAccount(); QuoteDataBean quote = order.getQuote(); HoldingDataBean holding = order.getHolding(); BigDecimal price = order.getPrice(); double quantity = order.getQuantity(); if (Log.doTrace()) Log.trace("TradeJpaAm:completeOrder--> Completing Order " + order.getOrderID() + "\n\t Order info: " + order + "\n\t Account info: " + account + "\n\t Quote info: " + quote + "\n\t Holding info: " + holding); HoldingDataBean newHolding = null; if (order.isBuy()) { /* * Complete a Buy operation - create a new Holding for the Account - * deduct the Order cost from the Account balance */ newHolding = createHolding(account, quote, quantity, price, entityManager); } try { entityManager.getTransaction().begin(); if (newHolding != null) { order.setHolding(newHolding); } if (order.isSell()) { /* * Complete a Sell operation - remove the Holding from the Account - * deposit the Order proceeds to the Account balance */ if (holding == null) { Log.error("TradeJpaAm:completeOrder -- Unable to sell order " + order.getOrderID() + " holding already sold"); order.cancel(); entityManager.getTransaction().commit(); return order; } else { entityManager.remove(holding); order.setHolding(null); } } order.setOrderStatus("closed"); order.setCompletionDate(new java.sql.Timestamp(System.currentTimeMillis())); if (Log.doTrace()) Log.trace("TradeJpaAm:completeOrder--> Completed Order " + order.getOrderID() + "\n\t Order info: " + order + "\n\t Account info: " + account + "\n\t Quote info: " + quote + "\n\t Holding info: " + holding); entityManager.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); entityManager.getTransaction().rollback(); } if (entityManager != null) { entityManager.close(); entityManager = null; } return order; } public void cancelOrder(Integer orderID, boolean twoPhase) { EntityManager entityManager = emf.createEntityManager(); if (Log.doTrace()) Log.trace("TradeJpaAm:cancelOrder", orderID + " twoPhase=" + twoPhase); OrderDataBeanImpl order = entityManager.find(OrderDataBeanImpl.class, orderID); /* * managed transaction */ try { entityManager.getTransaction().begin(); order.cancel(); entityManager.getTransaction().commit(); } catch (Exception e) { entityManager.getTransaction().rollback(); entityManager.close(); entityManager = null; } entityManager.close(); } public void orderCompleted(String userID, Integer orderID) { if (Log.doActionTrace()) Log.trace("TradeAction:orderCompleted", userID, orderID); if (Log.doTrace()) Log.trace("OrderCompleted", userID, orderID); } public Collection<OrderDataBean> getOrders(String userID) { if (Log.doTrace()) Log.trace("TradeJpaAm:getOrders", userID); EntityManager entityManager = emf.createEntityManager(); AccountProfileDataBeanImpl profile = entityManager.find(AccountProfileDataBeanImpl.class, userID); AccountDataBean account = profile.getAccount(); entityManager.close(); return account.getOrders(); } public Collection<OrderDataBean> getClosedOrders(String userID) { if (Log.doTrace()) Log.trace("TradeJpaAm:getClosedOrders", userID); EntityManager entityManager = emf.createEntityManager(); try { // Get the primary keys for all the closed Orders for this // account. /* * managed transaction */ entityManager.getTransaction().begin(); Query query = entityManager.createNamedQuery("orderejb.closedOrders"); query.setParameter("userID", userID); entityManager.getTransaction().commit(); Collection results = query.getResultList(); Iterator itr = results.iterator(); // Spin through the orders to populate the lazy quote fields while (itr.hasNext()) { OrderDataBeanImpl thisOrder = (OrderDataBeanImpl) itr.next(); thisOrder.getQuote(); } if (TradeConfig.jpaLayer == TradeConfig.OPENJPA) { Query updateStatus = entityManager.createNamedQuery("orderejb.completeClosedOrders"); /* * managed transaction */ try { entityManager.getTransaction().begin(); updateStatus.setParameter("userID", userID); updateStatus.executeUpdate(); entityManager.getTransaction().commit(); } catch (Exception e) { entityManager.getTransaction().rollback(); entityManager.close(); entityManager = null; } } else if (TradeConfig.jpaLayer == TradeConfig.HIBERNATE) { /* * Add logic to do update orders operation, because JBoss5' * Hibernate 3.3.1GA DB2Dialect and MySQL5Dialect do not work * with annotated query "orderejb.completeClosedOrders" defined * in OrderDatabean */ Query findaccountid = entityManager.createNativeQuery( "select " + "a.ACCOUNTID, " + "a.LOGINCOUNT, " + "a.LOGOUTCOUNT, " + "a.LASTLOGIN, " + "a.CREATIONDATE, " + "a.BALANCE, " + "a.OPENBALANCE, " + "a.PROFILE_USERID " + "from accountejb a where a.profile_userid = ?", org.apache.aries.samples.ariestrader.entities.AccountDataBeanImpl.class); findaccountid.setParameter(1, userID); AccountDataBeanImpl account = (AccountDataBeanImpl) findaccountid.getSingleResult(); Integer accountid = account.getAccountID(); Query updateStatus = entityManager.createNativeQuery("UPDATE orderejb o SET o.orderStatus = 'completed' WHERE " + "o.orderStatus = 'closed' AND o.ACCOUNT_ACCOUNTID = ?"); updateStatus.setParameter(1, accountid.intValue()); updateStatus.executeUpdate(); } if (entityManager != null) { entityManager.close(); entityManager = null; } return results; } catch (Exception e) { Log.error("TradeJpaAm.getClosedOrders", e); entityManager.close(); entityManager = null; throw new RuntimeException( "TradeJpaAm.getClosedOrders - error", e); } } public QuoteDataBean createQuote(String symbol, String companyName, BigDecimal price) { EntityManager entityManager = emf.createEntityManager(); try { QuoteDataBeanImpl quote = new QuoteDataBeanImpl(symbol, companyName, 0, price, price, price, price, 0); /* * managed transaction */ try { entityManager.getTransaction().begin(); entityManager.persist(quote); entityManager.getTransaction().commit(); } catch (Exception e) { entityManager.getTransaction().rollback(); } if (Log.doTrace()) Log.trace("TradeJpaAm:createQuote-->" + quote); if (entityManager != null) { entityManager.close(); entityManager = null; } return quote; } catch (Exception e) { Log.error("TradeJpaAm:createQuote -- exception creating Quote", e); entityManager.close(); entityManager = null; throw new RuntimeException(e); } } public QuoteDataBean getQuote(String symbol) { if (Log.doTrace()) Log.trace("TradeJpaAm:getQuote", symbol); EntityManager entityManager = emf.createEntityManager(); QuoteDataBeanImpl qdb = entityManager.find(QuoteDataBeanImpl.class, symbol); if (entityManager != null) { entityManager.close(); entityManager = null; } return qdb; } public Collection<QuoteDataBean> getAllQuotes() { if (Log.doTrace()) Log.trace("TradeJpaAm:getAllQuotes"); EntityManager entityManager = emf.createEntityManager(); Query query = entityManager.createNamedQuery("quoteejb.allQuotes"); if (entityManager != null) { entityManager.close(); entityManager = null; } return query.getResultList(); } public QuoteDataBean updateQuotePriceVolume(String symbol, BigDecimal changeFactor, double sharesTraded) { if (!TradeConfig.getUpdateQuotePrices()) { return new QuoteDataBeanImpl(); } if (Log.doTrace()) Log.trace("TradeJpaAm:updateQuote", symbol, changeFactor); /* * Add logic to determine JPA layer, because JBoss5' Hibernate 3.3.1GA * DB2Dialect and MySQL5Dialect do not work with annotated query * "quoteejb.quoteForUpdate" defined in QuoteDataBeanImpl */ EntityManager entityManager = emf.createEntityManager(); QuoteDataBeanImpl quote = null; if (TradeConfig.jpaLayer == TradeConfig.HIBERNATE) { quote = entityManager.find(QuoteDataBeanImpl.class, symbol); } else if (TradeConfig.jpaLayer == TradeConfig.OPENJPA) { Query q = entityManager.createNamedQuery("quoteejb.quoteForUpdate"); q.setParameter(1, symbol); quote = (QuoteDataBeanImpl) q.getSingleResult(); } BigDecimal oldPrice = quote.getPrice(); if (quote.getPrice().equals(TradeConfig.PENNY_STOCK_PRICE)) { changeFactor = TradeConfig.PENNY_STOCK_RECOVERY_MIRACLE_MULTIPLIER; } BigDecimal newPrice = changeFactor.multiply(oldPrice).setScale(2, BigDecimal.ROUND_HALF_UP); /* * managed transaction */ try { quote.setPrice(newPrice); quote.setVolume(quote.getVolume() + sharesTraded); quote.setChange((newPrice.subtract(quote.getOpen()).doubleValue())); if (newPrice.compareTo(quote.getHigh()) == 1) quote.setHigh(newPrice); else if (newPrice.compareTo(quote.getLow()) == -1) quote.setLow(newPrice); entityManager.getTransaction().begin(); entityManager.merge(quote); entityManager.getTransaction().commit(); } catch (Exception e) { entityManager.getTransaction().rollback(); } if (entityManager != null) { entityManager.close(); entityManager = null; } this.publishQuotePriceChange(quote, oldPrice, changeFactor, sharesTraded); return quote; } public Collection<HoldingDataBean> getHoldings(String userID) { if (Log.doTrace()) Log.trace("TradeJpaAm:getHoldings", userID); EntityManager entityManager = emf.createEntityManager(); /* * managed transaction */ entityManager.getTransaction().begin(); Query query = entityManager.createNamedQuery("holdingejb.holdingsByUserID"); query.setParameter("userID", userID); entityManager.getTransaction().commit(); Collection<HoldingDataBean> holdings = query.getResultList(); /* * Inflate the lazy data members */ Iterator itr = holdings.iterator(); while (itr.hasNext()) { ((HoldingDataBean) itr.next()).getQuote(); } entityManager.close(); entityManager = null; return holdings; } public HoldingDataBean getHolding(Integer holdingID) { if (Log.doTrace()) Log.trace("TradeJpaAm:getHolding", holdingID); EntityManager entityManager = emf.createEntityManager(); return entityManager.find(HoldingDataBeanImpl.class, holdingID); } public AccountDataBean getAccountData(String userID) { if (Log.doTrace()) Log.trace("TradeJpaAm:getAccountData", userID); EntityManager entityManager = emf.createEntityManager(); AccountProfileDataBeanImpl profile = entityManager.find(AccountProfileDataBeanImpl.class, userID); /* * Inflate the lazy data memebers */ AccountDataBean account = profile.getAccount(); account.getProfile(); // Added to populate transient field for account account.setProfileID(profile.getUserID()); entityManager.close(); entityManager = null; return account; } public AccountProfileDataBean getAccountProfileData(String userID) { if (Log.doTrace()) Log.trace("TradeJpaAm:getProfileData", userID); EntityManager entityManager = emf.createEntityManager(); AccountProfileDataBeanImpl apb = entityManager.find(AccountProfileDataBeanImpl.class, userID); entityManager.close(); entityManager = null; return apb; } public AccountProfileDataBean updateAccountProfile(String userID, String password, String fullName, String address, String email, String creditcard) throws Exception { EntityManager entityManager = emf.createEntityManager(); if (Log.doTrace()) Log.trace("TradeJpaAm:updateAccountProfileData", userID); /* * // Retrieve the previous account profile in order to get account * data... hook it into new object AccountProfileDataBean temp = * entityManager.find(AccountProfileDataBean.class, * profileData.getUserID()); // In order for the object to merge * correctly, the account has to be hooked into the temp object... // - * may need to reverse this and obtain the full object first * * profileData.setAccount(temp.getAccount()); * * //TODO this might not be correct temp = * entityManager.merge(profileData); //System.out.println(temp); */ AccountProfileDataBeanImpl temp = entityManager.find(AccountProfileDataBeanImpl.class, userID); temp.setAddress(address); temp.setPassword(password); temp.setFullName(fullName); temp.setCreditCard(creditcard); temp.setEmail(email); /* * Managed Transaction */ try { entityManager.getTransaction().begin(); entityManager.merge(temp); entityManager.getTransaction().commit(); entityManager.close(); } catch (Exception e) { entityManager.getTransaction().rollback(); entityManager.close(); entityManager = null; } return temp; } public AccountDataBean login(String userID, String password) throws Exception { EntityManager entityManager = emf.createEntityManager(); AccountProfileDataBeanImpl profile = entityManager.find(AccountProfileDataBeanImpl.class, userID); if (profile == null) { throw new RuntimeException("No such user: " + userID); } /* * Managed Transaction */ entityManager.getTransaction().begin(); entityManager.merge(profile); AccountDataBean account = profile.getAccount(); if (Log.doTrace()) Log.trace("TradeJpaAm:login", userID, password); account.login(password); entityManager.getTransaction().commit(); if (Log.doTrace()) Log.trace("TradeJpaAm:login(" + userID + "," + password + ") success" + account); entityManager.close(); return account; } public void logout(String userID) { if (Log.doTrace()) Log.trace("TradeJpaAm:logout", userID); EntityManager entityManager = emf.createEntityManager(); AccountProfileDataBeanImpl profile = entityManager.find(AccountProfileDataBeanImpl.class, userID); AccountDataBean account = profile.getAccount(); /* * Managed Transaction */ try { entityManager.getTransaction().begin(); account.logout(); entityManager.getTransaction().commit(); entityManager.close(); } catch (Exception e) { entityManager.getTransaction().rollback(); entityManager.close(); entityManager = null; } if (Log.doTrace()) Log.trace("TradeJpaAm:logout(" + userID + ") success"); } public AccountDataBean register(String userID, String password, String fullname, String address, String email, String creditcard, BigDecimal openBalance) { AccountDataBeanImpl account = null; AccountProfileDataBeanImpl profile = null; EntityManager entityManager = emf.createEntityManager(); if (Log.doTrace()) Log.trace("TradeJpaAm:register", userID, password, fullname, address, email, creditcard, openBalance); // Check to see if a profile with the desired userID already exists profile = entityManager.find(AccountProfileDataBeanImpl.class, userID); if (profile != null) { Log.error("Failed to register new Account - AccountProfile with userID(" + userID + ") already exists"); return null; } else { profile = new AccountProfileDataBeanImpl(userID, password, fullname, address, email, creditcard); account = new AccountDataBeanImpl(0, 0, null, new Timestamp(System.currentTimeMillis()), openBalance, openBalance, userID); profile.setAccount((AccountDataBean)account); account.setProfile((AccountProfileDataBean)profile); /* * managed Transaction */ try { entityManager.getTransaction().begin(); entityManager.persist(profile); entityManager.persist(account); entityManager.getTransaction().commit(); } catch (Exception e) { entityManager.getTransaction().rollback(); entityManager.close(); entityManager = null; } } return account; } /* * NO LONGER USE */ private void publishQuotePriceChange(QuoteDataBean quote, BigDecimal oldPrice, BigDecimal changeFactor, double sharesTraded) { if (!TradeConfig.getPublishQuotePriceChange()) return; Log.error("TradeJpaAm:publishQuotePriceChange - is not implemented for this runtime mode"); throw new UnsupportedOperationException("TradeJpaAm:publishQuotePriceChange - is not implemented for this runtime mode"); } /* * new Method() that takes EntityManager as a parameter */ private OrderDataBean createOrder(AccountDataBean account, QuoteDataBean quote, HoldingDataBean holding, String orderType, double quantity, EntityManager entityManager) { OrderDataBeanImpl order; if (Log.doTrace()) Log.trace("TradeJpaAm:createOrder(orderID=" + " account=" + ((account == null) ? null : account.getAccountID()) + " quote=" + ((quote == null) ? null : quote.getSymbol()) + " orderType=" + orderType + " quantity=" + quantity); try { order = new OrderDataBeanImpl(orderType, "open", new Timestamp(System.currentTimeMillis()), null, quantity, quote.getPrice().setScale(FinancialUtils.SCALE, FinancialUtils.ROUND), TradeConfig.getOrderFee(orderType), account, quote, holding); entityManager.persist(order); } catch (Exception e) { Log.error("TradeJpaAm:createOrder -- failed to create Order", e); throw new RuntimeException("TradeJpaAm:createOrder -- failed to create Order", e); } return order; } private HoldingDataBean createHolding(AccountDataBean account, QuoteDataBean quote, double quantity, BigDecimal purchasePrice, EntityManager entityManager) throws Exception { HoldingDataBeanImpl newHolding = new HoldingDataBeanImpl(quantity, purchasePrice, new Timestamp(System.currentTimeMillis()), account, quote); try { /* * manage transactions */ entityManager.getTransaction().begin(); entityManager.persist(newHolding); entityManager.getTransaction().commit(); } catch (Exception e) { entityManager.getTransaction().rollback(); entityManager.close(); entityManager = null; } return newHolding; } public double investmentReturn(double investment, double NetValue) throws Exception { if (Log.doTrace()) Log.trace("TradeJpaAm:investmentReturn"); double diff = NetValue - investment; double ir = diff / investment; return ir; } public QuoteDataBean pingTwoPhase(String symbol) throws Exception { Log .error("TradeJpaAm:pingTwoPhase - is not implemented for this runtime mode"); throw new UnsupportedOperationException("TradeJpaAm:pingTwoPhase - is not implemented for this runtime mode"); } class quotePriceComparator implements java.util.Comparator { public int compare(Object quote1, Object quote2) { double change1 = ((QuoteDataBean) quote1).getChange(); double change2 = ((QuoteDataBean) quote2).getChange(); return new Double(change2).compareTo(change1); } } /** * Get mode - returns the persistence mode (TradeConfig.JPA) * * @return TradeConfig.ModeType */ public TradeConfig.ModeType getMode() { return TradeConfig.ModeType.JPA_AM; } }
8,208
0
Create_ds/aries/samples/ariestrader/modules/ariestrader-persist-jdbc/src/main/java/org/apache/aries/samples/ariestrader/persist
Create_ds/aries/samples/ariestrader/modules/ariestrader-persist-jdbc/src/main/java/org/apache/aries/samples/ariestrader/persist/jdbc/KeySequenceDirect.java
/** * 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. */ package org.apache.aries.samples.ariestrader.persist.jdbc; import java.util.Collection; import java.util.Iterator; import java.util.HashMap; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import org.apache.aries.samples.ariestrader.util.*; public class KeySequenceDirect { private static HashMap keyMap = new HashMap(); public static synchronized Integer getNextID(Connection conn, String keyName, boolean inSession, boolean inGlobalTxn) throws Exception { Integer nextID = null; // First verify we have allocated a block of keys // for this key name // Then verify the allocated block has not been depleted // allocate a new block if necessary if (keyMap.containsKey(keyName) == false) allocNewBlock(conn, keyName, inSession, inGlobalTxn); Collection block = (Collection) keyMap.get(keyName); Iterator ids = block.iterator(); if (ids.hasNext() == false) ids = allocNewBlock(conn, keyName, inSession, inGlobalTxn).iterator(); // get and return a new unique key nextID = (Integer) ids.next(); if (Log.doTrace()) Log.trace("KeySequenceDirect:getNextID inSession(" + inSession + ") - return new PK ID for Entity type: " + keyName + " ID=" + nextID); return nextID; } private static Collection allocNewBlock(Connection conn, String keyName, boolean inSession, boolean inGlobalTxn) throws Exception { try { if (inGlobalTxn == false && !inSession) conn.commit(); // commit any pending txns PreparedStatement stmt = conn.prepareStatement(getKeyForUpdateSQL); stmt.setString(1, keyName); ResultSet rs = stmt.executeQuery(); if (!rs.next()) { // No keys found for this name - create a new one PreparedStatement stmt2 = conn.prepareStatement(createKeySQL); int keyVal = 0; stmt2.setString(1, keyName); stmt2.setInt(2, keyVal); stmt2.executeUpdate(); stmt2.close(); stmt.close(); stmt = conn.prepareStatement(getKeyForUpdateSQL); stmt.setString(1, keyName); rs = stmt.executeQuery(); rs.next(); } int keyVal = rs.getInt("keyval"); stmt.close(); stmt = conn.prepareStatement(updateKeyValueSQL); stmt.setInt(1, keyVal + TradeConfig.KEYBLOCKSIZE); stmt.setString(2, keyName); stmt.executeUpdate(); stmt.close(); Collection block = new KeyBlock(keyVal, keyVal + TradeConfig.KEYBLOCKSIZE - 1); keyMap.put(keyName, block); if (inGlobalTxn == false && !inSession) conn.commit(); return block; } catch (Exception e) { String error = "KeySequenceDirect:allocNewBlock - failure to allocate new block of keys for Entity type: " + keyName; Log.error(e, error); throw new Exception(error + e.toString()); } } private static final String getKeyForUpdateSQL = "select * from keygenejb kg where kg.keyname = ? for update"; private static final String createKeySQL = "insert into keygenejb " + "( keyname, keyval ) " + "VALUES ( ? , ? )"; private static final String updateKeyValueSQL = "update keygenejb set keyval = ? " + "where keyname = ?"; }
8,209
0
Create_ds/aries/samples/ariestrader/modules/ariestrader-persist-jdbc/src/main/java/org/apache/aries/samples/ariestrader/persist
Create_ds/aries/samples/ariestrader/modules/ariestrader-persist-jdbc/src/main/java/org/apache/aries/samples/ariestrader/persist/jdbc/TradeJdbc.java
/** * 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. */ package org.apache.aries.samples.ariestrader.persist.jdbc; import java.math.BigDecimal; import java.util.Collection; import java.util.ArrayList; import javax.sql.DataSource; import org.apache.aries.samples.ariestrader.api.TradeServices; import org.apache.aries.samples.ariestrader.beans.AccountDataBeanImpl; import org.apache.aries.samples.ariestrader.beans.AccountProfileDataBeanImpl; import org.apache.aries.samples.ariestrader.beans.HoldingDataBeanImpl; import org.apache.aries.samples.ariestrader.beans.OrderDataBeanImpl; import org.apache.aries.samples.ariestrader.beans.QuoteDataBeanImpl; import org.apache.aries.samples.ariestrader.api.persistence.AccountDataBean; import org.apache.aries.samples.ariestrader.api.persistence.AccountProfileDataBean; import org.apache.aries.samples.ariestrader.api.persistence.HoldingDataBean; import org.apache.aries.samples.ariestrader.api.persistence.MarketSummaryDataBean; import org.apache.aries.samples.ariestrader.api.persistence.OrderDataBean; import org.apache.aries.samples.ariestrader.api.persistence.QuoteDataBean; import org.apache.aries.samples.ariestrader.util.FinancialUtils; import org.apache.aries.samples.ariestrader.util.Log; import org.apache.aries.samples.ariestrader.util.ServiceUtilities; import org.apache.aries.samples.ariestrader.util.TradeConfig; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Timestamp; /** * TradeJdbc uses direct JDBC access to a * <code>javax.sql.DataSource</code> to implement the business methods of the * Trade online broker application. These business methods represent the * features and operations that can be performed by customers of the brokerage * such as login, logout, get a stock quote, buy or sell a stock, etc. and are * specified in the {@link org.apache.aries.samples.ariestrader.TradeServices} * interface * * Note: In order for this class to be thread-safe, a new TradeJDBC must be * created for each call to a method from the TradeInterface interface. * Otherwise, pooled connections may not be released. * * @see org.apache.aries.samples.ariestrader.TradeServices * */ public class TradeJdbc implements TradeServices { private DataSource dataSource= null; private static BigDecimal ZERO = new BigDecimal(0.0); private boolean inGlobalTxn = false; private boolean inSession = false; private static int connCount = 0; private static Integer lock = new Integer(0); private static boolean initialized = false; /** * Zero arg constructor for TradeJdbc */ public TradeJdbc() { } public TradeJdbc(boolean inSession) { this.inSession = inSession; } /** * set data source */ public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } /** * setInSession */ public void setInSession(boolean inSession) { this.inSession = inSession; } /** * @see TradeServices#getMarketSummary() */ public MarketSummaryDataBean getMarketSummary() throws Exception { MarketSummaryDataBean marketSummaryData = null; Connection conn = null; try { if (Log.doTrace()) Log.trace("TradeJdbc:getMarketSummary - inSession(" + this.inSession + ")"); conn = getConn(); PreparedStatement stmt = getStatement(conn, getTSIAQuotesOrderByChangeSQL, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ArrayList topGainersData = new ArrayList(5); ArrayList topLosersData = new ArrayList(5); ResultSet rs = stmt.executeQuery(); int count = 0; while (rs.next() && (count++ < 5)) { QuoteDataBean quoteData = getQuoteDataFromResultSet(rs); topLosersData.add(quoteData); } stmt.close(); stmt = getStatement(conn, "select * from quoteejb q where q.symbol like 's:1__' order by q.change1 DESC", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); rs = stmt.executeQuery(); count = 0; while (rs.next() && (count++ < 5)) { QuoteDataBean quoteData = getQuoteDataFromResultSet(rs); topGainersData.add(quoteData); } stmt.close(); BigDecimal TSIA = ZERO; BigDecimal openTSIA = ZERO; double volume = 0.0; if ((topGainersData.size() > 0) || (topLosersData.size() > 0)) { stmt = getStatement(conn, getTSIASQL); rs = stmt.executeQuery(); if (!rs.next()) Log.error("TradeJdbc:getMarketSummary -- error w/ getTSIASQL -- no results"); else TSIA = rs.getBigDecimal("TSIA"); stmt.close(); stmt = getStatement(conn, getOpenTSIASQL); rs = stmt.executeQuery(); if (!rs.next()) Log.error("TradeJdbc:getMarketSummary -- error w/ getOpenTSIASQL -- no results"); else openTSIA = rs.getBigDecimal("openTSIA"); stmt.close(); stmt = getStatement(conn, getTSIATotalVolumeSQL); rs = stmt.executeQuery(); if (!rs.next()) Log.error("TradeJdbc:getMarketSummary -- error w/ getTSIATotalVolumeSQL -- no results"); else volume = rs.getDouble("totalVolume"); stmt.close(); } commit(conn); marketSummaryData = new MarketSummaryDataBean(TSIA, openTSIA, volume, topGainersData, topLosersData); } catch (Exception e) { Log.error("TradeJdbc:getMarketSummary -- error getting summary", e); rollBack(conn, e); } finally { releaseConn(conn); } return marketSummaryData; } /** * @see TradeServices#buy(String, String, double) */ public OrderDataBean buy(String userID, String symbol, double quantity, int orderProcessingMode) throws Exception { Connection conn = null; OrderDataBean orderData = null; /* * total = (quantity * purchasePrice) + orderFee */ BigDecimal total; try { if (Log.doTrace()) Log.trace("TradeJdbc:buy - inSession(" + this.inSession + ")", userID, symbol, new Double(quantity)); conn = getConn(); AccountDataBean accountData = getAccountData(conn, userID); QuoteDataBean quoteData = getQuoteData(conn, symbol); HoldingDataBean holdingData = null; // the buy operation will create // the holding orderData = createOrder(conn, accountData, quoteData, holdingData, "buy", quantity); // Update -- account should be credited during completeOrder BigDecimal price = quoteData.getPrice(); BigDecimal orderFee = orderData.getOrderFee(); total = (new BigDecimal(quantity).multiply(price)).add(orderFee); // subtract total from account balance creditAccountBalance(conn, accountData, total.negate()); completeOrder(conn, orderData.getOrderID()); orderData = getOrderData(conn, orderData.getOrderID().intValue()); commit(conn); } catch (Exception e) { Log.error("TradeJdbc:buy error - rolling back", e); rollBack(conn, e); } finally { releaseConn(conn); } //after the purchase or sale of a stock, update the stocks volume and // price updateQuotePriceVolume(symbol, TradeConfig.getRandomPriceChangeFactor(), quantity); return orderData; } /** * @see TradeServices#sell(String, Integer) */ public OrderDataBean sell(String userID, Integer holdingID, int orderProcessingMode) throws Exception { Connection conn = null; OrderDataBean orderData = null; /* * total = (quantity * purchasePrice) + orderFee */ BigDecimal total; try { if (Log.doTrace()) Log.trace("TradeJdbc:sell - inSession(" + this.inSession + ")", userID, holdingID); conn = getConn(); AccountDataBean accountData = getAccountData(conn, userID); HoldingDataBean holdingData = getHoldingData(conn, holdingID.intValue()); QuoteDataBean quoteData = null; if (holdingData != null) quoteData = getQuoteData(conn, holdingData.getQuoteID()); if ((accountData == null) || (holdingData == null) || (quoteData == null)) { String error = "TradeJdbc:sell -- error selling stock -- unable to find: \n\taccount=" + accountData + "\n\tholding=" + holdingData + "\n\tquote=" + quoteData + "\nfor user: " + userID + " and holdingID: " + holdingID; Log.error(error); rollBack(conn, new Exception(error)); return orderData; } double quantity = holdingData.getQuantity(); orderData = createOrder(conn, accountData, quoteData, holdingData, "sell", quantity); // Set the holdingSymbol purchaseDate to selling to signify the sell // is "inflight" updateHoldingStatus(conn, holdingData.getHoldingID(), holdingData.getQuoteID()); // UPDATE -- account should be credited during completeOrder BigDecimal price = quoteData.getPrice(); BigDecimal orderFee = orderData.getOrderFee(); total = (new BigDecimal(quantity).multiply(price)).subtract(orderFee); creditAccountBalance(conn, accountData, total); completeOrder(conn, orderData.getOrderID()); orderData = getOrderData(conn, orderData.getOrderID().intValue()); commit(conn); } catch (Exception e) { Log.error("TradeJdbc:sell error", e); rollBack(conn, e); } finally { releaseConn(conn); } if (!(orderData.getOrderStatus().equalsIgnoreCase("cancelled"))) //after the purchase or sell of a stock, update the stocks volume // and price updateQuotePriceVolume(orderData.getSymbol(), TradeConfig.getRandomPriceChangeFactor(), orderData.getQuantity()); return orderData; } /** * @see TradeServices#queueOrder(Integer) */ public void queueOrder(Integer orderID, boolean twoPhase) throws Exception { throw new RuntimeException("TradeServices#queueOrder(Integer) is not supported in this runtime mode"); } /** * @see TradeServices#completeOrder(Integer) */ public OrderDataBean completeOrder(Integer orderID, boolean twoPhase) throws Exception { OrderDataBean orderData = null; Connection conn = null; try { // twoPhase if (Log.doTrace()) Log.trace("TradeJdbc:completeOrder - inSession(" + this.inSession + ")", orderID); setInGlobalTxn(!inSession && twoPhase); conn = getConn(); orderData = completeOrder(conn, orderID); commit(conn); } catch (Exception e) { Log.error("TradeJdbc:completeOrder -- error completing order", e); rollBack(conn, e); cancelOrder(orderID, twoPhase); } finally { releaseConn(conn); } return orderData; } private OrderDataBean completeOrder(Connection conn, Integer orderID) throws Exception { OrderDataBean orderData = null; if (Log.doTrace()) Log.trace("TradeJdbc:completeOrderInternal - inSession(" + this.inSession + ")", orderID); PreparedStatement stmt = getStatement(conn, getOrderSQL); stmt.setInt(1, orderID.intValue()); ResultSet rs = stmt.executeQuery(); if (!rs.next()) { Log.error("TradeJdbc:completeOrder -- unable to find order: " + orderID); stmt.close(); return orderData; } orderData = getOrderDataFromResultSet(rs); String orderType = orderData.getOrderType(); String orderStatus = orderData.getOrderStatus(); // if (order.isCompleted()) if ((orderStatus.compareToIgnoreCase("completed") == 0) || (orderStatus.compareToIgnoreCase("alertcompleted") == 0) || (orderStatus.compareToIgnoreCase("cancelled") == 0)) throw new Exception("TradeJdbc:completeOrder -- attempt to complete Order that is already completed"); int accountID = rs.getInt("account_accountID"); String quoteID = rs.getString("quote_symbol"); int holdingID = rs.getInt("holding_holdingID"); BigDecimal price = orderData.getPrice(); double quantity = orderData.getQuantity(); BigDecimal orderFee = orderData.getOrderFee(); // get the data for the account and quote // the holding will be created for a buy or extracted for a sell /* * Use the AccountID and Quote Symbol from the Order AccountDataBean accountData = getAccountData(accountID, * conn); QuoteDataBean quoteData = getQuoteData(conn, quoteID); */ String userID = getAccountProfileData(conn, new Integer(accountID)).getUserID(); HoldingDataBean holdingData = null; if (Log.doTrace()) Log.trace("TradeJdbc:completeOrder--> Completing Order " + orderData.getOrderID() + "\n\t Order info: " + orderData + "\n\t Account info: " + accountID + "\n\t Quote info: " + quoteID); // if (order.isBuy()) if (orderType.compareToIgnoreCase("buy") == 0) { /* * Complete a Buy operation - create a new Holding for the Account - deduct the Order cost from the Account * balance */ holdingData = createHolding(conn, accountID, quoteID, quantity, price); updateOrderHolding(conn, orderID.intValue(), holdingData.getHoldingID().intValue()); } // if (order.isSell()) { if (orderType.compareToIgnoreCase("sell") == 0) { /* * Complete a Sell operation - remove the Holding from the Account - deposit the Order proceeds to the * Account balance */ holdingData = getHoldingData(conn, holdingID); if (holdingData == null) Log.debug("TradeJdbc:completeOrder:sell -- user: " + userID + " already sold holding: " + holdingID); else removeHolding(conn, holdingID, orderID.intValue()); } updateOrderStatus(conn, orderData.getOrderID(), "closed"); if (Log.doTrace()) Log.trace("TradeJdbc:completeOrder--> Completed Order " + orderData.getOrderID() + "\n\t Order info: " + orderData + "\n\t Account info: " + accountID + "\n\t Quote info: " + quoteID + "\n\t Holding info: " + holdingData); stmt.close(); commit(conn); // signify this order for user userID is complete orderCompleted(userID, orderID); return orderData; } /** * @see TradeServices#cancelOrder(Integer, boolean) */ public void cancelOrder(Integer orderID, boolean twoPhase) throws Exception { Connection conn = null; try { if (Log.doTrace()) Log.trace("TradeJdbc:cancelOrder - inSession(" + this.inSession + ")", orderID); setInGlobalTxn(!inSession && twoPhase); conn = getConn(); cancelOrder(conn, orderID); commit(conn); } catch (Exception e) { Log.error("TradeJdbc:cancelOrder -- error cancelling order: " + orderID, e); rollBack(conn, e); } finally { releaseConn(conn); } } private void cancelOrder(Connection conn, Integer orderID) throws Exception { updateOrderStatus(conn, orderID, "cancelled"); } public void orderCompleted(String userID, Integer orderID) throws Exception { // throw new UnsupportedOperationException("TradeJdbc:orderCompleted method not supported"); if (Log.doTrace()) Log.trace("OrderCompleted", userID, orderID); } private HoldingDataBean createHolding(Connection conn, int accountID, String symbol, double quantity, BigDecimal purchasePrice) throws Exception { Timestamp purchaseDate = new Timestamp(System.currentTimeMillis()); PreparedStatement stmt = getStatement(conn, createHoldingSQL); Integer holdingID = KeySequenceDirect.getNextID(conn, "holding", inSession, getInGlobalTxn()); stmt.setInt(1, holdingID.intValue()); stmt.setTimestamp(2, purchaseDate); stmt.setBigDecimal(3, purchasePrice); stmt.setDouble(4, quantity); stmt.setString(5, symbol); stmt.setInt(6, accountID); stmt.executeUpdate(); stmt.close(); return getHoldingData(conn, holdingID.intValue()); } private void removeHolding(Connection conn, int holdingID, int orderID) throws Exception { PreparedStatement stmt = getStatement(conn, removeHoldingSQL); stmt.setInt(1, holdingID); stmt.executeUpdate(); stmt.close(); // set the HoldingID to NULL for the purchase and sell order now that // the holding as been removed stmt = getStatement(conn, removeHoldingFromOrderSQL); stmt.setInt(1, holdingID); stmt.executeUpdate(); stmt.close(); } private OrderDataBean createOrder(Connection conn, AccountDataBean accountData, QuoteDataBean quoteData, HoldingDataBean holdingData, String orderType, double quantity) throws Exception { Timestamp currentDate = new Timestamp(System.currentTimeMillis()); PreparedStatement stmt = getStatement(conn, createOrderSQL); Integer orderID = KeySequenceDirect.getNextID(conn, "order", inSession, getInGlobalTxn()); stmt.setInt(1, orderID.intValue()); stmt.setString(2, orderType); stmt.setString(3, "open"); stmt.setTimestamp(4, currentDate); stmt.setDouble(5, quantity); stmt.setBigDecimal(6, quoteData.getPrice().setScale(FinancialUtils.SCALE, FinancialUtils.ROUND)); stmt.setBigDecimal(7, TradeConfig.getOrderFee(orderType)); stmt.setInt(8, accountData.getAccountID().intValue()); if (holdingData == null) stmt.setNull(9, java.sql.Types.INTEGER); else stmt.setInt(9, holdingData.getHoldingID().intValue()); stmt.setString(10, quoteData.getSymbol()); stmt.executeUpdate(); stmt.close(); return getOrderData(conn, orderID.intValue()); } /** * @see TradeServices#getOrders(String) */ public Collection getOrders(String userID) throws Exception { Collection orderDataBeans = new ArrayList(); Connection conn = null; try { if (Log.doTrace()) Log.trace("TradeJdbc:getOrders - inSession(" + this.inSession + ")", userID); conn = getConn(); PreparedStatement stmt = getStatement(conn, getOrdersByUserSQL); stmt.setString(1, userID); ResultSet rs = stmt.executeQuery(); // TODO: return top 5 orders for now -- next version will add a // getAllOrders method // also need to get orders sorted by order id descending int i = 0; while ((rs.next()) && (i++ < 5)) { OrderDataBean orderData = getOrderDataFromResultSet(rs); orderDataBeans.add(orderData); } stmt.close(); commit(conn); } catch (Exception e) { Log.error("TradeJdbc:getOrders -- error getting user orders", e); rollBack(conn, e); } finally { releaseConn(conn); } return orderDataBeans; } /** * @see TradeServices#getClosedOrders(String) */ public Collection getClosedOrders(String userID) throws Exception { Collection orderDataBeans = new ArrayList(); Connection conn = null; try { if (Log.doTrace()) Log.trace("TradeJdbc:getClosedOrders - inSession(" + this.inSession + ")", userID); conn = getConn(); PreparedStatement stmt = getStatement(conn, getClosedOrdersSQL); stmt.setString(1, userID); ResultSet rs = stmt.executeQuery(); while (rs.next()) { OrderDataBean orderData = getOrderDataFromResultSet(rs); orderData.setOrderStatus("completed"); updateOrderStatus(conn, orderData.getOrderID(), orderData.getOrderStatus()); orderDataBeans.add(orderData); } stmt.close(); commit(conn); } catch (Exception e) { Log.error("TradeJdbc:getOrders -- error getting user orders", e); rollBack(conn, e); } finally { releaseConn(conn); } return orderDataBeans; } /** * @see TradeServices#createQuote(String, String, BigDecimal) */ public QuoteDataBean createQuote(String symbol, String companyName, BigDecimal price) throws Exception { QuoteDataBean quoteData = null; Connection conn = null; try { if (Log.doTrace()) Log.traceEnter("TradeJdbc:createQuote - inSession(" + this.inSession + ")"); price = price.setScale(FinancialUtils.SCALE, FinancialUtils.ROUND); double volume = 0.0, change = 0.0; conn = getConn(); PreparedStatement stmt = getStatement(conn, createQuoteSQL); stmt.setString(1, symbol); // symbol stmt.setString(2, companyName); // companyName stmt.setDouble(3, volume); // volume stmt.setBigDecimal(4, price); // price stmt.setBigDecimal(5, price); // open stmt.setBigDecimal(6, price); // low stmt.setBigDecimal(7, price); // high stmt.setDouble(8, change); // change stmt.executeUpdate(); stmt.close(); commit(conn); quoteData = new QuoteDataBeanImpl(symbol, companyName, volume, price, price, price, price, change); if (Log.doTrace()) Log.traceExit("TradeJdbc:createQuote"); } catch (Exception e) { Log.error("TradeJdbc:createQuote -- error creating quote", e); } finally { releaseConn(conn); } return quoteData; } /** * @see TradeServices#getQuote(String) */ public QuoteDataBean getQuote(String symbol) throws Exception { QuoteDataBean quoteData = null; Connection conn = null; if ((symbol == null) || (symbol.length() == 0) || (symbol.length() > 10)) { if (Log.doTrace()) { Log.trace("TradeJdbc:getQuote --- primitive workload"); } return new QuoteDataBeanImpl("Invalid symbol", "", 0.0, FinancialUtils.ZERO, FinancialUtils.ZERO, FinancialUtils.ZERO, FinancialUtils.ZERO, 0.0); } try { if (Log.doTrace()) Log.trace("TradeJdbc:getQuote - inSession(" + this.inSession + ")", symbol); conn = getConn(); quoteData = getQuote(conn, symbol); commit(conn); } catch (Exception e) { Log.error("TradeJdbc:getQuote -- error getting quote", e); rollBack(conn, e); } finally { releaseConn(conn); } return quoteData; } private QuoteDataBean getQuote(Connection conn, String symbol) throws Exception { QuoteDataBean quoteData = null; PreparedStatement stmt = getStatement(conn, getQuoteSQL); stmt.setString(1, symbol); // symbol ResultSet rs = stmt.executeQuery(); if (!rs.next()) Log.error("TradeJdbc:getQuote -- failure no result.next() for symbol: " + symbol); else quoteData = getQuoteDataFromResultSet(rs); stmt.close(); return quoteData; } private QuoteDataBean getQuoteForUpdate(Connection conn, String symbol) throws Exception { QuoteDataBean quoteData = null; PreparedStatement stmt = getStatement(conn, getQuoteForUpdateSQL); stmt.setString(1, symbol); // symbol ResultSet rs = stmt.executeQuery(); if (!rs.next()) Log.error("TradeJdbc:getQuote -- failure no result.next()"); else quoteData = getQuoteDataFromResultSet(rs); stmt.close(); return quoteData; } /** * @see TradeServices#getAllQuotes(String) */ public Collection getAllQuotes() throws Exception { Collection quotes = new ArrayList(); QuoteDataBean quoteData = null; Connection conn = null; if (Log.doTrace()) Log.trace("TradeJdbc:getAllQuotes"); try { conn = getConn(); PreparedStatement stmt = getStatement(conn, getAllQuotesSQL); ResultSet rs = stmt.executeQuery(); while (!rs.next()) { quoteData = getQuoteDataFromResultSet(rs); quotes.add(quoteData); } stmt.close(); } catch (Exception e) { Log.error("TradeJdbc:getAllQuotes", e); rollBack(conn, e); } finally { releaseConn(conn); } return quotes; } /** * @see TradeServices#getHoldings(String) */ public Collection getHoldings(String userID) throws Exception { Collection holdingDataBeans = new ArrayList(); Connection conn = null; try { if (Log.doTrace()) Log.trace("TradeJdbc:getHoldings - inSession(" + this.inSession + ")", userID); conn = getConn(); PreparedStatement stmt = getStatement(conn, getHoldingsForUserSQL); stmt.setString(1, userID); ResultSet rs = stmt.executeQuery(); while (rs.next()) { HoldingDataBean holdingData = getHoldingDataFromResultSet(rs); holdingDataBeans.add(holdingData); } stmt.close(); commit(conn); } catch (Exception e) { Log.error("TradeJdbc:getHoldings -- error getting user holings", e); rollBack(conn, e); } finally { releaseConn(conn); } return holdingDataBeans; } /** * @see TradeServices#getHolding(Integer) */ public HoldingDataBean getHolding(Integer holdingID) throws Exception { HoldingDataBean holdingData = null; Connection conn = null; try { if (Log.doTrace()) Log.trace("TradeJdbc:getHolding - inSession(" + this.inSession + ")", holdingID); conn = getConn(); holdingData = getHoldingData(holdingID.intValue()); commit(conn); } catch (Exception e) { Log.error("TradeJdbc:getHolding -- error getting holding " + holdingID + "", e); rollBack(conn, e); } finally { releaseConn(conn); } return holdingData; } /** * @see TradeServices#getAccountData(String) */ public AccountDataBean getAccountData(String userID) throws Exception { try { AccountDataBean accountData = null; Connection conn = null; try { if (Log.doTrace()) Log.trace("TradeJdbc:getAccountData - inSession(" + this.inSession + ")", userID); conn = getConn(); accountData = getAccountData(conn, userID); commit(conn); } catch (Exception e) { Log.error("TradeJdbc:getAccountData -- error getting account data", e); rollBack(conn, e); } finally { releaseConn(conn); } return accountData; } catch (Exception e) { throw new Exception(e.getMessage(), e); } } private AccountDataBean getAccountData(Connection conn, String userID) throws Exception { PreparedStatement stmt = getStatement(conn, getAccountForUserSQL); stmt.setString(1, userID); ResultSet rs = stmt.executeQuery(); AccountDataBean accountData = getAccountDataFromResultSet(rs); stmt.close(); return accountData; } private AccountDataBean getAccountDataForUpdate(Connection conn, String userID) throws Exception { PreparedStatement stmt = getStatement(conn, getAccountForUserForUpdateSQL); stmt.setString(1, userID); ResultSet rs = stmt.executeQuery(); AccountDataBean accountData = getAccountDataFromResultSet(rs); stmt.close(); return accountData; } /** * @see TradeServices#getAccountData(String) */ public AccountDataBean getAccountData(int accountID) throws Exception { AccountDataBean accountData = null; Connection conn = null; try { if (Log.doTrace()) Log.trace("TradeJdbc:getAccountData - inSession(" + this.inSession + ")", new Integer(accountID)); conn = getConn(); accountData = getAccountData(accountID, conn); commit(conn); } catch (Exception e) { Log.error("TradeJdbc:getAccountData -- error getting account data", e); rollBack(conn, e); } finally { releaseConn(conn); } return accountData; } private AccountDataBean getAccountData(int accountID, Connection conn) throws Exception { PreparedStatement stmt = getStatement(conn, getAccountSQL); stmt.setInt(1, accountID); ResultSet rs = stmt.executeQuery(); AccountDataBean accountData = getAccountDataFromResultSet(rs); stmt.close(); return accountData; } private QuoteDataBean getQuoteData(Connection conn, String symbol) throws Exception { QuoteDataBean quoteData = null; PreparedStatement stmt = getStatement(conn, getQuoteSQL); stmt.setString(1, symbol); ResultSet rs = stmt.executeQuery(); if (!rs.next()) Log.error("TradeJdbc:getQuoteData -- could not find quote for symbol=" + symbol); else quoteData = getQuoteDataFromResultSet(rs); stmt.close(); return quoteData; } private HoldingDataBean getHoldingData(int holdingID) throws Exception { HoldingDataBean holdingData = null; Connection conn = null; try { conn = getConn(); holdingData = getHoldingData(conn, holdingID); commit(conn); } catch (Exception e) { Log.error("TradeJdbc:getHoldingData -- error getting data", e); rollBack(conn, e); } finally { releaseConn(conn); } return holdingData; } private HoldingDataBean getHoldingData(Connection conn, int holdingID) throws Exception { HoldingDataBean holdingData = null; PreparedStatement stmt = getStatement(conn, getHoldingSQL); stmt.setInt(1, holdingID); ResultSet rs = stmt.executeQuery(); if (!rs.next()) Log.error("TradeJdbc:getHoldingData -- no results -- holdingID=" + holdingID); else holdingData = getHoldingDataFromResultSet(rs); stmt.close(); return holdingData; } private OrderDataBean getOrderData(Connection conn, int orderID) throws Exception { OrderDataBean orderData = null; if (Log.doTrace()) Log.trace("TradeJdbc:getOrderData(conn, " + orderID + ")"); PreparedStatement stmt = getStatement(conn, getOrderSQL); stmt.setInt(1, orderID); ResultSet rs = stmt.executeQuery(); if (!rs.next()) Log.error("TradeJdbc:getOrderData -- no results for orderID:" + orderID); else orderData = getOrderDataFromResultSet(rs); stmt.close(); return orderData; } /** * @see TradeServices#getAccountProfileData(String) */ public AccountProfileDataBean getAccountProfileData(String userID) throws Exception { AccountProfileDataBean accountProfileData = null; Connection conn = null; try { if (Log.doTrace()) Log.trace("TradeJdbc:getAccountProfileData - inSession(" + this.inSession + ")", userID); conn = getConn(); accountProfileData = getAccountProfileData(conn, userID); commit(conn); } catch (Exception e) { Log.error("TradeJdbc:getAccountProfileData -- error getting profile data", e); rollBack(conn, e); } finally { releaseConn(conn); } return accountProfileData; } private AccountProfileDataBean getAccountProfileData(Connection conn, String userID) throws Exception { PreparedStatement stmt = getStatement(conn, getAccountProfileSQL); stmt.setString(1, userID); ResultSet rs = stmt.executeQuery(); AccountProfileDataBean accountProfileData = getAccountProfileDataFromResultSet(rs); stmt.close(); return accountProfileData; } private AccountProfileDataBean getAccountProfileData(Connection conn, Integer accountID) throws Exception { PreparedStatement stmt = getStatement(conn, getAccountProfileForAccountSQL); stmt.setInt(1, accountID.intValue()); ResultSet rs = stmt.executeQuery(); AccountProfileDataBean accountProfileData = getAccountProfileDataFromResultSet(rs); stmt.close(); return accountProfileData; } /** * @see TradeServices#updateAccountProfile(AccountProfileDataBean) */ public AccountProfileDataBean updateAccountProfile(String userID, String password, String fullName, String address, String email, String creditcard) throws Exception { AccountProfileDataBean accountProfileData = null; Connection conn = null; try { if (Log.doTrace()) Log.trace("TradeJdbc:updateAccountProfileData - inSession(" + this.inSession + ")", userID); conn = getConn(); updateAccountProfile(conn, userID, password, fullName, address, email, creditcard); accountProfileData = getAccountProfileData(conn, userID); commit(conn); } catch (Exception e) { Log.error("TradeJdbc:getAccountProfileData -- error getting profile data", e); rollBack(conn, e); } finally { releaseConn(conn); } return accountProfileData; } private void creditAccountBalance(Connection conn, AccountDataBean accountData, BigDecimal credit) throws Exception { PreparedStatement stmt = getStatement(conn, creditAccountBalanceSQL); stmt.setBigDecimal(1, credit); stmt.setInt(2, accountData.getAccountID().intValue()); stmt.executeUpdate(); stmt.close(); } // Set Timestamp to zero to denote sell is inflight // UPDATE -- could add a "status" attribute to holding private void updateHoldingStatus(Connection conn, Integer holdingID, String symbol) throws Exception { Timestamp ts = new Timestamp(0); PreparedStatement stmt = getStatement(conn, "update holdingejb set purchasedate= ? where holdingid = ?"); stmt.setTimestamp(1, ts); stmt.setInt(2, holdingID.intValue()); stmt.executeUpdate(); stmt.close(); } private void updateOrderStatus(Connection conn, Integer orderID, String status) throws Exception { PreparedStatement stmt = getStatement(conn, updateOrderStatusSQL); stmt.setString(1, status); stmt.setTimestamp(2, new Timestamp(System.currentTimeMillis())); stmt.setInt(3, orderID.intValue()); stmt.executeUpdate(); stmt.close(); } private void updateOrderHolding(Connection conn, int orderID, int holdingID) throws Exception { PreparedStatement stmt = getStatement(conn, updateOrderHoldingSQL); stmt.setInt(1, holdingID); stmt.setInt(2, orderID); stmt.executeUpdate(); stmt.close(); } private void updateAccountProfile(Connection conn, String userID, String password, String fullName, String address, String email, String creditcard) throws Exception { PreparedStatement stmt = getStatement(conn, updateAccountProfileSQL); stmt.setString(1, password); stmt.setString(2, fullName); stmt.setString(3, address); stmt.setString(4, email); stmt.setString(5, creditcard); stmt.setString(6, userID); stmt.executeUpdate(); stmt.close(); } public QuoteDataBean updateQuotePriceVolume(String symbol, BigDecimal changeFactor, double sharesTraded) throws Exception { if (Log.doTrace()) Log.trace("TradeJdbc:updateQuotePriceVolume", symbol, changeFactor, new Double(sharesTraded)); return updateQuotePriceVolumeInt(symbol, changeFactor, sharesTraded, TradeConfig.getPublishQuotePriceChange()); } /** * Update a quote's price and volume * * @param symbol * The PK of the quote * @param changeFactor * the percent to change the old price by (between 50% and 150%) * @param sharedTraded * the ammount to add to the current volume * @param publishQuotePriceChange * used by the PingJDBCWrite Primitive to ensure no JMS is used, should be true for all normal calls to * this API */ public QuoteDataBean updateQuotePriceVolumeInt(String symbol, BigDecimal changeFactor, double sharesTraded, boolean publishQuotePriceChange) throws Exception { if (TradeConfig.getUpdateQuotePrices() == false) return new QuoteDataBeanImpl(); QuoteDataBean quoteData = null; Connection conn = null; try { if (Log.doTrace()) Log.trace("TradeJdbc:updateQuotePriceVolume - inSession(" + this.inSession + ")", symbol, changeFactor, new Double(sharesTraded)); conn = getConn(); quoteData = getQuoteForUpdate(conn, symbol); BigDecimal oldPrice = quoteData.getPrice(); double newVolume = quoteData.getVolume() + sharesTraded; if (oldPrice.equals(TradeConfig.PENNY_STOCK_PRICE)) { changeFactor = TradeConfig.PENNY_STOCK_RECOVERY_MIRACLE_MULTIPLIER; } else if (oldPrice.compareTo(TradeConfig.MAXIMUM_STOCK_PRICE) > 0) { changeFactor = TradeConfig.MAXIMUM_STOCK_SPLIT_MULTIPLIER; } BigDecimal newPrice = changeFactor.multiply(oldPrice).setScale(2, BigDecimal.ROUND_HALF_UP); BigDecimal low = quoteData.getLow(); BigDecimal high= quoteData.getHigh(); if (newPrice.compareTo(high) == 1) high = newPrice; else if (newPrice.compareTo(low) == -1) low = newPrice; updateQuotePriceVolume(conn, quoteData.getSymbol(), newPrice, newVolume, low, high); quoteData = getQuote(conn, symbol); commit(conn); } catch (Exception e) { Log.error("TradeJdbc:updateQuotePriceVolume -- error updating quote price/volume for symbol:" + symbol); rollBack(conn, e); throw e; } finally { releaseConn(conn); } return quoteData; } private void updateQuotePriceVolume(Connection conn, String symbol, BigDecimal newPrice, double newVolume, BigDecimal low, BigDecimal high) throws Exception { PreparedStatement stmt = getStatement(conn, updateQuotePriceVolumeSQL); stmt.setBigDecimal(1, newPrice); stmt.setBigDecimal(2, newPrice); stmt.setDouble(3, newVolume); stmt.setBigDecimal(4, low); stmt.setBigDecimal(5, high); stmt.setString(6, symbol); stmt.executeUpdate(); stmt.close(); } /** * @see TradeServices#login(String, String) */ public AccountDataBean login(String userID, String password) throws Exception { AccountDataBean accountData = null; Connection conn = null; try { if (Log.doTrace()) Log.trace("TradeJdbc:login - inSession(" + this.inSession + ")", userID, password); conn = getConn(); PreparedStatement stmt = getStatement(conn, getAccountProfileSQL); stmt.setString(1, userID); ResultSet rs = stmt.executeQuery(); if (!rs.next()) { Log.error("TradeJdbc:login -- failure to find account for" + userID); throw new RuntimeException("Cannot find account for" + userID); } String pw = rs.getString("passwd"); stmt.close(); if ((pw == null) || (pw.equals(password) == false)) { String error = "TradeJdbc:Login failure for user: " + userID + "\n\tIncorrect password-->" + userID + ":" + password; Log.error(error); throw new Exception(error); } stmt = getStatement(conn, loginSQL); stmt.setTimestamp(1, new Timestamp(System.currentTimeMillis())); stmt.setString(2, userID); stmt.executeUpdate(); stmt.close(); stmt = getStatement(conn, getAccountForUserSQL); stmt.setString(1, userID); rs = stmt.executeQuery(); accountData = getAccountDataFromResultSet(rs); stmt.close(); commit(conn); } catch (Exception e) { Log.error("TradeJdbc:login -- error logging in user", e); rollBack(conn, e); } finally { releaseConn(conn); } return accountData; /* * setLastLogin( new Timestamp(System.currentTimeMillis()) ); setLoginCount( getLoginCount() + 1 ); */ } /** * @see TradeServices#logout(String) */ public void logout(String userID) throws Exception { Connection conn = null; if (Log.doTrace()) Log.trace("TradeJdbc:logout - inSession(" + this.inSession + ")", userID); try { conn = getConn(); PreparedStatement stmt = getStatement(conn, logoutSQL); stmt.setString(1, userID); stmt.executeUpdate(); stmt.close(); commit(conn); } catch (Exception e) { Log.error("TradeJdbc:logout -- error logging out user", e); rollBack(conn, e); } finally { releaseConn(conn); } } /** * @see TradeServices#register(String, String, String, String, String, String, BigDecimal, boolean) */ public AccountDataBean register(String userID, String password, String fullname, String address, String email, String creditCard, BigDecimal openBalance) throws Exception { AccountDataBean accountData = null; Connection conn = null; try { if (Log.doTrace()) Log.traceEnter("TradeJdbc:register - inSession(" + this.inSession + ")"); conn = getConn(); PreparedStatement stmt = getStatement(conn, createAccountSQL); Integer accountID = KeySequenceDirect.getNextID(conn, "account", inSession, getInGlobalTxn()); BigDecimal balance = openBalance; Timestamp creationDate = new Timestamp(System.currentTimeMillis()); Timestamp lastLogin = creationDate; int loginCount = 0; int logoutCount = 0; stmt.setInt(1, accountID.intValue()); stmt.setTimestamp(2, creationDate); stmt.setBigDecimal(3, openBalance); stmt.setBigDecimal(4, balance); stmt.setTimestamp(5, lastLogin); stmt.setInt(6, loginCount); stmt.setInt(7, logoutCount); stmt.setString(8, userID); stmt.executeUpdate(); stmt.close(); stmt = getStatement(conn, createAccountProfileSQL); stmt.setString(1, userID); stmt.setString(2, password); stmt.setString(3, fullname); stmt.setString(4, address); stmt.setString(5, email); stmt.setString(6, creditCard); stmt.executeUpdate(); stmt.close(); commit(conn); accountData = new AccountDataBeanImpl(accountID, loginCount, logoutCount, lastLogin, creationDate, balance, openBalance, userID); if (Log.doTrace()) Log.traceExit("TradeJdbc:register"); } catch (Exception e) { Log.error("TradeJdbc:register -- error registering new user", e); } finally { releaseConn(conn); } return accountData; } private AccountDataBean getAccountDataFromResultSet(ResultSet rs) throws Exception { AccountDataBean accountData = null; if (!rs.next()) Log.error("TradeJdbc:getAccountDataFromResultSet -- cannot find account data"); else accountData = new AccountDataBeanImpl(new Integer(rs.getInt("accountID")), rs.getInt("loginCount"), rs .getInt("logoutCount"), rs.getTimestamp("lastLogin"), rs.getTimestamp("creationDate"), rs .getBigDecimal("balance"), rs.getBigDecimal("openBalance"), rs.getString("profile_userID")); return accountData; } private AccountProfileDataBean getAccountProfileDataFromResultSet(ResultSet rs) throws Exception { AccountProfileDataBean accountProfileData = null; if (!rs.next()) Log.error("TradeJdbc:getAccountProfileDataFromResultSet -- cannot find accountprofile data"); else accountProfileData = new AccountProfileDataBeanImpl(rs.getString("userID"), rs.getString("passwd"), rs.getString("fullName"), rs .getString("address"), rs.getString("email"), rs.getString("creditCard")); return accountProfileData; } private HoldingDataBean getHoldingDataFromResultSet(ResultSet rs) throws Exception { HoldingDataBean holdingData = null; holdingData = new HoldingDataBeanImpl(new Integer(rs.getInt("holdingID")), rs.getDouble("quantity"), rs .getBigDecimal("purchasePrice"), rs.getTimestamp("purchaseDate"), rs.getString("quote_symbol")); return holdingData; } private QuoteDataBean getQuoteDataFromResultSet(ResultSet rs) throws Exception { QuoteDataBean quoteData = null; quoteData = new QuoteDataBeanImpl(rs.getString("symbol"), rs.getString("companyName"), rs.getDouble("volume"), rs .getBigDecimal("price"), rs.getBigDecimal("open1"), rs.getBigDecimal("low"), rs.getBigDecimal("high"), rs.getDouble("change1")); return quoteData; } private OrderDataBean getOrderDataFromResultSet(ResultSet rs) throws Exception { OrderDataBean orderData = null; orderData = new OrderDataBeanImpl(new Integer(rs.getInt("orderID")), rs.getString("orderType"), rs.getString("orderStatus"), rs.getTimestamp("openDate"), rs.getTimestamp("completionDate"), rs .getDouble("quantity"), rs.getBigDecimal("price"), rs.getBigDecimal("orderFee"), rs .getString("quote_symbol")); return orderData; } private void releaseConn(Connection conn) throws Exception { try { if (conn != null) { conn.close(); if (Log.doTrace()) { synchronized (lock) { connCount--; } Log.trace("TradeJdbc:releaseConn -- connection closed, connCount=" + connCount); } } } catch (Exception e) { Log.error("TradeJdbc:releaseConnection -- failed to close connection", e); } } /* * Lookup the TradeData DataSource */ private void lookupDataSource() throws Exception { if (dataSource == null) { dataSource = (DataSource) ServiceUtilities.getOSGIService(DataSource.class.getName(),TradeConfig.OSGI_DS_NAME_FILTER); } } /* * Allocate a new connection to the datasource */ private Connection getConn() throws Exception { Connection conn = null; lookupDataSource(); conn = dataSource.getConnection(); conn.setAutoCommit(false); if (Log.doTrace()) { synchronized (lock) { connCount++; } Log.trace("TradeJdbc:getConn -- new connection allocated, IsolationLevel=" + conn.getTransactionIsolation() + " connectionCount = " + connCount); } return conn; } /* * Commit the provided connection if not under Global Transaction scope - conn.commit() is not allowed in a global * transaction. the txn manager will perform the commit */ private void commit(Connection conn) throws Exception { if (!inSession) { if ((getInGlobalTxn() == false) && (conn != null)) conn.commit(); } } /* * Rollback the statement for the given connection */ private void rollBack(Connection conn, Exception e) throws Exception { if (!inSession) { Log.log("TradeJdbc:rollBack -- rolling back conn due to previously caught exception -- inGlobalTxn=" + getInGlobalTxn()); if ((getInGlobalTxn() == false) && (conn != null)) conn.rollback(); else throw e; // Throw the exception // so the Global txn manager will rollBack } } /* * Allocate a new prepared statment for this connection */ private PreparedStatement getStatement(Connection conn, String sql) throws Exception { return conn.prepareStatement(sql); } private PreparedStatement getStatement(Connection conn, String sql, int type, int concurrency) throws Exception { return conn.prepareStatement(sql, type, concurrency); } private static final String createQuoteSQL = "insert into quoteejb " + "( symbol, companyName, volume, price, open1, low, high, change1 ) " + "VALUES ( ? , ? , ? , ? , ? , ? , ? , ? )"; private static final String createAccountSQL = "insert into accountejb " + "( accountid, creationDate, openBalance, balance, lastLogin, loginCount, logoutCount, profile_userid) " + "VALUES ( ? , ? , ? , ? , ? , ? , ? , ? )"; private static final String createAccountProfileSQL = "insert into accountprofileejb " + "( userid, passwd, fullname, address, email, creditcard ) " + "VALUES ( ? , ? , ? , ? , ? , ? )"; private static final String createHoldingSQL = "insert into holdingejb " + "( holdingid, purchaseDate, purchasePrice, quantity, quote_symbol, account_accountid ) " + "VALUES ( ? , ? , ? , ? , ? , ? )"; private static final String createOrderSQL = "insert into orderejb " + "( orderid, ordertype, orderstatus, opendate, quantity, price, orderfee, account_accountid, holding_holdingid, quote_symbol) " + "VALUES ( ? , ? , ? , ? , ? , ? , ? , ? , ? , ?)"; private static final String removeHoldingSQL = "delete from holdingejb where holdingid = ?"; private static final String removeHoldingFromOrderSQL = "update orderejb set holding_holdingid=null where holding_holdingid = ?"; private final static String updateAccountProfileSQL = "update accountprofileejb set " + "passwd = ?, fullname = ?, address = ?, email = ?, creditcard = ? " + "where userid = (select profile_userid from accountejb a " + "where a.profile_userid=?)"; private final static String loginSQL = "update accountejb set lastLogin=?, logincount=logincount+1 " + "where profile_userid=?"; private static final String logoutSQL = "update accountejb set logoutcount=logoutcount+1 " + "where profile_userid=?"; private static final String getAccountSQL = "select * from accountejb a where a.accountid = ?"; private final static String getAccountProfileSQL = "select * from accountprofileejb ap where ap.userid = " + "(select profile_userid from accountejb a where a.profile_userid=?)"; private final static String getAccountProfileForAccountSQL = "select * from accountprofileejb ap where ap.userid = " + "(select profile_userid from accountejb a where a.accountid=?)"; private static final String getAccountForUserSQL = "select * from accountejb a where a.profile_userid = " + "( select userid from accountprofileejb ap where ap.userid = ?)"; private static final String getAccountForUserForUpdateSQL = "select * from accountejb a where a.profile_userid = " + "( select userid from accountprofileejb ap where ap.userid = ?) for update"; private static final String getHoldingSQL = "select * from holdingejb h where h.holdingid = ?"; private static final String getHoldingsForUserSQL = "select * from holdingejb h where h.account_accountid = " + "(select a.accountid from accountejb a where a.profile_userid = ?)"; private static final String getOrderSQL = "select * from orderejb o where o.orderid = ?"; private static final String getOrdersByUserSQL = "select * from orderejb o where o.account_accountid = " + "(select a.accountid from accountejb a where a.profile_userid = ?)"; private static final String getClosedOrdersSQL = "select * from orderejb o " + "where o.orderstatus = 'closed' AND o.account_accountid = " + "(select a.accountid from accountejb a where a.profile_userid = ?)"; private static final String getQuoteSQL = "select * from quoteejb q where q.symbol=?"; private static final String getAllQuotesSQL = "select * from quoteejb q"; private static final String getQuoteForUpdateSQL = "select * from quoteejb q where q.symbol=? For Update"; private static final String getTSIAQuotesOrderByChangeSQL = "select * from quoteejb q " + "where q.symbol like 's:1__' order by q.change1"; private static final String getTSIASQL = "select SUM(price)/count(*) as TSIA from quoteejb q " + "where q.symbol like 's:1__'"; private static final String getOpenTSIASQL = "select SUM(open1)/count(*) as openTSIA from quoteejb q " + "where q.symbol like 's:1__'"; private static final String getTSIATotalVolumeSQL = "select SUM(volume) as totalVolume from quoteejb q " + "where q.symbol like 's:1__'"; private static final String creditAccountBalanceSQL = "update accountejb set " + "balance = balance + ? " + "where accountid = ?"; private static final String updateOrderStatusSQL = "update orderejb set " + "orderstatus = ?, completiondate = ? " + "where orderid = ?"; private static final String updateOrderHoldingSQL = "update orderejb set " + "holding_holdingID = ? " + "where orderid = ?"; private static final String updateQuotePriceVolumeSQL = "update quoteejb set " + "price = ?, change1 = ? - open1, volume = ?, low = ?, high = ? " + "where symbol = ?"; public void init() { if (initialized) return; if (Log.doTrace()) Log.trace("TradeJdbc:init -- *** initializing"); if (Log.doTrace()) Log.trace("TradeJdbc:init -- +++ initialized"); initialized = true; } public void destroy() { try { if (!initialized) return; Log.trace("TradeJdbc:destroy"); } catch (Exception e) { Log.error("TradeJdbc:destroy", e); } } /** * Gets the inGlobalTxn * * @return Returns a boolean */ private boolean getInGlobalTxn() { return inGlobalTxn; } /** * Sets the inGlobalTxn * * @param inGlobalTxn * The inGlobalTxn to set */ private void setInGlobalTxn(boolean inGlobalTxn) { this.inGlobalTxn = inGlobalTxn; } /** * Get mode - returns the persistence mode (TradeConfig.JDBC) * * @return TradeConfig.ModeType */ public TradeConfig.ModeType getMode() { return TradeConfig.ModeType.JDBC; } }
8,210
0
Create_ds/aries/samples/ariestrader/modules/ariestrader-persist-jpa-cm/src/main/java/org/apache/aries/samples/ariestrader/persist/jpa
Create_ds/aries/samples/ariestrader/modules/ariestrader-persist-jpa-cm/src/main/java/org/apache/aries/samples/ariestrader/persist/jpa/cm/TradeJpaCm.java
/** * 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. */ package org.apache.aries.samples.ariestrader.persist.jpa.cm; import java.math.BigDecimal; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import javax.persistence.EntityManager; import javax.persistence.Query; import org.apache.aries.samples.ariestrader.api.TradeServices; import org.apache.aries.samples.ariestrader.entities.AccountDataBeanImpl; import org.apache.aries.samples.ariestrader.entities.AccountProfileDataBeanImpl; import org.apache.aries.samples.ariestrader.entities.HoldingDataBeanImpl; import org.apache.aries.samples.ariestrader.entities.OrderDataBeanImpl; import org.apache.aries.samples.ariestrader.entities.QuoteDataBeanImpl; import org.apache.aries.samples.ariestrader.api.persistence.AccountDataBean; import org.apache.aries.samples.ariestrader.api.persistence.AccountProfileDataBean; import org.apache.aries.samples.ariestrader.api.persistence.HoldingDataBean; import org.apache.aries.samples.ariestrader.api.persistence.MarketSummaryDataBean; import org.apache.aries.samples.ariestrader.api.persistence.OrderDataBean; import org.apache.aries.samples.ariestrader.api.persistence.QuoteDataBean; import org.apache.aries.samples.ariestrader.util.FinancialUtils; import org.apache.aries.samples.ariestrader.util.Log; import org.apache.aries.samples.ariestrader.util.TradeConfig; /** * TradeJpaCm uses JPA via Container Managed (CM) Entity * Managers to implement the business methods of the Trade * online broker application. These business methods represent * the features and operations that can be performed by * customers of the brokerage such as login, logout, get a stock * quote, buy or sell a stock, etc. and are specified in the * {@link org.apache.aries.samples.ariestrader.TradeServices} * interface * * @see org.apache.aries.samples.ariestrader.TradeServices * */ public class TradeJpaCm implements TradeServices { private EntityManager entityManager; private static boolean initialized = false; // @PersistenceContext(unitName="ariestrader-cm") public void setEntityManager (EntityManager em) { entityManager = em; } /** * Zero arg constructor for TradeJpaCm */ public TradeJpaCm() { } public void init() { if (initialized) return; if (Log.doTrace()) Log.trace("TradeJpaCm:init -- *** initializing"); if (Log.doTrace()) Log.trace("TradeJpaCm:init -- +++ initialized"); initialized = true; } public void destroy() { try { if (!initialized) return; Log.trace("TradeJpaCm:destroy"); } catch (Exception e) { Log.error("TradeJpaCm:destroy", e); } } public MarketSummaryDataBean getMarketSummary() { MarketSummaryDataBean marketSummaryData; try { if (Log.doTrace()) Log.trace("TradeJpaCm:getMarketSummary -- getting market summary"); // Find Trade Stock Index Quotes (Top 100 quotes) // ordered by their change in value Collection<QuoteDataBean> quotes; Query query = entityManager.createNamedQuery("quoteejb.quotesByChange"); quotes = query.getResultList(); QuoteDataBean[] quoteArray = (QuoteDataBean[]) quotes.toArray(new QuoteDataBean[quotes.size()]); ArrayList<QuoteDataBean> topGainers = new ArrayList<QuoteDataBean>( 5); ArrayList<QuoteDataBean> topLosers = new ArrayList<QuoteDataBean>(5); BigDecimal TSIA = FinancialUtils.ZERO; BigDecimal openTSIA = FinancialUtils.ZERO; double totalVolume = 0.0; if (quoteArray.length > 5) { for (int i = 0; i < 5; i++) topGainers.add(quoteArray[i]); for (int i = quoteArray.length - 1; i >= quoteArray.length - 5; i--) topLosers.add(quoteArray[i]); for (QuoteDataBean quote : quoteArray) { BigDecimal price = quote.getPrice(); BigDecimal open = quote.getOpen(); double volume = quote.getVolume(); TSIA = TSIA.add(price); openTSIA = openTSIA.add(open); totalVolume += volume; } TSIA = TSIA.divide(new BigDecimal(quoteArray.length), FinancialUtils.ROUND); openTSIA = openTSIA.divide(new BigDecimal(quoteArray.length), FinancialUtils.ROUND); } marketSummaryData = new MarketSummaryDataBean(TSIA, openTSIA, totalVolume, topGainers, topLosers); } catch (Exception e) { Log.error("TradeJpaCm:getMarketSummary", e); throw new RuntimeException("TradeJpaCm:getMarketSummary -- error ", e); } return marketSummaryData; } public OrderDataBean buy(String userID, String symbol, double quantity, int orderProcessingMode) throws Exception { OrderDataBean order = null; BigDecimal total; try { if (Log.doTrace()) Log.trace("TradeJpaCm:buy", userID, symbol, quantity, orderProcessingMode); AccountProfileDataBeanImpl profile = entityManager.find(AccountProfileDataBeanImpl.class, userID); AccountDataBean account = profile.getAccount(); QuoteDataBeanImpl quote = entityManager.find(QuoteDataBeanImpl.class, symbol); HoldingDataBeanImpl holding = null; // The holding will be created by this buy order order = createOrder( account, (QuoteDataBean) quote, (HoldingDataBean) holding, "buy", quantity); // order = createOrder(account, quote, holding, "buy", quantity); // UPDATE - account should be credited during completeOrder BigDecimal price = quote.getPrice(); BigDecimal orderFee = order.getOrderFee(); BigDecimal balance = account.getBalance(); total = (new BigDecimal(quantity).multiply(price)).add(orderFee); account.setBalance(balance.subtract(total)); if (orderProcessingMode == TradeConfig.SYNCH) completeOrder(order.getOrderID(), false); else if (orderProcessingMode == TradeConfig.ASYNCH_2PHASE) queueOrder(order.getOrderID(), true); } catch (Exception e) { Log.error("TradeJpaCm:buy(" + userID + "," + symbol + "," + quantity + ") --> failed", e); /* On exception - cancel the order */ // TODO figure out how to do this with JPA if (order != null) order.cancel(); throw new RuntimeException(e); } // after the purchase or sale of a stock, update the stocks volume and // price updateQuotePriceVolume(symbol, TradeConfig.getRandomPriceChangeFactor(), quantity); return order; } public OrderDataBean sell(String userID, Integer holdingID, int orderProcessingMode) throws Exception { OrderDataBean order = null; BigDecimal total; try { if (Log.doTrace()) Log.trace("TradeJpaCm:sell", userID, holdingID, orderProcessingMode); AccountProfileDataBeanImpl profile = entityManager.find(AccountProfileDataBeanImpl.class, userID); AccountDataBean account = profile.getAccount(); HoldingDataBeanImpl holding = entityManager.find(HoldingDataBeanImpl.class, holdingID); if (holding == null) { Log.error("TradeJpaCm:sell User " + userID + " attempted to sell holding " + holdingID + " which has already been sold"); OrderDataBean orderData = new OrderDataBeanImpl(); orderData.setOrderStatus("cancelled"); entityManager.persist(orderData); return orderData; } QuoteDataBean quote = holding.getQuote(); double quantity = holding.getQuantity(); order = createOrder(account, quote, holding, "sell", quantity); // UPDATE the holding purchase data to signify this holding is // "inflight" to be sold // -- could add a new holdingStatus attribute to holdingEJB holding.setPurchaseDate(new java.sql.Timestamp(0)); // UPDATE - account should be credited during completeOrder BigDecimal price = quote.getPrice(); BigDecimal orderFee = order.getOrderFee(); BigDecimal balance = account.getBalance(); total = (new BigDecimal(quantity).multiply(price)).subtract(orderFee); account.setBalance(balance.add(total)); if (orderProcessingMode == TradeConfig.SYNCH) completeOrder(order.getOrderID(), false); else if (orderProcessingMode == TradeConfig.ASYNCH_2PHASE) queueOrder(order.getOrderID(), true); } catch (Exception e) { Log.error("TradeJpaCm:sell(" + userID + "," + holdingID + ") --> failed", e); // TODO figure out JPA cancel if (order != null) order.cancel(); throw new RuntimeException("TradeJpaCm:sell(" + userID + "," + holdingID + ")", e); } if (!(order.getOrderStatus().equalsIgnoreCase("cancelled"))) //after the purchase or sell of a stock, update the stocks volume and price updateQuotePriceVolume(order.getSymbol(), TradeConfig.getRandomPriceChangeFactor(), order.getQuantity()); return order; } public void queueOrder(Integer orderID, boolean twoPhase) { Log .error("TradeJpaCm:queueOrder() not implemented for this runtime mode"); throw new UnsupportedOperationException( "TradeJpaCm:queueOrder() not implemented for this runtime mode"); } public OrderDataBean completeOrder(Integer orderID, boolean twoPhase) throws Exception { OrderDataBeanImpl order = null; if (Log.doTrace()) Log.trace("TradeJpaCm:completeOrder", orderID + " twoPhase=" + twoPhase); order = entityManager.find(OrderDataBeanImpl.class, orderID); order.getQuote(); if (order == null) { Log.error("TradeJpaCm:completeOrder -- Unable to find Order " + orderID + " FBPK returned " + order); return null; } if (order.isCompleted()) { throw new RuntimeException("Error: attempt to complete Order that is already completed\n" + order); } AccountDataBean account = order.getAccount(); QuoteDataBean quote = order.getQuote(); HoldingDataBean holding = order.getHolding(); BigDecimal price = order.getPrice(); double quantity = order.getQuantity(); if (Log.doTrace()) Log.trace("TradeJpaCm:completeOrder--> Completing Order " + order.getOrderID() + "\n\t Order info: " + order + "\n\t Account info: " + account + "\n\t Quote info: " + quote + "\n\t Holding info: " + holding); HoldingDataBean newHolding = null; if (order.isBuy()) { /* * Complete a Buy operation - create a new Holding for the Account - * deduct the Order cost from the Account balance */ newHolding = createHolding(account, quote, quantity, price); } try { if (newHolding != null) { order.setHolding(newHolding); } if (order.isSell()) { /* * Complete a Sell operation - remove the Holding from the Account - * deposit the Order proceeds to the Account balance */ if (holding == null) { Log.error("TradeJpaCm:completeOrder -- Unable to sell order " + order.getOrderID() + " holding already sold"); order.cancel(); return order; } else { entityManager.remove(holding); order.setHolding(null); } } order.setOrderStatus("closed"); order.setCompletionDate(new java.sql.Timestamp(System.currentTimeMillis())); if (Log.doTrace()) Log.trace("TradeJpaCm:completeOrder--> Completed Order " + order.getOrderID() + "\n\t Order info: " + order + "\n\t Account info: " + account + "\n\t Quote info: " + quote + "\n\t Holding info: " + holding); } catch (Exception e) { e.printStackTrace(); } return order; } public void cancelOrder(Integer orderID, boolean twoPhase) throws Exception { if (Log.doTrace()) Log.trace("TradeJpaCm:cancelOrder", orderID + " twoPhase=" + twoPhase); OrderDataBeanImpl order = entityManager.find(OrderDataBeanImpl.class, orderID); order.cancel(); } public void orderCompleted(String userID, Integer orderID) { if (Log.doActionTrace()) Log.trace("TradeAction:orderCompleted", userID, orderID); if (Log.doTrace()) Log.trace("OrderCompleted", userID, orderID); } public Collection<OrderDataBean> getOrders(String userID) { if (Log.doTrace()) Log.trace("TradeJpaCm:getOrders", userID); AccountProfileDataBeanImpl profile = entityManager.find(AccountProfileDataBeanImpl.class, userID); AccountDataBean account = profile.getAccount(); return account.getOrders(); } public Collection<OrderDataBean> getClosedOrders(String userID) throws Exception { if (Log.doTrace()) Log.trace("TradeJpaCm:getClosedOrders", userID); try { // Get the primary keys for all the closed Orders for this // account. Query query = entityManager.createNamedQuery("orderejb.closedOrders"); query.setParameter("userID", userID); Collection results = query.getResultList(); Iterator itr = results.iterator(); // Spin through the orders to populate the lazy quote fields while (itr.hasNext()) { OrderDataBeanImpl thisOrder = (OrderDataBeanImpl) itr.next(); thisOrder.getQuote(); } if (TradeConfig.jpaLayer == TradeConfig.OPENJPA) { Query updateStatus = entityManager.createNamedQuery("orderejb.completeClosedOrders"); updateStatus.setParameter("userID", userID); updateStatus.executeUpdate(); } else if (TradeConfig.jpaLayer == TradeConfig.HIBERNATE) { /* * Add logic to do update orders operation, because JBoss5' * Hibernate 3.3.1GA DB2Dialect and MySQL5Dialect do not work * with annotated query "orderejb.completeClosedOrders" defined * in OrderDatabean */ Query findaccountid = entityManager.createNativeQuery( "select " + "a.ACCOUNTID, " + "a.LOGINCOUNT, " + "a.LOGOUTCOUNT, " + "a.LASTLOGIN, " + "a.CREATIONDATE, " + "a.BALANCE, " + "a.OPENBALANCE, " + "a.PROFILE_USERID " + "from accountejb a where a.profile_userid = ?", org.apache.aries.samples.ariestrader.entities.AccountDataBeanImpl.class); findaccountid.setParameter(1, userID); AccountDataBeanImpl account = (AccountDataBeanImpl) findaccountid.getSingleResult(); Integer accountid = account.getAccountID(); Query updateStatus = entityManager.createNativeQuery("UPDATE orderejb o SET o.orderStatus = 'completed' WHERE " + "o.orderStatus = 'closed' AND o.ACCOUNT_ACCOUNTID = ?"); updateStatus.setParameter(1, accountid.intValue()); updateStatus.executeUpdate(); } return results; } catch (Exception e) { Log.error("TradeJpaCm.getClosedOrders", e); throw new RuntimeException( "TradeJpaCm.getClosedOrders - error", e); } } public QuoteDataBean createQuote(String symbol, String companyName, BigDecimal price) throws Exception { try { QuoteDataBeanImpl quote = new QuoteDataBeanImpl(symbol, companyName, 0, price, price, price, price, 0); entityManager.persist(quote); if (Log.doTrace()) Log.trace("TradeJpaCm:createQuote-->" + quote); return quote; } catch (Exception e) { Log.error("TradeJpaCm:createQuote -- exception creating Quote", e); throw new RuntimeException(e); } } public QuoteDataBean getQuote(String symbol) { if (Log.doTrace()) Log.trace("TradeJpaCm:getQuote", symbol); QuoteDataBeanImpl qdb = entityManager.find(QuoteDataBeanImpl.class, symbol); return qdb; } public Collection<QuoteDataBean> getAllQuotes() { if (Log.doTrace()) Log.trace("TradeJpaCm:getAllQuotes"); Query query = entityManager.createNamedQuery("quoteejb.allQuotes"); return query.getResultList(); } public QuoteDataBean updateQuotePriceVolume(String symbol, BigDecimal changeFactor, double sharesTraded) throws Exception { if (!TradeConfig.getUpdateQuotePrices()) { return new QuoteDataBeanImpl(); } if (Log.doTrace()) Log.trace("TradeJpaCm:updateQuote", symbol, changeFactor); /* * Add logic to determine JPA layer, because JBoss5' Hibernate 3.3.1GA * DB2Dialect and MySQL5Dialect do not work with annotated query * "quoteejb.quoteForUpdate" defined in QuoteDataBeanImpl */ QuoteDataBeanImpl quote = null; if (TradeConfig.jpaLayer == TradeConfig.HIBERNATE) { quote = entityManager.find(QuoteDataBeanImpl.class, symbol); } else if (TradeConfig.jpaLayer == TradeConfig.OPENJPA) { Query q = entityManager.createNamedQuery("quoteejb.quoteForUpdate"); q.setParameter(1, symbol); quote = (QuoteDataBeanImpl) q.getSingleResult(); } BigDecimal oldPrice = quote.getPrice(); if (quote.getPrice().equals(TradeConfig.PENNY_STOCK_PRICE)) { changeFactor = TradeConfig.PENNY_STOCK_RECOVERY_MIRACLE_MULTIPLIER; } BigDecimal newPrice = changeFactor.multiply(oldPrice).setScale(2, BigDecimal.ROUND_HALF_UP); quote.setPrice(newPrice); quote.setVolume(quote.getVolume() + sharesTraded); quote.setChange((newPrice.subtract(quote.getOpen()).doubleValue())); if (newPrice.compareTo(quote.getHigh()) == 1) quote.setHigh(newPrice); else if (newPrice.compareTo(quote.getLow()) == -1) quote.setLow(newPrice); entityManager.merge(quote); this.publishQuotePriceChange(quote, oldPrice, changeFactor, sharesTraded); return quote; } public Collection<HoldingDataBean> getHoldings(String userID) throws Exception { if (Log.doTrace()) Log.trace("TradeJpaCm:getHoldings", userID); Collection<HoldingDataBean> holdings = null; Query query = entityManager.createNamedQuery("holdingejb.holdingsByUserID"); query.setParameter("userID", userID); holdings = query.getResultList(); /* * Inflate the lazy data members */ Iterator itr = holdings.iterator(); while (itr.hasNext()) { ((HoldingDataBean) itr.next()).getQuote(); } return holdings; } public HoldingDataBean getHolding(Integer holdingID) { if (Log.doTrace()) Log.trace("TradeJpaCm:getHolding", holdingID); return entityManager.find(HoldingDataBeanImpl.class, holdingID); } public AccountDataBean getAccountData(String userID) { if (Log.doTrace()) Log.trace("TradeJpaCm:getAccountData", userID); AccountProfileDataBeanImpl profile = entityManager.find(AccountProfileDataBeanImpl.class, userID); /* * Inflate the lazy data memebers */ AccountDataBean account = profile.getAccount(); account.getProfile(); // Added to populate transient field for account account.setProfileID(profile.getUserID()); return account; } public AccountProfileDataBean getAccountProfileData(String userID) { if (Log.doTrace()) Log.trace("TradeJpaCm:getProfileData", userID); AccountProfileDataBeanImpl apb = entityManager.find(AccountProfileDataBeanImpl.class, userID); return apb; } public AccountProfileDataBean updateAccountProfile( String userID, String password, String fullName, String address, String email, String creditcard) throws Exception { if (Log.doTrace()) Log.trace("TradeJpaCm:updateAccountProfileData", userID); /* * // Retrieve the previous account profile in order to get account * data... hook it into new object AccountProfileDataBean temp = * entityManager.find(AccountProfileDataBean.class, * profileData.getUserID()); // In order for the object to merge * correctly, the account has to be hooked into the temp object... // - * may need to reverse this and obtain the full object first * * profileData.setAccount(temp.getAccount()); * * //TODO this might not be correct temp = * entityManager.merge(profileData); //System.out.println(temp); */ AccountProfileDataBeanImpl temp = entityManager.find(AccountProfileDataBeanImpl.class, userID); temp.setAddress(address); temp.setPassword(password); temp.setFullName(fullName); temp.setCreditCard(creditcard); temp.setEmail(email); entityManager.merge(temp); return temp; } public AccountDataBean login(String userID, String password) throws Exception { AccountProfileDataBeanImpl profile = entityManager.find(AccountProfileDataBeanImpl.class, userID); if (profile == null) { throw new RuntimeException("No such user: " + userID); } entityManager.merge(profile); AccountDataBean account = profile.getAccount(); if (Log.doTrace()) Log.trace("TradeJpaCm:login", userID, password); account.login(password); if (Log.doTrace()) Log.trace("TradeJpaCm:login(" + userID + "," + password + ") success" + account); return account; } public void logout(String userID) throws Exception { if (Log.doTrace()) Log.trace("TradeJpaCm:logout", userID); AccountProfileDataBeanImpl profile = entityManager.find(AccountProfileDataBeanImpl.class, userID); AccountDataBean account = profile.getAccount(); account.logout(); if (Log.doTrace()) Log.trace("TradeJpaCm:logout(" + userID + ") success"); } public AccountDataBean register(String userID, String password, String fullname, String address, String email, String creditcard, BigDecimal openBalance) throws Exception { AccountDataBeanImpl account = null; AccountProfileDataBeanImpl profile = null; if (Log.doTrace()) Log.trace("TradeJpaCm:register", userID, password, fullname, address, email, creditcard, openBalance); // Check to see if a profile with the desired userID already exists profile = entityManager.find(AccountProfileDataBeanImpl.class, userID); if (profile != null) { Log.error("Failed to register new Account - AccountProfile with userID(" + userID + ") already exists"); return null; } else { profile = new AccountProfileDataBeanImpl(userID, password, fullname, address, email, creditcard); account = new AccountDataBeanImpl(0, 0, null, new Timestamp(System.currentTimeMillis()), openBalance, openBalance, userID); profile.setAccount((AccountDataBean)account); account.setProfile((AccountProfileDataBean)profile); entityManager.persist(profile); entityManager.persist(account); // Uncomment this line to verify that datasources has been enlisted. After rebuild attempt to register a user with // a user id "fail". After the exception is thrown the database should not contain the user "fail" even though // the profile and account have already been persisted. // if (userID.equals("fail")) throw new RuntimeException("**** enlisted datasource validated via rollback test ****"); } return account; } /* * NO LONGER USE */ private void publishQuotePriceChange(QuoteDataBean quote, BigDecimal oldPrice, BigDecimal changeFactor, double sharesTraded) { if (!TradeConfig.getPublishQuotePriceChange()) return; Log.error("TradeJpaCm:publishQuotePriceChange - is not implemented for this runtime mode"); throw new UnsupportedOperationException("TradeJpaCm:publishQuotePriceChange - is not implemented for this runtime mode"); } private OrderDataBean createOrder(AccountDataBean account, QuoteDataBean quote, HoldingDataBean holding, String orderType, double quantity) { OrderDataBeanImpl order; if (Log.doTrace()) Log.trace("TradeJpaCm:createOrder(orderID=" + " account=" + ((account == null) ? null : account.getAccountID()) + " quote=" + ((quote == null) ? null : quote.getSymbol()) + " orderType=" + orderType + " quantity=" + quantity); try { order = new OrderDataBeanImpl(orderType, "open", new Timestamp(System.currentTimeMillis()), null, quantity, quote.getPrice().setScale(FinancialUtils.SCALE, FinancialUtils.ROUND), TradeConfig.getOrderFee(orderType), account, quote, holding); entityManager.persist(order); } catch (Exception e) { Log.error("TradeJpaCm:createOrder -- failed to create Order", e); throw new RuntimeException("TradeJpaCm:createOrder -- failed to create Order", e); } return order; } private HoldingDataBean createHolding(AccountDataBean account, QuoteDataBean quote, double quantity, BigDecimal purchasePrice) throws Exception { HoldingDataBeanImpl newHolding = new HoldingDataBeanImpl(quantity, purchasePrice, new Timestamp(System.currentTimeMillis()), account, quote); entityManager.persist(newHolding); return newHolding; } public double investmentReturn(double investment, double NetValue) throws Exception { if (Log.doTrace()) Log.trace("TradeJpaCm:investmentReturn"); double diff = NetValue - investment; double ir = diff / investment; return ir; } public QuoteDataBean pingTwoPhase(String symbol) throws Exception { Log.error("TradeJpaCm:pingTwoPhase - is not implemented for this runtime mode"); throw new UnsupportedOperationException("TradeJpaCm:pingTwoPhase - is not implemented for this runtime mode"); } class quotePriceComparator implements java.util.Comparator { public int compare(Object quote1, Object quote2) { double change1 = ((QuoteDataBean) quote1).getChange(); double change2 = ((QuoteDataBean) quote2).getChange(); return new Double(change2).compareTo(change1); } } /** * Get mode - returns the persistence mode (TradeConfig.JPA) * * @return TradeConfig.ModeType */ public TradeConfig.ModeType getMode() { return TradeConfig.ModeType.JPA_CM; } }
8,211
0
Create_ds/aries/samples/ariestrader/modules/ariestrader-web/src/main/java/org/apache/aries/samples/ariestrader
Create_ds/aries/samples/ariestrader/modules/ariestrader-web/src/main/java/org/apache/aries/samples/ariestrader/web/OrdersAlertFilter.java
/** * 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. */ package org.apache.aries.samples.ariestrader.web; import java.io.IOException; import javax.servlet.*; import javax.servlet.http.*; import org.apache.aries.samples.ariestrader.api.TradeServicesManager; import org.apache.aries.samples.ariestrader.api.TradeServiceUtilities; import org.apache.aries.samples.ariestrader.api.TradeServices; import org.apache.aries.samples.ariestrader.util.*; public class OrdersAlertFilter implements Filter { private static TradeServicesManager tradeServicesManager = null; /** * Constructor for CompletedOrdersAlertFilter */ public OrdersAlertFilter() { super(); } /** * @see Filter#init(FilterConfig) */ private FilterConfig filterConfig = null; public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig = filterConfig; } /** * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain) */ public void doFilter( ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { if (filterConfig == null) return; if (tradeServicesManager == null) { tradeServicesManager = TradeServiceUtilities.getTradeServicesManager(); } TradeServices tradeServices = tradeServicesManager.getTradeServices(); 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) ) { java.util.Collection closedOrders = tradeServices.getClosedOrders(userID); if ( (closedOrders!=null) && (closedOrders.size() > 0) ) { req.setAttribute("closedOrders", closedOrders); } if (Log.doTrace()) { Log.printCollection("OrdersAlertFilter: userID="+userID+" closedOrders=", closedOrders); } } } } } catch (Exception e) { Log.error(e, "OrdersAlertFilter - Error checking for closedOrders"); } ServletContext sc = filterConfig.getServletContext(); chain.doFilter(req, resp/*wrapper*/); } /** * @see Filter#destroy() */ public void destroy() { this.filterConfig = null; } }
8,212
0
Create_ds/aries/samples/ariestrader/modules/ariestrader-web/src/main/java/org/apache/aries/samples/ariestrader
Create_ds/aries/samples/ariestrader/modules/ariestrader-web/src/main/java/org/apache/aries/samples/ariestrader/web/TradeAppServlet.java
/** * 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. */ package org.apache.aries.samples.ariestrader.web; import javax.servlet.*; import javax.servlet.http.*; import org.apache.aries.samples.ariestrader.api.TradeServicesManager; import org.apache.aries.samples.ariestrader.api.TradeServiceUtilities; import org.apache.aries.samples.ariestrader.api.TradeServices; import org.apache.aries.samples.ariestrader.util.*; import java.io.IOException; /** * * 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. */ public class TradeAppServlet extends HttpServlet { private static TradeServicesManager tradeServicesManager = null; /** * Servlet initialization method. */ public void init(ServletConfig config) throws ServletException { super.init(config); java.util.Enumeration en = config.getInitParameterNames(); while (en.hasMoreElements()) { String parm = (String) en.nextElement(); String value = config.getInitParameter(parm); TradeConfig.setConfigParam(parm, value); } } /** * Returns a string that contains information about TradeScenarioServlet * * @return The servlet information */ 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 */ 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 */ 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; resp.setContentType("text/html"); if (tradeServicesManager == null) { tradeServicesManager = TradeServiceUtilities.getTradeServicesManager(); } TradeServices tradeServices = tradeServicesManager.getTradeServices(); TradeServletAction tsAction = new TradeServletAction(tradeServices); // 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 { System.out.println("TradeAppServlet: Invalid Action=" + action); tsAction.doWelcome(ctx, req, resp, "TradeAppServlet: Invalid Action" + action); } } }
8,213
0
Create_ds/aries/samples/ariestrader/modules/ariestrader-web/src/main/java/org/apache/aries/samples/ariestrader
Create_ds/aries/samples/ariestrader/modules/ariestrader-web/src/main/java/org/apache/aries/samples/ariestrader/web/TradeServletAction.java
/** * Licensed to4the 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. */ package org.apache.aries.samples.ariestrader.web; import javax.servlet.*; import javax.servlet.http.*; import org.apache.aries.samples.ariestrader.api.TradeServices; import org.apache.aries.samples.ariestrader.api.persistence.*; import org.apache.aries.samples.ariestrader.util.*; import java.io.IOException; import java.util.Collection; import java.util.Iterator; import java.util.ArrayList; import java.math.BigDecimal; /** * 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 TradeServices} methods to actually perform each * trading operation. * */ public class TradeServletAction { private TradeServices tradeServices = null; public TradeServletAction(TradeServices tradeServices) { this.tradeServices = tradeServices; } /** * 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 = tradeServices.getAccountData(userID); AccountProfileDataBean accountProfileData = tradeServices .getAccountProfileData(userID); ArrayList orderDataBeans = (TradeConfig.getLongRun() ? new ArrayList() : (ArrayList) tradeServices.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; } try { if (doUpdate) { tradeServices.updateAccountProfile(userID, password, fullName, address, email, creditcard); 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 = tradeServices.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 = tradeServices.getAccountData(userID); Collection holdingDataBeans = tradeServices.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 = tradeServices.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 (Exception e) { 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 = tradeServices.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 { tradeServices.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 forward 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(); } 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 holdings for this user Collection quoteDataBeans = new ArrayList(); Collection holdingDataBeans = tradeServices.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 = tradeServices.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 { String results = ""; // 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 = tradeServices.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 = tradeServices.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); } }
8,214
0
Create_ds/aries/samples/ariestrader/modules/ariestrader-web/src/main/java/org/apache/aries/samples/ariestrader
Create_ds/aries/samples/ariestrader/modules/ariestrader-web/src/main/java/org/apache/aries/samples/ariestrader/web/TradeConfigServlet.java
/** * 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. */ package org.apache.aries.samples.ariestrader.web; import javax.servlet.*; import javax.servlet.http.*; import org.apache.aries.samples.ariestrader.api.TradeDBManager; import org.apache.aries.samples.ariestrader.api.TradeServiceUtilities; import org.apache.aries.samples.ariestrader.api.persistence.RunStatsDataBean; import org.apache.aries.samples.ariestrader.util.Log; import org.apache.aries.samples.ariestrader.util.TradeConfig; import java.io.IOException; /** * TradeConfigServlet provides a servlet interface to adjust AriesTrader runtime parameters. * TradeConfigServlet updates values in the {@link org.apache.aries.samples.ariestrader.web.TradeConfig} JavaBean holding * all configuration and runtime parameters for the Trade application * */ public class TradeConfigServlet extends HttpServlet { private static TradeDBManager tradeDBManager = null; /** * Servlet initialization method. */ 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(); if (tradeDBManager == null) { tradeDBManager = TradeServiceUtilities.getTradeDBManager(); } try { runStatsData = tradeDBManager.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 parameters * 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(TradeConfig.ModeType.values()[i]); } } catch (Exception e) { 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" + TradeConfig.runTimeModeNames[TradeConfig.getRunTimeMode().ordinal()] + "\n"; /* Add JPA layer choice to avoid some ugly Hibernate bugs */ String jpaLayerStr = req.getParameter("JPALayer"); if (jpaLayerStr != null) { try { int i = Integer.parseInt(jpaLayerStr); if ((i >= 0) && (i < TradeConfig.jpaLayerNames.length)) //Input validation TradeConfig.jpaLayer = i; } catch (Exception e) { Log.error( e, "TradeConfigServlet.doConfigUpdate(..): minor exception caught", "trying to set JPALayer to " + jpaLayerStr, "reverting to current value"); } // If the value is bad, simply revert to current } currentConfigStr += "\t\tJPALayer:\t\t" + TradeConfig.jpaLayerNames[TradeConfig.jpaLayer] + "\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.orderProcessingMode = i; } catch (Exception e) { 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" + TradeConfig.orderProcessingModeNames[TradeConfig.orderProcessingMode] + "\n"; String accessModeStr = req.getParameter("AcessMode"); if (accessModeStr != null) { try { int i = Integer.parseInt(accessModeStr); if ((i >= 0) && (i < TradeConfig.accessModeNames.length) && (i != TradeConfig.getAccessMode())) //Input validation TradeConfig.setAccessMode(i); } catch (Exception e) { 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\tAcessMode:\t\t" + TradeConfig.accessModeNames[TradeConfig.getAccessMode()] + "\n"; String workloadMixStr = req.getParameter("WorkloadMix"); if (workloadMixStr != null) { try { int i = Integer.parseInt(workloadMixStr); if ((i >= 0) && (i < TradeConfig.workloadMixNames.length)) //Input validation TradeConfig.workloadMix = i; } catch (Exception e) { Log.error( e, "TradeConfigServlet.doConfigUpdate(..): minor exception caught", "trying to set workloadMix to " + workloadMixStr, "reverting to current value"); } // If the value is bad, simply revert to current } currentConfigStr += "\t\tWorkload Mix:\t\t" + TradeConfig.workloadMixNames[TradeConfig.workloadMix] + "\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.webInterface = 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" + 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.cachingType = 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" + TradeConfig.cachingTypeNames[TradeConfig.cachingType] + "\n"; String parm = req.getParameter("SOAP_URL"); if ((parm != null) && (parm.length() > 0)) { if (!TradeConfig.getSoapURL().equals(parm)) { TradeConfig.setSoapURL(parm); } } else { TradeConfig.setSoapURL(null); } 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) { Log.error( e, "TradeConfigServlet: minor exception caught", "trying to set max_quotes, error on parsing int " + parm, "reverting to current value " + TradeConfig.getMAX_QUOTES()); } //On error, revert to saved } currentConfigStr += "\t\t#Trade Users:\t\t" + TradeConfig.getMAX_USERS() + "\n"; currentConfigStr += "\t\t#Trade Quotes:\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\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"; String enableTrace = req.getParameter("EnableTrace"); if (enableTrace != null) Log.setTrace(true); else Log.setTrace(false); String enableActionTrace = req.getParameter("EnableActionTrace"); if (enableActionTrace != null) Log.setActionTrace(true); else Log.setActionTrace(false); 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"; System.out.println(currentConfigStr); } 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 AriesTrader Configuration:</br></b>"); return; } else if (action.equals("updateConfig")) { doConfigUpdate(req, resp); result = "<B><BR>AriesTrader 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(), false); result = "AriesTrader Database Built - " + TradeConfig.getMAX_USERS() + "users created"; } else if (action.equals("buildDBTables")) { resp.setContentType("text/html"); new TradeBuildDB(resp.getWriter(), true); } doConfigDisplay(req, resp, result + "Current AriesTrader 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()); } } }
8,215
0
Create_ds/aries/samples/ariestrader/modules/ariestrader-web/src/main/java/org/apache/aries/samples/ariestrader
Create_ds/aries/samples/ariestrader/modules/ariestrader-web/src/main/java/org/apache/aries/samples/ariestrader/web/TradeScenarioServlet.java
/** * 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. */ package org.apache.aries.samples.ariestrader.web; import javax.servlet.*; import javax.servlet.http.*; import org.apache.aries.samples.ariestrader.api.persistence.*; import org.apache.aries.samples.ariestrader.util.*; import java.util.Collection; import java.util.Iterator; import java.io.IOException; import java.io.PrintWriter; /** * 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. */ public class TradeScenarioServlet extends HttpServlet { /** * Servlet initialization method. */ public void init(ServletConfig config) throws ServletException { super.init(config); java.util.Enumeration en = config.getInitParameterNames(); while ( en.hasMoreElements() ) { String parm = (String) en.nextElement(); String value = config.getInitParameter(parm); TradeConfig.setConfigParam(parm, value); } } /** * Returns a string that contains information about TradeScenarioServlet * * @return The servlet information */ 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 */ 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 */ 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 String scenarioAction = (String) 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 final static String tasPathPrefix = "/app?action="; }
8,216
0
Create_ds/aries/samples/ariestrader/modules/ariestrader-web/src/main/java/org/apache/aries/samples/ariestrader
Create_ds/aries/samples/ariestrader/modules/ariestrader-web/src/main/java/org/apache/aries/samples/ariestrader/web/TradeBuildDB.java
/** * 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. */ package org.apache.aries.samples.ariestrader.web; import java.io.BufferedReader; import java.io.File; import java.io.InputStreamReader; import java.io.IOException; import java.math.BigDecimal; import java.net.URL; import java.util.ArrayList; import org.apache.aries.samples.ariestrader.api.TradeDBManager; import org.apache.aries.samples.ariestrader.api.TradeServicesManager; import org.apache.aries.samples.ariestrader.api.TradeServiceUtilities; import org.apache.aries.samples.ariestrader.api.TradeServices; import org.apache.aries.samples.ariestrader.api.persistence.*; import org.apache.aries.samples.ariestrader.util.*; /** * TradeBuildDB uses operations provided by the TradeApplication to * (a) create the Database tables * (b) populate a AriesTrader database without creating the tables. * Specifically, a new AriesTrader 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 { private static TradeServicesManager tradeServicesManager = null; private static TradeDBManager tradeDBManager = null; /** * Populate a Trade DB using standard out as a log */ public TradeBuildDB() throws Exception { this(new java.io.PrintWriter(System.out), false); } /** * Re-create the AriesTrader db tables and populate them OR just populate a * AriesTrader DB, logging to the provided output stream */ public TradeBuildDB(java.io.PrintWriter out, boolean createTables) throws Exception { String symbol, companyName; int errorCount = 0; // Give up gracefully after 10 errors if (tradeServicesManager == null) { tradeServicesManager = TradeServiceUtilities.getTradeServicesManager(); } TradeServices tradeServices = tradeServicesManager.getTradeServices(); if (tradeDBManager == null) { tradeDBManager = TradeServiceUtilities.getTradeDBManager(); } // TradeStatistics.statisticsEnabled=false; // disable statistics out.println("<HEAD><BR><EM> TradeBuildDB: Building AriesTrader Database...</EM><BR>" + "This operation will take several minutes. Please wait...</HEAD>"); out.println("<BODY>"); if (createTables) { boolean success = false; String dbProductName = null; String fileLocation = null; URL ddlFile = null; Object[] sqlBuffer = null; // Find out the Database being used try { dbProductName = tradeDBManager.checkDBProductName(); } catch (Exception e) { Log.error(e, "TradeBuildDB: Unable to check DB Product name"); } if (dbProductName == null) { out.println("<BR>TradeBuildDB: **** Unable to check DB Product name," + "please check Database/AppServer configuration and retry ****</BR></BODY>"); return; } // Locate DDL file for the specified database try { out.println("<BR>TradeBuildDB: **** Database Product detected: " + dbProductName + " ****</BR>"); if (dbProductName.startsWith("DB2/")) { // if db is DB2 fileLocation = File.separatorChar + "dbscripts" + File.separatorChar + "db2" + File.separatorChar + "Table.ddl"; } else if (dbProductName.startsWith("Apache Derby")) { // if db is Derby fileLocation = File.separatorChar + "dbscripts" + File.separatorChar + "derby" + File.separatorChar + "Table.ddl"; } else if (dbProductName.startsWith("Oracle")) { // if the Db is Oracle fileLocation = File.separatorChar + "dbscripts" + File.separatorChar + "oracle" + File.separatorChar + "Table.ddl"; } else { // Unsupported "Other" Database fileLocation = File.separatorChar + "dbscripts" + File.separatorChar + "other" + File.separatorChar + "Table.ddl"; out.println("<BR>TradeBuildDB: **** This Database is " + "unsupported/untested use at your own risk ****</BR>"); } ddlFile = this.getClass().getResource(fileLocation); } catch (Exception e) { Log.error(e, "TradeBuildDB: Unable to locate DDL file for the specified database"); out.println("<BR>TradeBuildDB: **** Unable to locate DDL file for " + "the specified database ****</BR></BODY>"); return; } // 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 AriesTrader tables out.println("<BR>TradeBuildDB: **** Dropping and Recreating the AriesTrader tables... ****</BR>"); try { success = tradeDBManager.recreateDBTables(sqlBuffer, out); } catch (Exception e) { Log.error(e, "TradeBuildDB: Unable to drop and recreate AriesTrader Db Tables, "+ "please check for database consistency before continuing"); } if (!success) { out.println("<BR>TradeBuildDB: **** Unable to drop and recreate AriesTrader Db Tables, "+ "please check for database consistency before continuing ****</BR></BODY>"); return; } out.println("<BR>TradeBuildDB: **** AriesTrader tables successfully created! ****</BR><BR><b> "+ "Please Stop and Re-start your AriesTrader application (or your application server) and then use "+ "the \"Repopulate AriesTrader 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 { tradeDBManager.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 { tradeServices.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 = tradeServices.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); } // 0-MAX_HOLDING (inclusive), avg holdings per user = (MAX-0)/2 int holdings = TradeConfig.rndInt(TradeConfig.getMAX_HOLDINGS() + 1); double quantity = 0; for (int j = 0; j < holdings; j++) { symbol = TradeConfig.rndSymbol(); quantity = TradeConfig.rndQuantity(); tradeServices.buy(userID, symbol, quantity, TradeConfig.orderProcessingMode); } if (i % 50 == 0) { out.println(" has " + holdings + " holdings."); out.flush(); } } else { out.println("<BR>UID " + userID + " already registered.</BR>"); out.flush(); } } 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(URL ddlFile) throws Exception { BufferedReader br = null; InputStreamReader ir = null; ArrayList sqlBuffer = new ArrayList(30); // initial capacity 30 assuming we have 30 ddl-sql statements to read try { if (Log.doTrace()) Log.traceEnter("TradeBuildDB:parseDDLToBuffer - " + ddlFile); ir = new InputStreamReader(ddlFile.openStream()); br = new BufferedReader(ir); 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(); } }
8,217
0
Create_ds/aries/samples/ariestrader/modules/ariestrader-web/src/main/java/org/apache/aries/samples/ariestrader/web
Create_ds/aries/samples/ariestrader/modules/ariestrader-web/src/main/java/org/apache/aries/samples/ariestrader/web/prims/PingServlet2Jsp.java
/** * 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. */ package org.apache.aries.samples.ariestrader.web.prims; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import org.apache.aries.samples.ariestrader.util.*; /** * * PingServlet2JSP tests a call from a servlet to a JavaServer Page providing server-side dynamic * HTML through JSP scripting. * */ public class PingServlet2Jsp extends HttpServlet { 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 */ 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 **/ 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()); } } }
8,218
0
Create_ds/aries/samples/ariestrader/modules/ariestrader-web/src/main/java/org/apache/aries/samples/ariestrader/web
Create_ds/aries/samples/ariestrader/modules/ariestrader-web/src/main/java/org/apache/aries/samples/ariestrader/web/prims/PingServlet2JNDI.java
/** * 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. */ package org.apache.aries.samples.ariestrader.web.prims; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import javax.sql.DataSource; import org.apache.aries.samples.ariestrader.util.*; /** * * PingServlet2JNDI performs a basic JNDI lookup of a JDBC DataSource * */ public class PingServlet2JNDI extends HttpServlet { 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 */ 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 **/ 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 { int iter = TradeConfig.getPrimIterations(); for (int ii = 0; ii < iter; ii++) { DataSource dataSource = (DataSource) ServiceUtilities.getOSGIService(DataSource.class.getName(),TradeConfig.OSGI_DS_NAME_FILTER); } 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 **/ 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: **/ public void init(ServletConfig config) throws ServletException { super.init(config); hitCount = 0; initTime = new java.util.Date().toString(); } }
8,219
0
Create_ds/aries/samples/ariestrader/modules/ariestrader-web/src/main/java/org/apache/aries/samples/ariestrader/web
Create_ds/aries/samples/ariestrader/modules/ariestrader-web/src/main/java/org/apache/aries/samples/ariestrader/web/prims/PingSession1.java
/** * 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. */ package org.apache.aries.samples.ariestrader.web.prims; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import org.apache.aries.samples.ariestrader.util.*; /** * * 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. * */ public class PingSession1 extends HttpServlet { 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 */ 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 **/ 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 exception Log.error(e, "PingSession1.doGet(..l.): error."); //set the server response 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 **/ 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: **/ public void init(ServletConfig config) throws ServletException { super.init(config); count = 0; hitCount = 0; initTime = new java.util.Date().toString(); } }
8,220
0
Create_ds/aries/samples/ariestrader/modules/ariestrader-web/src/main/java/org/apache/aries/samples/ariestrader/web
Create_ds/aries/samples/ariestrader/modules/ariestrader-web/src/main/java/org/apache/aries/samples/ariestrader/web/prims/PingJDBCRead.java
/** * 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. */ package org.apache.aries.samples.ariestrader.web.prims; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import org.apache.aries.samples.ariestrader.api.TradeServiceUtilities; import org.apache.aries.samples.ariestrader.api.TradeServices; import org.apache.aries.samples.ariestrader.api.persistence.*; import org.apache.aries.samples.ariestrader.util.*; /** * * PingJDBCReadPrepStmt uses a prepared statement for database read access. * This primative uses {@link org.apache.aries.samples.ariestrader.direct.TradeJEEDirect} to set the price of a random stock * (generated by {@link org.apache.aries.samples.ariestrader.Trade_Config}) through the use of prepared statements. * */ public class PingJDBCRead extends HttpServlet { 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 */ 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 **/ 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 (via TradeServices) uses prepared statements so I am going to make use of it's code. TradeServices tradeServices = TradeServiceUtilities.getTradeServices("(mode=JDBC)"); symbol = TradeConfig.rndSymbol(); QuoteDataBean quoteData = null; int iter = TradeConfig.getPrimIterations(); for (int ii = 0; ii < iter; ii++) { quoteData = tradeServices.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 **/ public String getServletInfo() { return "Basic JDBC Read using a prepared statment, makes use of TradeJdbc class via TradeServices"; } /** * called when the class is loaded to initialize the servlet * @param config ServletConfig: **/ public void init(ServletConfig config) throws ServletException { super.init(config); hitCount = 0; initTime = new java.util.Date().toString(); } }
8,221
0
Create_ds/aries/samples/ariestrader/modules/ariestrader-web/src/main/java/org/apache/aries/samples/ariestrader/web
Create_ds/aries/samples/ariestrader/modules/ariestrader-web/src/main/java/org/apache/aries/samples/ariestrader/web/prims/ExplicitGC.java
/** * 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. */ package org.apache.aries.samples.ariestrader.web.prims; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import org.apache.aries.samples.ariestrader.util.*; /** * * ExplicitGC invokes System.gc(). This allows one to gather min / max heap statistics. * */ public class ExplicitGC extends HttpServlet { 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 */ 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 **/ 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 **/ public String getServletInfo() { return "Generate Explicit GC to VM"; } /** * called when the class is loaded to initialize the servlet * @param config ServletConfig: **/ public void init(ServletConfig config) throws ServletException { super.init(config); initTime = new java.util.Date().toString(); hitCount = 0; } }
8,222
0
Create_ds/aries/samples/ariestrader/modules/ariestrader-web/src/main/java/org/apache/aries/samples/ariestrader/web
Create_ds/aries/samples/ariestrader/modules/ariestrader-web/src/main/java/org/apache/aries/samples/ariestrader/web/prims/PingServlet2Include.java
/** * 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. */ package org.apache.aries.samples.ariestrader.web.prims; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import org.apache.aries.samples.ariestrader.util.*; /** * * 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} * */ public class PingServlet2Include extends HttpServlet { 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 */ 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 **/ 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); } 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: **/ public void init(ServletConfig config) throws ServletException { super.init(config); initTime = new java.util.Date().toString(); hitCount = 0; } }
8,223
0
Create_ds/aries/samples/ariestrader/modules/ariestrader-web/src/main/java/org/apache/aries/samples/ariestrader/web
Create_ds/aries/samples/ariestrader/modules/ariestrader-web/src/main/java/org/apache/aries/samples/ariestrader/web/prims/PingServletWriter.java
/** * 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. */ package org.apache.aries.samples.ariestrader.web.prims; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import org.apache.aries.samples.ariestrader.util.*; /** * * PingServlet extends PingServlet by using a PrintWriter for formatted * output vs. the output stream used by {@link PingServlet}. * */ public class PingServletWriter extends HttpServlet { 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 */ 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 **/ 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 **/ 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: **/ public void init(ServletConfig config) throws ServletException { super.init(config); hitCount = 0; initTime = new java.util.Date().toString(); } }
8,224
0
Create_ds/aries/samples/ariestrader/modules/ariestrader-web/src/main/java/org/apache/aries/samples/ariestrader/web
Create_ds/aries/samples/ariestrader/modules/ariestrader-web/src/main/java/org/apache/aries/samples/ariestrader/web/prims/PingServlet2ServletRcv.java
/** * 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. */ package org.apache.aries.samples.ariestrader.web.prims; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import org.apache.aries.samples.ariestrader.util.*; /** * * 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. * */ public class PingServlet2ServletRcv extends HttpServlet { 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 */ 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 **/ 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: **/ public void init(ServletConfig config) throws ServletException { super.init(config); initTime = new java.util.Date().toString(); } }
8,225
0
Create_ds/aries/samples/ariestrader/modules/ariestrader-web/src/main/java/org/apache/aries/samples/ariestrader/web
Create_ds/aries/samples/ariestrader/modules/ariestrader-web/src/main/java/org/apache/aries/samples/ariestrader/web/prims/PingServlet2IncludeRcv.java
/** * 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. */ package org.apache.aries.samples.ariestrader.web.prims; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; /** * * 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} * */ public class PingServlet2IncludeRcv extends HttpServlet { /** * 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 */ 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 **/ public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // do nothing but get included by PingServlet2Include } }
8,226
0
Create_ds/aries/samples/ariestrader/modules/ariestrader-web/src/main/java/org/apache/aries/samples/ariestrader/web
Create_ds/aries/samples/ariestrader/modules/ariestrader-web/src/main/java/org/apache/aries/samples/ariestrader/web/prims/PingServlet.java
/** * 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. */ package org.apache.aries.samples.ariestrader.web.prims; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import org.apache.aries.samples.ariestrader.util.*; /** * * PingServlet tests fundamental dynamic HTML creation functionality through * server side servlet processing. * */ public class PingServlet extends HttpServlet { 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 */ 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 **/ 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 **/ public String getServletInfo() { return "Basic dynamic HTML generation through a servlet"; } /** * called when the class is loaded to initialize the servlet * @param config ServletConfig: **/ public void init(ServletConfig config) throws ServletException { super.init(config); initTime = new java.util.Date().toString(); hitCount = 0; } }
8,227
0
Create_ds/aries/samples/ariestrader/modules/ariestrader-web/src/main/java/org/apache/aries/samples/ariestrader/web
Create_ds/aries/samples/ariestrader/modules/ariestrader-web/src/main/java/org/apache/aries/samples/ariestrader/web/prims/PingServlet2Servlet.java
/** * 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. */ package org.apache.aries.samples.ariestrader.web.prims; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import org.apache.aries.samples.ariestrader.util.*; /** * * 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} * */ public class PingServlet2Servlet extends HttpServlet { 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 */ 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 **/ 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()); } } }
8,228
0
Create_ds/aries/samples/ariestrader/modules/ariestrader-web/src/main/java/org/apache/aries/samples/ariestrader/web
Create_ds/aries/samples/ariestrader/modules/ariestrader-web/src/main/java/org/apache/aries/samples/ariestrader/web/prims/PingBean.java
/** * 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. */ package org.apache.aries.samples.ariestrader.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; } }
8,229
0
Create_ds/aries/samples/ariestrader/modules/ariestrader-web/src/main/java/org/apache/aries/samples/ariestrader/web
Create_ds/aries/samples/ariestrader/modules/ariestrader-web/src/main/java/org/apache/aries/samples/ariestrader/web/prims/PingSession3.java
/** * 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. */ package org.apache.aries.samples.ariestrader.web.prims; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import org.apache.aries.samples.ariestrader.util.*; /** * * 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. * */ public class PingSession3 extends HttpServlet { 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 */ 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 **/ 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 exception Log.error(e, "PingSession3.doGet(..l.): error."); //set the server response 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 **/ 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: **/ public void init(ServletConfig config) throws ServletException { super.init(config); hitCount = 0; initTime = new java.util.Date().toString(); } }
8,230
0
Create_ds/aries/samples/ariestrader/modules/ariestrader-web/src/main/java/org/apache/aries/samples/ariestrader/web
Create_ds/aries/samples/ariestrader/modules/ariestrader-web/src/main/java/org/apache/aries/samples/ariestrader/web/prims/PingJDBCWrite.java
/** * 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. */ package org.apache.aries.samples.ariestrader.web.prims; import java.io.*; import java.math.BigDecimal; import javax.servlet.*; import javax.servlet.http.*; import org.apache.aries.samples.ariestrader.api.TradeServiceUtilities; import org.apache.aries.samples.ariestrader.api.TradeServices; import org.apache.aries.samples.ariestrader.api.persistence.*; import org.apache.aries.samples.ariestrader.util.*; /** * * PingJDBCReadPrepStmt uses a prepared statement * for database update. Statement parameters are set dynamically on each request. * This primative uses {@link org.apache.aries.samples.ariestrader.direct.TradeJEEDirect} to set the price of a random stock * (generated by {@link org.apache.aries.samples.ariestrader.Trade_Config}) through the use of prepared statements. * */ public class PingJDBCWrite extends HttpServlet { 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 **/ 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 via TradeServices makes use of prepared statements so I am going to reuse the existing code. TradeServices tradeServices = TradeServiceUtilities.getTradeServices("(mode=JDBC)"); //update the price of our symbol QuoteDataBean quoteData = null; int iter = TradeConfig.getPrimIterations(); for (int ii = 0; ii < iter; ii++) { quoteData = tradeServices.updateQuotePriceVolume(symbol, newPrice, 100.0); } //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 **/ 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: **/ 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 */ public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doGet(req, res); }}
8,231
0
Create_ds/aries/samples/ariestrader/modules/ariestrader-web/src/main/java/org/apache/aries/samples/ariestrader/web
Create_ds/aries/samples/ariestrader/modules/ariestrader-web/src/main/java/org/apache/aries/samples/ariestrader/web/prims/PingSession3Object.java
/** * 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. */ package org.apache.aries.samples.ariestrader.web.prims; import java.io.*; /** * * 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 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"); // 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=(double)19.0; j=(double)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()); * } *} */ }
8,232
0
Create_ds/aries/samples/ariestrader/modules/ariestrader-web/src/main/java/org/apache/aries/samples/ariestrader/web
Create_ds/aries/samples/ariestrader/modules/ariestrader-web/src/main/java/org/apache/aries/samples/ariestrader/web/prims/PingSession2.java
/** * 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. */ package org.apache.aries.samples.ariestrader.web.prims; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import org.apache.aries.samples.ariestrader.util.*; /** * * 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 * */ public class PingSession2 extends HttpServlet { 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 */ 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 **/ 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 exception Log.error(e, "PingSession2.doGet(...): error."); //set the server response 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 **/ 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: **/ public void init(ServletConfig config) throws ServletException { super.init(config); hitCount = 0; initTime = new java.util.Date().toString(); } }
8,233
0
Create_ds/aries/samples/blog/blog-biz/src/main/java/org/apache/aries/samples/blog
Create_ds/aries/samples/blog/blog-biz/src/main/java/org/apache/aries/samples/blog/biz/BlogCommentManagerImpl.java
/** * 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. */ package org.apache.aries.samples.blog.biz; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.aries.samples.blog.api.BlogComment; import org.apache.aries.samples.blog.api.BlogCommentManager; import org.apache.aries.samples.blog.api.comment.persistence.BlogCommentService; import org.apache.aries.samples.blog.api.comment.persistence.Comment; public class BlogCommentManagerImpl implements BlogCommentManager { private BlogCommentService commentService; private boolean commentServiceValid; // Injected via blueprint public void setCommentService(BlogCommentService bcs) { commentService = bcs; } public void createComment(String comment, String email, long entryId) { commentService.createComment(comment, email, entryId); } public List<? extends BlogComment> getCommentsByAuthor(String email) { List<? extends Comment> comment = commentService.getCommentsForAuthor(email); return adaptComment(comment); } public List<? extends BlogComment> getCommentsForPost(long id) { List<? extends Comment> comment = commentService.getCommentsForEntry(id); return adaptComment(comment); } public void deleteComment(int id) { commentService.delete(id); } private List<? extends BlogComment> adaptComment( List<? extends Comment> comments) { List<BlogComment> list = new ArrayList<BlogComment>(); Iterator<? extends Comment> c = comments.iterator(); while (c.hasNext()) { list.add(new BlogCommentImpl(c.next())); } return list; } public boolean isCommentingAvailable() { return commentServiceValid; } public void blogServiceBound(BlogCommentService comment, Map props) { commentServiceValid = true; } public void blogServiceUnbound(BlogCommentService comment, Map props) { } }
8,234
0
Create_ds/aries/samples/blog/blog-biz/src/main/java/org/apache/aries/samples/blog
Create_ds/aries/samples/blog/blog-biz/src/main/java/org/apache/aries/samples/blog/biz/BlogListIterator.java
/** * 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. */ package org.apache.aries.samples.blog.biz; import java.lang.reflect.Constructor; import java.util.ListIterator; public class BlogListIterator<B, F> implements ListIterator<F> { private ListIterator<? extends B> internalListIterator; private Class<? extends F> frontendClazz; private Class<B> backendClazz; public BlogListIterator(ListIterator<? extends B> listIterator, Class<? extends F> frontendClazz, Class<B> backendClazz) { this.internalListIterator = listIterator; this.frontendClazz = frontendClazz; this.backendClazz = backendClazz; } public void add(Object e) { throw new UnsupportedOperationException(""); } public boolean hasNext() { return internalListIterator.hasNext(); } public boolean hasPrevious() { return internalListIterator.hasPrevious(); } public F next() { try { return getConstructor().newInstance(internalListIterator.next()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } public int nextIndex() { return internalListIterator.nextIndex(); } public F previous() { try { return getConstructor().newInstance(internalListIterator.previous()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } public int previousIndex() { // TODO Auto-generated method stub return 0; } public void remove() { throw new UnsupportedOperationException( "Modifications to the list are not supported"); } public void set(Object e) { throw new UnsupportedOperationException( "Modifications to the list are not supported"); } private Constructor<F> getConstructor() { Constructor<F> c; try { c = (Constructor<F>) frontendClazz.getConstructor(backendClazz); return c; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } }
8,235
0
Create_ds/aries/samples/blog/blog-biz/src/main/java/org/apache/aries/samples/blog
Create_ds/aries/samples/blog/blog-biz/src/main/java/org/apache/aries/samples/blog/biz/BlogImpl.java
/** * 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. */ package org.apache.aries.samples.blog.biz; import org.apache.aries.samples.blog.api.Blog; /** Implementation of Blog */ public class BlogImpl implements Blog { public String getBlogTitle() { return "Sample Blog"; } }
8,236
0
Create_ds/aries/samples/blog/blog-biz/src/main/java/org/apache/aries/samples/blog
Create_ds/aries/samples/blog/blog-biz/src/main/java/org/apache/aries/samples/blog/biz/BlogListAdapter.java
/** * 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. */ package org.apache.aries.samples.blog.biz; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; public class BlogListAdapter<F, B> implements List<F> { private List<? extends B> backendList; private Class<? extends F> frontendClazz; private Class<B> backendClazz; public BlogListAdapter(List<? extends B> backendList, Class<? extends F> frontendClazz, Class<B> backendClazz) { this.backendList = backendList; this.frontendClazz = frontendClazz; this.backendClazz = backendClazz; } public void add() { throw new UnsupportedOperationException( "Modifications to the list are not supported"); } public boolean add(F e) { throw new UnsupportedOperationException( "Modifications to the list are not supported"); } public void add(int index, F element) { throw new UnsupportedOperationException( "Modifications to the list are not supported"); } public boolean addAll(Collection<? extends F> c) { throw new UnsupportedOperationException( "Modifications to the list are not supported"); } public boolean addAll(int index, Collection<? extends F> c) { throw new UnsupportedOperationException( "Modifications to the list are not supported"); } public void clear() { throw new UnsupportedOperationException( "Modifications to the list are not supported"); } public boolean contains(Object o) { throw new UnsupportedOperationException("Contains() is not supported"); } public boolean containsAll(Collection<?> c) { throw new UnsupportedOperationException( "ContainsAll() is not supported"); } public F get(int index) { Constructor<F> c; try { c = (Constructor<F>) frontendClazz.getConstructor(backendClazz); return c.newInstance(backendList.get(index)); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } public int indexOf(Object o) { throw new UnsupportedOperationException("IndexOf() is not supported"); } public boolean isEmpty() { return backendList.isEmpty(); } public Iterator iterator() { return new BlogListIterator(backendList.listIterator(), frontendClazz, backendClazz); } public int lastIndexOf(Object o) { throw new UnsupportedOperationException( "lastIndexOf() is not supported"); } public ListIterator listIterator() { return new BlogListIterator(backendList.listIterator(), frontendClazz, backendClazz); } public ListIterator listIterator(int index) { return new BlogListIterator(backendList.listIterator(index), frontendClazz, backendClazz); } public boolean remove(Object o) { throw new UnsupportedOperationException( "Modifications to the list are not supported"); } public F remove(int index) { throw new UnsupportedOperationException( "Modifications to the list are not supported"); } public boolean removeAll(Collection c) { throw new UnsupportedOperationException( "Modifications to the list are not supported"); } public boolean retainAll(Collection c) { throw new UnsupportedOperationException( "Modifications to the list are not supported"); } public Object set(int index, Object element) { throw new UnsupportedOperationException( "Modifications to the list are not supported"); } public int size() { return backendList.size(); } public List subList(int fromIndex, int toIndex) { throw new UnsupportedOperationException("subList() is not supported"); } public Object[] toArray() { throw new UnsupportedOperationException("toArray() is not supported"); } public Object[] toArray(Object[] a) { throw new UnsupportedOperationException( "toArray(Object[] a) is not supported"); } }
8,237
0
Create_ds/aries/samples/blog/blog-biz/src/main/java/org/apache/aries/samples/blog
Create_ds/aries/samples/blog/blog-biz/src/main/java/org/apache/aries/samples/blog/biz/BlogEntryImpl.java
/** * 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. */ package org.apache.aries.samples.blog.biz; import java.util.Date; import org.apache.aries.samples.blog.api.BlogAuthor; import org.apache.aries.samples.blog.api.BlogEntry; import org.apache.aries.samples.blog.api.persistence.Entry; /** Implementation of a BlogPast */ public class BlogEntryImpl implements BlogEntry { public Entry theEntry; public BlogEntryImpl(Entry blogEntry) { theEntry = blogEntry; } public BlogAuthor getAuthor() { return new BlogAuthorImpl(theEntry.getAuthor()); } public String getBody() { return theEntry.getBlogText(); } public String getTitle() { return theEntry.getTitle(); } public String getAuthorEmail() { return theEntry.getAuthor().getEmail(); } public Date getPublishDate() { return theEntry.getPublishDate(); } public long getId() { return theEntry.getId(); } }
8,238
0
Create_ds/aries/samples/blog/blog-biz/src/main/java/org/apache/aries/samples/blog
Create_ds/aries/samples/blog/blog-biz/src/main/java/org/apache/aries/samples/blog/biz/BlogCommentImpl.java
/** * 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. */ package org.apache.aries.samples.blog.biz; import java.util.Date; import java.util.Calendar; import org.apache.aries.samples.blog.api.BlogAuthor; import org.apache.aries.samples.blog.api.BlogComment; import org.apache.aries.samples.blog.api.BlogEntry; import org.apache.aries.samples.blog.api.comment.persistence.Comment; public class BlogCommentImpl implements BlogComment { private static Calendar cal = Calendar.getInstance(); private Comment comment; public BlogCommentImpl(Comment c) { comment = c; } /** Get comment * @return the String representing the comment */ public String getComment() { return comment.getComment(); } /** Get the author of the comment * @return the BlogAuthor instance */ public BlogAuthor getAuthor() { return new BlogAuthorImpl(comment.getAuthor()); } /** Get the parent blog post for the comment * @return the BlogPost instance the comment is attached to. */ public BlogEntry getEntry() { return new BlogEntryImpl(comment.getEntry()); } /** Get the Id value of the comment * @return the integer id of the comment */ public int getId() { return comment.getId(); } /** Get the creation date for the comment * @return the String representation of the date the comment was * created in dd-mm-yyyy format. */ public String getCommentCreationDate() { Date dc = comment.getCreationDate(); int year; int month; int date; synchronized (cal) { cal.setTime(dc); year = cal.get(Calendar.YEAR); month = cal.get(Calendar.MONTH) + 1; date = cal.get(Calendar.DATE); } return year + "-" + month + "-" + date; } }
8,239
0
Create_ds/aries/samples/blog/blog-biz/src/main/java/org/apache/aries/samples/blog
Create_ds/aries/samples/blog/blog-biz/src/main/java/org/apache/aries/samples/blog/biz/BlogEntryManagerImpl.java
/** * 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. */ package org.apache.aries.samples.blog.biz; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.apache.aries.samples.blog.api.BlogAuthor; import org.apache.aries.samples.blog.api.BlogEntry; import org.apache.aries.samples.blog.api.BlogEntryManager; import org.apache.aries.samples.blog.api.persistence.BlogPersistenceService; import org.apache.aries.samples.blog.api.persistence.Entry; public class BlogEntryManagerImpl implements BlogEntryManager { private BlogPersistenceService persistenceService; // Injected via blueprint public void setPersistenceService(BlogPersistenceService persistenceService) { this.persistenceService = persistenceService; } public void createBlogPost(String email, String title, String blogText, List<String> tags) { persistenceService.createBlogPost(email, title, blogText, tags); } public Entry findBlogEntryByTitle(String title) { return persistenceService.findBlogEntryByTitle(title); } public List<? extends BlogEntry> getAllBlogEntries() { List<? extends Entry> entries = persistenceService.getAllBlogEntries(); return adaptEntries(entries); } public List<? extends BlogEntry> getBlogEntries(int firstPostIndex, int noOfPosts) { List<? extends Entry> entries = persistenceService.getBlogEntries(firstPostIndex, noOfPosts); return adaptEntries(entries); } public List<? extends BlogEntry> getBlogsForAuthor(String emailAddress) { List <?extends Entry> entries= persistenceService.getBlogsForAuthor(emailAddress); return adaptEntries(entries); } public List<? extends BlogEntry> getBlogEntriesModifiedBetween(String startDate, String endDate) throws ParseException { if(startDate == null || "".equals(startDate)) throw new IllegalArgumentException("A valid start date must be supplied"); if(endDate == null || "".equals(endDate)) throw new IllegalArgumentException("A valid end date must be supplied"); SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); Date start = sdf.parse(startDate); Date end = sdf.parse(endDate); List <? extends Entry> entries = persistenceService.getBlogEntriesModifiedBetween(start, end); return adaptEntries(entries); } public int getNoOfPosts() { return persistenceService.getNoOfBlogEntries(); } public void removeBlogEntry(BlogAuthor a, String title, String publishDate) throws ParseException { if(a == null) throw new IllegalArgumentException("An author must be specified"); if(title == null) title = ""; if(publishDate == null) throw new IllegalArgumentException("The article must have a publication date"); Date pubDate = parseDate(publishDate); long found = -920234218060948564L; for(BlogEntry b : a.getEntries()) { if(title.equals(b.getTitle()) && pubDate.equals(b.getPublishDate())){ found = b.getId(); break; } } persistenceService.removeBlogEntry(found); } public void updateBlogEntry(BlogEntry originalEntry, BlogAuthor a, String title, String publishDate, String blogText, List<String> tags) throws ParseException { if (originalEntry.getAuthor() == null || originalEntry.getAuthorEmail() == null) throw new IllegalArgumentException("An author must be specified"); if (title == null) title = ""; if (publishDate == null) throw new IllegalArgumentException( "The article must have a publication date"); long found = -920234218060948564L; Date pubDate = parseDate(publishDate); for (BlogEntry b : getBlogsForAuthor(originalEntry.getAuthorEmail() )) { if (title.equals(b.getTitle()) && pubDate.equals(b.getPublishDate())) { found = b.getId(); break; } } if (found == -920234218060948564L) throw new IllegalArgumentException("No blog entry could be found"); String email = a.getEmailAddress(); if (tags == null) { tags = new ArrayList<String>(); } Date updatedDate = new Date(System.currentTimeMillis()); persistenceService.updateBlogEntry(found, email, title, blogText, tags, updatedDate); } private Date parseDate(String dateString) throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); return sdf.parse(dateString); } public BlogEntry getBlogPost(long id) { return new BlogEntryImpl(persistenceService.getBlogEntryById(id)); } private List <? extends BlogEntry> adaptEntries(List<? extends Entry> entries) { return new BlogListAdapter<BlogEntry, Entry>(entries, BlogEntryImpl.class, Entry.class); } }
8,240
0
Create_ds/aries/samples/blog/blog-biz/src/main/java/org/apache/aries/samples/blog
Create_ds/aries/samples/blog/blog-biz/src/main/java/org/apache/aries/samples/blog/biz/BlogAuthorManagerImpl.java
/** * 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. */ package org.apache.aries.samples.blog.biz; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import org.apache.aries.samples.blog.api.*; import org.apache.aries.samples.blog.api.persistence.Author; import org.apache.aries.samples.blog.api.persistence.BlogPersistenceService; public class BlogAuthorManagerImpl implements BlogAuthorManager { private BlogPersistenceService persistenceService; // Blueprint injection used to set the persistenceService public void setPersistenceService(BlogPersistenceService persistenceService) { this.persistenceService = persistenceService; } public void createAuthor(String email, String dob, String name, String displayName, String bio) throws ParseException { if(email == null) throw new IllegalArgumentException("Email must not be null"); Date dateOfBirth; dateOfBirth = (dob == null || "".equals(dob)) ? null : new SimpleDateFormat("yyyy-MM-dd").parse(dob); persistenceService.createAuthor(email, dateOfBirth, name, displayName, bio); } public List<? extends BlogAuthor> getAllAuthors() { List<? extends Author> authors = persistenceService.getAllAuthors(); return adaptAuthor(authors); } public BlogAuthor getAuthor(String emailAddress) { if(emailAddress == null) throw new IllegalArgumentException("Email must not be null"); Author a = persistenceService.getAuthor(emailAddress); if (a != null) return new BlogAuthorImpl(a); else return null; } public void removeAuthor(String emailAddress) { if(emailAddress == null) throw new IllegalArgumentException("Email must not be null"); persistenceService.removeAuthor(emailAddress); } public void updateAuthor(String email, String dob, String name, String displayName, String bio) throws ParseException { if(email == null) throw new IllegalArgumentException("Email must not be null"); Date dateOfBirth; dateOfBirth = (dob == null || "".equals(dob)) ? null : new SimpleDateFormat("yyyy-MM-dd").parse(dob); persistenceService.updateAuthor(email, dateOfBirth, name, displayName, bio); } private List<? extends BlogAuthor> adaptAuthor(List<? extends Author> authors) { return new BlogListAdapter<BlogAuthor, Author>(authors, BlogAuthorImpl.class, Author.class); } }
8,241
0
Create_ds/aries/samples/blog/blog-biz/src/main/java/org/apache/aries/samples/blog
Create_ds/aries/samples/blog/blog-biz/src/main/java/org/apache/aries/samples/blog/biz/BloggingServiceImpl.java
/** * 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. */ package org.apache.aries.samples.blog.biz; import java.text.ParseException; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.apache.aries.samples.blog.api.BlogAuthor; import org.apache.aries.samples.blog.api.BlogAuthorManager; import org.apache.aries.samples.blog.api.BlogComment; import org.apache.aries.samples.blog.api.BlogCommentManager; import org.apache.aries.samples.blog.api.BlogEntry; import org.apache.aries.samples.blog.api.BlogEntryManager; import org.apache.aries.samples.blog.api.BloggingService; /** Implementation of the BloggingService */ public class BloggingServiceImpl implements BloggingService { private BlogEntryManager blogEntryManager; private BlogAuthorManager blogAuthorManager; private BlogCommentManager blogCommentManager; // Injected via blueprint public void setBlogEntryManager(BlogEntryManager blogPostManager) { this.blogEntryManager = blogPostManager; } // Injected via blueprint public void setBlogAuthorManager(BlogAuthorManager authorManager) { this.blogAuthorManager = authorManager; } // Injected via blueprint public void setBlogCommentManager(BlogCommentManager commentManager) { this.blogCommentManager = commentManager; } public String getBlogTitle() { return new BlogImpl().getBlogTitle(); } public BlogAuthor getBlogAuthor(String email) { return blogAuthorManager.getAuthor(email); } public void createBlogAuthor(String email, String nickName, String name, String bio, String dob) { try { blogAuthorManager.createAuthor(email, dob, name, nickName, bio); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void updateBlogAuthor(String email, String nickName, String name, String bio, String dob) { try { blogAuthorManager.updateAuthor(email, dob, name, nickName, bio); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public BlogEntry getPost(long id) { return blogEntryManager.getBlogPost(id); } public List<? extends BlogEntry> getBlogEntries(int firstPostIndex, int noOfPosts) { return blogEntryManager.getBlogEntries(firstPostIndex, noOfPosts); } public List<? extends BlogEntry> getAllBlogEntries() { return blogEntryManager.getAllBlogEntries(); } public int getNoOfEntries() { return blogEntryManager.getNoOfPosts(); } public void createBlogEntry(String email, String title, String blogText, String tags) { blogEntryManager.createBlogPost(email, title, blogText, Arrays .asList(tags.split(","))); } public void createBlogComment(String comment, String authorEmail, long id) { if (blogCommentManager != null) { blogCommentManager.createComment(comment, authorEmail, id); } } public void deleteBlogComment(BlogComment comment) { if (blogCommentManager != null) { blogCommentManager.deleteComment(comment.getId()); } } public List<? extends BlogComment> getCommentsForEntry(BlogEntry entry) { if (blogCommentManager != null) { return blogCommentManager.getCommentsForPost(entry.getId()); } return Collections.<BlogComment>emptyList(); } public BlogEntry getBlogEntry(long id) { return blogEntryManager.getBlogPost(id); } public boolean isCommentingAvailable() { if (blogCommentManager != null) { return blogCommentManager.isCommentingAvailable(); } return false; } }
8,242
0
Create_ds/aries/samples/blog/blog-biz/src/main/java/org/apache/aries/samples/blog
Create_ds/aries/samples/blog/blog-biz/src/main/java/org/apache/aries/samples/blog/biz/BlogAuthorImpl.java
/** * 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. */ package org.apache.aries.samples.blog.biz; import java.util.Calendar; import java.util.Date; import java.util.List; import org.apache.aries.samples.blog.api.BlogAuthor; import org.apache.aries.samples.blog.api.BlogEntry; import org.apache.aries.samples.blog.api.persistence.Author; import org.apache.aries.samples.blog.api.persistence.Entry; public class BlogAuthorImpl implements BlogAuthor { private static Calendar cal = Calendar.getInstance(); private Author author; public BlogAuthorImpl(Author a) { author = a; } public String getBio() { return author.getBio(); } public String getEmailAddress() { return author.getEmail(); } public String getFullName() { return author.getName(); } public String getName() { return author.getDisplayName(); } public String getDateOfBirth() { Date dob = author.getDob(); int year = 0; int month = 0; int date = 0; synchronized (cal) { if (dob != null) { cal.setTime(dob); year = cal.get(Calendar.YEAR); month = cal.get(Calendar.MONTH) + 1; date = cal.get(Calendar.DATE); } } return year + "-" + month + "-" + date; } public List<? extends BlogEntry> getEntries() { return adapt(author.getEntries()); } private List<? extends BlogEntry> adapt(List<? extends Entry> list) { List<BlogEntryImpl> bei = null; ; return bei; } }
8,243
0
Create_ds/aries/samples/blog/blog-comment-ejb/src/main/java/org/apache/aries/samples/blog/comment
Create_ds/aries/samples/blog/blog-comment-ejb/src/main/java/org/apache/aries/samples/blog/comment/ejb/CommentImpl.java
/** * 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. */ package org.apache.aries.samples.blog.comment.ejb; import java.util.Date; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.apache.aries.samples.blog.api.comment.persistence.Comment; import org.apache.aries.samples.blog.api.persistence.Author; import org.apache.aries.samples.blog.api.persistence.BlogPersistenceService; import org.apache.aries.samples.blog.api.persistence.Entry; @Entity(name="Comment") public class CommentImpl implements Comment{ @Id @GeneratedValue private int id; private String comment; @Temporal(TemporalType.TIMESTAMP) private Date creationDate; //Details for author private String authorId; //Details for entry private long entryId; public CommentImpl(String comment, String authorId, long entryId) { this.comment = comment; this.authorId = authorId; this.entryId = entryId; this.creationDate = new Date(); } public String getComment() { return comment; } public Date getCreationDate() { return creationDate; } public int getId() { return id; } public Author getAuthor() { try { BlogPersistenceService bps = (BlogPersistenceService) new InitialContext().lookup( "osgi:service/" + BlogPersistenceService.class.getName()); return bps.getAuthor(authorId); } catch (NamingException e) { throw new RuntimeException(e); } } public Entry getEntry() { try { BlogPersistenceService bps = (BlogPersistenceService) new InitialContext().lookup( "osgi:service/" + BlogPersistenceService.class.getName()); return bps.getBlogEntryById(entryId); } catch (NamingException e) { throw new RuntimeException(e); } } public String getAuthorId() { return authorId; } public void setAuthorId(String authorId) { this.authorId = authorId; } public long getEntryId() { return entryId; } public void setEntryId(long entryId) { this.entryId = entryId; } public void setId(int id) { this.id = id; } public void setComment(String comment) { this.comment = comment; } public void setCreationDate(Date creationDate) { this.creationDate = creationDate; } }
8,244
0
Create_ds/aries/samples/blog/blog-comment-ejb/src/main/java/org/apache/aries/samples/blog/comment
Create_ds/aries/samples/blog/blog-comment-ejb/src/main/java/org/apache/aries/samples/blog/comment/ejb/BlogCommentEJB.java
/** * 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. */ package org.apache.aries.samples.blog.comment.ejb; import java.util.List; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; import org.apache.aries.samples.blog.api.comment.persistence.BlogCommentService; import org.apache.aries.samples.blog.api.comment.persistence.Comment; @Stateless(name="Commenting") public class BlogCommentEJB implements BlogCommentService { @PersistenceContext(unitName="blogComments") private EntityManager commentEM; public void createComment(String comment, String author, long entryId) { commentEM.persist(new CommentImpl(comment, author, entryId)); } public void delete(int id) { CommentImpl c = commentEM.find(CommentImpl.class, id); if(c != null) commentEM.remove(c); } public List<? extends Comment> getCommentsForAuthor(String authorId) { TypedQuery<CommentImpl> q = commentEM.createQuery( "SELECT c FROM Comment c WHERE c.authorId = :authorId", CommentImpl.class); q.setParameter("authorId", authorId); return q.getResultList(); } public List<? extends Comment> getCommentsForEntry(long entryId) { TypedQuery<CommentImpl> q = commentEM.createQuery( "SELECT c FROM Comment c WHERE c.entryId = :entryId", CommentImpl.class); q.setParameter("entryId", entryId); return q.getResultList(); } }
8,245
0
Create_ds/aries/samples/blog/blog-itests/src/test/java/org/apache/aries/samples/blog
Create_ds/aries/samples/blog/blog-itests/src/test/java/org/apache/aries/samples/blog/itests/QuiesceBlogSampleWithEbaTest.java
/* * 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. */ package org.apache.aries.samples.blog.itests; import static org.junit.Assert.assertTrue; import java.util.Arrays; import java.util.Collections; import javax.inject.Inject; import org.apache.aries.application.management.AriesApplicationContext; import org.apache.aries.quiesce.manager.QuiesceManager; import org.junit.Test; import org.ops4j.pax.exam.CoreOptions; import org.ops4j.pax.exam.options.MavenArtifactUrlReference; import org.osgi.framework.Bundle; public class QuiesceBlogSampleWithEbaTest extends AbstractBlogIntegrationTest { @Inject QuiesceManager quiesceMgr; @Test public void test() throws Exception { resolveBundles(); MavenArtifactUrlReference eba = CoreOptions.maven() .groupId("org.apache.aries.samples.blog") .artifactId("org.apache.aries.samples.blog.jpa.eba") .versionAsInProject() .type("eba"); AriesApplicationContext ctx = installEba(eba); /* Find and check all the blog sample bundles */ Bundle bapi = assertBundleStarted("org.apache.aries.samples.blog.api"); Bundle bweb = assertBundleStarted("org.apache.aries.samples.blog.web"); Bundle bbiz = assertBundleStarted("org.apache.aries.samples.blog.biz"); Bundle bper = assertBundleStarted("org.apache.aries.samples.blog.persistence.jpa"); Bundle bds = assertBundleStarted("org.apache.aries.samples.blog.datasource"); Bundle txs = assertBundleStarted("org.apache.aries.transaction.manager"); assertBlogServicesStarted(); checkBlogWebAccess(); //So Blog is working properly, let's quiesce it, we would expect to get a JPA and a Blueprint //participant quiesceMgr.quiesce(500, Collections.singletonList(bapi)); Thread.sleep(1000); // Blog api bundle should now be stopped, but others should still be running assertResolved(bapi); assertActive(bweb); assertActive(bbiz); assertActive(bper); quiesceMgr.quiesce(500, Arrays.asList(bapi, bweb, bbiz, bper)); Thread.sleep(1000); // All blog bundles should now be stopped assertResolved(bapi); assertResolved(bweb); assertResolved(bbiz); assertResolved(bper); // Check we can start them again after quiesce and everything works as before bapi.start(); bweb.start(); bbiz.start(); bper.start(); assertBlogServicesStarted(); assertBlogServicesStarted(); System.out.println("Checking if blog works again after restart"); checkBlogWebAccess(); ctx.stop(); manager.uninstall(ctx); } }
8,246
0
Create_ds/aries/samples/blog/blog-itests/src/test/java/org/apache/aries/samples/blog
Create_ds/aries/samples/blog/blog-itests/src/test/java/org/apache/aries/samples/blog/itests/AbstractBlogIntegrationTest.java
/* * 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. */ package org.apache.aries.samples.blog.itests; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.ops4j.pax.exam.CoreOptions.composite; import static org.ops4j.pax.exam.CoreOptions.frameworkProperty; import static org.ops4j.pax.exam.CoreOptions.junitBundles; import static org.ops4j.pax.exam.CoreOptions.mavenBundle; import static org.ops4j.pax.exam.CoreOptions.options; import static org.ops4j.pax.exam.CoreOptions.systemProperty; import static org.ops4j.pax.exam.CoreOptions.vmOption; import static org.ops4j.pax.exam.CoreOptions.when; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import javax.inject.Inject; import javax.sql.XADataSource; import javax.transaction.TransactionManager; import org.apache.aries.application.management.AriesApplication; import org.apache.aries.application.management.AriesApplicationContext; import org.apache.aries.application.management.AriesApplicationManager; import org.apache.aries.samples.blog.api.BloggingService; import org.apache.aries.samples.blog.api.persistence.BlogPersistenceService; import org.junit.runner.RunWith; import org.ops4j.pax.exam.Configuration; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.junit.PaxExam; import org.ops4j.pax.exam.options.MavenArtifactUrlReference; import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy; import org.ops4j.pax.exam.spi.reactors.PerClass; import org.osgi.framework.Bundle; import org.osgi.framework.ServiceReference; @RunWith(PaxExam.class) @ExamReactorStrategy(PerClass.class) public abstract class AbstractBlogIntegrationTest extends org.apache.aries.itest.AbstractIntegrationTest { private static final int CONNECTION_TIMEOUT = 30000; public static final long DEFAULT_TIMEOUT = 60000; @Inject AriesApplicationManager manager; protected AriesApplicationContext installEba(MavenArtifactUrlReference eba) throws Exception { AriesApplication app = manager.createApplication(new URL(eba.getURL())); AriesApplicationContext ctx = manager.install(app); ctx.start(); return ctx; } protected Bundle assertBundleStarted(String symName) { Bundle bundle = context().getBundleByName(symName); assertNotNull("Bundle " + symName + " not found", bundle); assertEquals(Bundle.ACTIVE, bundle.getState()); return bundle; } protected void assertActive(Bundle bundle) { assertTrue("Bundle " + bundle.getSymbolicName() + " should be ACTIVE but is in state " + bundle.getState(), bundle.getState() == Bundle.ACTIVE); } protected void assertResolved(Bundle bundle) { assertTrue("Bundle " + bundle.getSymbolicName() + " should be ACTIVE but is in state " + bundle.getState(), bundle.getState() == Bundle.RESOLVED); } @SuppressWarnings("rawtypes") protected void listBundleServices(Bundle b) { ServiceReference []srb = b.getRegisteredServices(); for(ServiceReference sr:srb){ System.out.println(b.getSymbolicName() + " SERVICE: "+sr); } } @SuppressWarnings("rawtypes") protected Boolean isServiceRegistered(Bundle b) { ServiceReference []srb = b.getRegisteredServices(); if(srb == null) { return false; } return true; } protected void checkBlogWebAccess() throws IOException, InterruptedException { Thread.sleep(1000); HttpURLConnection conn = makeConnection("http://localhost:8080/blog/ViewBlog"); String response = getHTTPResponse(conn); /* Uncomment for additional debug */ /* System.out.println("ZZZZZ " + response); System.out.println("ZZZZZ " + conn.getResponseCode()); System.out.println("ZZZZZ " + HttpURLConnection.HTTP_OK); */ assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode()); assertTrue("The response did not contain the expected content", response.contains("Blog home")); } public static String getHTTPResponse(HttpURLConnection conn) throws IOException { StringBuilder response = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "ISO-8859-1")); try { for (String s = reader.readLine(); s != null; s = reader.readLine()) { response.append(s).append("\r\n"); } } finally { reader.close(); } return response.toString(); } public static HttpURLConnection makeConnection(String contextPath) throws IOException { URL url = new URL(contextPath); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(CONNECTION_TIMEOUT); conn.connect(); return conn; } protected Option baseOptions() { String localRepo = System.getProperty("maven.repo.local"); if (localRepo == null) { localRepo = System.getProperty("org.ops4j.pax.url.mvn.localRepository"); } return composite( junitBundles(), mavenBundle("org.ops4j.pax.logging", "pax-logging-api", "1.7.2"), mavenBundle("org.ops4j.pax.logging", "pax-logging-service", "1.7.2"), mavenBundle("org.apache.aries.testsupport", "org.apache.aries.testsupport.unit").versionAsInProject(), // this is how you set the default log level when using pax // logging (logProfile) systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level").value("INFO"), when(localRepo != null).useOptions(vmOption("-Dorg.ops4j.pax.url.mvn.localRepository=" + localRepo)) ); } @Configuration public Option[] configuration() { return options( baseOptions(), frameworkProperty("org.osgi.framework.system.packages") .value("javax.accessibility,javax.activation,javax.activity,javax.annotation,javax.annotation.processing,javax.crypto,javax.crypto.interfaces,javax.crypto.spec,javax.imageio,javax.imageio.event,javax.imageio.metadata,javax.imageio.plugins.bmp,javax.imageio.plugins.jpeg,javax.imageio.spi,javax.imageio.stream,javax.jws,javax.jws.soap,javax.lang.model,javax.lang.model.element,javax.lang.model.type,javax.lang.model.util,javax.management,javax.management.loading,javax.management.modelmbean,javax.management.monitor,javax.management.openmbean,javax.management.relation,javax.management.remote,javax.management.remote.rmi,javax.management.timer,javax.naming,javax.naming.directory,javax.naming.event,javax.naming.ldap,javax.naming.spi,javax.net,javax.net.ssl,javax.print,javax.print.attribute,javax.print.attribute.standard,javax.print.event,javax.rmi,javax.rmi.CORBA,javax.rmi.ssl,javax.script,javax.security.auth,javax.security.auth.callback,javax.security.auth.kerberos,javax.security.auth.login,javax.security.auth.spi,javax.security.auth.x500,javax.security.cert,javax.security.sasl,javax.sound.midi,javax.sound.midi.spi,javax.sound.sampled,javax.sound.sampled.spi,javax.sql,javax.sql.rowset,javax.sql.rowset.serial,javax.sql.rowset.spi,javax.swing,javax.swing.border,javax.swing.colorchooser,javax.swing.event,javax.swing.filechooser,javax.swing.plaf,javax.swing.plaf.basic,javax.swing.plaf.metal,javax.swing.plaf.multi,javax.swing.plaf.synth,javax.swing.table,javax.swing.text,javax.swing.text.html,javax.swing.text.html.parser,javax.swing.text.rtf,javax.swing.tree,javax.swing.undo,javax.tools,javax.xml,javax.xml.bind,javax.xml.bind.annotation,javax.xml.bind.annotation.adapters,javax.xml.bind.attachment,javax.xml.bind.helpers,javax.xml.bind.util,javax.xml.crypto,javax.xml.crypto.dom,javax.xml.crypto.dsig,javax.xml.crypto.dsig.dom,javax.xml.crypto.dsig.keyinfo,javax.xml.crypto.dsig.spec,javax.xml.datatype,javax.xml.namespace,javax.xml.parsers,javax.xml.soap,javax.xml.stream,javax.xml.stream.events,javax.xml.stream.util,javax.xml.transform,javax.xml.transform.dom,javax.xml.transform.sax,javax.xml.transform.stax,javax.xml.transform.stream,javax.xml.validation,javax.xml.ws,javax.xml.ws.handler,javax.xml.ws.handler.soap,javax.xml.ws.http,javax.xml.ws.soap,javax.xml.ws.spi,javax.xml.xpath,org.ietf.jgss,org.omg.CORBA,org.omg.CORBA.DynAnyPackage,org.omg.CORBA.ORBPackage,org.omg.CORBA.TypeCodePackage,org.omg.CORBA.portable,org.omg.CORBA_2_3,org.omg.CORBA_2_3.portable,org.omg.CosNaming,org.omg.CosNaming.NamingContextExtPackage,org.omg.CosNaming.NamingContextPackage,org.omg.Dynamic,org.omg.DynamicAny,org.omg.DynamicAny.DynAnyFactoryPackage,org.omg.DynamicAny.DynAnyPackage,org.omg.IOP,org.omg.IOP.CodecFactoryPackage,org.omg.IOP.CodecPackage,org.omg.Messaging,org.omg.PortableInterceptor,org.omg.PortableInterceptor.ORBInitInfoPackage,org.omg.PortableServer,org.omg.PortableServer.CurrentPackage,org.omg.PortableServer.POAManagerPackage,org.omg.PortableServer.POAPackage,org.omg.PortableServer.ServantLocatorPackage,org.omg.PortableServer.portable,org.omg.SendingContext,org.omg.stub.java.rmi,org.w3c.dom,org.w3c.dom.bootstrap,org.w3c.dom.css,org.w3c.dom.events,org.w3c.dom.html,org.w3c.dom.ls,org.w3c.dom.ranges,org.w3c.dom.stylesheets,org.w3c.dom.traversal,org.w3c.dom.views,org.xml.sax,org.xml.sax.ext,org.xml.sax.helpers"), // Log //mavenBundle("org.ops4j.pax.logging", "pax-logging-api").versionAsInProject(), //mavenBundle("org.ops4j.pax.logging", "pax-logging-service").versionAsInProject(), // Felix mvn url handler - do we need this? //mavenBundle("org.ops4j.pax.url", "pax-url-aether").versionAsInProject(), mavenBundle("org.eclipse.equinox", "cm").versionAsInProject(), mavenBundle("org.eclipse.osgi", "services").versionAsInProject(), mavenBundle("org.apache.xbean", "xbean-asm4-shaded").versionAsInProject(), mavenBundle("org.apache.xbean", "xbean-finder-shaded").versionAsInProject(), mavenBundle("org.ops4j.pax.web", "pax-web-jetty-bundle").versionAsInProject(), mavenBundle("org.ops4j.pax.web", "pax-web-extender-war").versionAsInProject(), //mavenBundle("org.ops4j.pax.web", "pax-web-jsp").versionAsInProject(), mavenBundle("org.apache.derby", "derby").versionAsInProject(), mavenBundle("org.apache.geronimo.specs", "geronimo-jpa_2.0_spec").versionAsInProject(), mavenBundle("org.apache.geronimo.specs", "geronimo-jta_1.1_spec").versionAsInProject(), mavenBundle("org.apache.geronimo.specs", "geronimo-j2ee-connector_1.5_spec").versionAsInProject(), mavenBundle("org.apache.geronimo.specs", "geronimo-servlet_2.5_spec").versionAsInProject(), mavenBundle("org.apache.geronimo.components", "geronimo-transaction").versionAsInProject(), mavenBundle("org.apache.openjpa", "openjpa").versionAsInProject(), mavenBundle("commons-lang", "commons-lang").versionAsInProject(), mavenBundle("commons-collections", "commons-collections").versionAsInProject(), mavenBundle("commons-pool", "commons-pool").versionAsInProject(), mavenBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.serp").versionAsInProject(), mavenBundle("org.apache.aries.quiesce", "org.apache.aries.quiesce.api").versionAsInProject(), mavenBundle("org.apache.aries.quiesce", "org.apache.aries.quiesce.manager").versionAsInProject(), mavenBundle("org.apache.aries.blueprint", "org.apache.aries.blueprint" ).versionAsInProject(), mavenBundle("org.apache.aries.proxy", "org.apache.aries.proxy").versionAsInProject(), mavenBundle("org.apache.aries", "org.apache.aries.util" ).versionAsInProject(), mavenBundle("org.apache.aries.jndi", "org.apache.aries.jndi" ).versionAsInProject(), mavenBundle("org.apache.felix", "org.apache.felix.fileinstall" ).versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.install" ).versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.api" ).versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.management" ).versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.runtime" ).versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.utils" ).versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.default.local.platform").versionAsInProject(), mavenBundle("org.apache.felix", "org.apache.felix.bundlerepository").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.resolver.obr").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.modeller").versionAsInProject(), mavenBundle("org.apache.aries.application", "org.apache.aries.application.deployment.management").versionAsInProject(), mavenBundle("org.apache.aries.jpa", "org.apache.aries.jpa.api" ).versionAsInProject(), mavenBundle("org.apache.aries.jpa", "org.apache.aries.jpa.container" ).versionAsInProject(), mavenBundle("org.apache.aries.jpa", "org.apache.aries.jpa.blueprint.aries" ).versionAsInProject(), mavenBundle("org.apache.aries.jpa", "org.apache.aries.jpa.container.context" ).versionAsInProject(), mavenBundle("org.apache.aries.transaction", "org.apache.aries.transaction.manager" ).versionAsInProject(), mavenBundle("org.apache.aries.transaction", "org.apache.aries.transaction.blueprint" ).versionAsInProject(), mavenBundle("org.apache.aries.transaction", "org.apache.aries.transaction.wrappers" ).versionAsInProject(), mavenBundle("org.ow2.asm", "asm-all" ).versionAsInProject(), mavenBundle("org.apache.aries.samples.blog", "org.apache.aries.samples.blog.datasource" ).versionAsInProject() ///vmOption("-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=7777"), ); } protected void assertBlogServicesStarted() { context().getService(BloggingService.class); context().getService(BlogPersistenceService.class); context().getService(XADataSource.class); context().getService(TransactionManager.class); } }
8,247
0
Create_ds/aries/samples/blog/blog-itests/src/test/java/org/apache/aries/samples/blog
Create_ds/aries/samples/blog/blog-itests/src/test/java/org/apache/aries/samples/blog/itests/JdbcBlogSampleWithEbaTest.java
/* * 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. */ package org.apache.aries.samples.blog.itests; import static org.ops4j.pax.exam.CoreOptions.maven; import org.apache.aries.application.management.AriesApplicationContext; import org.junit.Test; import org.ops4j.pax.exam.options.MavenArtifactUrlReference; public class JdbcBlogSampleWithEbaTest extends AbstractBlogIntegrationTest { @Test public void test() throws Exception { MavenArtifactUrlReference eba = maven() .groupId("org.apache.aries.samples.blog") .artifactId("org.apache.aries.samples.blog.jdbc.eba") .versionAsInProject() .type("eba"); AriesApplicationContext ctx = installEba(eba); /* Check that the Blog Sample bundles are present an started */ assertBundleStarted("org.apache.aries.samples.blog.api"); assertBundleStarted("org.apache.aries.samples.blog.web"); assertBundleStarted("org.apache.aries.samples.blog.biz"); assertBundleStarted("org.apache.aries.samples.blog.persistence.jdbc"); assertBlogServicesStarted(); checkBlogWebAccess(); ctx.stop(); manager.uninstall(ctx); } }
8,248
0
Create_ds/aries/samples/blog/blog-itests/src/test/java/org/apache/aries/samples/blog
Create_ds/aries/samples/blog/blog-itests/src/test/java/org/apache/aries/samples/blog/itests/JpaBlogSampleWithEbaTest.java
/* * 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. */ package org.apache.aries.samples.blog.itests; import static org.ops4j.pax.exam.CoreOptions.maven; import org.apache.aries.application.management.AriesApplicationContext; import org.junit.Test; import org.ops4j.pax.exam.options.MavenArtifactUrlReference; public class JpaBlogSampleWithEbaTest extends AbstractBlogIntegrationTest { @Test public void test() throws Exception { MavenArtifactUrlReference eba = maven() .groupId("org.apache.aries.samples.blog") .artifactId("org.apache.aries.samples.blog.jpa.eba") .versionAsInProject() .type("eba"); AriesApplicationContext ctx = installEba(eba); /* Find and check all the blog sample bundles */ assertBundleStarted("org.apache.aries.samples.blog.api"); assertBundleStarted("org.apache.aries.samples.blog.web"); assertBundleStarted("org.apache.aries.samples.blog.biz"); assertBundleStarted("org.apache.aries.samples.blog.persistence.jpa"); assertBundleStarted("org.apache.aries.samples.blog.datasource"); assertBundleStarted("org.apache.aries.transaction.manager"); assertBlogServicesStarted(); checkBlogWebAccess(); ctx.stop(); manager.uninstall(ctx); } }
8,249
0
Create_ds/aries/samples/blog/blog-web/src/main/java/org/apache/aries/samples/blog
Create_ds/aries/samples/blog/blog-web/src/main/java/org/apache/aries/samples/blog/web/AddCommentForm.java
/** * 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. */ package org.apache.aries.samples.blog.web; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.aries.samples.blog.web.util.HTMLOutput; public class AddCommentForm extends HttpServlet{ private static final long serialVersionUID = 4989805137759774598L; public static final String ERROR_MESSAGES_ID = "commentErrorMessages"; public static final String ID = "comment"; protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PrintWriter out = resp.getWriter(); String postId = checkPostId(req.getParameter("postId")); // if we have a valid postId, display the add comment page if (postId != null) { HTMLOutput.writeHTMLHeaderPartOne(out, "Add Comment"); HTMLOutput.writeDojoUses(out, "dojo.parser", "dijit.dijit", "dijit.Editor", "dijit.form.TextBox"); out.println("<script type=\"text/javascript\">"); out.println("function storeCommentContent() {"); out.println("var textBox = dijit.byId('textArea');"); out.println("var textArea = dojo.byId('text');"); out.println("textArea.value = textBox.getValue();"); out.println("}"); out.println("</script>"); HTMLOutput.writeHTMLHeaderPartTwo(out); List<String> errors = null; if (req.getSession() != null) errors = (List<String>) req.getSession().getAttribute( ERROR_MESSAGES_ID); if (errors != null) { out.println("\t\t\t<div id=\"errorMessages\">"); for (String msg : errors) { out.println("\t\t\t\t<div class=\"errorMessage\">" + msg + "</div>"); } out.println("\t\t\t</div>"); req.getSession().removeAttribute("commentErrorMessages"); } out .println("<form name=\"createComment\" method=\"get\" action=\"AddComment\">"); out .println("<div class=\"textEntry\"><textarea dojoType=\"dijit.Editor\" id=\"textArea\" name=\"textArea\"></textarea></div>"); out .println("<div class=\"textEntry\"><label>Email <input dojoType=\"dijit.form.TextBox\" type=\"text\" name=\"email\" /></label></div>"); out .println("<input type=\"hidden\" name=\"text\" id=\"text\" value=\"\"/>"); out.print("<input type=\"hidden\" name=\"postId\" value=\""); out.print(postId); out.println("\"/>"); out .println("<input class=\"submit\" type=\"submit\" value=\"Submit\" name=\"Submit\" onclick=\"storeCommentContent()\"/>"); out.println("</form>"); HTMLOutput.writeHTMLFooter(out); } else { // otherwise show the blog RequestDispatcher dispatch = getServletContext() .getRequestDispatcher("ViewBlog"); dispatch.forward(req, resp); } } private String checkPostId(String parameter) { if (parameter != null && parameter.matches("^\\d*$")) return parameter; return null; } }
8,250
0
Create_ds/aries/samples/blog/blog-web/src/main/java/org/apache/aries/samples/blog
Create_ds/aries/samples/blog/blog-web/src/main/java/org/apache/aries/samples/blog/web/ViewAuthor.java
/** * 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. */ package org.apache.aries.samples.blog.web; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.aries.samples.blog.api.BlogAuthor; import org.apache.aries.samples.blog.api.BloggingService; import org.apache.aries.samples.blog.web.util.HTMLOutput; import org.apache.aries.samples.blog.web.util.JNDIHelper; public class ViewAuthor extends HttpServlet { private static final long serialVersionUID = 3020369464892668248L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String email = req.getParameter("email"); if (email == null || "".equals(email)) { // TODO dispatch to another page } else { PrintWriter out = resp.getWriter(); BloggingService service = JNDIHelper.getBloggingService(); BlogAuthor author = service.getBlogAuthor(email); HTMLOutput.writeHTMLHeaderPartOne(out, author.getName()); HTMLOutput.writeHTMLHeaderPartTwo(out); out.println("<h3>Name</h3>"); out.print("<div class=\"text\">"); out.print(author.getFullName()); out.println("</div>"); out.println("<h3>Nick Name</h3>"); out.print("<div class=\"text\">"); out.print(author.getName()); out.println("</div>"); out.println("<h3>Email</h3>"); out.print("<div class=\"text\">"); out.print(author.getEmailAddress()); out.println("</div>"); out.println("<h3>DOB</h3>"); out.print("<div class=\"text\">"); out.print(author.getDateOfBirth()); out.println("</div>"); out.println("<h3>Bio</h3>"); out.print("<div class=\"text\">"); out.print(author.getBio()); out.println("</div>"); out.print("<a href=\"EditAuthorForm?email="); out.print(author.getEmailAddress()); out.println("\">Edit Author Information</a>"); HTMLOutput.writeHTMLFooter(out); } } }
8,251
0
Create_ds/aries/samples/blog/blog-web/src/main/java/org/apache/aries/samples/blog
Create_ds/aries/samples/blog/blog-web/src/main/java/org/apache/aries/samples/blog/web/EditAuthor.java
/** * 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. */ package org.apache.aries.samples.blog.web; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.aries.samples.blog.api.BloggingService; import org.apache.aries.samples.blog.web.util.FormServlet; import org.apache.aries.samples.blog.web.util.FormatChecker; import org.apache.aries.samples.blog.web.util.JNDIHelper; public class EditAuthor extends HttpServlet { private static final long serialVersionUID = -8881545878284864977L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // This method will update or create an author depending on the // existence of the author in the database. // The authors email address is the key in the database, thus if // the email address is not in the database we create this as a // new author. String email = req.getParameter("email"); String nickName = req.getParameter("nickName"); String name = req.getParameter("name"); String bio = req.getParameter("bio"); String dob = req.getParameter("dob"); if (email == null || email.equals("")) { storeParam(req, "email", email); storeParam(req, "nickName", nickName); storeParam(req, "name", name); storeParam(req, "bio", bio); storeParam(req, "dob", dob); FormServlet.addError(req, "The email field is required."); resp.sendRedirect("EditAuthorForm"); }else if (!FormatChecker.isValidEmail(email)) { storeParam(req, "email", email); storeParam(req, "nickName", nickName); storeParam(req, "name", name); storeParam(req, "bio", bio); storeParam(req, "dob", dob); FormServlet.addError(req, "The email field is not properly formatted"); resp.sendRedirect("EditAuthorForm"); } else { BloggingService service = JNDIHelper.getBloggingService(); if (service.getBlogAuthor(email) != null) { // do an update service.updateBlogAuthor(email, nickName, name, bio, dob); } else { // do a create service.createBlogAuthor(email, nickName, name, bio, dob); } RequestDispatcher dispatch = getServletContext().getRequestDispatcher("/ViewAuthor"); dispatch.forward(req, resp); } } private void storeParam(HttpServletRequest req, String param, String value) { FormServlet.storeParam(req, EditAuthorForm.ID, param, value); } }
8,252
0
Create_ds/aries/samples/blog/blog-web/src/main/java/org/apache/aries/samples/blog
Create_ds/aries/samples/blog/blog-web/src/main/java/org/apache/aries/samples/blog/web/EditAuthorForm.java
/** * 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. */ package org.apache.aries.samples.blog.web; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.http.HttpServletRequest; import org.apache.aries.samples.blog.api.BlogAuthor; import org.apache.aries.samples.blog.api.BloggingService; import org.apache.aries.samples.blog.web.util.FormServlet; import org.apache.aries.samples.blog.web.util.FormatChecker; import org.apache.aries.samples.blog.web.util.HTMLOutput; import org.apache.aries.samples.blog.web.util.JNDIHelper; public class EditAuthorForm extends FormServlet { private static final long serialVersionUID = 4996935653835900015L; public static final String ID = "author"; public EditAuthorForm() { super(ID); } @Override protected void writeCustomHeaderContent(HttpServletRequest req, PrintWriter out) { HTMLOutput.writeDojoUses(out, "dijit.form.TextBox", "dijit.form.DateTextBox", "dijit.form.Textarea"); } @Override protected String getPageTitle(HttpServletRequest req) throws IOException { String pageTitle = "Create Author"; BloggingService service = JNDIHelper.getBloggingService(); String email = getEmail(req); if (email != null && !!!"".equals(email)) { BlogAuthor author = service.getBlogAuthor(email); if (author != null) { pageTitle = "Update " + author.getName() + "'s profile"; } } return pageTitle; } private String getEmail(HttpServletRequest req) { String email = retrieveOrEmpty(req, "email"); if ("".equals(email)) { email = req.getParameter("email"); } if(FormatChecker.isValidEmail(email)) return email; else return null; } @Override protected void writeForm(HttpServletRequest req, PrintWriter out) throws IOException { String name = retrieveOrEmpty(req, "name"); String nickName = retrieveOrEmpty(req, "nickName"); String bio = retrieveOrEmpty(req, "bio"); String dob = retrieveOrEmpty(req, "dob"); String email = getEmail(req); BloggingService service = JNDIHelper.getBloggingService(); if (email != null && !!!"".equals(email)) { BlogAuthor author = service.getBlogAuthor(email); if ("".equals(name)) name = author.getFullName(); if ("".equals(nickName)) nickName = author.getName(); if ("".equals(bio)) bio = author.getBio(); if ("".equals(dob)) dob = author.getDateOfBirth(); } else { email = ""; } out.println("<form method=\"get\" action=\"EditAuthor\">"); out.print("<div class=\"textEntry\"><label>Name <input dojoType=\"dijit.form.TextBox\" type=\"text\" name=\"name\" value=\""); out.print(name); out.println("\"/></label></div>"); out.print("<div class=\"textEntry\"><label>Nickname <input dojoType=\"dijit.form.TextBox\" type=\"text\" name=\"nickName\" value=\""); out.print(nickName); out.println("\"/></label></div>"); out.print("<div class=\"textEntry\"><label>Email <input dojoType=\"dijit.form.TextBox\" type=\"text\" name=\"email\" value=\""); out.print(email); out.println("\"/></label></div>"); out.print("<div class=\"textEntry\"><label>Date of Birth <input dojoType=\"dijit.form.DateTextBox\" type=\"text\" name=\"dob\" required=\"true\" value=\""); out.print(dob); out.println("\"/></label></div>"); out.print("<div class=\"textEntry\"><label>Bio <textarea dojoType=\"dijit.form.Textarea\" style=\"width:300px\" name=\"bio\">"); out.print(bio); out.println("</textarea></label></div>"); out.println("<input class=\"submit\" type=\"submit\" value=\"Submit\" name=\"Submit\"/>"); out.println("</form>"); } }
8,253
0
Create_ds/aries/samples/blog/blog-web/src/main/java/org/apache/aries/samples/blog
Create_ds/aries/samples/blog/blog-web/src/main/java/org/apache/aries/samples/blog/web/CreateBlogEntryForm.java
/** * 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. */ package org.apache.aries.samples.blog.web; import java.io.PrintWriter; import javax.servlet.http.HttpServletRequest; import org.apache.aries.samples.blog.web.util.FormServlet; import org.apache.aries.samples.blog.web.util.HTMLOutput; public class CreateBlogEntryForm extends FormServlet { private static final long serialVersionUID = -6484228320837122235L; public static final String ID = "post"; public CreateBlogEntryForm() { super(ID); } @Override protected String getPageTitle(HttpServletRequest req) { return "Create Blog Post"; } @Override protected void writeForm(HttpServletRequest req, PrintWriter out) { String email = retrieveOrEmpty(req, "email"); String title = retrieveOrEmpty(req, "title"); String text = retrieveOrEmpty(req, "text"); String tags = retrieveOrEmpty(req, "tags"); out.println("<form name=\"createPost\" method=\"post\" action=\"CreateBlogEntry\">"); out.println("<div class=\"textEntry\"><label>Title <input dojoType=\"dijit.form.TextBox\" type=\"text\" name=\"title\" value=\"" + title + "\"/></label></div>"); out.println("<div class=\"textEntry\"><textarea dojoType=\"dijit.Editor\" id=\"text\" name=\"text\">" + text + "</textarea></div>"); out.println("<div class=\"textEntry\"><label>Email <input dojoType=\"dijit.form.TextBox\" type=\"text\" name=\"email\" value=\"" + email + "\"/></label></div>"); out.println("<div class=\"textEntry\"><label>Tags &nbsp;<input dojoType=\"dijit.form.TextBox\" type=\"text\" name=\"tags\" value=\"" + tags + "\"/></label></div>"); out.println("<input type=\"hidden\" name=\"text\" id=\"text\" value=\"\"/>"); out.println("<input class=\"submit\" type=\"submit\" value=\"Submit\" name=\"Submit\" onclick=\"storeBlogContent();return true;\"/>"); out.println("</form>"); } @Override protected void writeCustomHeaderContent(HttpServletRequest req, PrintWriter out) { HTMLOutput.writeDojoUses(out, "dojo.parser", "dijit.dijit", "dijit.Editor", "dijit.form.TextBox"); out.println("<script type=\"text/javascript\">"); out.println(" function storeBlogContent() {"); out.println(" var textBox = dijit.byId('textArea');"); out.println(" var textArea = dojo.byId('text');"); out.println(" textArea.value = textBox.getValue();"); out.println(" }"); out.println("</script>"); } }
8,254
0
Create_ds/aries/samples/blog/blog-web/src/main/java/org/apache/aries/samples/blog
Create_ds/aries/samples/blog/blog-web/src/main/java/org/apache/aries/samples/blog/web/CreateBlogEntry.java
/** * 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. */ package org.apache.aries.samples.blog.web; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.aries.samples.blog.api.BloggingService; import org.apache.aries.samples.blog.web.util.FormServlet; import org.apache.aries.samples.blog.web.util.JNDIHelper; public class CreateBlogEntry extends HttpServlet { private static final long serialVersionUID = -6484228320837122235L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{ doPost(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // new blog entry values String email = req.getParameter("email"); String title = req.getParameter("title"); String text = req.getParameter("text"); String tags = req.getParameter("tags"); BloggingService service = JNDIHelper.getBloggingService(); if (service.getBlogAuthor(email) != null) { service.createBlogEntry(email, title, text, tags); resp.sendRedirect("ViewBlog"); } else { storeParam(req, "email", email); storeParam(req, "title", title); storeParam(req, "text", text); storeParam(req, "tags", tags); if (email.equals("")) FormServlet.addError(req, "The email field is required."); else FormServlet.addError(req, "The author's email is not valid."); resp.sendRedirect("CreateBlogEntryForm"); } } private void storeParam(HttpServletRequest req, String param, String value) { FormServlet.storeParam(req, CreateBlogEntryForm.ID, param, value); } }
8,255
0
Create_ds/aries/samples/blog/blog-web/src/main/java/org/apache/aries/samples/blog
Create_ds/aries/samples/blog/blog-web/src/main/java/org/apache/aries/samples/blog/web/AddComment.java
/** * 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. */ package org.apache.aries.samples.blog.web; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.aries.samples.blog.api.BloggingService; import org.apache.aries.samples.blog.web.util.JNDIHelper; public class AddComment extends HttpServlet { private static final long serialVersionUID = -920234218060948564L; public static final String ERROR_MESSAGES_ID = "commentErrorMessages"; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // email address of the comment's author String email = req.getParameter("email"); // the id of the blog entry to which this comment is associated long postId = Long.parseLong(req.getParameter("postId")); // the text of the comment String text = req.getParameter("text"); BloggingService service = JNDIHelper.getBloggingService(); // retrieve the blog entry and create the associated comment if (service.getBlogAuthor(email) != null) { service.createBlogComment(text, email, postId); resp.sendRedirect("ViewBlog"); } else { if (email.equals("")) addError(req, "The email field is required."); else addError(req, "The email filed is not valid."); resp.sendRedirect("AddCommentForm?postId=" + postId); } } public static void addError(HttpServletRequest req, String error) { HttpSession session = req.getSession(); if (session != null) { @SuppressWarnings("unchecked") List<String> errors = (List<String>) session .getAttribute(ERROR_MESSAGES_ID); if (errors == null) { errors = new ArrayList<String>(); session.setAttribute(ERROR_MESSAGES_ID, errors); } errors.add(error); } } }
8,256
0
Create_ds/aries/samples/blog/blog-web/src/main/java/org/apache/aries/samples/blog
Create_ds/aries/samples/blog/blog-web/src/main/java/org/apache/aries/samples/blog/web/ViewBlog.java
/** * 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. */ package org.apache.aries.samples.blog.web; import java.io.IOException; import java.io.PrintWriter; import java.text.DateFormat; import java.util.Calendar; import java.util.Date; import java.util.Iterator; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.aries.samples.blog.api.BlogComment; import org.apache.aries.samples.blog.api.BlogEntry; import org.apache.aries.samples.blog.api.BloggingService; import org.apache.aries.samples.blog.web.util.HTMLOutput; import org.apache.aries.samples.blog.web.util.JNDIHelper; public class ViewBlog extends HttpServlet { private static final long serialVersionUID = -1854915218416871420L; private static final int POSTS_PER_PAGE = 10; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PrintWriter out = resp.getWriter(); BloggingService service = JNDIHelper.getBloggingService(); String blogTitle = service.getBlogTitle(); // TODO cope with the service being null, redirect elsewhere. HTMLOutput.writeHTMLHeaderPartOne(out, blogTitle); HTMLOutput.writeDojoUses(out, "dojo.parser"); HTMLOutput.writeHTMLHeaderPartTwo(out); int maxPage = (service.getNoOfEntries()-1) / POSTS_PER_PAGE; int pageNoInt = 0; String pageNo = req.getParameter("page"); if (pageNo != null) { try { pageNoInt = Integer.parseInt(pageNo)-1; if (pageNoInt > maxPage) pageNoInt = maxPage; else if (pageNoInt < 0) pageNoInt = 0; } catch (NumberFormatException e) { e.printStackTrace(); } } Iterator<? extends BlogEntry> posts = service.getBlogEntries(pageNoInt * POSTS_PER_PAGE, POSTS_PER_PAGE).iterator(); out.println("<div class=\"links\"><a href=\"CreateBlogEntryForm\">Create New Post</a> <a href=\"EditAuthorForm\">Create Author</a></div>"); Date currentDate = null; for (int i = 0; posts.hasNext(); i++) { BlogEntry post = posts.next(); if (doesNotMatch(post.getPublishDate(), currentDate)) { currentDate = post.getPublishDate(); out.print("<div class=\"postDate\">"); //out.print(DateFormat.getDateInstance(DateFormat.FULL).format(currentDate)); if (currentDate != null) { out.print(DateFormat.getDateInstance(DateFormat.FULL).format(currentDate)); } out.println("</div>"); } out.print("\t\t<div class=\"post\" id=\""); out.print(i); out.println("\">"); out.print("\t\t\t<div class=\"postTitle\">"); out.print(post.getTitle()); out.print("</div>"); out.print("\t\t\t<div class=\"postBody\">"); out.print(post.getBody()); out.println("</div>"); out.print("\t\t\t<div class=\"postAuthor\"><a href=\"ViewAuthor?email="); out.print(post.getAuthorEmail()); out.print("\">"); out.print(post.getAuthor().getFullName()); out.println("</a></div>"); if (service.isCommentingAvailable()) { out.print("<div class=\"links\"><a href=\"AddCommentForm?postId="); out.print(post.getId()); out.print("\">Add Comment</a></div>"); List<? extends BlogComment> comments = service .getCommentsForEntry(post); int size = comments.size(); out.print("<div class=\"commentTitle\""); if (size > 0) { out.print("onclick=\"expand("); out.print(post.getId()); out.print(")\""); } out.print(" style=\"cursor: pointer;\">Comments ("); out.print(size); out.println(")</div>"); if (size > 0) { out.print("<div id=\"comments"); out.print(post.getId()); out.println("\">"); for (BlogComment comment : comments) { out.println("<div class=\"comment\">"); out.println(comment.getComment()); out.println("</div>"); out .print("\t\t\t<div class=\"commentAuthor\"><a href=\"ViewAuthor?email="); out.print(comment.getAuthor().getEmailAddress()); out.print("\">"); out.print( comment.getAuthor().getName()); out.println("</a></div>"); } out.println("</div>"); } } out.println("\t\t</div>"); } /* * Translate indices from 0-indexed to 1-indexed */ writePager(out, pageNoInt+1, maxPage+1); HTMLOutput.writeHTMLFooter(out); } /** * Write a paging bar (if there is more than a single page) * * @param out * @param currentPage Page number (indices starting from 1) * @param maxPage (indices starting from 1) */ private void writePager(PrintWriter out, int currentPage, int maxPage) { /* * No paging is needed if we only have a single page */ if (maxPage > 1) { out.println("<div id=\"pagination\">"); if (currentPage > 1) { out.println("<a href=\"ViewBlog?page=1\">&lt;&lt;</a>"); out.println("<a href=\"ViewBlog?page="+(currentPage-1)+"\">&lt;</a>"); } else { out.println("<span>&lt;&lt;</span>"); out.println("<span>&lt;</span>"); } out.println(currentPage + " of " + maxPage); if (currentPage < maxPage) { out.println("<a href=\"ViewBlog?page="+(currentPage+1)+"\">&gt;</a>"); out.println("<a href=\"ViewBlog?page=" + maxPage + "\">&gt;&gt;</a>"); } else { out.println("<span>&gt;&gt;</span>"); out.println("<span>&gt;</span>"); } out.println("</div>"); } } private boolean doesNotMatch(Date publishDate, Date currentDate) { if (currentDate == null) return true; Calendar publish = Calendar.getInstance(); Calendar current = Calendar.getInstance(); publish.setTime(publishDate); current.setTime(currentDate); boolean differentYear = publish.get(Calendar.YEAR) != current.get(Calendar.YEAR); boolean differentMonth = publish.get(Calendar.MONTH) != current.get(Calendar.MONTH); boolean differentDayOfMonth = publish.get(Calendar.DAY_OF_MONTH) != current.get(Calendar.DAY_OF_MONTH); return differentYear || differentMonth || differentDayOfMonth; } }
8,257
0
Create_ds/aries/samples/blog/blog-web/src/main/java/org/apache/aries/samples/blog/web
Create_ds/aries/samples/blog/blog-web/src/main/java/org/apache/aries/samples/blog/web/util/HTMLOutput.java
/** * 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. */ package org.apache.aries.samples.blog.web.util; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collection; /** * Utility class to provide html headers, footers, dojo use and blogging * service. */ public class HTMLOutput { public static final void writeHTMLHeaderPartOne(PrintWriter out, String pageTitle) { out.println("<html>"); out.println(" <head>"); out .println(" <link type=\"text/css\" rel=\"stylesheet\" href=\"style/blog.css\"></link>"); out.println(" <meta name=\"keywords\" content=\"...\">"); out.println(" <meta name=\"description\" content=\"...\">"); out.print(" <title>"); out.print(pageTitle); out.println(" </title>"); out .println(" <META http-equiv=\"Content-Type\" content=\"text/html;charset=UTF-8\">"); out.println(" </head>"); } public static final void writeDojoUses(PrintWriter out, String... modules) { out .println("<link rel=\"Stylesheet\" href=\"http://ajax.googleapis.com/ajax/libs/dojo/1.4.0/dijit/themes/tundra/tundra.css\" type=\"text/css\" media=\"screen\"/>"); out .println("<link rel=\"Stylesheet\" href=\"http://ajax.googleapis.com/ajax/libs/dojo/1.4.0/dijit/themes/nihilo/nihilo.css\" type=\"text/css\" media=\"screen\"/>"); out .println("<link rel=\"Stylesheet\" href=\"http://ajax.googleapis.com/ajax/libs/dojo/1.4.0/dijit/themes/soria/soria.css\" type=\"text/css\" media=\"screen\"/>"); out .println("<script type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/dojo/1.4.0/dojo/dojo.xd.js\" djConfig=\"parseOnLoad: true\"></script>"); out.println("<script type=\"text/javascript\">"); out.println("dojo.require(\"dojo.parser\");"); for (String module : modules) { out.print("dojo.require(\""); out.print(module); out.println("\");"); } out.println("</script>"); } public static final void writeHTMLHeaderPartTwo(PrintWriter out) { writeHTMLHeaderPartTwo(out, new ArrayList<String>()); } public static final void writeHTMLHeaderPartTwo(PrintWriter out, Collection<String> errorMessages) { out.println(" <body class=\"soria\">"); out .println(" <TABLE width=\"100%\" cellpadding=\"0\" cellspacing=\"0\">"); out.println(" <TR width=\"100%\">"); out.println(" <TD id=\"cell-0-0\" colspan=\"2\">&nbsp;</TD>"); out.println(" <TD id=\"cell-0-1\">&nbsp;</TD>"); out.println(" <TD id=\"cell-0-2\" colspan=\"2\">&nbsp;</TD>"); out.println(" </TR>"); out.println(" <TR width=\"100%\">"); out.println(" <TD id=\"cell-1-0\">&nbsp;</TD>"); out.println(" <TD id=\"cell-1-1\">&nbsp;</TD>"); out.println(" <TD id=\"cell-1-2\">"); out.println(" <DIV style=\"padding: 5px;\">"); out.println(" <DIV id=\"banner\">"); out .println(" <TABLE border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">"); out.println(" <TR>"); out.println(" <TD align=\"left\" class=\"topbardiv\" nowrap=\"\">"); out .println(" <A href=\"http://aries.apache.org/\" title=\"Apache Aries \">"); out .println(" <IMG border=\"0\" src=\"images/Arieslogo_Horizontal.gif\">"); out.println(" </A>"); out.println(" </TD>"); out.println(" <TD align=\"right\" nowrap=\"\">"); out .println(" <A href=\"http://www.apache.org/\" title=\"The Apache Software Foundation\">"); out .println(" <IMG border=\"0\" src=\"images/feather.png\">"); out.println(" </A>"); out.println(" </TD>"); out.println(" </TR> "); out.println(" </TABLE>"); out.println(" </DIV>"); out.println(" </DIV>"); out.println(" <DIV id=\"top-menu\">"); out .println(" <TABLE border=\"0\" cellpadding=\"1\" cellspacing=\"0\" width=\"100%\">"); out.println(" <TR>"); out.println(" <TD>"); out.println(" <DIV align=\"left\">"); out.println(" <!-- Breadcrumbs -->"); out.println(" <!-- Breadcrumbs -->"); out.println(" </DIV>"); out.println(" </TD>"); out.println(" <TD>"); out.println(" <DIV align=\"right\">"); out.println(" <!-- Quicklinks -->"); out.println(" <p><a href=\"ViewBlog\" style=\"text-decoration: none; color: white\">Blog home</a></p>"); out.println(" <!-- Quicklinks -->"); out.println(" </DIV>"); out.println(" </TD>"); out.println(" </TR>"); out.println(" </TABLE>"); out.println(" </DIV>"); out.println(" </TD>"); out.println(" <TD id=\"cell-1-3\">&nbsp;</TD>"); out.println(" <TD id=\"cell-1-4\">&nbsp;</TD>"); out.println(" </TR>"); out.println(" <TR width=\"100%\">"); out.println(" <TD id=\"cell-2-0\" colspan=\"2\">&nbsp;</TD>"); out.println(" <TD id=\"cell-2-1\">"); out.println(" <TABLE>"); out.println(" <TR height=\"100%\" valign=\"top\">"); out.println(" <TD height=\"100%\"></td>"); out.println(" <TD height=\"100%\" width=\"100%\">"); out.println(" <H1>Apache Aries Sample Blog</H1><br>"); if (!!!errorMessages.isEmpty()) { out.println("\t\t\t<div id=\"errorMessages\">"); for (String msg : errorMessages) { out.println("\t\t\t\t<div class=\"errorMessage\">" + msg + "</div>"); } out.println("\t\t\t</div>"); } out.println(" <div id=\"mainContent\" class=\"mainContent\">"); } public static final void writeHTMLFooter(PrintWriter out) { out.println(" <BR>"); out.println(" </DIV>"); out.println(" </TD>"); out.println(" </TR>"); out.println(" </TABLE>"); out.println(" </TD>"); out.println(" <TD id=\"cell-2-2\" colspan=\"2\">&nbsp;</TD>"); out.println(" </TR>"); out.println(" <TR width=\"100%\">"); out.println(" <TD id=\"cell-3-0\">&nbsp;</TD>"); out.println(" <TD id=\"cell-3-1\">&nbsp;</TD>"); out.println(" <TD id=\"cell-3-2\">"); out.println(" <DIV id=\"footer\">"); out.println(" <!-- Footer -->"); out.println(" </DIV>"); out.println(" </TD>"); out.println(" <TD id=\"cell-3-3\">&nbsp;</TD>"); out.println(" <TD id=\"cell-3-4\">&nbsp;</TD>"); out.println(" </TR>"); out.println(" <TR width=\"100%\">"); out.println(" <TD id=\"cell-4-0\" colspan=\"2\">&nbsp;</TD>"); out.println(" <TD id=\"cell-4-1\">&nbsp;</TD>"); out.println(" <TD id=\"cell-4-2\" colspan=\"2\">&nbsp;</TD>"); out.println(" </TR>"); out.println(" </TABLE>"); out.println(" </BODY>"); out.println("</HTML> "); } }
8,258
0
Create_ds/aries/samples/blog/blog-web/src/main/java/org/apache/aries/samples/blog/web
Create_ds/aries/samples/blog/blog-web/src/main/java/org/apache/aries/samples/blog/web/util/FormServlet.java
/** * 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. */ package org.apache.aries.samples.blog.web.util; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public abstract class FormServlet extends HttpServlet { private static final long serialVersionUID = -1019904995493434571L; public static final String ERROR_MESSAGES_ID = "errorMessages"; private String id; public static void addError(HttpServletRequest req, String error) { HttpSession session = req.getSession(); if (session != null) { @SuppressWarnings("unchecked") List<String> errors = (List<String>) session.getAttribute(ERROR_MESSAGES_ID); if (errors == null) { errors = new ArrayList<String>(); session.setAttribute(ERROR_MESSAGES_ID, errors); } errors.add(error); } } public static void storeParam(HttpServletRequest req, String id, String param, String value) { HttpSession session = req.getSession(); if (session != null) session.setAttribute(id + ":" + param, value); } protected FormServlet(String id) { this.id = id; } protected abstract void writeCustomHeaderContent(HttpServletRequest req, PrintWriter out); protected abstract void writeForm(HttpServletRequest req, PrintWriter out) throws IOException; protected abstract String getPageTitle(HttpServletRequest req) throws IOException; protected String retrieveOrEmpty(HttpServletRequest req, String param) { HttpSession session = req.getSession(); String value = ""; if (session != null) { value = (String) session.getAttribute(id+":"+param); if (value == null) { value = ""; } } return value; } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,IOException { PrintWriter out = resp.getWriter(); HTMLOutput.writeHTMLHeaderPartOne(out, getPageTitle(req)); writeCustomHeaderContent(req, out); List<String> errors = null; if (req.getSession() != null) errors = (List<String>) req.getSession().getAttribute(ERROR_MESSAGES_ID); if (errors == null) { try { HTMLOutput.writeHTMLHeaderPartTwo(out); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { try { HTMLOutput.writeHTMLHeaderPartTwo(out, errors); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } writeForm(req, out); HTMLOutput.writeHTMLFooter(out); cleanupSession(req); } private void cleanupSession(HttpServletRequest req) { HttpSession session = req.getSession(); if (session != null) { @SuppressWarnings("unchecked") Enumeration<String> names = session.getAttributeNames(); while (names.hasMoreElements()) { String name = names.nextElement(); if (name.startsWith(id+":")) session.removeAttribute(name); } session.removeAttribute("errorMessages"); } } }
8,259
0
Create_ds/aries/samples/blog/blog-web/src/main/java/org/apache/aries/samples/blog/web
Create_ds/aries/samples/blog/blog-web/src/main/java/org/apache/aries/samples/blog/web/util/JNDIHelper.java
/** * 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. */ package org.apache.aries.samples.blog.web.util; import java.io.IOException; import javax.naming.InitialContext; import javax.naming.NamingException; import org.apache.aries.samples.blog.api.BloggingService; public class JNDIHelper { public static final BloggingService getBloggingService() throws IOException { try { InitialContext ic = new InitialContext(); return (BloggingService) ic.lookup("osgi:service/" + BloggingService.class.getName()); } catch (NamingException e) { e.printStackTrace(); IOException ioe = new IOException( "Blogging service resolution failed"); ioe.initCause(e); throw ioe; } } }
8,260
0
Create_ds/aries/samples/blog/blog-web/src/main/java/org/apache/aries/samples/blog/web
Create_ds/aries/samples/blog/blog-web/src/main/java/org/apache/aries/samples/blog/web/util/FormatChecker.java
/** * 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. */ package org.apache.aries.samples.blog.web.util; public class FormatChecker { public static boolean isValidEmail(String email) { if (email != null && email.matches("^(?:[a-zA-Z0-9_'^&amp;/+-])+(?:\\.(?:[a-zA-Z0-9_'^&amp;/+-])+)*@(?:(?:\\[?(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))\\.){3}(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\]?)|(?:[a-zA-Z0-9-]+\\.)+(?:[a-zA-Z]){2,}\\.?)$")) return true; return false; } }
8,261
0
Create_ds/aries/samples/blog/blog-api/src/main/java/org/apache/aries/samples/blog
Create_ds/aries/samples/blog/blog-api/src/main/java/org/apache/aries/samples/blog/api/Blog.java
/** * 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. */ package org.apache.aries.samples.blog.api; public interface Blog { /** * Gets the title of the blog * @return currently returns the fixed value of "Aries Sample Blog" */ String getBlogTitle(); }
8,262
0
Create_ds/aries/samples/blog/blog-api/src/main/java/org/apache/aries/samples/blog
Create_ds/aries/samples/blog/blog-api/src/main/java/org/apache/aries/samples/blog/api/BlogEntry.java
/** * 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. */ package org.apache.aries.samples.blog.api; import java.util.Date; public interface BlogEntry { /** * Get the title of the blog posting. * @return the title String */ String getTitle(); /** * Get the body of the blog posting. * @return the body content as a String */ String getBody(); /** * Get the author of the blog entry. * @return the author's display name or email address if display name is null */ BlogAuthor getAuthor(); /** * Get the email address of the author of the blog posting. * @return the author's email address */ String getAuthorEmail(); /** * Get the publish date of a blog posting. * @return the date of publish */ public Date getPublishDate(); /** * Get the Id value for the blog posting. * @return the id value */ public long getId(); }
8,263
0
Create_ds/aries/samples/blog/blog-api/src/main/java/org/apache/aries/samples/blog
Create_ds/aries/samples/blog/blog-api/src/main/java/org/apache/aries/samples/blog/api/BlogEntryManager.java
/** * 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. */ package org.apache.aries.samples.blog.api; import java.text.ParseException; import java.util.List; import org.apache.aries.samples.blog.api.persistence.Entry; public interface BlogEntryManager { /** * Create a blog posting. * @param email the author's email * @param title the title of the entry * @param blogText the text of the entry * @param tags tags associated with the blog entry */ public void createBlogPost(String email, String title, String blogText, List<String> tags); /** * Find a specific blog entry by title. * @param title the title to search for * @return the blog entry */ public Entry findBlogEntryByTitle(String title); /** * Retrieve all blog entries. * @return a List<BlogEntry> of all blog entries */ public List<? extends BlogEntry> getAllBlogEntries(); /** * Retrieve all blog entries for a specific author. * @param emailAddress the email address of the author in question * @return a List<BlogEntry> */ public List<? extends BlogEntry> getBlogsForAuthor(String emailAddress); /** * Retrieve all blog entries created between a specified date range. * @param startDate the start date * @param endDate the end date * @return a List<BlogEntry> * @throws ParseException */ public List<?extends BlogEntry> getBlogEntriesModifiedBetween(String startDate, String endDate) throws ParseException; /** * Get N posts from the database starting at post number X * * @param firstPostIndex the first post to retrieve * @param noOfPosts the number of posts to retrieve in total * @return a List<BlogEntry> of N posts */ public List<? extends BlogEntry> getBlogEntries(int firstPostIndex, int noOfPosts); /** * Get the total number of blog entries in the database * @return the int number of entries */ public int getNoOfPosts(); /** * Remove a specific blog entry. * @param a the author of the blog entry * @param title the title of the blog entry * @param publishDate the publication date of the blog entry * @throws ParseException */ public void removeBlogEntry(BlogAuthor author, String title, String publishDate) throws ParseException; /** * Update a blog entry. * @param originalEntry the original blog entry * @param a the author of the blog entry * @param title the title of the blog entry * @param publishDate the publication date of the blog entry * @param blogText the text content of the blog entry * @param tags any assocaited tags for the blog entry * @throws ParseException */ public void updateBlogEntry(BlogEntry originalEntry, BlogAuthor a, String title, String publishDate, String blogText, List<String> tags) throws ParseException; /** * Get the specified blog posting. * @param id the id of the blog posting * @return the blog post */ public BlogEntry getBlogPost(long id); }
8,264
0
Create_ds/aries/samples/blog/blog-api/src/main/java/org/apache/aries/samples/blog
Create_ds/aries/samples/blog/blog-api/src/main/java/org/apache/aries/samples/blog/api/BlogCommentManager.java
/** * 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. */ package org.apache.aries.samples.blog.api; import java.util.List; public interface BlogCommentManager { /** * Create a comment by an author (email) against a post (Id) * @param comment * @param email * @param entryId */ public void createComment(String comment, String email, long entryId); /** * Get all the comments made by an author * @param email * @return a list of comments made by an author */ public List<? extends BlogComment> getCommentsByAuthor(String email); /** * * @param id * @return A list of comments made about an entry */ public List<? extends BlogComment> getCommentsForPost(long id); /** * Delete a specific comment using it's id * @param id */ public void deleteComment(int id); /** * Check to see whether the comment service is available * @return */ public boolean isCommentingAvailable(); }
8,265
0
Create_ds/aries/samples/blog/blog-api/src/main/java/org/apache/aries/samples/blog
Create_ds/aries/samples/blog/blog-api/src/main/java/org/apache/aries/samples/blog/api/BloggingService.java
/** * 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. */ package org.apache.aries.samples.blog.api; import java.util.List; public interface BloggingService { /** * Get the blog * @return the title of the Blog */ String getBlogTitle(); /** * Get the author associated with a given email address. * * @param email the email address of interest * @return the blog author with the supplied email address */ BlogAuthor getBlogAuthor(String email); /** * Get the blog post with the specified id. * * @param id the blog entry id * @return the blog post */ BlogEntry getBlogEntry(long id); /** * Update the attributes of an author. * * @param email the email address of the author being updated * @param nickName the display name for this author * @param name the full name for this author * @param bio the biography for this author * @param dob the date of birth for this author */ void updateBlogAuthor(String email, String nickName, String name, String bio, String dob); /** * Get the number of entries(posts) in the blog * @return the number of posts. */ public int getNoOfEntries(); /** * Get the a number of entries starting at the teh first index * @param firstPostIndex * @param noOfPosts * @return a list of BlogEntries */ public List<? extends BlogEntry> getBlogEntries(int firstPostIndex, int noOfPosts); /** * Get all the blog entries * @return a lost of BlogEntrys */ public List<? extends BlogEntry> getAllBlogEntries(); /** * Create a new author. * * @param email the author's email address * @param nickName the author's display name * @param name the author's full name * @param bio the author's biography * @param dob the author's date of birth */ void createBlogAuthor(String email, String nickName, String name, String bio, String dob); /** * * @param email the email address of the author * @param title the title of the post * @param blogText the test of the post * @param tags list of tags associated with the post */ void createBlogEntry(String email, String title, String blogText, String tags); /** * Retrieve the state of the blog commenting service * * @return true if available else false */ boolean isCommentingAvailable(); /** * Create a comment * @param text * @param email * @param entryId */ void createBlogComment(String text, String email, long entryId); /** * Get the comments associated with an entry * @param entry * @return a list of comments for an entry (post) */ List <? extends BlogComment> getCommentsForEntry(BlogEntry entry); }
8,266
0
Create_ds/aries/samples/blog/blog-api/src/main/java/org/apache/aries/samples/blog
Create_ds/aries/samples/blog/blog-api/src/main/java/org/apache/aries/samples/blog/api/BlogAuthor.java
/** * 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. */ package org.apache.aries.samples.blog.api; import java.util.List; public interface BlogAuthor { /** Get the author's display name * @return the display name String */ String getName(); /** Get the author's full name * @return the full name String */ String getFullName(); /** Get the author's email address * @return the email address String */ String getEmailAddress(); /** Get the author's biography * @return the biography String */ String getBio(); /** Get the author's date of birth * @return the date of birth String (dd-mm-yyyy) */ String getDateOfBirth(); /** * * @return a list of Blog Entries */ List <? extends BlogEntry> getEntries(); }
8,267
0
Create_ds/aries/samples/blog/blog-api/src/main/java/org/apache/aries/samples/blog
Create_ds/aries/samples/blog/blog-api/src/main/java/org/apache/aries/samples/blog/api/BlogAuthorManager.java
/** * 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. */ package org.apache.aries.samples.blog.api; import java.text.ParseException; import java.util.List; public interface BlogAuthorManager { /** * Create an author. * @param email the author's email address, this is used as the key in the database * @param dob the author's date of birth * @param name the author's full name * @param displayName the author's display name * @param bio the author's biography * @throws ParseException */ public void createAuthor(String email, String dob, String name, String displayName, String bio) throws ParseException; /** * Get all authors from the database. * @return a List<Author> of all authors in the database */ public List<? extends BlogAuthor> getAllAuthors(); /** * Get an individual author. * @param emailAddress - the email address of the author to retrieve * @return the author */ public BlogAuthor getAuthor(String emailAddress); /** * Delete an author from the database. * @param emailAddress the email address of the author to delete */ public void removeAuthor(String emailAddress); /** * Update a specific author. * @param email the email address of the author being updated. * @param dob the new date of birth (as a string) * @param name the new full name * @param displayName the new display name * @param bio the new biography * @throws ParseException */ public void updateAuthor(String email, String dob, String name, String displayName, String bio) throws ParseException; }
8,268
0
Create_ds/aries/samples/blog/blog-api/src/main/java/org/apache/aries/samples/blog
Create_ds/aries/samples/blog/blog-api/src/main/java/org/apache/aries/samples/blog/api/BlogComment.java
/** * 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. */ package org.apache.aries.samples.blog.api; public interface BlogComment { /** Get comment * @return the String representing the comment */ String getComment(); /** Get the author of the comment * @return the BlogAuthor instance */ BlogAuthor getAuthor(); /** Get the parent blog post for the comment * @return the BlogPost instance the comment is attached to. */ BlogEntry getEntry(); /** Get the Id value of the comment * @return the integer id of the comment */ int getId(); /** Get the creation date for the comment * @return the String representation of the date the comment was * created in dd-mm-yyyy format. */ String getCommentCreationDate(); }
8,269
0
Create_ds/aries/samples/blog/blog-api/src/main/java/org/apache/aries/samples/blog/api/comment
Create_ds/aries/samples/blog/blog-api/src/main/java/org/apache/aries/samples/blog/api/comment/persistence/BlogCommentService.java
/** * 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. */ package org.apache.aries.samples.blog.api.comment.persistence; import java.util.List; public interface BlogCommentService { /** * Create a comment against a blog entry. * * @param comment the comment text * @param author the author * @param blogEntry the blog entry against which we are commenting */ void createComment(String comment, String authorEmail, long entryId); /** * Delete a blog entry comment * * @param comment the comment being deleted. */ void delete(int id); /** * Get comments for a given blog entry post. * * @param id the blog entry id * @return a List<BlogComment> for the blog entry */ List<? extends Comment> getCommentsForEntry(long id); /** * Get comments for a given author. * * @param emailAddress the email address of the author * @return a List<BlogComment> for the given email address */ List<? extends Comment> getCommentsForAuthor(String emailAddress); }
8,270
0
Create_ds/aries/samples/blog/blog-api/src/main/java/org/apache/aries/samples/blog/api/comment
Create_ds/aries/samples/blog/blog-api/src/main/java/org/apache/aries/samples/blog/api/comment/persistence/Comment.java
/** * 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. */ package org.apache.aries.samples.blog.api.comment.persistence; import java.util.Date; import org.apache.aries.samples.blog.api.persistence.Author; import org.apache.aries.samples.blog.api.persistence.Entry; public interface Comment { /** Get comment * @return the String representing the comment */ String getComment(); /** Get the author of the comment * @return the BlogAuthor instance */ Author getAuthor(); /** Get the parent blog post for the comment * @return the BlogPost instance the comment is attached to. */ Entry getEntry(); /** Get the Id value of the comment * @return the integer id of the comment */ int getId(); /** Get the creation date for the comment * @return the String representation of the date the comment was * created in dd-mm-yyyy format. */ Date getCreationDate(); }
8,271
0
Create_ds/aries/samples/blog/blog-api/src/main/java/org/apache/aries/samples/blog/api
Create_ds/aries/samples/blog/blog-api/src/main/java/org/apache/aries/samples/blog/api/persistence/Author.java
/** * 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. */ package org.apache.aries.samples.blog.api.persistence; import java.util.Date; import java.util.List; public interface Author { /** Get the author's email address */ public String getEmail(); /** Get the author's full name */ public String getName(); /** Get the author's displayed name */ public String getDisplayName(); /** Get the author's biographical information */ public String getBio(); /** Get the author's date of birth */ public Date getDob(); /** Get the author's blog posts */ public List<? extends Entry> getEntries(); }
8,272
0
Create_ds/aries/samples/blog/blog-api/src/main/java/org/apache/aries/samples/blog/api
Create_ds/aries/samples/blog/blog-api/src/main/java/org/apache/aries/samples/blog/api/persistence/BlogPersistenceService.java
/** * 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. */ package org.apache.aries.samples.blog.api.persistence; import java.util.Date; import java.util.List; /** * This is the interface for the persistence layer of the blog * application. This persistence layer is registered in the service * registry and is used by the main application layer. * */ public interface BlogPersistenceService { /** * Get all the blog entries in the data store * @return a list of BlogEntry objects */ public List<? extends Entry> getAllBlogEntries(); /** * Get the number of blog entries in the data store * @return the number of blog entries */ public int getNoOfBlogEntries(); /** * Get the first N most recent posts starting from post X * @param firstPostIndex - The index of the first post to be retrieved * @param no - The number of posts to be retrieved starting from firstPostIndex */ public List<? extends Entry> getBlogEntries(int firstPostIndex, int no); /** * Get all the blog entries made by a particular * author * * @param emailAddress the author's email address * @return a list of BlogEntry objects */ public List<? extends Entry> getBlogsForAuthor(String emailAddress); /** * Get a BlogEntry that has a given title * @param title the title of interest * @return A BlogEntry with a specific title (or null if no entry exists in the * data store) */ public Entry findBlogEntryByTitle(String title); /** * Get BlogEntries created or modified between two specified dates * @param start The Date defining the start of the time period * @param end The Date defining the end of the time period * @return A list of BlogEntry objects */ public List<? extends Entry> getBlogEntriesModifiedBetween(Date start, Date end); /** * Obtain a given Blog post using its unique id. * * @param postId the posts unique id. * @return the Blog post. */ public Entry getBlogEntryById(long postId); /** * Get the details for an author * @param emailAddress the Author's email address * @return An Author object */ public Author getAuthor(String emailAddress); /** * Get all authors in the database * @return a List of Authors */ public List<? extends Author> getAllAuthors(); /** * Create an author in the database * * @param emailAddress * The author's email address * @param dob * The author's date of birth * @param name * The author's name * @param displayName * ?? * @param bio * The author's bio. */ public void createAuthor(String email, Date dob, String name, String displayName, String bio); /** * Create an Blog post in the database * * @param a * The author * @param title * The title of the post * @param blogText * The text of the post * @param tags * ?? */ public void createBlogPost(String email, String title, String blogText, List<String> tags); /** * Update an author in the database * @param */ public void updateAuthor(String email, Date dob, String name, String displayName, String bio); /** * Update an post in the database * * @param email The author's email * @param title The title of the post * @param blogText The text of the blog * @param tags The list of tags * @param updatedDate The date the update was made */ public void updateBlogEntry(long id, String email, String title, String blogText, List<String> tags, Date updatedDate); /** * Remove the author with the specified email address * * @param emailAddress the email address of the author to remove */ public void removeAuthor(String emailAddress); /** * Remove the specified BlogEntry, note that this must be a BlogEntry returned by * this service. * * @param id the unique id of the blog entry to remove */ public void removeBlogEntry(long id); }
8,273
0
Create_ds/aries/samples/blog/blog-api/src/main/java/org/apache/aries/samples/blog/api
Create_ds/aries/samples/blog/blog-api/src/main/java/org/apache/aries/samples/blog/api/persistence/Entry.java
/** * 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. */ package org.apache.aries.samples.blog.api.persistence; import java.util.Date; import java.util.List; public interface Entry { /** Get the author of this blog post */ public Author getAuthor(); /** Get the publish date of this blog post */ public Date getPublishDate(); /** Get the title of this blog post */ public String getTitle(); /** Get the tags for this blog post */ public List<String> getTags(); /** Get the text for this blog post */ public String getBlogText(); /** get the Blog post id */ public long getId(); /** * @return The date of the last update to this blog or null if it has never * been modified */ public Date getUpdatedDate(); }
8,274
0
Create_ds/aries/samples/blog/blog-persistence-jpa/src/main/java/org/apache/aries/samples/blog/persistence
Create_ds/aries/samples/blog/blog-persistence-jpa/src/main/java/org/apache/aries/samples/blog/persistence/jpa/BlogPersistenceServiceImpl.java
/** * 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. */ package org.apache.aries.samples.blog.persistence.jpa; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.Query; import org.apache.aries.samples.blog.api.persistence.BlogPersistenceService; import org.apache.aries.samples.blog.api.persistence.Entry; import org.apache.aries.samples.blog.persistence.jpa.entity.AuthorImpl; import org.apache.aries.samples.blog.persistence.jpa.entity.EntryImpl; /** * This class is the implementation of the blogPersistenceService */ public class BlogPersistenceServiceImpl implements BlogPersistenceService { private EntityManager em; public BlogPersistenceServiceImpl() { } public void setEntityManager(EntityManager e) { em = e; } public void createAuthor(String email, Date dob, String name, String displayName, String bio) { AuthorImpl a = new AuthorImpl(); a.setEmail(email); a.setName(name); a.setDisplayName(displayName); a.setBio(bio); a.setDob(dob); em.persist(a); } public void createBlogPost(String authorEmail, String title, String blogText, List<String> tags) { AuthorImpl a = em.find(AuthorImpl.class, authorEmail); EntryImpl b = new EntryImpl(); Date publishDate = new Date(System.currentTimeMillis()); b.setBlogText(blogText); b.setAuthor(a); b.setTitle((title == null) ? "" : title); b.setPublishDate(publishDate); b.setTags((tags == null) ? new ArrayList<String>() : tags); a.updateEntries(b); em.persist(b); em.merge(b.getAuthor()); } public Entry findBlogEntryByTitle(String title) { Query q = em .createQuery("SELECT e FROM BLOGENTRY e WHERE e.title = ?1"); q.setParameter(1, title); Entry b = (Entry) q.getSingleResult(); return b; } public List<AuthorImpl> getAllAuthors() { @SuppressWarnings("unchecked") List<AuthorImpl> list = em.createQuery("SELECT a FROM AUTHOR a") .getResultList(); return list; } public List<EntryImpl> getAllBlogEntries() { @SuppressWarnings("unchecked") List<EntryImpl> list = em.createQuery( "SELECT b FROM BLOGENTRY b ORDER BY b.publishDate DESC") .getResultList(); return list; } public int getNoOfBlogEntries() { Number n = (Number) em.createQuery( "SELECT COUNT(b) FROM BLOGENTRY b").getSingleResult(); return n.intValue(); } public List<EntryImpl> getBlogEntries(int firstPostIndex, int noOfPosts) { Query q = em .createQuery("SELECT b FROM BLOGENTRY b ORDER BY b.publishDate DESC"); q.setFirstResult(firstPostIndex); q.setMaxResults(noOfPosts); @SuppressWarnings("unchecked") List<EntryImpl> list = q.getResultList(); return list; } public AuthorImpl getAuthor(String emailAddress) { AuthorImpl a = em.find(AuthorImpl.class, emailAddress); return a; } public List<EntryImpl> getBlogEntriesModifiedBetween(Date start, Date end) { Query q = em .createQuery("SELECT b FROM BLOGENTRY b WHERE (b.updatedDate >= :start AND b.updatedDate <= :end) OR (b.publishDate >= :start AND b.publishDate <= :end) ORDER BY b.publishDate ASC"); q.setParameter("start", start); q.setParameter("end", end); @SuppressWarnings("unchecked") List<EntryImpl> list = q.getResultList(); return list; } public List<EntryImpl> getBlogsForAuthor(String emailAddress) { List<EntryImpl> list = em.find(AuthorImpl.class, emailAddress) .getEntries(); return list; } public void updateAuthor(String email, Date dob, String name, String displayName, String bio) { AuthorImpl a = em.find(AuthorImpl.class, email); a.setEmail(email); a.setName(name); a.setDisplayName(displayName); a.setBio(bio); a.setDob(dob); em.merge(a); } public void updateBlogEntry(long id, String email, String title, String blogText, List<String> tags, Date updatedDate) { EntryImpl b = em.find(EntryImpl.class, id); b.setTitle(title); b.setBlogText(blogText); b.setTags(tags); b.setUpdatedDate(updatedDate); em.merge(b); } public void removeAuthor(String emailAddress) { em.remove(em.find(AuthorImpl.class, emailAddress)); } public void removeBlogEntry(long id) { EntryImpl b = em.find(EntryImpl.class, id); b = em.merge(b); b.getAuthor().getEntries().remove(b); em.remove(em.merge(b)); em.merge(b.getAuthor()); } public EntryImpl getBlogEntryById(long postId) { EntryImpl b = em.find(EntryImpl.class, postId); return b; } public void setPublishDate (long postId, Date date) { //Added for testing EntryImpl b = em.find(EntryImpl.class, postId); b.setPublishDate(date); em.merge(b); } public void setUpdatedDate (long postId, Date date) { //Added for testing EntryImpl b = em.find(EntryImpl.class, postId); b.setUpdatedDate(date); em.merge(b); } }
8,275
0
Create_ds/aries/samples/blog/blog-persistence-jpa/src/main/java/org/apache/aries/samples/blog/persistence/jpa
Create_ds/aries/samples/blog/blog-persistence-jpa/src/main/java/org/apache/aries/samples/blog/persistence/jpa/entity/EntryImpl.java
/** * 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. */ package org.apache.aries.samples.blog.persistence.jpa.entity; import java.util.Date; import java.util.List; import javax.persistence.Entity; import javax.persistence.Table; import javax.persistence.Id; import javax.persistence.GeneratedValue; import javax.persistence.FetchType; import javax.persistence.ManyToOne; import javax.persistence.Column; import org.apache.aries.samples.blog.api.persistence.Entry; /** * This class represents a blog entry */ @Entity(name = "BLOGENTRY") @Table(name = "BLOGENTRY") public class EntryImpl implements Entry { /** An auto-generated primary key */ @Id @GeneratedValue private Long id; /** The author of the blog post */ @ManyToOne(fetch=FetchType.EAGER) private AuthorImpl author; /** The date the post was published */ private Date publishDate; /** The date the post was last updated */ private Date updatedDate; /** The title of the post */ private String title; /** Tags associated with the post */ private List<String> tags; /** The text of the blog */ @Column(length=10000) private String blogText; /** Get the author of this blog post */ public AuthorImpl getAuthor() { return author; } /** Set the author of this blog post */ public void setAuthor(AuthorImpl author) { this.author = author; } /** Get the publish date of this blog post */ public Date getPublishDate() { return publishDate; } /** Set the publish date of this blog post */ public void setPublishDate(Date publishDate) { this.publishDate = publishDate; } /** Get the title of this blog post */ public String getTitle() { return title; } /** Set the title of this blog post */ public void setTitle(String title) { this.title = title; } /** Get the tags for this blog post */ public List<String> getTags() { return tags; } /** Set the tags for this blog post */ public void setTags(List<String> tags) { this.tags = tags; } /** Get the text for this blog post */ public String getBlogText() { return blogText; } /** Set the text for this blog post */ public void setBlogText(String blogText) { this.blogText = blogText; } /** get the Blog post id */ public long getId() { return id; } /** Set the id */ public void setId(Long id) { this.id = id; } /** * @return The date of the last update to this blog * or null if it has never been modified */ public Date getUpdatedDate() { return updatedDate; } /** * Set the date that the blog post was last updated * * @param updatedDate */ public void setUpdatedDate(Date updatedDate) { this.updatedDate = updatedDate; } }
8,276
0
Create_ds/aries/samples/blog/blog-persistence-jpa/src/main/java/org/apache/aries/samples/blog/persistence/jpa
Create_ds/aries/samples/blog/blog-persistence-jpa/src/main/java/org/apache/aries/samples/blog/persistence/jpa/entity/AuthorImpl.java
/** * 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. */ package org.apache.aries.samples.blog.persistence.jpa.entity; import java.util.Date; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.OrderBy; import javax.persistence.Table; import org.apache.aries.samples.blog.api.persistence.Author; /** * This class represents a blog post Author */ @Entity(name = "AUTHOR") @Table(name = "AUTHOR") public class AuthorImpl implements Author { /** The author's email address */ @Id @Column(nullable = false) private String email; /** The author's full name */ private String name; /** The display name for this author */ private String displayName; /** A short bio for this author */ private String bio; /** The Author's date of birth */ private Date dob; /** The blog entries posted by this user */ @OneToMany(cascade = {CascadeType.REMOVE}, fetch = FetchType.EAGER) @OrderBy("publishDate DESC") private List<EntryImpl> posts; /** Get the author's email address */ public String getEmail() { return email; } /** Get the author's full name */ public String getName() { return name; } /** Get the author's displayed name */ public String getDisplayName() { return displayName; } /** Get the author's biographical information */ public String getBio() { return bio; } /** Get the author's date of birth */ public Date getDob() { return dob; } /** Get the author's blog posts */ public List<EntryImpl> getEntries() { return posts; } // Set methods are not defined in the interface /** Set the author's email address */ public void setEmail(String email) { this.email = email; } /** Set the author's full name */ public void setName(String name) { this.name = name; } /** Set the author's displayed name */ public void setDisplayName(String displayName) { this.displayName = displayName; } /** Set the author's biographical information */ public void setBio(String bio) { this.bio = bio; } /** Set the author's date of birth */ public void setDob(Date dob) { this.dob = dob; } /** Update the author's blog posts */ public void updateEntries(EntryImpl b) { this.posts.add(b); } /** set the author's blog posts */ public void setEntries(List<EntryImpl> lb) { this.posts = lb; } }
8,277
0
Create_ds/aries/samples/blog/blog-persistence-jdbc/src/main/java/org/apache/aries/samples/blog/persistence
Create_ds/aries/samples/blog/blog-persistence-jdbc/src/main/java/org/apache/aries/samples/blog/persistence/jdbc/Statements.java
/* * 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. */ package org.apache.aries.samples.blog.persistence.jdbc; public class Statements { private static final String I_THR_TRY_ELEMENT = "I_THR_TRY_ELEMENT"; private static final String I_THR_TRY_AUTHOR_EMAIL = "I_THR_TRY_AUTHOR_EMAIL"; public static final String I_BLGNTRY_AUTHOR = "I_BLGNTRY_AUTHOR"; public static final String AUTHOR_TABLE_NAME = "AUTHOR"; public static final String AUTHOR_BLOG_ENTRY_TABLE_NAME = "AUTHOR_BLOGENTRY"; public static final String BLOG_ENTRY_TABLE_NAME = "BLOGENTRY"; public static final String COMMENT_ENTRY_TABLE_NAME = "COMMENT"; private String[] dropSchemaStatements; private String[] createSchemaStatements; public synchronized String[] getCreateSchemaStatements() { if (createSchemaStatements == null) { createSchemaStatements = new String[] { "CREATE TABLE " + AUTHOR_TABLE_NAME + " (email VARCHAR(255) NOT NULL, " + "bio VARCHAR(255), displayName VARCHAR(255), " + "dob TIMESTAMP, name VARCHAR(255), PRIMARY KEY (email))", "CREATE TABLE " + AUTHOR_BLOG_ENTRY_TABLE_NAME + " (AUTHOR_EMAIL VARCHAR(255), POSTS_ID BIGINT)", "CREATE TABLE " + BLOG_ENTRY_TABLE_NAME + " (id BIGINT NOT NULL, blogText VARCHAR(10000), " + "publishDate TIMESTAMP, title VARCHAR(255), updatedDate TIMESTAMP, " + "AUTHOR_EMAIL VARCHAR(255), PRIMARY KEY (id))", "CREATE TABLE " + COMMENT_ENTRY_TABLE_NAME + " (id BIGINT NOT NULL, comment VARCHAR(255), creationDate TIMESTAMP, " + "AUTHOR_EMAIL VARCHAR(255), BLOGENTRY_ID BIGINT)", "CREATE INDEX " + I_THR_TRY_AUTHOR_EMAIL + " ON " + AUTHOR_BLOG_ENTRY_TABLE_NAME + " (AUTHOR_EMAIL)", "CREATE INDEX " + I_THR_TRY_ELEMENT + " ON " + AUTHOR_BLOG_ENTRY_TABLE_NAME + " (POSTS_ID)", "CREATE INDEX " + I_BLGNTRY_AUTHOR + " ON " + BLOG_ENTRY_TABLE_NAME + " (AUTHOR_EMAIL)", "DELETE FROM " + AUTHOR_TABLE_NAME, "DELETE FROM " + AUTHOR_BLOG_ENTRY_TABLE_NAME, "DELETE FROM " + BLOG_ENTRY_TABLE_NAME, "DELETE FROM " + COMMENT_ENTRY_TABLE_NAME }; } return createSchemaStatements; } public synchronized String[] getDropSchemaStatements() { if (dropSchemaStatements == null) { dropSchemaStatements = new String[] { "DROP INDEX " + I_THR_TRY_ELEMENT, "DROP INDEX " + I_BLGNTRY_AUTHOR, "DROP INDEX " + I_THR_TRY_AUTHOR_EMAIL, "DROP TABLE " + COMMENT_ENTRY_TABLE_NAME, "DROP TABLE " + BLOG_ENTRY_TABLE_NAME, "DROP TABLE " + AUTHOR_BLOG_ENTRY_TABLE_NAME, "DROP TABLE " + AUTHOR_TABLE_NAME }; } return dropSchemaStatements; } }
8,278
0
Create_ds/aries/samples/blog/blog-persistence-jdbc/src/main/java/org/apache/aries/samples/blog/persistence
Create_ds/aries/samples/blog/blog-persistence-jdbc/src/main/java/org/apache/aries/samples/blog/persistence/jdbc/BlogPersistenceServiceImpl.java
/** * 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. */ package org.apache.aries.samples.blog.persistence.jdbc; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.text.ParseException; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.sql.DataSource; import org.apache.aries.samples.blog.api.persistence.BlogPersistenceService; import org.apache.aries.samples.blog.persistence.jdbc.entity.AuthorImpl; import org.apache.aries.samples.blog.persistence.jdbc.entity.EntryImpl; /** * This class is the implementation of the blogPersistenceService */ public class BlogPersistenceServiceImpl implements BlogPersistenceService { private DataSource dataSource; private Statements statements; public BlogPersistenceServiceImpl() { this.statements = new Statements(); } /** * set data source */ public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } public void init() { Statement s = null; Connection connection = null; try { connection = dataSource.getConnection(); s = connection.createStatement(); String[] createStatments = this.statements .getCreateSchemaStatements(); for (int i = 0; i < createStatments.length; i++) { s.execute(createStatments[i]); } } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } finally { if (s != null) { try { s.close(); } catch (Throwable e) { } } if (connection != null) { try { connection.close(); } catch (Throwable e) { } } } } public void destroy() { Statement s = null; Connection connection = null; try { connection = dataSource.getConnection(); s = connection.createStatement(); String[] dropStatments = this.statements.getDropSchemaStatements(); for (int i = 0; i < dropStatments.length; i++) { s.execute(dropStatments[i]); } } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } finally { if (s != null) { try { s.close(); } catch (Throwable e) { } } if (connection != null) { try { connection.close(); } catch (Throwable e) { } } } } /** * Create an author record * * @param a * The author object to be created * @throws ParseException * @throws ParseException */ public void createAuthor(String email, Date dob, String name, String displayName, String bio) { try { Connection connection = dataSource.getConnection(); String sql = "INSERT INTO AUTHOR VALUES (?,?,?,?,?)"; PreparedStatement ppsm = connection.prepareStatement(sql); ppsm.setString(1, email); ppsm.setString(2, bio); ppsm.setString(3, displayName); if (dob != null) ppsm.setDate(4, new java.sql.Date(dob.getTime())); else ppsm.setDate(4, null); ppsm.setString(5, name); int insertRows = ppsm.executeUpdate(); ppsm.close(); connection.close(); if (insertRows != 1) throw new IllegalArgumentException("The Author " + email + " cannot be inserted."); } catch (SQLException e) { e.printStackTrace(); throw new IllegalArgumentException(e.getMessage()); } } /** * Create a blog entry record * * @param a * The author * @param title * The title of the post * @param blogText * The text of the post * @param tags * */ public void createBlogPost(String authorEmail, String title, String blogText, List<String> tags) { AuthorImpl a = getAuthor(authorEmail); if(title == null) title = ""; Date publishDate = new Date(System.currentTimeMillis()); if(tags == null) tags = new ArrayList<String>(); try { Connection connection = dataSource.getConnection(); // let's find the max id from the blogentry table String sql = "SELECT max(id) FROM BLOGENTRY"; PreparedStatement ppsm = connection.prepareStatement(sql); ResultSet rs = ppsm.executeQuery(); // we only expect to have one row returned rs.next(); long max_id = rs.getLong(1); ppsm.close(); long post_id = max_id + 1; sql = "INSERT INTO BLOGENTRY VALUES (?,?,?,?,?,?)"; ppsm = connection.prepareStatement(sql); ppsm.setLong(1, post_id); ppsm.setString(2, blogText); if (publishDate != null) ppsm .setDate(3, new java.sql.Date(publishDate .getTime())); else ppsm.setDate(3, null); ppsm.setString(4, title); ppsm.setDate(5, null); ppsm.setString(6, a.getEmail()); int rows = ppsm.executeUpdate(); if (rows != 1) throw new IllegalArgumentException( "The blog entry record cannot be inserted: " + blogText); ppsm.close(); // insert a row in the relationship table sql = "INSERT INTO Author_BlogEntry VALUES (?,?)"; ppsm = connection.prepareStatement(sql); ppsm.setString(1, a.getEmail()); ppsm.setLong(2, post_id); rows = ppsm.executeUpdate(); ppsm.close(); connection.close(); if (rows != 1) throw new IllegalArgumentException( "The Author_BlogEntry record cannot be inserted: " + a.getEmail() + " , " + post_id); } catch (SQLException sqle) { sqle.printStackTrace(); } } /** * Find the blog entry record with the specified title * * @param The title to be searched * @return The blogEntry record */ public EntryImpl findBlogEntryByTitle(String title) { EntryImpl be = null; String sql = "SELECT * FROM BlogEntry e WHERE e.title = '" + title + "'"; List<EntryImpl> blogEntries = findBlogs(sql); // just return the first blog entry for the time being if ((blogEntries != null) && (blogEntries.size() > 0)) be = blogEntries.get(0); return be; } /** * Return all author records in the Author table * * @return the list of Author records */ public List<AuthorImpl> getAllAuthors() { String sql = "SELECT * FROM Author"; List<AuthorImpl> list = findAuthors(sql); return list; } /** * Return all blog entry records from BlogEntry table with the most recent * published blog entries first * * @return a list of blogEntry object */ public List<EntryImpl> getAllBlogEntries() { String sql = "SELECT * FROM BlogEntry b ORDER BY b.publishDate DESC"; List<EntryImpl> list = findBlogs(sql); return list; } /** * Return the number of the blog entry records * * @return the number of the blog Entry records */ public int getNoOfBlogEntries() { int count = 0; String sql = "SELECT count(*) FROM BLOGENTRY"; try { Connection connection = dataSource.getConnection(); PreparedStatement ppsm = connection.prepareStatement(sql); ResultSet rs = ppsm.executeQuery(); // we only expect to have one row returned rs.next(); count = rs.getInt(1); ppsm.close(); connection.close(); } catch (SQLException sqle) { sqle.printStackTrace(); } return count; } /** * Return the portion of blog Entries * * @param firstPostIndex * The index of the first blog entry to be returned * @param noOfPosts * The number of blog entry to be returned * @return The list of the blog entry record */ public List<EntryImpl> getBlogEntries(int firstPostIndex, int noOfPosts) { String sql = "SELECT * FROM BlogEntry b ORDER BY b.publishDate DESC"; List<EntryImpl> emptyList = new ArrayList<EntryImpl>(); List<EntryImpl> blogs = findBlogs(sql); // we only return a portion of the list if (blogs == null) return emptyList; // We need to make sure we won't throw IndexOutOfBoundException if the // supplied // index is out of the list range int maximumIndex = blogs.size(); // if the first index is minus or greater than the last item index of // the list, return an empty list if ((firstPostIndex < 0) || (noOfPosts <= 0) || (firstPostIndex > maximumIndex)) return emptyList; // return the required number of the blog entries or the available blog // entries int lastIndex = noOfPosts + firstPostIndex; // we need to make sure we return the blog entries at most up to the // final record return (blogs.subList(firstPostIndex, (lastIndex > maximumIndex) ? maximumIndex : lastIndex)); } /** * Return the author with the specified email address * * @param emailAddress * The email address * @return The author record */ public AuthorImpl getAuthor(String emailAddress) { String sql = "SELECT * FROM AUTHOR a where a.email='" + emailAddress + "'"; List<AuthorImpl> authors = findAuthors(sql); if (authors.size() == 0) return null; else if (authors.size() > 1) throw new IllegalArgumentException( "Email address should be unique per author"); return authors.get(0); // just return the first author } /** * Return the blog entries modified between the date range of [start, end] * * @param start * The start date * @param end * The end date * @return The list of blog entries */ public List<EntryImpl> getBlogEntriesModifiedBetween(Date start, Date end) { // String sql = "SELECT * FROM BlogEntry b WHERE (b.updatedDate >= " + // startTS +" AND b.updatedDate <= " + endTS + ") OR (b.publishDate >= " // +startTS + " AND b.publishDate <= " + endTS + // ") ORDER BY b.publishDate ASC"; String sql = "SELECT * FROM BlogEntry b WHERE (Date(b.updatedDate) BETWEEN '" + start + "' AND '" + end + "') OR (Date(b.publishDate) BETWEEN '" + start + "' AND '" + end + "') ORDER BY b.publishDate ASC"; return findBlogs(sql); } /** * Return a list of blog entries belonging to the author with the specified * email address * * @param emailAddress * the author's email address * @return The list of blog entries */ public List<EntryImpl> getBlogsForAuthor(String emailAddress) { String sql = "SELECT * FROM BlogEntry b WHERE b.AUTHOR_EMAIL='" + emailAddress + "'"; return findBlogs(sql); } /** * Update the author record * * @param email * The email associated with an author * @param dob * The author's date of birth * @param name * the author's name * @param displayName * The displayName * @param bio * The aouthor's bio */ public void updateAuthor(String email, Date dob, String name, String displayName, String bio) { String sql = "UPDATE AUTHOR a SET bio = ?, displayName = ?, dob = ?, name =? WHERE email ='" + email + "'"; int updatedRows = 0; try { Connection connection = dataSource.getConnection(); PreparedStatement ppsm = connection.prepareStatement(sql); ppsm.setString(1, bio); ppsm.setString(2, displayName); if (dob != null) ppsm.setDate(3, new java.sql.Date(dob.getTime())); else ppsm.setDate(3, null); ppsm.setString(4, name); updatedRows = ppsm.executeUpdate(); ppsm.close(); connection.close(); if (updatedRows != 1) throw new IllegalArgumentException("The Author " + email + " cannot be updated."); } catch (SQLException e) { e.printStackTrace(); } } /** * Update the blog entry record * * */ public void updateBlogEntry(long id, String email, String title, String blogText, List<String> tags, Date updatedDate) { if (id == -1) throw new IllegalArgumentException( "Not a BlogEntry returned by this interface"); EntryImpl b = getBlogEntryById(id); String sql_se = "SELECT * FROM BLOGENTRY bp WHERE bp.id = " + id; String email_old = null; // let's find out the email address for the blog post to see whether the // table Author_BlogEntry needs to be updated // if the email is updated, we need to update the table Author_BlogEntry // to reflect the change. try { Connection connection = dataSource.getConnection(); PreparedStatement ppsm = connection.prepareStatement(sql_se); ResultSet rs = ppsm.executeQuery(); // there should be just one record rs.next(); email_old = rs.getString("AUTHOR_EMAIL"); ppsm.close(); connection.close(); } catch (SQLException sqle) { sqle.printStackTrace(); } String sql = "UPDATE BLOGENTRY bp SET bp.blogText = ?, bp.publishDate = ?, bp.title = ?, bp.updatedDate = ?, bp.AUTHOR_EMAIL = ? where bp.id = " + id; int updatedRows = 0; try { Connection connection = dataSource.getConnection(); PreparedStatement ppsm = connection.prepareStatement(sql); ppsm.setString(1, blogText); if (b.getPublishDate() != null) ppsm .setDate(2, new java.sql.Date(b.getPublishDate() .getTime())); else ppsm.setDate(2, null); ppsm.setString(3, b.getTitle()); if (b.getUpdatedDate() != null) ppsm .setDate(4, new java.sql.Date(b.getUpdatedDate() .getTime())); else ppsm.setDate(4, null); ppsm.setString(5, email); updatedRows = ppsm.executeUpdate(); ppsm.close(); connection.close(); if (updatedRows != 1) throw new IllegalArgumentException("The Blog " + b.getId() + " cannot be updated."); } catch (SQLException e) { e.printStackTrace(); } // if the email address is changed, we need to need to update the // relationship table Author_BlogEntry if ((email_old != null) && (!!!email_old.equals(email))) { // update the table Author_BlogEntry String sql_ab = "UDPATE Author_BlogEntry ab SET ab.AUTHOR_EMAIL = '" + email + "'"; updatedRows = 0; try { Connection connection = dataSource.getConnection(); PreparedStatement ppsm = connection.prepareStatement(sql_ab); updatedRows = ppsm.executeUpdate(); ppsm.close(); connection.close(); if (updatedRows != 1) throw new IllegalArgumentException( "The Author_BlogEntry with the postsID " + b.getId() + " cannot be updated."); } catch (SQLException e) { e.printStackTrace(); } } } /** * Delete the author record with the specified email address * * @param emailAddress * The author's email address * */ public void removeAuthor(String emailAddress) { // we need to remove the author and its blog entries try { String sql = "DELETE FROM BLOGENTRY bp WHERE bp.AUTHOR_EMAIL = '" + emailAddress + "'"; Connection connection = dataSource.getConnection(); PreparedStatement ppsm = connection.prepareStatement(sql); ppsm.executeUpdate(); ppsm.close(); // delete the records from Author_BlogEntry sql = "DELETE FROM Author_BlogEntry ab WHERE ab.AUTHOR_EMAIL = '" + emailAddress + "'"; ppsm = connection.prepareStatement(sql); ppsm.executeUpdate(); ppsm.close(); // delete the author record sql = "DELETE FROM Author a WHERE a.EMAIL = '" + emailAddress + "'"; ppsm = connection.prepareStatement(sql); ppsm.executeUpdate(); ppsm.close(); connection.close(); } catch (SQLException sqle) { sqle.printStackTrace(); } } /** * Delete the blog entry record specified by the blogEntry * * @param blogEntry * the blog entry record to be deleted */ public void removeBlogEntry(long id) { if (id == -1) throw new IllegalArgumentException( "Not a BlogEntry returned by this interface"); try { String sql = "DELETE FROM BLOGENTRY bp WHERE bp.id = " + id; Connection connection = dataSource.getConnection(); PreparedStatement ppsm = connection.prepareStatement(sql); ppsm.executeUpdate(); ppsm.close(); // We also need to delete the records from Author_BlogEntry, as this // table is a kind of link between author and blogentry record sql = "DELETE FROM Author_BlogEntry ab WHERE ab.POSTS_ID = " + id; ppsm = connection.prepareStatement(sql); ppsm.executeUpdate(); ppsm.close(); connection.close(); } catch (SQLException sqle) { sqle.printStackTrace(); } } /** * Return the blog entry record with the specified id * * @param postId * The blogEntry record id */ public EntryImpl getBlogEntryById(long postId) { String sql = "SELECT * FROM BlogEntry b WHERE b.id = " + postId; List<EntryImpl> blogs = findBlogs(sql); if (blogs.size() == 0) return null; if (blogs.size() > 1) throw new IllegalArgumentException("Blog id is not unique"); return blogs.get(0); } /** * Return a list of authors with the sql query * * @param sql * The SQL query * @return A list of author records */ private List<AuthorImpl> findAuthors(String sql) { List<AuthorImpl> authorList = new ArrayList<AuthorImpl>(); try { Connection connection = dataSource.getConnection(); PreparedStatement ppsm = connection.prepareStatement(sql); ResultSet ars = ppsm.executeQuery(); while (ars.next()) { AuthorImpl ar = new AuthorImpl(); ar.setBio(ars.getString("bio")); ar.setDisplayName(ars.getString("displayName")); ar.setDob(ars.getDate("dob")); String email = ars.getString("email"); ar.setEmail(email); ar.setName(ars.getString("name")); // let's find the blog entries for the author String sql_be = "SELECT * FROM BLOGENTRY be WHERE be.AUTHOR_EMAIL = '" + email + "'"; PreparedStatement ppsm2 = connection.prepareStatement(sql_be); ResultSet rs = ppsm2.executeQuery(); List<EntryImpl> blogs = new ArrayList<EntryImpl>(); while (rs.next()) { EntryImpl blog = new EntryImpl(); blog.setAuthor(ar); blog.setId(rs.getLong("id")); blog.setBlogText(rs.getString("blogText")); blog.setPublishDate(rs.getDate("publishDate")); blog.setTitle(rs.getString("title")); blog.setUpdatedDate(rs.getDate("updatedDate")); blogs.add(blog); } ar.setEntries(blogs); authorList.add(ar); ppsm2.close(); } ppsm.close(); connection.close(); } catch (Exception e) { e.printStackTrace(); } return authorList; } /** * Return a list of blog entries with the sql query * * @param sql * The sql query to be executed * @return a list of blogEntry records */ private List<EntryImpl> findBlogs(String sql) { List<EntryImpl> blogEntryList = new ArrayList<EntryImpl>(); try { Connection connection = dataSource.getConnection(); PreparedStatement ppsm = connection.prepareStatement(sql); ResultSet blogrs = ppsm.executeQuery(); while (blogrs.next()) { EntryImpl be = new EntryImpl(); be.setId(blogrs.getLong("id")); be.setBlogText(blogrs.getString("blogText")); be.setPublishDate(blogrs.getDate("publishDate")); be.setTitle(blogrs.getString("title")); be.setUpdatedDate(blogrs.getDate("updatedDate")); // find the author email address String author_email = blogrs.getString("AUTHOR_EMAIL"); String author_sql = "SELECT * FROM Author a WHERE a.email ='" + author_email + "'"; List<AuthorImpl> authors = findAuthors(author_sql); // there should be just one entry, as email is the primary key // for the Author table if (authors.size() != 1) throw new IllegalArgumentException( "We got more than one author with the same email address. This is wrong"); else be.setAuthor(authors.get(0)); blogEntryList.add(be); } ppsm.close(); connection.close(); } catch (Exception e) { e.printStackTrace(); } return blogEntryList; } }
8,279
0
Create_ds/aries/samples/blog/blog-persistence-jdbc/src/main/java/org/apache/aries/samples/blog/persistence/jdbc
Create_ds/aries/samples/blog/blog-persistence-jdbc/src/main/java/org/apache/aries/samples/blog/persistence/jdbc/entity/EntryImpl.java
/** * 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. */ package org.apache.aries.samples.blog.persistence.jdbc.entity; import java.util.Date; import java.util.List; import org.apache.aries.samples.blog.api.persistence.Entry; /** * This class represents a blog entry */ public class EntryImpl implements Entry { /** An auto-generated primary key */ private Long id; /** The author of the blog post */ private AuthorImpl author; /** The date the post was published */ private Date publishDate; /** The date the post was last updated */ private Date updatedDate; /** The title of the post */ private String title; /** Tags associated with the post */ private List<String> tags; /** The text of the blog */ private String blogText; /** Get the author of this blog post */ public AuthorImpl getAuthor() { return author; } /** Set the author of this blog post */ public void setAuthor(AuthorImpl author) { this.author = author; } /** Get the publish date of this blog post */ public Date getPublishDate() { return publishDate; } /** Set the publish date of this blog post */ public void setPublishDate(Date publishDate) { this.publishDate = publishDate; } /** Get the title of this blog post */ public String getTitle() { return title; } /** Set the title of this blog post */ public void setTitle(String title) { this.title = title; } /** Get the tags for this blog post */ public List<String> getTags() { return tags; } /** Set the tags for this blog post */ public void setTags(List<String> tags) { this.tags = tags; } /** Get the text for this blog post */ public String getBlogText() { return blogText; } /** Set the text for this blog post */ public void setBlogText(String blogText) { this.blogText = blogText; } /** get the Blog post id */ public long getId() { return id; } /** Set the id */ public void setId(Long id) { this.id = id; } /** * @return The date of the last update to this blog * or null if it has never been modified */ public Date getUpdatedDate() { return updatedDate; } /** * Set the date that the blog post was last updated * * @param updatedDate */ public void setUpdatedDate(Date updatedDate) { this.updatedDate = updatedDate; } }
8,280
0
Create_ds/aries/samples/blog/blog-persistence-jdbc/src/main/java/org/apache/aries/samples/blog/persistence/jdbc
Create_ds/aries/samples/blog/blog-persistence-jdbc/src/main/java/org/apache/aries/samples/blog/persistence/jdbc/entity/AuthorImpl.java
/** * 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. */ package org.apache.aries.samples.blog.persistence.jdbc.entity; import java.util.Date; import java.util.List; import org.apache.aries.samples.blog.api.persistence.Author; /** * This class represents a blog post Author */ public class AuthorImpl implements Author { /** The author's email address */ private String email; /** The author's full name */ private String name; /** The display name for this author */ private String displayName; /** A short bio for this author */ private String bio; /** The Author's date of birth */ private Date dob; /** The blog entries posted by this user */ private List<EntryImpl> posts; /** Get the author's email address */ public String getEmail() { return email; } /** Set the author's email address */ public void setEmail(String email) { this.email = email; } /** Get the author's full name */ public String getName() { return name; } /** Set the author's full name */ public void setName(String name) { this.name = name; } /** Get the author's displayed name */ public String getDisplayName() { return displayName; } /** Set the author's displayed name */ public void setDisplayName(String displayName) { this.displayName = displayName; } /** Get the author's biographical information */ public String getBio() { return bio; } /** Set the author's biographical information */ public void setBio(String bio) { this.bio = bio; } /** Get the author's date of birth */ public Date getDob() { return dob; } /** Set the author's date of birth */ public void setDob(Date dob) { this.dob = dob; } /** Get the author's blog posts */ public List<EntryImpl> getEntries() { return posts; } /** Set the author's blog posts */ public void setEntries(List<EntryImpl> posts) { this.posts = posts; } }
8,281
0
Create_ds/aries/samples/blueprint/helloworld/helloworld-client/src/main/java/org/apache/aries/samples/blueprint/helloworld
Create_ds/aries/samples/blueprint/helloworld/helloworld-client/src/main/java/org/apache/aries/samples/blueprint/helloworld/client/HelloWorldClient.java
/** * 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. */ package org.apache.aries.samples.blueprint.helloworld.client; import org.apache.aries.samples.blueprint.helloworld.api.HelloWorldService; public class HelloWorldClient { HelloWorldService helloWorldService = null; public void startUp() { System.out.println("========>>>>Client HelloWorld: About to execute a method from the Hello World service"); helloWorldService.hello(); System.out.println("========>>>>Client HelloWorld: ... if you didn't just see a Hello World message something went wrong"); } public HelloWorldService getHelloWorldService() { return helloWorldService; } public void setHelloWorldService(HelloWorldService helloWorldService) { this.helloWorldService = helloWorldService; } }
8,282
0
Create_ds/aries/samples/blueprint/helloworld/helloworld-api/src/main/java/org/apache/aries/samples/blueprint/helloworld
Create_ds/aries/samples/blueprint/helloworld/helloworld-api/src/main/java/org/apache/aries/samples/blueprint/helloworld/api/HelloWorldService.java
/** * 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. */ package org.apache.aries.samples.blueprint.helloworld.api; public interface HelloWorldService { public void hello(); public void startUp(); }
8,283
0
Create_ds/aries/samples/blueprint/helloworld/helloworld-itests/src/test/java/org/apache/aries/samples/blueprint/helloworld
Create_ds/aries/samples/blueprint/helloworld/helloworld-itests/src/test/java/org/apache/aries/samples/blueprint/helloworld/itests/AbstractIntegrationTest.java
/* * 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. */ package org.apache.aries.samples.blueprint.helloworld.itests; import static org.ops4j.pax.exam.CoreOptions.options; import static org.ops4j.pax.exam.CoreOptions.wrappedBundle; import static org.ops4j.pax.exam.OptionUtils.combine; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Properties; import org.junit.After; import org.junit.Before; import org.ops4j.pax.exam.CoreOptions; import org.ops4j.pax.exam.Inject; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.options.MavenArtifactProvisionOption; import org.ops4j.pax.url.mvn.Handler; import org.ops4j.pax.url.mvn.ServiceConstants; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.Constants; import org.osgi.framework.Filter; import org.osgi.framework.FrameworkUtil; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceReference; import org.osgi.util.tracker.ServiceTracker; public abstract class AbstractIntegrationTest { private static final int CONNECTION_TIMEOUT = 30000; public static final long DEFAULT_TIMEOUT = 60000; @Inject protected BundleContext bundleContext; private List<ServiceTracker> srs; @Before public void setUp() { srs = new ArrayList<ServiceTracker>(); } @After public void tearDown() throws Exception{ for (ServiceTracker st : srs) { if (st != null) { st.close(); } } } public static MavenArtifactProvisionOption mavenBundle(String groupId, String artifactId) { return CoreOptions.mavenBundle().groupId(groupId).artifactId(artifactId).versionAsInProject(); } public static MavenArtifactProvisionOption mavenBundleInTest(String groupId, String artifactId) { return CoreOptions.mavenBundle().groupId(groupId).artifactId(artifactId).version(getArtifactVersion(groupId, artifactId)); } public static String getArtifactVersion( final String groupId, final String artifactId ) { final Properties dependencies = new Properties(); try { InputStream in = getFileFromClasspath("META-INF/maven/dependencies.properties"); try { dependencies.load(in); } finally { in.close(); } final String version = dependencies.getProperty( groupId + "/" + artifactId + "/version" ); if( version == null ) { throw new RuntimeException( "Could not resolve version. Do you have a dependency for " + groupId + "/" + artifactId + " in your maven project?" ); } return version; } catch( IOException e ) { // TODO throw a better exception throw new RuntimeException( "Could not resolve version. Did you configured the plugin in your maven project?" + "Or maybe you did not run the maven build and you are using an IDE?" ); } } protected Bundle getInstalledBundle(String symbolicName) { for (Bundle b : bundleContext.getBundles()) { if (b.getSymbolicName().equals(symbolicName)) { return b; } } return null; } private static InputStream getFileFromClasspath( final String filePath ) throws FileNotFoundException { try { URL fileURL = AbstractIntegrationTest.class.getClassLoader().getResource( filePath ); if( fileURL == null ) { throw new FileNotFoundException( "File [" + filePath + "] could not be found in classpath" ); } return fileURL.openStream(); } catch (IOException e) { throw new FileNotFoundException( "File [" + filePath + "] could not be found: " + e.getMessage() ); } } protected void listBundleServices(Bundle b) { ServiceReference []srb = b.getRegisteredServices(); for(ServiceReference sr:srb){ System.out.println(b.getSymbolicName() + " SERVICE: "+sr); } } protected Boolean isServiceRegistered(Bundle b) { ServiceReference []srb = b.getRegisteredServices(); if(srb == null) { return false; } return true; } protected void waitForServices(Bundle b, String sclass) { try { BundleContext bc = b.getBundleContext(); String bsn = b.getSymbolicName(); ServiceTracker st = new ServiceTracker(bc, sclass, null); st.open(); Object bac = st.waitForService(DEFAULT_TIMEOUT); /* Uncomment for debug */ /* if(bac == null) { System.out.println("SERVICE NOTFOUND " + bsn); } else { System.out.println("SERVICE FOUND " + bsn); } */ st.close(); return; } catch (Exception e) { System.out.println("Failed to register services for " + b.getSymbolicName() + e.getMessage()); } } protected static Option[] updateOptions(Option[] options) { if ("IBM Corporation".equals(System.getProperty("java.vendor"))) { Option[] ibmOptions = options( wrappedBundle(mavenBundle("org.ops4j.pax.exam", "pax-exam-junit")) ); options = combine(ibmOptions, options); } return options; } public static String getHTTPResponse(HttpURLConnection conn) throws IOException { StringBuilder response = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "ISO-8859-1")); try { for (String s = reader.readLine(); s != null; s = reader.readLine()) { response.append(s).append("\r\n"); } } finally { reader.close(); } return response.toString(); } public static HttpURLConnection makeConnection(String contextPath) throws IOException { URL url = new URL(contextPath); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(CONNECTION_TIMEOUT); conn.connect(); return conn; } protected <T> T getOsgiService(Class<T> type, long timeout) { return getOsgiService(type, null, timeout); } protected <T> T getOsgiService(Class<T> type) { return getOsgiService(type, null, DEFAULT_TIMEOUT); } protected <T> T getOsgiService(Class<T> type, String filter, long timeout) { return getOsgiService(null, type, filter, timeout); } protected <T> T getOsgiService(BundleContext bc, Class<T> type, String filter, long timeout) { ServiceTracker tracker = null; try { String flt; if (filter != null) { if (filter.startsWith("(")) { flt = "(&(" + Constants.OBJECTCLASS + "=" + type.getName() + ")" + filter + ")"; } else { flt = "(&(" + Constants.OBJECTCLASS + "=" + type.getName() + ")(" + filter + "))"; } } else { flt = "(" + Constants.OBJECTCLASS + "=" + type.getName() + ")"; } Filter osgiFilter = FrameworkUtil.createFilter(flt); tracker = new ServiceTracker(bc == null ? bundleContext : bc, osgiFilter, null); tracker.open(); // add tracker to the list of trackers we close at tear down srs.add(tracker); Object x = tracker.waitForService(timeout); Object svc = type.cast(x); if (svc == null) { throw new RuntimeException("Gave up waiting for service " + flt); } return type.cast(svc); } catch (InvalidSyntaxException e) { throw new IllegalArgumentException("Invalid filter", e); } catch (InterruptedException e) { throw new RuntimeException(e); } } public static URL getUrlToEba(String groupId, String artifactId) throws MalformedURLException { String artifactVersion = getArtifactVersion(groupId, artifactId); // Need to use handler from org.ops4j.pax.url.mvn URL urlToEba = new URL(null, ServiceConstants.PROTOCOL + ":" + groupId + "/" +artifactId + "/" + artifactVersion + "/eba", new Handler()); return urlToEba; } }
8,284
0
Create_ds/aries/samples/blueprint/helloworld/helloworld-itests/src/test/java/org/apache/aries/samples/blueprint/helloworld
Create_ds/aries/samples/blueprint/helloworld/helloworld-itests/src/test/java/org/apache/aries/samples/blueprint/helloworld/itests/HelloworldSampleTest.java
/* * 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. */ package org.apache.aries.samples.blueprint.helloworld.itests; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.ops4j.pax.exam.CoreOptions.bootDelegationPackages; import static org.ops4j.pax.exam.CoreOptions.equinox; import static org.ops4j.pax.exam.CoreOptions.options; import static org.ops4j.pax.exam.CoreOptions.systemProperty; import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.vmOption; import org.osgi.service.blueprint.container.BlueprintContainer; import org.junit.Test; import org.junit.runner.RunWith; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.junit.JUnit4TestRunner; import org.osgi.framework.Bundle; @RunWith(JUnit4TestRunner.class) public class HelloworldSampleTest extends AbstractIntegrationTest { @Test public void testBundlesStart() throws Exception { /* Check that the HelloWorld Sample bundles are present an started */ Bundle bapi = getInstalledBundle("org.apache.aries.samples.blueprint.helloworld.api"); assertNotNull(bapi); failInBundleNotActiveInFiveSeconds(bapi); assertEquals(Bundle.ACTIVE, bapi.getState()); Bundle bcli = getInstalledBundle("org.apache.aries.samples.blueprint.helloworld.client"); assertNotNull(bcli); failInBundleNotActiveInFiveSeconds(bcli); Bundle bser = getInstalledBundle("org.apache.aries.samples.blueprint.helloworld.server"); assertNotNull(bser); failInBundleNotActiveInFiveSeconds(bser); } @Test public void testClientBlueprintContainerOnlyStartsWhenServiceStarted() throws Exception { // Stop everything before we start Bundle bcli = getInstalledBundle("org.apache.aries.samples.blueprint.helloworld.client"); assertNotNull(bcli); bcli.stop(); Bundle bser = getInstalledBundle("org.apache.aries.samples.blueprint.helloworld.server"); assertNotNull(bser); bser.stop(); // Wait for everything to shut down Thread.sleep(1000); // When everything is stopped, there should be no blueprint container for either the client or the server assertClientBlueprintContainerNull(); assertServerBlueprintContainerNull(); // If we start the client first, it shouldn't have a blueprint container bcli.start(); // Wait for everything to get started Thread.sleep(1000); assertClientBlueprintContainerNull(); // Then when we start the server both it and the client should have blueprint containers bser.start(); // Wait for everything to get started Thread.sleep(1000); assertClientBlueprintContainerNotNull(); assertServerBlueprintContainerNotNull(); } private BlueprintContainer getBlueprintContainer(String bundleName) { BlueprintContainer container = null; try { container = getOsgiService(BlueprintContainer.class, "(osgi.blueprint.container.symbolicname=" + bundleName + ")", 500); } catch (RuntimeException e) { // Just return null if we couldn't get the container } return container; } private BlueprintContainer getClientBlueprintContainer() { return getBlueprintContainer("org.apache.aries.samples.blueprint.helloworld.client"); } private BlueprintContainer getServerBlueprintContainer() { return getBlueprintContainer("org.apache.aries.samples.blueprint.helloworld.server"); } private void assertClientBlueprintContainerNotNull() { assertNotNull("There was no blueprint container for the client bundle.", getClientBlueprintContainer()); } private void assertClientBlueprintContainerNull() { assertNull("There was a blueprint container for the client bundle when we didn't expect one.", getClientBlueprintContainer()); } private void assertServerBlueprintContainerNotNull() { assertNotNull("There was no blueprint container for the server bundle.", getServerBlueprintContainer()); } private void assertServerBlueprintContainerNull() { assertNull("There was a blueprint container for the server bundle when we didn't expect one.", getServerBlueprintContainer()); } private void failInBundleNotActiveInFiveSeconds(Bundle bapi) { for (int i = 0; i < 5 && Bundle.ACTIVE != bapi.getState(); i++) { try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } assertEquals("The bundle " + bapi.getSymbolicName() + " " + bapi.getVersion() + " is not active", Bundle.ACTIVE, bapi.getState()); } @org.ops4j.pax.exam.junit.Configuration public static Option[] configuration() { Option[] options = options( bootDelegationPackages("javax.transaction", "javax.transaction.*"), vmOption("-Dorg.osgi.framework.system.packages=javax.accessibility,javax.activation,javax.activity,javax.annotation,javax.annotation.processing,javax.crypto,javax.crypto.interfaces,javax.crypto.spec,javax.imageio,javax.imageio.event,javax.imageio.metadata,javax.imageio.plugins.bmp,javax.imageio.plugins.jpeg,javax.imageio.spi,javax.imageio.stream,javax.jws,javax.jws.soap,javax.lang.model,javax.lang.model.element,javax.lang.model.type,javax.lang.model.util,javax.management,javax.management.loading,javax.management.modelmbean,javax.management.monitor,javax.management.openmbean,javax.management.relation,javax.management.remote,javax.management.remote.rmi,javax.management.timer,javax.naming,javax.naming.directory,javax.naming.event,javax.naming.ldap,javax.naming.spi,javax.net,javax.net.ssl,javax.print,javax.print.attribute,javax.print.attribute.standard,javax.print.event,javax.rmi,javax.rmi.CORBA,javax.rmi.ssl,javax.script,javax.security.auth,javax.security.auth.callback,javax.security.auth.kerberos,javax.security.auth.login,javax.security.auth.spi,javax.security.auth.x500,javax.security.cert,javax.security.sasl,javax.sound.midi,javax.sound.midi.spi,javax.sound.sampled,javax.sound.sampled.spi,javax.sql,javax.sql.rowset,javax.sql.rowset.serial,javax.sql.rowset.spi,javax.swing,javax.swing.border,javax.swing.colorchooser,javax.swing.event,javax.swing.filechooser,javax.swing.plaf,javax.swing.plaf.basic,javax.swing.plaf.metal,javax.swing.plaf.multi,javax.swing.plaf.synth,javax.swing.table,javax.swing.text,javax.swing.text.html,javax.swing.text.html.parser,javax.swing.text.rtf,javax.swing.tree,javax.swing.undo,javax.tools,javax.xml,javax.xml.bind,javax.xml.bind.annotation,javax.xml.bind.annotation.adapters,javax.xml.bind.attachment,javax.xml.bind.helpers,javax.xml.bind.util,javax.xml.crypto,javax.xml.crypto.dom,javax.xml.crypto.dsig,javax.xml.crypto.dsig.dom,javax.xml.crypto.dsig.keyinfo,javax.xml.crypto.dsig.spec,javax.xml.datatype,javax.xml.namespace,javax.xml.parsers,javax.xml.soap,javax.xml.stream,javax.xml.stream.events,javax.xml.stream.util,javax.xml.transform,javax.xml.transform.dom,javax.xml.transform.sax,javax.xml.transform.stax,javax.xml.transform.stream,javax.xml.validation,javax.xml.ws,javax.xml.ws.handler,javax.xml.ws.handler.soap,javax.xml.ws.http,javax.xml.ws.soap,javax.xml.ws.spi,javax.xml.xpath,org.ietf.jgss,org.omg.CORBA,org.omg.CORBA.DynAnyPackage,org.omg.CORBA.ORBPackage,org.omg.CORBA.TypeCodePackage,org.omg.CORBA.portable,org.omg.CORBA_2_3,org.omg.CORBA_2_3.portable,org.omg.CosNaming,org.omg.CosNaming.NamingContextExtPackage,org.omg.CosNaming.NamingContextPackage,org.omg.Dynamic,org.omg.DynamicAny,org.omg.DynamicAny.DynAnyFactoryPackage,org.omg.DynamicAny.DynAnyPackage,org.omg.IOP,org.omg.IOP.CodecFactoryPackage,org.omg.IOP.CodecPackage,org.omg.Messaging,org.omg.PortableInterceptor,org.omg.PortableInterceptor.ORBInitInfoPackage,org.omg.PortableServer,org.omg.PortableServer.CurrentPackage,org.omg.PortableServer.POAManagerPackage,org.omg.PortableServer.POAPackage,org.omg.PortableServer.ServantLocatorPackage,org.omg.PortableServer.portable,org.omg.SendingContext,org.omg.stub.java.rmi,org.w3c.dom,org.w3c.dom.bootstrap,org.w3c.dom.css,org.w3c.dom.events,org.w3c.dom.html,org.w3c.dom.ls,org.w3c.dom.ranges,org.w3c.dom.stylesheets,org.w3c.dom.traversal,org.w3c.dom.views,org.xml.sax,org.xml.sax.ext,org.xml.sax.helpers,javax.transaction;partial=true;mandatory:=partial,javax.transaction.xa;partial=true;mandatory:=partial"), // Log mavenBundle("org.ops4j.pax.logging", "pax-logging-api"), mavenBundle("org.ops4j.pax.logging", "pax-logging-service"), // Felix mvn url handler - do we need this? mavenBundle("org.ops4j.pax.url", "pax-url-mvn"), // this is how you set the default log level when using pax // logging (logProfile) systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level") .value("DEBUG"), // Bundles mavenBundle("org.eclipse.equinox", "cm"), mavenBundle("org.eclipse.osgi", "services"), mavenBundle("org.apache.aries.blueprint", "org.apache.aries.blueprint" ), mavenBundle("org.apache.aries.proxy", "org.apache.aries.proxy"), mavenBundle("org.apache.aries", "org.apache.aries.util" ), mavenBundle("org.ow2.asm", "asm-all" ), mavenBundle("org.apache.aries.samples.blueprint.helloworld", "org.apache.aries.samples.blueprint.helloworld.api"), mavenBundle("org.apache.aries.samples.blueprint.helloworld", "org.apache.aries.samples.blueprint.helloworld.server"), mavenBundle("org.apache.aries.samples.blueprint.helloworld", "org.apache.aries.samples.blueprint.helloworld.client"), /* For debugging, uncomment the next two lines */ /*vmOption ("-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=7777"), waitForFrameworkStartup(), */ /* For debugging, add these imports: import static org.ops4j.pax.exam.CoreOptions.waitForFrameworkStartup; import static org.ops4j.pax.exam.container.def.PaxRunnerOptions.vmOption; */ equinox().version("3.5.0") ); options = updateOptions(options); return options; } }
8,285
0
Create_ds/aries/samples/blueprint/helloworld/helloworld-server/src/main/java/org/apache/aries/samples/blueprint/helloworld
Create_ds/aries/samples/blueprint/helloworld/helloworld-server/src/main/java/org/apache/aries/samples/blueprint/helloworld/server/HelloWorldServiceImpl.java
/** * 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. */ package org.apache.aries.samples.blueprint.helloworld.server; import org.apache.aries.samples.blueprint.helloworld.api.*; public class HelloWorldServiceImpl implements HelloWorldService { public void hello() { System.out.println("======>>> A message from the server: Hello World!"); } public void startUp() { System.out.println("======>>> Starting HelloWorld Server"); } }
8,286
0
Create_ds/aries/samples/blueprint/idverifier/idverifier-server/src/main/java/org/apache/aries/samples/blueprint/idverifier
Create_ds/aries/samples/blueprint/idverifier/idverifier-server/src/main/java/org/apache/aries/samples/blueprint/idverifier/server/PersonIDVerifierSimpleImpl.java
/** * 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. */ /** * @author forrestxm * */ package org.apache.aries.samples.blueprint.idverifier.server; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.aries.samples.blueprint.idverifier.api.PersonIDVerifier; public class PersonIDVerifierSimpleImpl implements PersonIDVerifier { String areacode; String birthcode; String suffixcode; String id; String area_str; String birth_str; String gender_str; static final String GENDER_MAN = "man"; static final String GENDER_WOMAN = "woman"; /** * @return the area_str */ public String getArea_str() { return area_str; } /** * @param areaStr the area_str to set */ public void setArea_str(String areaStr) { area_str = areaStr; } /** * @return the birth_str */ public String getBirth_str() { return birth_str; } /** * @param birthStr the birth_str to set */ public void setBirth_str(String birthStr) { birth_str = birthStr; } /** * @return the gender_str */ public String getGender_str() { return gender_str; } /** * @param genderStr the gender_str to set */ public void setGender_str(String genderStr) { gender_str = genderStr; } /** * @return the areacode */ public String getAreacode() { return areacode; } /** * @param areacode the areacode to set */ public void setAreacode(String areacode) { this.areacode = areacode; } /** * @return the birthcode */ public String getBirthcode() { return birthcode; } /** * @param birthcode the birthcode to set */ public void setBirthcode(String birthcode) { this.birthcode = birthcode; } /** * @return the suffixcode */ public String getSuffixcode() { return suffixcode; } /** * @param suffixcode the suffixcode to set */ public void setSuffixcode(String suffixcode) { this.suffixcode = suffixcode; } /** * @return the id */ public String getId() { return id; } public void setId(String id) { this.id = id; } public String getArea() { return this.getArea_str(); } public String getBirthday() { return this.getBirth_str(); } public String getGender() { return this.getGender_str(); } public boolean verify() { boolean b = false; b = isValidID() && isValidArea() && isValidBirth() && isValidSuffix(); return b; } boolean isValidID(){ boolean b = false; if (this.id.length() == 18) { b = true; this.setAreacode(this.id.substring(0, 6)); this.setBirthcode(this.id.substring(6, 14)); this.setSuffixcode(this.id.substring(14)); } return b; } boolean isValidArea(){ boolean b = false; Pattern p = Pattern.compile("\\d{6}"); Matcher m = p.matcher(getAreacode()); if (m.matches()){ this.setArea_str(getAreacode()); b = true; } return b; } boolean isValidBirth() { String birthdate = toDateFormat(getBirthcode(), "-"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); try { this.setBirth_str(sdf.format(sdf.parse(birthdate))); return true; } catch (ParseException e) { e.printStackTrace(); } return false; } boolean isValidSuffix() { boolean b = false; Pattern p = Pattern.compile("\\d{3}[\\dX]"); Matcher m = p.matcher(getSuffixcode()); if(m.matches()){ b = true; setGender(getSuffixcode()); } return b; } String toDateFormat(String s, String delimiter) { StringBuffer sb = new StringBuffer(); sb.append(s.substring(0, 4)); sb.append(delimiter); sb.append(s.substring(4, 6)); sb.append(delimiter); sb.append(s.substring(6)); return sb.toString(); } private void setGender(String s){ int gender = Integer.parseInt(new Character(s.charAt(2)).toString()); int remain = gender % 2; if (remain == 0 ){ this.setGender_str(GENDER_WOMAN); } else { this.setGender_str(GENDER_MAN); } } }
8,287
0
Create_ds/aries/samples/blueprint/idverifier/idverifier-server/src/main/java/org/apache/aries/samples/blueprint/idverifier
Create_ds/aries/samples/blueprint/idverifier/idverifier-server/src/main/java/org/apache/aries/samples/blueprint/idverifier/server/SimpleVerifierRegistrationListener.java
/** * 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. */ package org.apache.aries.samples.blueprint.idverifier.server; import java.util.Iterator; import java.util.Map; import java.util.Set; /** * @author forrestxm * */ public class SimpleVerifierRegistrationListener { public void reg(PersonIDVerifierSimpleImpl svcobject, Map props){ //svcobject.doAfterReg(); System.out.println("********Registered bean "+svcobject.getClass().getName()+" as a service**********"); System.out.println("********Print service properties**************"); Set keyset = props.keySet(); Iterator iter = keyset.iterator(); while(iter.hasNext()){ Object keyobj = iter.next(); Object valueobj = props.get(keyobj); System.out.println(keyobj + "=" + valueobj); } } public void unreg(PersonIDVerifierSimpleImpl svcobject, Map props){ System.out.println("********Unregistering service bean "+svcobject.getClass().getName()+"**********"); } }
8,288
0
Create_ds/aries/samples/blueprint/idverifier/idverifier-server/src/main/java/org/apache/aries/samples/blueprint/idverifier
Create_ds/aries/samples/blueprint/idverifier/idverifier-server/src/main/java/org/apache/aries/samples/blueprint/idverifier/server/PersonIDVerifierComplexImpl.java
/** * 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. */ package org.apache.aries.samples.blueprint.idverifier.server; /** * @author forrestxm * */ import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Map; import java.util.Set; import org.apache.aries.samples.blueprint.idverifier.api.PersonIDVerifier; public class PersonIDVerifierComplexImpl extends PersonIDVerifierSimpleImpl implements PersonIDVerifier { private String datepattern; private Map<String, String> definedAreacode; private int[] coefficient; @Override public boolean verify() { boolean b = false; b = super.isValidID() && super.isValidSuffix() && this.isValidBirth() && this.isValidArea() && this.isValidCheckCode(); return b; } @Override boolean isValidBirth(){ String birthdate = toDateFormat(getBirthcode(), "-"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); try { Date birthday = sdf.parse(birthdate); SimpleDateFormat sdf_usecustom = new SimpleDateFormat(datepattern); this.setBirth_str(sdf_usecustom.format(birthday)); return true; } catch (ParseException e) { e.printStackTrace(); } return false; } @Override boolean isValidArea() { boolean b = false; if (super.isValidArea() && definedAreacode.containsValue(getAreacode())) { b = true; Set<String> keys = definedAreacode.keySet(); for (String key:keys){ String value = definedAreacode.get(key); if (value.equals(getAreacode())){ super.setArea_str(key); break; } } } return b; } public boolean isValidCheckCode() { boolean b = false; int[] codes = this.Char2Number(id.substring(0, 17)); String[] validcheckcodes = { "1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2" }; int sum = 0; for (int i = 0; i < 17; i++) { sum = sum + codes[i] * coefficient[i]; } int remain = sum % 11; String checkcode = id.substring(17); b = validcheckcodes[remain].equals(checkcode); return b; } private int[] Char2Number(String id) { int[] numbers = new int[17]; for (int i = 0; i < 17; i++) { numbers[i] = Integer.parseInt(new Character(id.charAt(i)).toString()); } return numbers; } /** * @return the datepattern */ public String getDatepattern() { return datepattern; } /** * @param datepattern * the datepattern to set */ public void setDatepattern(String datepattern) { this.datepattern = datepattern; } /** * @return the definedAreacode */ public Map<String, String> getDefinedAreacode() { return definedAreacode; } /** * @param definedAreacode * the definedAreacode to set */ public void setDefinedAreacode(Map<String, String> definedAreacode) { this.definedAreacode = definedAreacode; } /** * @return the coefficient */ public int[] getCoefficient() { return coefficient; } /** * @param coefficient * the coefficient to set */ public void setCoefficient(int[] coefficient) { this.coefficient = coefficient; } }
8,289
0
Create_ds/aries/samples/blueprint/idverifier/idverifier-server/src/main/java/org/apache/aries/samples/blueprint/idverifier
Create_ds/aries/samples/blueprint/idverifier/idverifier-server/src/main/java/org/apache/aries/samples/blueprint/idverifier/server/ComplexVerifierRegistrationListener.java
/** * 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. */ package org.apache.aries.samples.blueprint.idverifier.server; import java.util.Iterator; import java.util.Map; import java.util.Set; /** * @author forrestxm * */ public class ComplexVerifierRegistrationListener { public void reg(PersonIDVerifierComplexImpl svcobject, Map props){ //svcobject.doAfterReg(); System.out.println("********Registered bean "+svcobject.getClass().getName()+" as a service**********"); System.out.println("********Print service properties**************"); Set keyset = props.keySet(); Iterator iter = keyset.iterator(); while(iter.hasNext()){ Object keyobj = iter.next(); Object valueobj = props.get(keyobj); System.out.println(keyobj + "=" + valueobj); } } public void unreg(PersonIDVerifierComplexImpl svcobject, Map props){ System.out.println("********Unregistering service bean "+svcobject.getClass().getName()+"**********"); } }
8,290
0
Create_ds/aries/samples/blueprint/idverifier/idverifier-api/src/main/java/org/apache/aries/samples/blueprint/idverifier
Create_ds/aries/samples/blueprint/idverifier/idverifier-api/src/main/java/org/apache/aries/samples/blueprint/idverifier/api/CreditRecordOperation.java
/** * 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. */ package org.apache.aries.samples.blueprint.idverifier.api; import java.util.Set; /** * @author forrestxm * */ public interface CreditRecordOperation { public Set<String> query(String personid); public boolean add(String arecord); public boolean remove(String personid, String recordNO); }
8,291
0
Create_ds/aries/samples/blueprint/idverifier/idverifier-api/src/main/java/org/apache/aries/samples/blueprint/idverifier
Create_ds/aries/samples/blueprint/idverifier/idverifier-api/src/main/java/org/apache/aries/samples/blueprint/idverifier/api/PersonIDVerifier.java
/** * 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. */ package org.apache.aries.samples.blueprint.idverifier.api; /** * @author forrestxm * */ public interface PersonIDVerifier { public void setId(String id); public boolean verify(); public String getArea(); public String getBirthday(); public String getGender(); }
8,292
0
Create_ds/aries/samples/blueprint/idverifier/idverifier-client/src/main/java/org/apache/aries/samples/blueprint/idverifier
Create_ds/aries/samples/blueprint/idverifier/idverifier-client/src/main/java/org/apache/aries/samples/blueprint/idverifier/client/CreditQueryRegistrationListener.java
/** * 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. */ package org.apache.aries.samples.blueprint.idverifier.client; import java.util.Iterator; import java.util.Map; import java.util.Set; /** * @author forrestxm * */ public class CreditQueryRegistrationListener { public void reg(CreditRecordOperationImpl svcobject, Map props){ //svcobject.doAfterReg(); System.out.println("********Registered bean "+svcobject.getClass().getName()+" as a service**********"); System.out.println("********Start of Printing service properties**************"); Set keyset = props.keySet(); Iterator iter = keyset.iterator(); while(iter.hasNext()){ Object keyobj = iter.next(); Object valueobj = props.get(keyobj); System.out.println(keyobj + "=" + valueobj); } System.out.println("********End of Printing service properties**************"); } public void unreg(CreditRecordOperationImpl svcobject, Map props){ System.out.println("********Unregistering service bean "+svcobject.getClass().getName()+"**********"); } }
8,293
0
Create_ds/aries/samples/blueprint/idverifier/idverifier-client/src/main/java/org/apache/aries/samples/blueprint/idverifier
Create_ds/aries/samples/blueprint/idverifier/idverifier-client/src/main/java/org/apache/aries/samples/blueprint/idverifier/client/VerifierServiceReferenceListener.java
/** * 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. */ package org.apache.aries.samples.blueprint.idverifier.client; import java.util.Map; import java.util.Set; import org.apache.aries.samples.blueprint.idverifier.api.PersonIDVerifier; import org.apache.aries.samples.blueprint.idverifier.server.PersonIDVerifierSimpleImpl; import org.apache.aries.samples.blueprint.idverifier.server.PersonIDVerifierComplexImpl; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; /** * @author forrestxm * */ public class VerifierServiceReferenceListener { public void bind(ServiceReference svcref) { System.out.println("**********" + this.getClass().getSimpleName() + " bind method via ServiceReference!*********"); // Get specific PersonIDVerifier implementation class Bundle svcproviderbundle = svcref.getBundle(); BundleContext svcproviderbundlectx = svcproviderbundle.getBundleContext(); Object svcbean = svcproviderbundlectx.getService(svcref); String svcbeanname = null; if (svcbean instanceof PersonIDVerifierSimpleImpl) { svcbeanname = ((PersonIDVerifierSimpleImpl)svcbean).getClass().getCanonicalName(); } else if (svcbean instanceof PersonIDVerifierComplexImpl){ svcbeanname = ((PersonIDVerifierComplexImpl)svcbean).getClass().getCanonicalName(); } System.out.println("Bundle " + svcproviderbundle.getSymbolicName() + " provides this service implemented by " + svcbeanname); // Print service users information System.out.println("**********Start of printing service's users**********"); Bundle[] usingbundles = svcref.getUsingBundles(); if (usingbundles != null) { int len = usingbundles.length; System.out.println("The service has " + len + " users!"); System.out.println("They are:"); for (int i = 0; i < len; i++) { System.out.println(usingbundles[i].getSymbolicName()); } System.out.println("All users are printed out!"); } System.out.println("**********End of printing service's users**********"); } public void bind(PersonIDVerifier svc) { System.out.println("**********This is service object proxy bind method!***********"); } public void unbind(ServiceReference svcref) { System.out.println("**********" + this.getClass().getSimpleName() + " unbind method via ServiceReference!*********"); // Get specific PersonIDVerifier implementation class Bundle svcproviderbundle = svcref.getBundle(); BundleContext svcproviderbundlectx = svcproviderbundle.getBundleContext(); Object svcbean = svcproviderbundlectx.getService(svcref); String svcbeanname = null; if (svcbean instanceof PersonIDVerifierSimpleImpl) { svcbeanname = ((PersonIDVerifierSimpleImpl)svcbean).getClass().getCanonicalName(); } else if (svcbean instanceof PersonIDVerifierComplexImpl){ svcbeanname = ((PersonIDVerifierComplexImpl)svcbean).getClass().getCanonicalName(); } System.out.println("Bundle " + svcproviderbundle.getSymbolicName() + " provides this service implemented by " + svcbeanname); // Print service users information System.out.println("**********Start of printing service's users**********"); Bundle[] usingbundles = svcref.getUsingBundles(); if (usingbundles != null) { int len = usingbundles.length; System.out.println("The service has " + len + " users!"); System.out.println("They are:"); for (int i = 0; i < len; i++) { System.out.println(usingbundles[i].getSymbolicName()); } System.out.println("All users are printed out!"); } System.out.println("**********End of printing service's users**********"); } public void unbind(PersonIDVerifier svc, Map props) { System.out.println("**********This is service object proxy unbind method!***********"); System.out.println("**********Start of printing service properties***********"); System.out.println("Service properties are:"); Set keys = props.keySet(); for (Object obj : keys) { Object valueobj = props.get(obj); System.out.println(obj + "=" + valueobj); } System.out.println("**********End of printing service properties***********"); } }
8,294
0
Create_ds/aries/samples/blueprint/idverifier/idverifier-client/src/main/java/org/apache/aries/samples/blueprint/idverifier
Create_ds/aries/samples/blueprint/idverifier/idverifier-client/src/main/java/org/apache/aries/samples/blueprint/idverifier/client/PersonalInfo.java
/** * 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. */ package org.apache.aries.samples.blueprint.idverifier.client; /** * @author forrestxm * */ public class PersonalInfo { private String personid; private String area; private String birthday; private String gender; public PersonalInfo(String personid, String area, String birth, String suffix){ this.personid = personid; this.area = area; this.birthday = birth; this.gender = suffix; } /** * @return the personid */ public String getPersonid() { return personid; } /** * @param personid the personid to set */ public void setPersonid(String personid) { this.personid = personid; } /** * @return the area_code */ public String getArea() { return area; } /** * @param areaCode the area_code to set */ public void setArea(String areaCode) { area = areaCode; } /** * @return the birth_code */ public String getBirthday() { return birthday; } /** * @param birthCode the birth_code to set */ public void setBirthday(String birthCode) { birthday = birthCode; } /** * @return the suffix_code */ public String getGender() { return gender; } /** * @param suffixCode the suffix_code to set */ public void setGender(String suffixCode) { gender = suffixCode; } @Override public String toString(){ System.out.println("********Start of Printing Personal Info**********"); System.out.println("Area: " + this.getArea()); System.out.println("Birthday: " + this.getBirthday()); System.out.println("Gender: "+ this.getGender()); System.out.println("********End of Printing Personal Info************"); String delimiter = ","; StringBuffer sb = new StringBuffer(); sb.append("PersonInfo ["); sb.append("personid="+this.getPersonid()+delimiter); sb.append("area=" + this.getArea()+ delimiter); sb.append("birthday=" + this.getBirthday() + delimiter); sb.append("gender="+ this.getGender()); sb.append("]"); return sb.toString(); } }
8,295
0
Create_ds/aries/samples/blueprint/idverifier/idverifier-client/src/main/java/org/apache/aries/samples/blueprint/idverifier
Create_ds/aries/samples/blueprint/idverifier/idverifier-client/src/main/java/org/apache/aries/samples/blueprint/idverifier/client/PersonCreditRecords.java
/** * 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. */ package org.apache.aries.samples.blueprint.idverifier.client; import java.util.HashSet; import java.util.Set; /** * @author forrestxm * */ public class PersonCreditRecords { private String personid; private Set<String> recordNOs; private Set<CreditRecord> records; public PersonCreditRecords(String personid){ this.personid = personid; this.recordNOs = new HashSet<String>(); this.records = new HashSet<CreditRecord>(); } public boolean add(CreditRecord arecord){ boolean b = false; if (arecord.getPersonid().equals(personid)){ if (!recordNOs.contains(arecord.getRecordNO())){ this.recordNOs.add(arecord.getRecordNO()); b = this.records.add(arecord); } } return b; } public boolean remove(CreditRecord arecord){ boolean b = false; if (arecord.getPersonid().equals(this.personid)){ if (recordNOs.contains(arecord.getRecordNO())){ this.recordNOs.remove(arecord.getRecordNO()); b = this.records.remove(getARecord(arecord.getRecordNO())); } } return b; } private CreditRecord getARecord(String recordNO){ CreditRecord target = null; for (CreditRecord arecord : getRecords()){ if (arecord.getRecordNO().equals(recordNO)){ target = arecord; break; } } return target; } public boolean isEmpty(){ boolean b = false; b = recordNOs.isEmpty() && records.isEmpty(); return b; } /** * @return the personid */ public String getPersonid() { return personid; } /** * @return the recordNOs */ public Set<String> getRecordNOs() { return recordNOs; } /** * @return the records */ public Set<CreditRecord> getRecords() { return records; } }
8,296
0
Create_ds/aries/samples/blueprint/idverifier/idverifier-client/src/main/java/org/apache/aries/samples/blueprint/idverifier
Create_ds/aries/samples/blueprint/idverifier/idverifier-client/src/main/java/org/apache/aries/samples/blueprint/idverifier/client/PersonBankBean.java
/** * 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. */ /** * @author forrestxm * */ package org.apache.aries.samples.blueprint.idverifier.client; import java.util.Set; import org.apache.aries.samples.blueprint.idverifier.api.*; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceRegistration; import org.osgi.framework.ServiceReference; import org.osgi.service.blueprint.container.BlueprintContainer; public class PersonBankBean { private PersonalInfo personinfo; private BankInfo bankinfo; private String bankinfobeanid; private CreditRecordOperation cro; private BlueprintContainer bpcontainer; private BundleContext bpbundlecontext; private ServiceRegistration svcreg4cro; public PersonBankBean(PersonalInfo info){ this.personinfo = info; } /** * @return the bankinfo */ public BankInfo getBankinfo() { return bankinfo; } /** * @param bankinfo the bankinfo to set */ public void setBankinfo(BankInfo bankinfo) { this.bankinfo = bankinfo; } /** * @return the bankinfobeanid */ public String getBankinfobeanid() { return bankinfobeanid; } /** * @param bankinfobeanid the bankinfobeanid to set */ public void setBankinfobeanid(String bankinfobeanid) { this.bankinfobeanid = bankinfobeanid; } /** * @return the bpcontainer */ public BlueprintContainer getBpcontainer() { return bpcontainer; } /** * @param bpcontainer the bpcontainer to set */ public void setBpcontainer(BlueprintContainer bpcontainer) { this.bpcontainer = bpcontainer; } /** * @return the cro */ public CreditRecordOperation getCro() { return cro; } /** * @param cro the cro to set */ public void setCro(CreditRecordOperation cro) { this.cro = cro; } /** * @return the svcreg4cro */ public ServiceRegistration getSvcreg4cro() { return svcreg4cro; } /** * @param svcreg4cro the svcreg4cro to set */ public void setSvcreg4cro(ServiceRegistration svcreg4cro) { this.svcreg4cro = svcreg4cro; } /** * @return the bpbundlecontext */ public BundleContext getBpbundlecontext() { return bpbundlecontext; } /** * @param bpbundlecontext the bpbundlecontext to set */ public void setBpbundlecontext(BundleContext bpbundlecontext) { this.bpbundlecontext = bpbundlecontext; } public void startUp(){ System.out.println("*******Start of Printing Personal Bank/Credit Information************"); this.personinfo.toString(); // get component instance of BankInfo at runtime this.setBankinfo((BankInfo)bpcontainer.getComponentInstance(this.getBankinfobeanid())); this.bankinfo.toString(); // get inlined service object from service registration object ServiceReference svcref = this.svcreg4cro.getReference(); this.setCro((CreditRecordOperation)this.bpbundlecontext.getService(svcref)); Set<String> allcreditrecords = cro.query(this.personinfo.getPersonid()); if (allcreditrecords.isEmpty()){ System.out.println("No credit records for id " + this.personinfo.getPersonid()); } else { System.out.println("The credit records for id " + this.personinfo.getPersonid() + " are as follows:"); for (String arecord : allcreditrecords){ System.out.println(arecord); } } System.out.println("*******End of Printing Personal Bank/Credit Information**************"); } }
8,297
0
Create_ds/aries/samples/blueprint/idverifier/idverifier-client/src/main/java/org/apache/aries/samples/blueprint/idverifier
Create_ds/aries/samples/blueprint/idverifier/idverifier-client/src/main/java/org/apache/aries/samples/blueprint/idverifier/client/IDConverter.java
/** * 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. */ package org.apache.aries.samples.blueprint.idverifier.client; import org.apache.aries.samples.blueprint.idverifier.api.*; import org.osgi.service.blueprint.container.Converter; import org.osgi.service.blueprint.container.ReifiedType; /** * @author forrestxm * */ public class IDConverter implements Converter { private PersonIDVerifier verifier; private String personid; /* * (non-Javadoc) * * @see * org.osgi.service.blueprint.container.Converter#canConvert(java.lang.Object * , org.osgi.service.blueprint.container.ReifiedType) */ // @Override public boolean canConvert(Object sourceObject, ReifiedType targetType) { boolean canorcannot = false; String id = null; if (targetType.getRawClass() == PersonalInfo.class) { if (sourceObject instanceof RandomIDChoice){ id = ((RandomIDChoice)sourceObject).getRandomID(); this.setPersonid(id); } //String personid = sourceObject.toString(); if (this.getPersonid() == null || this.getPersonid().length() != 18) return false; verifier.setId(this.getPersonid()); canorcannot = this.verifier.verify(); } return canorcannot; } /* * (non-Javadoc) * * @see * org.osgi.service.blueprint.container.Converter#convert(java.lang.Object, * org.osgi.service.blueprint.container.ReifiedType) */ // @Override public Object convert(Object sourceObject, ReifiedType targetType) throws Exception { return new PersonalInfo(this.getPersonid(), verifier.getArea(), verifier.getBirthday(), verifier.getGender()); } /** * @return the verifier */ public PersonIDVerifier getVerifier() { return verifier; } /** * @param verifier * the verifier to set */ public void setVerifier(PersonIDVerifier verifier) { this.verifier = verifier; } /** * @return the personid */ public String getPersonid() { return personid; } /** * @param personid the personid to set */ public void setPersonid(String personid) { this.personid = personid; } }
8,298
0
Create_ds/aries/samples/blueprint/idverifier/idverifier-client/src/main/java/org/apache/aries/samples/blueprint/idverifier
Create_ds/aries/samples/blueprint/idverifier/idverifier-client/src/main/java/org/apache/aries/samples/blueprint/idverifier/client/CreditRecordOperationImpl.java
/** * 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. */ package org.apache.aries.samples.blueprint.idverifier.client; import java.util.HashSet; import java.util.Set; import org.apache.aries.samples.blueprint.idverifier.api.CreditRecordOperation; /** * @author forrestxm * */ public class CreditRecordOperationImpl implements CreditRecordOperation { private CreditRecordStore recordstore; public CreditRecordOperationImpl(CreditRecordStore recordstore) { super(); this.recordstore = recordstore; } /* * (non-Javadoc) * * @see * org.apache.aries.blueprint.sample.complex.client.CreditRecordOperation * #add(java.lang.String) */ public boolean add(String arecord) { boolean b = true; CreditRecord record = new CreditRecord(arecord); b = recordstore.add(record); return b; } /* * (non-Javadoc) * * @see * org.apache.aries.blueprint.sample.complex.client.CreditRecordOperation * #query(java.lang.String) */ public Set<String> query(String personid) { Set<String> results = new HashSet<String>(); if (recordstore.getPersonidindex().contains(personid)){ Set<CreditRecord> allrecords = recordstore.getAPersonRecords(personid).getRecords(); for (CreditRecord arecord : allrecords){ results.add(arecord.toString()); } } return results; } /* * (non-Javadoc) * * @see * org.apache.aries.blueprint.sample.complex.client.CreditRecordOperation * #remove(java.lang.String) */ public boolean remove(String personid, String recordNO) { boolean b = false; Set<String> persons = recordstore.getPersonidindex(); if (persons.contains(personid)) { CreditRecord targetproxy = new CreditRecord(); targetproxy.setPersonid(personid); targetproxy.setRecordNO(recordNO); b = recordstore.getAPersonRecords(personid).remove(targetproxy); } return b; } }
8,299