From 50c401383bb0f08fd51dcf2fa7dcc2a661e867f5 Mon Sep 17 00:00:00 2001 From: domgiles Date: Mon, 3 Aug 2020 16:07:30 +0100 Subject: [PATCH] Benchmark transactions --- README.md | 15 +- .../benchmarks/JSON/CreateCollection.java | 211 ++++++++ .../benchmarks/JSON/GetPassengerDetails.java | 96 ++++ .../benchmarks/JSON/InsertNewPassenger.java | 141 +++++ .../JSON/RemovePassengerDetails.java | 97 ++++ .../JSON/UpdatePassengerDetails.java | 175 +++++++ .../PeriodToPeriodComparison.java | 123 +++++ .../ProductMonthlySalesRollupCube.java | 75 +++ .../ProductSalesRollupCube.java | 74 +++ .../SalesByCountryForGivenYear.java | 82 +++ .../SalesByQuarterCountry.java | 84 +++ .../dsstransactions/SalesByWeekCountry.java | 84 +++ .../dsstransactions/SalesCubeByMonth.java | 74 +++ .../dsstransactions/SalesCubeByWeek.java | 75 +++ .../dsstransactions/SalesHistory.java | 123 +++++ .../dsstransactions/SalesMovingAverage.java | 74 +++ .../dsstransactions/SalesRollupByMonth.java | 78 +++ .../dsstransactions/SalesRollupByWeek.java | 79 +++ .../dsstransactions/SimpleLookUp.java | 54 ++ .../TopSalesWithinQuarter.java | 87 +++ .../dsstransactions/TopSalesWithinWeek.java | 88 ++++ .../dsstransactions/WeekToWeekComparison.java | 125 +++++ .../BrowseAndUpdateOrders.java | 75 +++ .../plsqltransactions/BrowseProducts.java | 76 +++ .../plsqltransactions/NewCustomerProcess.java | 152 ++++++ .../NewCustomerProcessV2.java | 168 ++++++ .../plsqltransactions/NewOrderProcess.java | 79 +++ .../plsqltransactions/OrderEntryProcess.java | 188 +++++++ .../OrdersByCountyQuery.java | 64 +++ .../plsqltransactions/ProcessOrders.java | 73 +++ .../SalesRepsOrdersQuery.java | 64 +++ .../UpdateCustomerDetailsV2.java | 157 ++++++ .../WarehouseActivityQuery.java | 65 +++ .../WarehouseOrdersQuery.java | 63 +++ .../storedprocedures/StoredProcedure1.java | 66 +++ .../storedprocedures/StoredProcedure2.java | 66 +++ .../storedprocedures/StoredProcedure3.java | 61 +++ .../storedprocedures/StoredProcedure4.java | 66 +++ .../storedprocedures/StoredProcedure5.java | 66 +++ .../storedprocedures/StoredProcedure6.java | 63 +++ .../swingbench/stresstest/StressTest.java | 76 +++ .../stresstest/StressTestDelete.java | 52 ++ .../stresstest/StressTestInsert.java | 58 ++ .../stresstest/StressTestSelect.java | 53 ++ .../stresstest/StressTestUpdate.java | 52 ++ .../transactions/BrowseAndUpdateOrders.java | 123 +++++ .../transactions/BrowseProducts.java | 73 +++ .../swingbench/transactions/JobTest.java | 7 + .../transactions/NewCustomerProcess.java | 242 +++++++++ .../transactions/NewOrderProcess.java | 268 ++++++++++ .../transactions/OrderEntryProcess.java | 494 ++++++++++++++++++ .../transactions/ProcessOrders.java | 114 ++++ .../transactions/ProductDetails.java | 34 ++ .../transactions/SalesRepsOrdersQuery.java | 83 +++ .../transactions/UpdateCustomerDetails.java | 176 +++++++ .../transactions/WarehouseActivityQuery.java | 100 ++++ .../transactions/WarehouseOrdersQuery.java | 76 +++ .../CallingCircleLineIdentifier.java | 55 ++ .../CallingCircle/CallingCircleProcess.java | 205 ++++++++ .../CallingCircle/CallingLineIdentifier.java | 79 +++ .../mike/CallingCircle/CustomerAccount.java | 91 ++++ .../CustomerCallingLineIdentifier.java | 97 ++++ .../NewCallingCircleProcess.java | 298 +++++++++++ .../CallingCircle/RetrieveHistoryProcess.java | 204 ++++++++ .../UpdateCallingCircleProcess.java | 280 ++++++++++ 65 files changed, 7114 insertions(+), 2 deletions(-) create mode 100644 src/com/dom/benchmarking/swingbench/benchmarks/JSON/CreateCollection.java create mode 100644 src/com/dom/benchmarking/swingbench/benchmarks/JSON/GetPassengerDetails.java create mode 100644 src/com/dom/benchmarking/swingbench/benchmarks/JSON/InsertNewPassenger.java create mode 100644 src/com/dom/benchmarking/swingbench/benchmarks/JSON/RemovePassengerDetails.java create mode 100644 src/com/dom/benchmarking/swingbench/benchmarks/JSON/UpdatePassengerDetails.java create mode 100644 src/com/dom/benchmarking/swingbench/dsstransactions/PeriodToPeriodComparison.java create mode 100644 src/com/dom/benchmarking/swingbench/dsstransactions/ProductMonthlySalesRollupCube.java create mode 100644 src/com/dom/benchmarking/swingbench/dsstransactions/ProductSalesRollupCube.java create mode 100644 src/com/dom/benchmarking/swingbench/dsstransactions/SalesByCountryForGivenYear.java create mode 100644 src/com/dom/benchmarking/swingbench/dsstransactions/SalesByQuarterCountry.java create mode 100644 src/com/dom/benchmarking/swingbench/dsstransactions/SalesByWeekCountry.java create mode 100644 src/com/dom/benchmarking/swingbench/dsstransactions/SalesCubeByMonth.java create mode 100644 src/com/dom/benchmarking/swingbench/dsstransactions/SalesCubeByWeek.java create mode 100644 src/com/dom/benchmarking/swingbench/dsstransactions/SalesHistory.java create mode 100644 src/com/dom/benchmarking/swingbench/dsstransactions/SalesMovingAverage.java create mode 100644 src/com/dom/benchmarking/swingbench/dsstransactions/SalesRollupByMonth.java create mode 100644 src/com/dom/benchmarking/swingbench/dsstransactions/SalesRollupByWeek.java create mode 100644 src/com/dom/benchmarking/swingbench/dsstransactions/SimpleLookUp.java create mode 100644 src/com/dom/benchmarking/swingbench/dsstransactions/TopSalesWithinQuarter.java create mode 100644 src/com/dom/benchmarking/swingbench/dsstransactions/TopSalesWithinWeek.java create mode 100644 src/com/dom/benchmarking/swingbench/dsstransactions/WeekToWeekComparison.java create mode 100644 src/com/dom/benchmarking/swingbench/plsqltransactions/BrowseAndUpdateOrders.java create mode 100644 src/com/dom/benchmarking/swingbench/plsqltransactions/BrowseProducts.java create mode 100644 src/com/dom/benchmarking/swingbench/plsqltransactions/NewCustomerProcess.java create mode 100644 src/com/dom/benchmarking/swingbench/plsqltransactions/NewCustomerProcessV2.java create mode 100644 src/com/dom/benchmarking/swingbench/plsqltransactions/NewOrderProcess.java create mode 100644 src/com/dom/benchmarking/swingbench/plsqltransactions/OrderEntryProcess.java create mode 100644 src/com/dom/benchmarking/swingbench/plsqltransactions/OrdersByCountyQuery.java create mode 100644 src/com/dom/benchmarking/swingbench/plsqltransactions/ProcessOrders.java create mode 100644 src/com/dom/benchmarking/swingbench/plsqltransactions/SalesRepsOrdersQuery.java create mode 100644 src/com/dom/benchmarking/swingbench/plsqltransactions/UpdateCustomerDetailsV2.java create mode 100644 src/com/dom/benchmarking/swingbench/plsqltransactions/WarehouseActivityQuery.java create mode 100644 src/com/dom/benchmarking/swingbench/plsqltransactions/WarehouseOrdersQuery.java create mode 100644 src/com/dom/benchmarking/swingbench/storedprocedures/StoredProcedure1.java create mode 100644 src/com/dom/benchmarking/swingbench/storedprocedures/StoredProcedure2.java create mode 100644 src/com/dom/benchmarking/swingbench/storedprocedures/StoredProcedure3.java create mode 100644 src/com/dom/benchmarking/swingbench/storedprocedures/StoredProcedure4.java create mode 100644 src/com/dom/benchmarking/swingbench/storedprocedures/StoredProcedure5.java create mode 100644 src/com/dom/benchmarking/swingbench/storedprocedures/StoredProcedure6.java create mode 100644 src/com/dom/benchmarking/swingbench/stresstest/StressTest.java create mode 100644 src/com/dom/benchmarking/swingbench/stresstest/StressTestDelete.java create mode 100644 src/com/dom/benchmarking/swingbench/stresstest/StressTestInsert.java create mode 100644 src/com/dom/benchmarking/swingbench/stresstest/StressTestSelect.java create mode 100644 src/com/dom/benchmarking/swingbench/stresstest/StressTestUpdate.java create mode 100644 src/com/dom/benchmarking/swingbench/transactions/BrowseAndUpdateOrders.java create mode 100644 src/com/dom/benchmarking/swingbench/transactions/BrowseProducts.java create mode 100644 src/com/dom/benchmarking/swingbench/transactions/JobTest.java create mode 100644 src/com/dom/benchmarking/swingbench/transactions/NewCustomerProcess.java create mode 100644 src/com/dom/benchmarking/swingbench/transactions/NewOrderProcess.java create mode 100644 src/com/dom/benchmarking/swingbench/transactions/OrderEntryProcess.java create mode 100644 src/com/dom/benchmarking/swingbench/transactions/ProcessOrders.java create mode 100644 src/com/dom/benchmarking/swingbench/transactions/ProductDetails.java create mode 100644 src/com/dom/benchmarking/swingbench/transactions/SalesRepsOrdersQuery.java create mode 100644 src/com/dom/benchmarking/swingbench/transactions/UpdateCustomerDetails.java create mode 100644 src/com/dom/benchmarking/swingbench/transactions/WarehouseActivityQuery.java create mode 100644 src/com/dom/benchmarking/swingbench/transactions/WarehouseOrdersQuery.java create mode 100644 src/com/mike/CallingCircle/CallingCircleLineIdentifier.java create mode 100644 src/com/mike/CallingCircle/CallingCircleProcess.java create mode 100644 src/com/mike/CallingCircle/CallingLineIdentifier.java create mode 100644 src/com/mike/CallingCircle/CustomerAccount.java create mode 100644 src/com/mike/CallingCircle/CustomerCallingLineIdentifier.java create mode 100644 src/com/mike/CallingCircle/NewCallingCircleProcess.java create mode 100644 src/com/mike/CallingCircle/RetrieveHistoryProcess.java create mode 100644 src/com/mike/CallingCircle/UpdateCallingCircleProcess.java diff --git a/README.md b/README.md index 9333f73..cea0100 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,15 @@ # Swingbench Public Repository -This repoistory serves as a public location to share the public aspects of swingbench. It will act as a location to download the latest version of the code and a place to raise issues. +This repository serves as a public location to share the public aspects of swingbench. It will act as a location to download the latest version of the code and a place to raise issues. + +If you encounter a problem please create a new issue. in the menu above describing as much of the problem as possible. Important information includes + +* Swingbench version number +* Platform (Mac, Windows, Linux) +* JDK Version (including whether it's OpenJDK or Oracle JDK) +* what you were trying to do +* debug information (collected with the command line option "-debug") +* Screen shots only where necessary, Please don't screen shot an error just copy the text into the issue. + +I will also host the latest build of the code at this location as well as the source code for the transactions used in the benchmarks. + -Updates incoming. diff --git a/src/com/dom/benchmarking/swingbench/benchmarks/JSON/CreateCollection.java b/src/com/dom/benchmarking/swingbench/benchmarks/JSON/CreateCollection.java new file mode 100644 index 0000000..eaf927f --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/benchmarks/JSON/CreateCollection.java @@ -0,0 +1,211 @@ +package com.dom.benchmarking.swingbench.benchmarks.JSON; + +import com.dom.util.OracleUtilities; + +import java.sql.Connection; +import java.sql.Statement; + +import java.util.HashMap; +import java.util.Map; +import java.util.logging.LogManager; + +import oracle.soda.OracleCollection; +import oracle.soda.OracleDatabase; +import oracle.soda.OracleDocument; +import oracle.soda.rdbms.OracleRDBMSClient; +import oracle.soda.rdbms.OracleRDBMSMetadataBuilder; + +import org.apache.commons.cli.BasicParser; +import org.apache.commons.cli.CommandLine; +import org.apache.commons.cli.CommandLineParser; +import org.apache.commons.cli.HelpFormatter; +import org.apache.commons.cli.Option; +import org.apache.commons.cli.OptionGroup; +import org.apache.commons.cli.Options; +import org.apache.commons.cli.ParseException; + + +public class CreateCollection { + + public enum CommandLineOptions { + USERNAME, + PASSWORD, + CONNECTSTRING + } + + public enum Operation { + DROP_COLLECTION, + CREATE_COLLECTION, + } + + public enum JSONParsing { + LAX, + STRICT, + STANDARD + } + + public enum JSONStorage { + VARCHAR, + BLOB, + CLOB + } + + public enum JSONCompression { + NONE, + LOW, + MEDIUM, + HIGH + } + + public enum JSONVersioning { + NONE, + UUID, + TIMESTAMP, + MD5, + SHA256, + SEQUENTIAL + } + + Operation operation = Operation.CREATE_COLLECTION; + JSONParsing parsing = JSONParsing.STANDARD; + JSONCompression compression = JSONCompression.NONE; + JSONStorage storage = JSONStorage.BLOB.VARCHAR; + JSONVersioning versioning = JSONVersioning.SHA256; + + public CreateCollection(String[] args) throws Exception { + super(); + Map commandLineOptions = parseCommandLine(args); + Connection connection = + OracleUtilities.getConnection(commandLineOptions.get(CommandLineOptions.USERNAME), commandLineOptions.get(CommandLineOptions.PASSWORD), "jdbc:oracle:thin:@" + + commandLineOptions.get(CommandLineOptions.CONNECTSTRING)); + System.out.println("Got Connection"); + OracleRDBMSClient client = new OracleRDBMSClient(); + OracleDatabase database = client.getDatabase(connection); + if (operation == Operation.CREATE_COLLECTION) { + Statement s = connection.createStatement(); + s.execute("create sequence PASSENGER_SEQ"); + OracleRDBMSMetadataBuilder metabuilder = client.createMetadataBuilder(); + metabuilder.keyColumnType("NUMBER"); + metabuilder.keyColumnAssignmentMethod("SEQUENCE"); + metabuilder.keyColumnSequenceName("PASSENGER_SEQ"); + metabuilder.contentColumnName("PASSENGER_INFO"); + metabuilder.contentColumnType(storage.toString()); + metabuilder.contentColumnCompress(compression.toString()); + metabuilder.contentColumnValidation(parsing.toString()); + OracleDocument meta = metabuilder.build(); + //Create a collection if it doesn't exist + OracleCollection collection = database.admin().createCollection("PASSENGERCOLLECTION", meta); + System.out.println("Collection Created"); + } else if (operation == Operation.DROP_COLLECTION) { + OracleCollection c = database.openCollection("PASSENGERCOLLECTION"); + c.admin().drop(); + System.out.println("Collection Dropped"); + Statement s = connection.createStatement(); + s.execute("drop sequence PASSENGER_SEQ"); + } + } + + public static void main(String args[]) { + try { + CreateCollection cc = new CreateCollection(args); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public Map parseCommandLine(String[] args) throws Exception { + Options options = getOptions(); + CommandLineParser clp = new BasicParser(); + Map commandLineParameters = new HashMap(); + CommandLine cl = null; + try { + cl = clp.parse(options, args); + + if (cl.hasOption("h")) { + HelpFormatter formatter = new HelpFormatter(); + formatter.printHelp("parameters:", options); + System.exit(0); + } else { + + + if (cl.hasOption("u")) { + commandLineParameters.put(CommandLineOptions.USERNAME, cl.getOptionValue("u")); + } + if (cl.hasOption("p")) { + commandLineParameters.put(CommandLineOptions.PASSWORD, cl.getOptionValue("p")); + } + if (cl.hasOption("cs")) { + commandLineParameters.put(CommandLineOptions.CONNECTSTRING, cl.getOptionValue("cs")); + } + if (cl.hasOption("parsing")) { + parsing = JSONParsing.valueOf(cl.getOptionValue("parsing")); + } + if (cl.hasOption("compression")) { + compression = JSONCompression.valueOf(cl.getOptionValue("compression")); + } + if (cl.hasOption("storage")) { + storage = JSONStorage.valueOf(cl.getOptionValue("storage")); + } + if (cl.hasOption("drop")) { + operation = Operation.DROP_COLLECTION; + } + if (cl.hasOption("create")) { + operation = Operation.CREATE_COLLECTION; + } + if (cl.hasOption("debug")) { + System.setProperty("java.util.logging.config.class", "com.dom.util.logging.LoggerConfig"); + LogManager.getLogManager().readConfiguration(); + } + } + return commandLineParameters; + } catch (ParseException e) { + System.out.println("ERROR : " + e.getMessage()); + HelpFormatter formatter = new HelpFormatter(); + formatter.printHelp("parameters:", options); + throw new RuntimeException(e.getMessage()); + } + } + + + public static Options getOptions() { + Options options = new Options(); + Option option5 = new Option("u", "username for connections (requires access to V$ tables i.e. system)"); + option5.setArgs(1); + option5.setRequired(true); + Option option6 = new Option("p", "password of user"); + option6.setArgs(1); + option6.setRequired(true); + Option option7 = new Option("cs", "connect string of database you wish to monitor. i.e. ///"); + option7.setArgs(1); + option7.setRequired(true); + OptionGroup og1 = new OptionGroup(); + Option option8 = new Option("drop", "drop collection"); + Option option9 = new Option("create", "create collection"); + og1.addOption(option8); + og1.addOption(option9); + og1.setRequired(true); + Option option10 = new Option("parsing", "valid values are STANDARD|LAX|STRICT"); + option10.setArgs(1); + option10.setRequired(false); + Option option11 = new Option("compression", "valid values are NONE|LOW|MEDIUM|HIGH"); + option11.setArgs(1); + option11.setRequired(false); + Option option12 = new Option("storage", "valid values are VARCHAR|BLOB|CLOB"); + option12.setArgs(1); + option12.setRequired(false); + + Option option100 = new Option("h", "print this message"); + option100.setLongOpt("help"); + Option option20 = new Option("debug", "turn on debug information"); + options.addOption(option5); + options.addOption(option6); + options.addOption(option7); + options.addOption(option10); + options.addOption(option11); + options.addOption(option12); + options.addOptionGroup(og1); + options.addOption(option20); + options.addOption(option100); + return options; + } +} diff --git a/src/com/dom/benchmarking/swingbench/benchmarks/JSON/GetPassengerDetails.java b/src/com/dom/benchmarking/swingbench/benchmarks/JSON/GetPassengerDetails.java new file mode 100644 index 0000000..b68f803 --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/benchmarks/JSON/GetPassengerDetails.java @@ -0,0 +1,96 @@ +package com.dom.benchmarking.swingbench.benchmarks.JSON; + +import com.dom.benchmarking.swingbench.event.JdbcTaskEvent; +import com.dom.benchmarking.swingbench.kernel.DatabaseTransaction; +import com.dom.benchmarking.swingbench.kernel.SwingBenchException; +import com.dom.benchmarking.swingbench.kernel.SwingBenchTask; +import com.dom.benchmarking.swingbench.utilities.RandomGenerator; +import oracle.soda.OracleCollection; +import oracle.soda.OracleDatabase; +import oracle.soda.OracleDocument; +import oracle.soda.rdbms.OracleRDBMSClient; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Map; +import java.util.Properties; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; +import java.util.logging.Level; +import java.util.logging.Logger; + +public class GetPassengerDetails extends DatabaseTransaction { + + private static final Logger logger = Logger.getLogger(GetPassengerDetails.class.getName()); + private static final Lock lock = new ReentrantLock(); + private static Long passengerRange = null; + private OracleRDBMSClient client = null; + + public GetPassengerDetails() { + super(); + } + + @Override + public void init(Map params) throws SwingBenchException { + Connection connection = (Connection) params.get(SwingBenchTask.JDBC_CONNECTION); + Properties prop = new Properties(); + prop.put("oracle.soda.sharedMetadataCache", "true"); + client = new OracleRDBMSClient(prop); + + lock.lock(); + if (passengerRange == null) { + logger.fine("Reference data loaded for GetPassengerDetails transaction"); + try (PreparedStatement ps = connection.prepareStatement( + "SELECT MAX(us.last_number)\n" + + "FROM user_sequences us\n" + + "WHERE us.sequence_name = 'PASSENGER_SEQ'")) { + ResultSet rs = ps.executeQuery(); + rs.next(); + passengerRange = rs.getLong(1); + } catch (SQLException se) { + logger.log(Level.SEVERE, "Error initialising GetPassengerDetails", se); + throw new SwingBenchException(se); + } + } + lock.unlock(); + } + + @Override + public void execute(Map params) throws SwingBenchException { + + long executeStart = 0; + try { + Connection connection = (Connection) params.get(SwingBenchTask.JDBC_CONNECTION); + + Long passengerKey = RandomGenerator.randomLong(1, passengerRange); + + initJdbcTask(); + + executeStart = System.nanoTime(); + try { + OracleDatabase database = client.getDatabase(connection); + OracleCollection collection = database.openCollection("PASSENGERCOLLECTION"); + OracleDocument doc = collection.find() + .key(passengerKey.toString()) + .getOne(); + if (doc != null) { + String json = doc.getContentAsString(); + } + addSelectStatements(1); + } catch (Exception oe) { + throw new SwingBenchException(oe); + } + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), true, getInfoArray())); + } catch (SwingBenchException sbe) { + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), false, getInfoArray())); + throw sbe; + } + } + + @Override + public void close() { + // TODO Implement this method + } +} diff --git a/src/com/dom/benchmarking/swingbench/benchmarks/JSON/InsertNewPassenger.java b/src/com/dom/benchmarking/swingbench/benchmarks/JSON/InsertNewPassenger.java new file mode 100644 index 0000000..6bafb86 --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/benchmarks/JSON/InsertNewPassenger.java @@ -0,0 +1,141 @@ +package com.dom.benchmarking.swingbench.benchmarks.JSON; + +import com.dom.benchmarking.swingbench.event.JdbcTaskEvent; +import com.dom.benchmarking.swingbench.kernel.DatabaseTransaction; +import com.dom.benchmarking.swingbench.kernel.SwingBenchException; +import com.dom.benchmarking.swingbench.kernel.SwingBenchTask; +import com.dom.benchmarking.swingbench.utilities.RandomGenerator; +import com.dom.util.Utilities; +import oracle.soda.OracleCollection; +import oracle.soda.OracleDatabase; +import oracle.soda.OracleDocument; +import oracle.soda.OracleException; +import oracle.soda.rdbms.OracleRDBMSClient; + +import javax.json.Json; +import javax.json.JsonBuilderFactory; +import javax.json.JsonObject; +import java.io.File; +import java.io.IOException; +import java.sql.Connection; +import java.sql.SQLException; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.UUID; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; +import java.util.logging.Level; +import java.util.logging.Logger; + +public class InsertNewPassenger extends DatabaseTransaction { + + private static final Logger logger = Logger.getLogger(InsertNewPassenger.class.getName()); + private static final String FIRST_NAMES_FILE = "data/lowerfirstnames.txt"; + private static final String LAST_NAMES_FILE = "data/lowerlastnames.txt"; + private static final String COUNTRIES_FILE = "data/countries.txt"; + private static final String US_AIRPORTS_FILE = "data/USAirportCodes.txt"; + private static final String NON_US_AIRPORTS_FILE = "data/NonUSAirportCodes.txt"; + private static final int BIO_SIZE = 128; + private static List firstNames = null; + private static List lastNames = null; + private static List countries = null; + private static List USAirports = null; + private static List NonUSAirports = null; + private static final Lock lock = new ReentrantLock(); + private OracleRDBMSClient client = null; + + public InsertNewPassenger() { + super(); + } + + @Override + public void init(Map params) throws SwingBenchException { + Properties prop = new Properties(); + prop.put("oracle.soda.sharedMetadataCache", "true"); + client = new OracleRDBMSClient(prop); + + String value = (String) params.get("SOE_FIRST_NAMES_LOC"); + File firstNamesFile = new File((value == null) ? FIRST_NAMES_FILE : value); + value = (String) params.get("SOE_LAST_NAMES_LOC"); + File lastNamesFile = new File((value == null) ? LAST_NAMES_FILE : value); + File countriesFiles = new File(COUNTRIES_FILE); + File usAirportsFiles = new File(US_AIRPORTS_FILE); + File nonUSAirportsFiles = new File(NON_US_AIRPORTS_FILE); + + lock.lock(); + try { + if (firstNames == null) { + firstNames = Utilities.cacheFile(firstNamesFile); + lastNames = Utilities.cacheFile(lastNamesFile); + countries = Utilities.cacheFile(countriesFiles); + USAirports = Utilities.cacheFile(usAirportsFiles); + NonUSAirports = Utilities.cacheFile(nonUSAirportsFiles); + logger.fine("Reference data loaded for InsertNewPassenger transaction"); + } + + } catch (IOException ie) { + logger.log(Level.SEVERE, "Unable to open data seed files : ", ie); + throw new SwingBenchException(ie); + } + lock.unlock(); + + } + + @Override + public void execute(Map params) throws SwingBenchException { + + long executeStart = 0; + try { + Connection connection = (Connection) params.get(SwingBenchTask.JDBC_CONNECTION); + String firstName = firstNames.get(RandomGenerator.randomInteger(0, firstNames.size())); + String lastName = lastNames.get(RandomGenerator.randomInteger(0, lastNames.size())); + String nationality = countries.get(RandomGenerator.randomInteger(0, countries.size())); + String USAirport = USAirports.get(RandomGenerator.randomInteger(0, USAirports.size())); + String nonUSAirport = NonUSAirports.get(RandomGenerator.randomInteger(0, NonUSAirports.size())); + Long flightDate = RandomGenerator.randomLong(959337930, 1432583142); + Long returnFlightDate = flightDate + (604800); + + initJdbcTask(); + + executeStart = System.nanoTime(); + try { + OracleDatabase database = client.getDatabase(connection); + OracleCollection collection = database.openCollection("PASSENGERCOLLECTION"); + JsonBuilderFactory jsonfactory = Json.createBuilderFactory(null); + JsonObject passengerJSON = jsonfactory.createObjectBuilder() + .add("ID", UUID.randomUUID().toString()) + .add("FirstName", lastName) + .add("LastName", firstName) + .add("Nationality", nationality) + .add("DOB", RandomGenerator.randomLong(-1262304000, 1432583142)) + .add("PassportNo", RandomGenerator.randomInteger(100000000, 999999999)) + .add("Flagged", "N") + .add("BioData", RandomGenerator.randomAlpha(BIO_SIZE, BIO_SIZE)) + .add("FlightHistory", jsonfactory.createArrayBuilder() + .add(jsonfactory.createObjectBuilder() + .add("FlightDate", flightDate).add("Airport", USAirport)) + .add(jsonfactory.createObjectBuilder() + .add("FlightDate", returnFlightDate).add("Airport", nonUSAirport))) + .build(); + + OracleDocument document = database.createDocumentFromString(passengerJSON.toString()); + collection.insert(document); + addInsertStatements(1); + connection.commit(); + addCommitStatements(1); + } catch (OracleException | SQLException oe) { + throw new SwingBenchException(oe.getMessage()); + } + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), true, getInfoArray())); + } catch (SwingBenchException sbe) { + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), false, getInfoArray())); + throw sbe; + } + } + + @Override + public void close() { + // TODO Implement this method + } +} diff --git a/src/com/dom/benchmarking/swingbench/benchmarks/JSON/RemovePassengerDetails.java b/src/com/dom/benchmarking/swingbench/benchmarks/JSON/RemovePassengerDetails.java new file mode 100644 index 0000000..013b033 --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/benchmarks/JSON/RemovePassengerDetails.java @@ -0,0 +1,97 @@ +package com.dom.benchmarking.swingbench.benchmarks.JSON; + +import com.dom.benchmarking.swingbench.event.JdbcTaskEvent; +import com.dom.benchmarking.swingbench.kernel.DatabaseTransaction; +import com.dom.benchmarking.swingbench.kernel.SwingBenchException; +import com.dom.benchmarking.swingbench.kernel.SwingBenchTask; +import com.dom.benchmarking.swingbench.utilities.RandomGenerator; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +import java.util.Map; +import java.util.Properties; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; +import java.util.logging.Level; +import java.util.logging.Logger; + +import oracle.soda.OracleCollection; +import oracle.soda.OracleDatabase; +import oracle.soda.rdbms.OracleRDBMSClient; + +public class RemovePassengerDetails extends DatabaseTransaction { + + private static final Logger logger = Logger.getLogger(RemovePassengerDetails.class.getName()); + private static final Lock lock = new ReentrantLock(); + private static Long passengerRange = null; + private OracleRDBMSClient client = null; + + public RemovePassengerDetails() { + super(); + } + + + @Override + public void init(Map params) throws SwingBenchException { + Connection connection = (Connection) params.get(SwingBenchTask.JDBC_CONNECTION); + Properties prop = new Properties(); + prop.put("oracle.soda.sharedMetadataCache", "true"); + client = new OracleRDBMSClient(prop); + + lock.lock(); + if (passengerRange == null) { + logger.fine("Reference data loaded for GetPassengerDetails transaction"); + try (PreparedStatement ps = connection.prepareStatement( + "SELECT MAX(us.last_number)\n" + + "FROM user_sequences us\n" + + "WHERE us.sequence_name = 'PASSENGER_SEQ'")) { + ResultSet rs = ps.executeQuery(); + rs.next(); + passengerRange = rs.getLong(1); + } catch (SQLException se) { + logger.log(Level.SEVERE, "Error initialising RemovePassengerDetails", se); + throw new SwingBenchException(se); + } + } + lock.unlock(); + } + + @Override + public void execute(Map params) throws SwingBenchException { + + long executeStart = 0; + try { + Connection connection = (Connection) params.get(SwingBenchTask.JDBC_CONNECTION); + Long passengerKey = RandomGenerator.randomLong(1, passengerRange); + + initJdbcTask(); + + executeStart = System.nanoTime(); + try { + OracleDatabase database = client.getDatabase(connection); + OracleCollection collection = database.openCollection("PASSENGERCOLLECTION"); + // Delete document from collection + collection.find() + .key(passengerKey.toString()) + .remove(); + addDeleteStatements(1); + connection.commit(); + addCommitStatements(1); + } catch (Exception oe) { + throw new SwingBenchException(oe); + } + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), true, getInfoArray())); + } catch (SwingBenchException sbe) { + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), false, getInfoArray())); + throw sbe; + } + } + + @Override + public void close() { + // TODO Implement this method + } +} diff --git a/src/com/dom/benchmarking/swingbench/benchmarks/JSON/UpdatePassengerDetails.java b/src/com/dom/benchmarking/swingbench/benchmarks/JSON/UpdatePassengerDetails.java new file mode 100644 index 0000000..a903ad8 --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/benchmarks/JSON/UpdatePassengerDetails.java @@ -0,0 +1,175 @@ +package com.dom.benchmarking.swingbench.benchmarks.JSON; + +import com.dom.benchmarking.swingbench.event.JdbcTaskEvent; +import com.dom.benchmarking.swingbench.kernel.DatabaseTransaction; +import com.dom.benchmarking.swingbench.kernel.SwingBenchException; +import com.dom.benchmarking.swingbench.kernel.SwingBenchTask; +import com.dom.benchmarking.swingbench.utilities.RandomGenerator; +import com.dom.util.Utilities; +import oracle.soda.OracleCollection; +import oracle.soda.OracleDatabase; +import oracle.soda.OracleDocument; +import oracle.soda.rdbms.OracleRDBMSClient; + +import javax.json.*; +import java.io.File; +import java.io.IOException; +import java.io.StringReader; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; +import java.util.logging.Level; +import java.util.logging.Logger; + +public class UpdatePassengerDetails extends DatabaseTransaction { + + private static final Logger logger = Logger.getLogger(UpdatePassengerDetails.class.getName()); + private static final Lock lock = new ReentrantLock(); + private static final String US_AIRPORTS_FILE = "data/USAirportCodes.txt"; + private static final String NON_US_AIRPORTS_FILE = "data/NonUSAirportCodes.txt"; + private static Long passengerRange = null; + private static List USAirports = null; + private static List NonUSAirports = null; + private OracleRDBMSClient client = null; + + public UpdatePassengerDetails() { + super(); + } + + @Override + public void init(Map params) throws SwingBenchException { + Connection connection = (Connection) params.get(SwingBenchTask.JDBC_CONNECTION); + File usAirportsFiles = new File(US_AIRPORTS_FILE); + File nonUSAirportsFiles = new File(NON_US_AIRPORTS_FILE); + Properties prop = new Properties(); + prop.put("oracle.soda.sharedMetadataCache", "true"); + client = new OracleRDBMSClient(prop); + + lock.lock(); + if (passengerRange == null) { + try (PreparedStatement ps = connection.prepareStatement( + "SELECT MAX(us.last_number)\n" + + "FROM user_sequences us\n" + + "WHERE us.sequence_name = 'PASSENGER_SEQ'")) { + ResultSet rs = ps.executeQuery(); + rs.next(); + passengerRange = rs.getLong(1); + } catch (SQLException se) { + logger.log(Level.FINE, "Error initialising UpdatePassengerDetails", se); + throw new SwingBenchException(se); + } + + } + try { + if (USAirports == null) { + USAirports = Utilities.cacheFile(usAirportsFiles); + NonUSAirports = Utilities.cacheFile(nonUSAirportsFiles); + logger.fine("Reference data loaded for UpdatePassengerDetails transaction"); + } + + } catch (IOException ie) { + logger.log(Level.FINE, "Error initialising UpdatePassengerDetails", ie); + throw new SwingBenchException(ie); + } + lock.unlock(); + } + + @Override + public void execute(Map params) throws SwingBenchException { + + + long executeStart = 0; + try { + Connection connection = (Connection) params.get(SwingBenchTask.JDBC_CONNECTION); + Long passengerKey = RandomGenerator.randomLong(1, passengerRange); + String USAirport = USAirports.get(RandomGenerator.randomInteger(0, USAirports.size())); + String nonUSAirport = NonUSAirports.get(RandomGenerator.randomInteger(0, NonUSAirports.size())); + Long flightDate = RandomGenerator.randomLong(959337930, 1432583142); + Long returnFlightDate = flightDate + (604800); + initJdbcTask(); + + executeStart = System.nanoTime(); + try { + + OracleDatabase database = client.getDatabase(connection); + OracleCollection collection = database.openCollection("PASSENGERCOLLECTION"); + OracleDocument doc = collection.find() + .key(passengerKey.toString()) + .getOne(); + addSelectStatements(1); + if (doc != null) { + JsonBuilderFactory jsonfactory = Json.createBuilderFactory(null); + JsonReader jsonReader = Json.createReader(new StringReader(doc.getContentAsString())); + JsonObject passenger = jsonReader.readObject(); + // JsonObjects are immutable (yuck) so we'll need to clone everything + // Clone everything apart from the array we want to update + JsonObjectBuilder clonedPassenger = cloneJson(passenger, "FlightHistory"); + // Now clone this array + JsonArrayBuilder clonedArray = cloneArray(passenger, "FlightHistory"); + //Now add an additional flight + JsonObject clonedJSON = clonedPassenger.add("FlightHistory", clonedArray.add(jsonfactory.createObjectBuilder() + .add("FlightDate", flightDate) + .add("Airport", USAirport)) + .add(jsonfactory.createObjectBuilder() + .add("FlightDate", returnFlightDate) + .add("Airport", nonUSAirport))) + .build(); + //JsonObject clonedJSON = clonedPassenger.add("FlightHistory",clonedArray).build(); + OracleDocument document = database.createDocumentFromString(clonedJSON.toString()); + //collection.find().key(passengerKey.toString()).version("v1").replaceOne(document); + collection.find() + .key(passengerKey.toString()) + .replaceOne(document); + addUpdateStatements(1); + connection.commit(); + addCommitStatements(1); + + } + addSelectStatements(1); + } catch (Exception oe) { + throw new SwingBenchException(oe); + } + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), true, getInfoArray())); + } catch (SwingBenchException sbe) { + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), false, getInfoArray())); + throw sbe; + } + } + + private JsonArrayBuilder cloneArray(JsonObject j, String arrayKey) { + JsonArrayBuilder ab = Json.createArrayBuilder(); + for (Map.Entry entry : j.entrySet()) { + if (entry.getKey() + .equals(arrayKey)) { + if (entry.getValue() instanceof JsonArray) { + JsonArray a = (JsonArray) entry.getValue(); + for (JsonValue jv : a) { + ab.add(jv); + } + } + } + } + return ab; + } + + private JsonObjectBuilder cloneJson(JsonObject j, String excludeString) { + JsonObjectBuilder newj = Json.createObjectBuilder(); + for (Map.Entry entry : j.entrySet()) { + if (!entry.getKey() + .equals(excludeString)) + newj.add(entry.getKey(), entry.getValue()); + } + return newj; + } + + @Override + public void close() { + // TODO Implement this method + } +} diff --git a/src/com/dom/benchmarking/swingbench/dsstransactions/PeriodToPeriodComparison.java b/src/com/dom/benchmarking/swingbench/dsstransactions/PeriodToPeriodComparison.java new file mode 100644 index 0000000..3a8ef29 --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/dsstransactions/PeriodToPeriodComparison.java @@ -0,0 +1,123 @@ +package com.dom.benchmarking.swingbench.dsstransactions; + + +import com.dom.benchmarking.swingbench.event.JdbcTaskEvent; +import com.dom.benchmarking.swingbench.kernel.SwingBenchException; +import com.dom.benchmarking.swingbench.kernel.SwingBenchTask; +import com.dom.benchmarking.swingbench.utilities.RandomGenerator; +import com.dom.util.OracleUtilities; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; + +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + + +public class PeriodToPeriodComparison extends SalesHistory { + private static final Logger logger = Logger.getLogger(PeriodToPeriodComparison.class.getName()); + + public PeriodToPeriodComparison() { + } + + public void init(Map param) throws SwingBenchException { + try { + if (!isDataCached()) { + synchronized (lock) { + if (!isDataCached()) { + Connection connection = (Connection) param.get(SwingBenchTask.JDBC_CONNECTION); + cacheData(connection); + } + } + } + } catch (SQLException e) { + logger.log(Level.SEVERE, "Failed to cache data with the following exception : ", e); + throw new SwingBenchException(e); + } + } + + public void execute(Map param) throws SwingBenchException { + Connection connection = (Connection) param.get(SwingBenchTask.JDBC_CONNECTION); + initJdbcTask(); + long executeStart = System.nanoTime(); + try { + OracleUtilities.setModuleInfo(connection, "PeriodToPeriodComparison"); + Statement st = connection.createStatement(); + String yearRange = getRandomStringData(2, 3, getYears(), null); + String lastYear = yearRange.substring(yearRange.indexOf(",") + 1, yearRange.length()); + int minWeek = RandomGenerator.randomInteger(1, 48); + int maxWeek = minWeek + 4; + String selectedProduct = getRandomStringData(1, 2, getProducts(), "'"); + + String sql = + "WITH v AS\n" + + " (SELECT p.Prod_Name Product_Name,\n" + + " t.Calendar_Year YEAR,\n" + + " t.Calendar_Week_Number Week,\n" + + " SUM(Amount_Sold) Sales\n" + + " FROM Sales s,\n" + + " Times t,\n" + + " Products p\n" + + " WHERE s.Time_id = t.Time_id\n" + + " AND s.Prod_id = p.Prod_id\n" + + " AND p.Prod_name IN (" + selectedProduct + ")\n" + + " and T.CALENDAR_YEAR IN (" + yearRange + ")\n" + + " AND t.Calendar_Week_Number BETWEEN " + minWeek + " AND " + maxWeek + "\n" + + " GROUP BY p.Prod_Name,\n" + + " t.Calendar_Year,\n" + + " t.Calendar_Week_Number\n" + + " )\n" + + "SELECT Product_Name Prod,\n" + + " YEAR,\n" + + " Week,\n" + + " Sales,\n" + + " Weekly_ytd_sales,\n" + + " Weekly_ytd_sales_prior_year\n" + + "FROM\n" + + " (SELECT --Start of year_over_year sales\n" + + " Product_Name,\n" + + " YEAR,\n" + + " Week,\n" + + " Sales,\n" + + " Weekly_ytd_sales,\n" + + " LAG(Weekly_ytd_sales, 1) OVER (PARTITION BY Product_Name, Week ORDER BY YEAR) Weekly_ytd_sales_prior_year\n" + + " FROM\n" + + " (SELECT -- Start of dense_sales\n" + + " v.Product_Name Product_Name,\n" + + " t.Year YEAR,\n" + + " t.Week Week,\n" + + " NVL(v.Sales,0) Sales,\n" + + " SUM(NVL(v.Sales,0)) OVER (PARTITION BY v.Product_Name, t.Year ORDER BY t.week) weekly_ytd_sales\n" + + " FROM v PARTITION BY (v.Product_Name)\n" + + " RIGHT OUTER JOIN\n" + + " (SELECT DISTINCT Calendar_Week_Number Week,\n" + + " Calendar_Year YEAR\n" + + " FROM Times\n" + + " WHERE Calendar_Year IN (" + yearRange + ")\n" + + " ) t\n" + + " ON (v.week = t.week\n" + + " AND v.Year = t.Year)\n" + + " ) dense_sales\n" + + " ) year_over_year_sales\n" + + "where year = " + lastYear + "\n" + + "AND WEEK BETWEEN " + minWeek + " AND " + maxWeek + "\n" + + "ORDER BY 1,2,3"; + logger.finest(sql); + ResultSet rs = st.executeQuery(sql); + rs.next(); + rs.close(); + st.close(); + addSelectStatements(1); + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), true, getInfoArray())); + } catch (SQLException ex) { + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), false, getInfoArray())); + throw new SwingBenchException(ex); + } + } + + public void close() { + } +} diff --git a/src/com/dom/benchmarking/swingbench/dsstransactions/ProductMonthlySalesRollupCube.java b/src/com/dom/benchmarking/swingbench/dsstransactions/ProductMonthlySalesRollupCube.java new file mode 100644 index 0000000..835561f --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/dsstransactions/ProductMonthlySalesRollupCube.java @@ -0,0 +1,75 @@ +package com.dom.benchmarking.swingbench.dsstransactions; + + +import com.dom.benchmarking.swingbench.event.JdbcTaskEvent; +import com.dom.benchmarking.swingbench.kernel.SwingBenchException; +import com.dom.benchmarking.swingbench.kernel.SwingBenchTask; +import com.dom.util.OracleUtilities; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; + +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + + +public class ProductMonthlySalesRollupCube extends SalesHistory { + private static final Logger logger = Logger.getLogger(ProductMonthlySalesRollupCube.class.getName()); + + public ProductMonthlySalesRollupCube() { + } + + public void init(Map param) throws SwingBenchException { + try { + if (!isDataCached()) { + synchronized (lock) { + if (!isDataCached()) { + Connection connection = (Connection) param.get(SwingBenchTask.JDBC_CONNECTION); + cacheData(connection); + } + } + } + } catch (SQLException e) { + logger.log(Level.SEVERE, "Failed to cache data with the following exception : ", e); + throw new SwingBenchException(e); + } + } + + public void execute(Map param) throws SwingBenchException { + Connection connection = (Connection) param.get(SwingBenchTask.JDBC_CONNECTION); + initJdbcTask(); + long executeStart = System.nanoTime(); + try { + OracleUtilities.setModuleInfo(connection, "ProductMonthlySalesRollupCube"); + Statement st = connection.createStatement(); + String sql = + "SELECT calendar_year,\n" + + " calendar_week_number, prod_name, SUM(amount_sold)\n" + + "FROM sales, times, products, customers, countries\n" + + "WHERE sales.time_id=times.time_id \n" + + " AND sales.prod_id=products.prod_id \n" + + " AND customers.country_id = countries.country_id \n" + + " AND sales.cust_id=customers.cust_id \n" + + " AND prod_name IN (" + getRandomStringData(2, 3, getProducts(), "'") + ") \n" + + " AND country_iso_code = " + getRandomStringData(1, 2, getCountries(), "'") + " AND times.calendar_month_desc = " + getRandomStringData(1, 2, getMonths(), "'") + " \n" + + " AND calendar_year=" + getRandomStringData(1, 2, getYears(), null) + " \n" + + "GROUP BY ROLLUP(calendar_year, calendar_week_number, prod_name)"; + logger.finest(sql); + ResultSet rs = st.executeQuery(sql); + rs.next(); + rs.close(); + st.close(); + addSelectStatements(1); + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), true, getInfoArray())); + } catch (SQLException ex) { + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), false, getInfoArray())); + throw new SwingBenchException(ex); + } + } + + public void close() { + } +} diff --git a/src/com/dom/benchmarking/swingbench/dsstransactions/ProductSalesRollupCube.java b/src/com/dom/benchmarking/swingbench/dsstransactions/ProductSalesRollupCube.java new file mode 100644 index 0000000..1e9df94 --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/dsstransactions/ProductSalesRollupCube.java @@ -0,0 +1,74 @@ +package com.dom.benchmarking.swingbench.dsstransactions; + + +import com.dom.benchmarking.swingbench.event.JdbcTaskEvent; +import com.dom.benchmarking.swingbench.kernel.SwingBenchException; +import com.dom.benchmarking.swingbench.kernel.SwingBenchTask; +import com.dom.util.OracleUtilities; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; + +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + + +public class ProductSalesRollupCube extends SalesHistory { + private static final Logger logger = Logger.getLogger(ProductSalesRollupCube.class.getName()); + + public ProductSalesRollupCube() { + } + + public void init(Map param) throws SwingBenchException { + try { + if (!isDataCached()) { + synchronized (lock) { + if (!isDataCached()) { + Connection connection = (Connection) param.get(SwingBenchTask.JDBC_CONNECTION); + cacheData(connection); + } + } + } + } catch (SQLException e) { + logger.log(Level.SEVERE, "Failed to cache data with the following exception : ", e); + throw new SwingBenchException(e); + } + } + + public void execute(Map param) throws SwingBenchException { + Connection connection = (Connection) param.get(SwingBenchTask.JDBC_CONNECTION); + initJdbcTask(); + long executeStart = System.nanoTime(); + try { + OracleUtilities.setModuleInfo(connection, "ProductSalesRollupCube"); + Statement st = connection.createStatement(); + String sql = + "SELECT calendar_year, calendar_quarter_number,\n" + + " calendar_month_number, SUM(amount_sold)\n" + + "FROM sales, times, products, customers, countries\n" + + "WHERE sales.time_id=times.time_id \n" + + " AND sales.prod_id=products.prod_id \n" + + " AND customers.country_id = countries.country_id \n" + + " AND sales.cust_id=customers.cust_id \n" + + " AND prod_name IN (" + getRandomStringData(1, 3, getProducts(), "'") + ") \n" + + " AND country_iso_code = " + getRandomStringData(1, 2, getCountries(), "'") + " AND calendar_year=" + getRandomStringData(1, 2, getYears(), null) + " \n" + + "GROUP BY ROLLUP(calendar_year, calendar_quarter_number, calendar_month_number)"; + logger.finest(sql); + ResultSet rs = st.executeQuery(sql); + rs.next(); + rs.close(); + st.close(); + addSelectStatements(1); + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), true, getInfoArray())); + } catch (SQLException ex) { + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), false, getInfoArray())); + throw new SwingBenchException(ex); + } + } + + public void close() { + } +} diff --git a/src/com/dom/benchmarking/swingbench/dsstransactions/SalesByCountryForGivenYear.java b/src/com/dom/benchmarking/swingbench/dsstransactions/SalesByCountryForGivenYear.java new file mode 100644 index 0000000..d54385c --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/dsstransactions/SalesByCountryForGivenYear.java @@ -0,0 +1,82 @@ +package com.dom.benchmarking.swingbench.dsstransactions; + + +import com.dom.benchmarking.swingbench.event.JdbcTaskEvent; +import com.dom.benchmarking.swingbench.kernel.SwingBenchException; +import com.dom.benchmarking.swingbench.kernel.SwingBenchTask; +import com.dom.util.OracleUtilities; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; + +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + + +public class SalesByCountryForGivenYear extends SalesHistory { + + private static final Logger logger = Logger.getLogger(SalesByCountryForGivenYear.class.getName()); + + public SalesByCountryForGivenYear() { + } + + public void init(Map param) throws SwingBenchException { + try { + if (!isDataCached()) { + synchronized (lock) { + if (!isDataCached()) { + Connection connection = (Connection) param.get(SwingBenchTask.JDBC_CONNECTION); + cacheData(connection); + } + } + } + } catch (SQLException e) { + logger.log(Level.SEVERE, "Failed to cache data with the following exception : ", e); + throw new SwingBenchException(e); + } + } + + public void execute(Map param) throws SwingBenchException { + Connection connection = (Connection) param.get(SwingBenchTask.JDBC_CONNECTION); + initJdbcTask(); + long executeStart = System.nanoTime(); + try { + OracleUtilities.setModuleInfo(connection, "SalesByCountryForGivenYear"); + Statement st = connection.createStatement(); + String sql = + "SELECT SUM(s.quantity_sold* p.prod_list_price),\n" + + " co.country_name,\n" + + " t.calendar_year\n" + + "FROM sales s,\n" + + " customers cu,\n" + + " countries co,\n" + + " products p,\n" + + " times t\n" + + "WHERE s.cust_id = cu.cust_id\n" + + "and s.prod_id = p.prod_id\n" + + "AND cu.country_id = co.country_id\n" + + "AND s.time_id = t.time_id\n" + + "and t.calendar_year = " + getRandomStringData(1, 2, getYears(), null) + "\n" + + " GROUP BY co.country_name,\n" + + " t.calendar_year\n" + + "ORDER BY t.calendar_year"; + logger.finest(sql); + ResultSet rs = st.executeQuery(sql); + rs.next(); + rs.close(); + st.close(); + addSelectStatements(1); + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), true, getInfoArray())); + } catch (SQLException ex) { + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), false, getInfoArray())); + throw new SwingBenchException(ex); + } + } + + public void close() { + } + +} diff --git a/src/com/dom/benchmarking/swingbench/dsstransactions/SalesByQuarterCountry.java b/src/com/dom/benchmarking/swingbench/dsstransactions/SalesByQuarterCountry.java new file mode 100644 index 0000000..2d1b805 --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/dsstransactions/SalesByQuarterCountry.java @@ -0,0 +1,84 @@ +package com.dom.benchmarking.swingbench.dsstransactions; + + +import com.dom.benchmarking.swingbench.event.JdbcTaskEvent; +import com.dom.benchmarking.swingbench.kernel.SwingBenchException; +import com.dom.benchmarking.swingbench.kernel.SwingBenchTask; +import com.dom.util.OracleUtilities; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; + +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + + +public class SalesByQuarterCountry extends SalesHistory { + + private static final Logger logger = Logger.getLogger(SalesByQuarterCountry.class.getName()); + + public SalesByQuarterCountry() { + } + + public void init(Map param) throws SwingBenchException { + try { + if (!isDataCached()) { + synchronized (lock) { + if (!isDataCached()) { + Connection connection = (Connection) param.get(SwingBenchTask.JDBC_CONNECTION); + cacheData(connection); + } + } + } + } catch (SQLException e) { + logger.log(Level.SEVERE, "Failed to cache data with the following exception : ", e); + throw new SwingBenchException(e); + } + } + + public void execute(Map param) throws SwingBenchException { + Connection connection = (Connection) param.get(SwingBenchTask.JDBC_CONNECTION); + initJdbcTask(); + long executeStart = System.nanoTime(); + try { + OracleUtilities.setModuleInfo(connection, "SalesByQuarterCountry"); + String month = getRandomStringData(1, 2, getMonths(), null); + String country = getRandomStringData(1, 2, getCountries(), null); + Statement st = connection.createStatement(); + String sql = + "SELECT SUM(amount_sold),\n" + + " t.calendar_month_desc,\n" + + " t.calendar_week_number,\n" + + " c.country_name\n" + + "FROM sales s,\n" + + " times t,\n" + + " countries c,\n" + + " customers cu\n" + + "WHERE s.time_id = t.time_id\n" + + "AND t.calendar_month_desc = '" + month + "'\n" + + "AND cu.country_id = c.country_id\n" + + "AND s.cust_id = cu.cust_id\n" + + "AND c.country_iso_code = '" + country + "'\n" + + "group by t.calendar_month_desc,\n" + + "t.calendar_week_number,\n" + + "c.country_name"; + logger.finest(sql); + ResultSet rs = st.executeQuery(sql); + rs.next(); + rs.close(); + st.close(); + addSelectStatements(1); + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), true, getInfoArray())); + } catch (SQLException ex) { + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), false, getInfoArray())); + throw new SwingBenchException(ex); + } + } + + public void close() { + } + +} diff --git a/src/com/dom/benchmarking/swingbench/dsstransactions/SalesByWeekCountry.java b/src/com/dom/benchmarking/swingbench/dsstransactions/SalesByWeekCountry.java new file mode 100644 index 0000000..735fe45 --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/dsstransactions/SalesByWeekCountry.java @@ -0,0 +1,84 @@ +package com.dom.benchmarking.swingbench.dsstransactions; + + +import com.dom.benchmarking.swingbench.event.JdbcTaskEvent; +import com.dom.benchmarking.swingbench.kernel.SwingBenchException; +import com.dom.benchmarking.swingbench.kernel.SwingBenchTask; +import com.dom.util.OracleUtilities; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; + +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + + +public class SalesByWeekCountry extends SalesHistory { + + private static final Logger logger = Logger.getLogger(SalesByWeekCountry.class.getName()); + + public SalesByWeekCountry() { + } + + public void init(Map param) throws SwingBenchException { + try { + if (!isDataCached()) { + synchronized (lock) { + if (!isDataCached()) { + Connection connection = (Connection) param.get(SwingBenchTask.JDBC_CONNECTION); + cacheData(connection); + } + } + } + } catch (SQLException e) { + logger.log(Level.SEVERE, "Failed to cache data with the following exception : ", e); + throw new SwingBenchException(e); + } + } + + public void execute(Map param) throws SwingBenchException { + Connection connection = (Connection) param.get(SwingBenchTask.JDBC_CONNECTION); + initJdbcTask(); + long executeStart = System.nanoTime(); + try { + OracleUtilities.setModuleInfo(connection, "SalesByWeekCountry"); + String week = getRandomStringData(1, 2, getWeeks(), null); + String country = getRandomStringData(1, 2, getCountries(), null); + Statement st = connection.createStatement(); + String sql = + "SELECT SUM(amount_sold),\n" + + " t.calendar_year, \n" + + " t.calendar_week_number,\n" + + " c.country_name\n" + + "FROM sales s,\n" + + " times t,\n" + + " countries c,\n" + + " customers cu\n" + + "WHERE s.time_id = t.time_id\n" + + "AND t.calendar_week_number = '" + week + "'\n" + + "AND t.calendar_year = " + getRandomStringData(1, 2, getYears(), "'") + " \n" + + "AND cu.country_id = c.country_id\n" + + "AND s.cust_id = cu.cust_id\n" + + "AND c.country_iso_code = '" + country + "'\n" + + "group by t.calendar_year, t.calendar_week_number,\n" + + "c.country_name"; + logger.finest(sql); + ResultSet rs = st.executeQuery(sql); + rs.next(); + rs.close(); + st.close(); + addSelectStatements(1); + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), true, getInfoArray())); + } catch (SQLException ex) { + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), false, getInfoArray())); + throw new SwingBenchException(ex); + } + } + + public void close() { + } + +} diff --git a/src/com/dom/benchmarking/swingbench/dsstransactions/SalesCubeByMonth.java b/src/com/dom/benchmarking/swingbench/dsstransactions/SalesCubeByMonth.java new file mode 100644 index 0000000..bb84836 --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/dsstransactions/SalesCubeByMonth.java @@ -0,0 +1,74 @@ +package com.dom.benchmarking.swingbench.dsstransactions; + + +import com.dom.benchmarking.swingbench.event.JdbcTaskEvent; +import com.dom.benchmarking.swingbench.kernel.SwingBenchException; +import com.dom.benchmarking.swingbench.kernel.SwingBenchTask; +import com.dom.util.OracleUtilities; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; + +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + + +public class SalesCubeByMonth extends SalesHistory { + private static final Logger logger = Logger.getLogger(SalesCubeByMonth.class.getName()); + + public SalesCubeByMonth() { + } + + public void init(Map param) throws SwingBenchException { + try { + if (!isDataCached()) { + synchronized (lock) { + if (!isDataCached()) { + Connection connection = (Connection) param.get(SwingBenchTask.JDBC_CONNECTION); + cacheData(connection); + } + } + } + } catch (SQLException e) { + logger.log(Level.SEVERE, "Failed to cache data with the following exception : ", e); + throw new SwingBenchException(e); + } + } + + public void execute(Map param) throws SwingBenchException { + Connection connection = (Connection) param.get(SwingBenchTask.JDBC_CONNECTION); + initJdbcTask(); + long executeStart = System.nanoTime(); + try { + OracleUtilities.setModuleInfo(connection, "SalesCubeByMonth"); + Statement st = connection.createStatement(); + String sql = + "SELECT channel_desc, calendar_month_desc, countries.country_iso_code,\n" + + " TO_CHAR(SUM(amount_sold), '9,999,999,999') SALES$\n" + + "FROM sales, customers, times, channels, countries\n" + + "WHERE sales.time_id=times.time_id AND sales.cust_id=customers.cust_id AND\n" + + " sales.channel_id= channels.channel_id\n" + + " AND customers.country_id = countries.country_id\n" + + " AND channels.channel_desc IN\n" + + " (" + getRandomStringData(1, 3, getChannels(), "'") + ") AND times.calendar_month_desc IN\n" + + " (" + getRandomStringData(2, 6, getMonths(), "'") + ") AND countries.country_iso_code IN (" + getRandomStringData(1, 4, getCountries(), "'") + ")\n" + + "GROUP BY CUBE(channel_desc, calendar_month_desc, countries.country_iso_code)"; + logger.finest(sql); + ResultSet rs = st.executeQuery(sql); + rs.next(); + rs.close(); + st.close(); + addSelectStatements(1); + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), true, getInfoArray())); + } catch (SQLException ex) { + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), false, getInfoArray())); + throw new SwingBenchException(ex); + } + } + + public void close() { + } +} diff --git a/src/com/dom/benchmarking/swingbench/dsstransactions/SalesCubeByWeek.java b/src/com/dom/benchmarking/swingbench/dsstransactions/SalesCubeByWeek.java new file mode 100644 index 0000000..e9f5ad3 --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/dsstransactions/SalesCubeByWeek.java @@ -0,0 +1,75 @@ +package com.dom.benchmarking.swingbench.dsstransactions; + + +import com.dom.benchmarking.swingbench.event.JdbcTaskEvent; +import com.dom.benchmarking.swingbench.kernel.SwingBenchException; +import com.dom.benchmarking.swingbench.kernel.SwingBenchTask; +import com.dom.util.OracleUtilities; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; + +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + + +public class SalesCubeByWeek extends SalesHistory { + private static final Logger logger = Logger.getLogger(SalesCubeByWeek.class.getName()); + + public SalesCubeByWeek() { + } + + public void init(Map param) throws SwingBenchException { + try { + if (!isDataCached()) { + synchronized (lock) { + if (!isDataCached()) { + Connection connection = (Connection) param.get(SwingBenchTask.JDBC_CONNECTION); + cacheData(connection); + } + } + } + } catch (SQLException e) { + logger.log(Level.SEVERE, "Failed to cache data with the following exception : ", e); + throw new SwingBenchException(e); + } + } + + public void execute(Map param) throws SwingBenchException { + Connection connection = (Connection) param.get(SwingBenchTask.JDBC_CONNECTION); + initJdbcTask(); + long executeStart = System.nanoTime(); + try { + OracleUtilities.setModuleInfo(connection, "SalesCubeByWeek"); + Statement st = connection.createStatement(); + String sql = + "SELECT channel_desc, calendar_week_number, countries.country_iso_code,\n" + + " TO_CHAR(SUM(amount_sold), '9,999,999,999') SALES$\n" + + "FROM sales, customers, times, channels, countries\n" + + "WHERE sales.time_id=times.time_id AND sales.cust_id=customers.cust_id AND\n" + + " sales.channel_id= channels.channel_id\n" + + " AND customers.country_id = countries.country_id\n" + + " AND channels.channel_desc IN\n" + + " (" + getRandomStringData(1, 3, getChannels(), "'") + ")" + " AND times.calendar_year = " + getRandomStringData(1, 2, getYears(), "'") + " \n" + + " AND times.calendar_week_number IN (" + getRandomStringData(2, 4, getWeeks(), "'") + ") \n" + + " AND countries.country_iso_code IN (" + getRandomStringData(1, 4, getCountries(), "'") + ")\n" + + "GROUP BY CUBE(channel_desc, calendar_week_number, countries.country_iso_code)"; + logger.finest(sql); + ResultSet rs = st.executeQuery(sql); + rs.next(); + rs.close(); + st.close(); + addSelectStatements(1); + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), true, getInfoArray())); + } catch (SQLException ex) { + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), false, getInfoArray())); + throw new SwingBenchException(ex); + } + } + + public void close() { + } +} diff --git a/src/com/dom/benchmarking/swingbench/dsstransactions/SalesHistory.java b/src/com/dom/benchmarking/swingbench/dsstransactions/SalesHistory.java new file mode 100644 index 0000000..ce71a86 --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/dsstransactions/SalesHistory.java @@ -0,0 +1,123 @@ +package com.dom.benchmarking.swingbench.dsstransactions; + + +import com.dom.benchmarking.swingbench.kernel.DatabaseTransaction; +import com.dom.benchmarking.swingbench.utilities.RandomGenerator; +import com.dom.util.OracleUtilities; + +import java.sql.Connection; +import java.sql.SQLException; + +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; + + +public abstract class SalesHistory extends DatabaseTransaction { + private static final Logger logger = Logger.getLogger(SalesHistory.class.getName()); + private static List weeks = new ArrayList(); + private static List months = new ArrayList(); + private static List countries = new ArrayList(); + private static List channels = new ArrayList(); + private static List years = new ArrayList(); + private static List products = new ArrayList(); + private static List quarters = new ArrayList(); + private static boolean dataCached = false; + protected static Object lock = new Object(); + + public SalesHistory() { + } + + protected void cacheData(Connection connection) throws SQLException { + years = OracleUtilities.cacheColumnDistinctValues(connection, "TIMES", "CALENDAR_YEAR"); + // years.add("2013"); + // years.add("2013"); + // years.add("2013"); + // years.add("2013"); + // years.add("2013"); + // years.add("2013"); + // years.add("2013"); + // years.add("2013"); + // years.add("2012"); + // years.add("2012"); + // years.add("2012"); + // years.add("2012"); + // years.add("2012"); + // years.add("2012"); + // years.add("2011"); + // years.add("2011"); + // years.add("2011"); + // years.add("2010"); + // years.add("2010"); + // years.add("2010"); + // years.add("2010"); + // years.add("2012"); // Skew data to current year + // years.add("2012"); + // years.add("2011"); + // years.add("2009"); + // years.add("2009"); + // years.add("2009"); + // years.add("2008"); + // years.add("2008"); + weeks = OracleUtilities.cacheColumnDistinctValues(connection, "TIMES", "CALENDAR_WEEK_NUMBER"); + months = OracleUtilities.cacheColumnDistinctValues(connection, "TIMES", "CALENDAR_MONTH_DESC"); + quarters = OracleUtilities.cacheColumnDistinctValues(connection, "TIMES", "CALENDAR_QUARTER_DESC"); + countries = OracleUtilities.cacheColumnDistinctValues(connection, "COUNTRIES", "COUNTRY_ISO_CODE"); + channels = OracleUtilities.cacheColumnDistinctValues(connection, "CHANNELS", "CHANNEL_DESC"); + products = OracleUtilities.cacheColumnDistinctValues(connection, "PRODUCTS", "PROD_NAME"); + logger.fine("Cached sales history reference data"); + dataCached = true; + } + + protected String getRandomStringData(int minNom, int maxNom, List data, String surroundWith) { + String result = ""; + try { + int nofMon = RandomGenerator.randomInteger(minNom, maxNom); + int start = RandomGenerator.randomInteger(0, (data.size() - nofMon)); + for (int i = start; i < (start + nofMon); i++) { + if (surroundWith != null) + result = surroundWith + data.get(i).replaceAll("'", "''") + surroundWith + "," + result; + else + result = data.get(i).replaceAll("'", "''") + "," + result; + } + result = result.substring(0, result.length() - 1); + } catch (StringIndexOutOfBoundsException e) { + logger.log(Level.SEVERE, "Unexpected Exception in getRandomString. String is [ " + result + " ]"); + throw e; + } + return result; + } + + public List getMonths() { + return months; + } + + public List getCountries() { + return countries; + } + + public List getChannels() { + return channels; + } + + public boolean isDataCached() { + return dataCached; + } + + public List getYears() { + return years; + } + + public List getProducts() { + return products; + } + + public List getQuarters() { + return quarters; + } + + public List getWeeks() { + return weeks; + } +} diff --git a/src/com/dom/benchmarking/swingbench/dsstransactions/SalesMovingAverage.java b/src/com/dom/benchmarking/swingbench/dsstransactions/SalesMovingAverage.java new file mode 100644 index 0000000..768fd36 --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/dsstransactions/SalesMovingAverage.java @@ -0,0 +1,74 @@ +package com.dom.benchmarking.swingbench.dsstransactions; + + +import com.dom.benchmarking.swingbench.event.JdbcTaskEvent; +import com.dom.benchmarking.swingbench.kernel.SwingBenchException; +import com.dom.benchmarking.swingbench.kernel.SwingBenchTask; +import com.dom.util.OracleUtilities; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; + +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + + +public class SalesMovingAverage extends SalesHistory { + private static final Logger logger = Logger.getLogger(SalesMovingAverage.class.getName()); + + public SalesMovingAverage() { + } + + public void init(Map param) throws SwingBenchException { + try { + if (!isDataCached()) { + synchronized (lock) { + if (!isDataCached()) { + Connection connection = (Connection) param.get(SwingBenchTask.JDBC_CONNECTION); + cacheData(connection); + } + } + } + } catch (SQLException e) { + logger.log(Level.SEVERE, "Failed to cache data with the following exception : ", e); + throw new SwingBenchException(e); + } + } + + public void execute(Map param) throws SwingBenchException { + Connection connection = (Connection) param.get(SwingBenchTask.JDBC_CONNECTION); + initJdbcTask(); + long executeStart = System.nanoTime(); + try { + OracleUtilities.setModuleInfo(connection, "SalesMovingAverage"); + Statement st = connection.createStatement(); + String sql = + "SELECT t.time_id,\n" + + " to_char(SUM(amount_sold), '9,999,999,999') AS sales,\n" + + " to_char(AVG(SUM(amount_sold)) over(ORDER BY t.time_id range BETWEEN INTERVAL '2' DAY preceding AND INTERVAL '2' DAY following), '9,999,999,999') AS\n" + + "centered_5_day_avg\n" + + "FROM sales s,\n" + + " times t\n" + + "WHERE t.calendar_month_desc IN(" + getRandomStringData(2, 5, getMonths(), "'") + ")\n" + + " AND s.time_id = t.time_id\n" + + "GROUP BY t.time_id\n" + + "ORDER BY t.time_id"; + logger.finest(sql); + ResultSet rs = st.executeQuery(sql); + rs.next(); + rs.close(); + st.close(); + addSelectStatements(1); + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), true, getInfoArray())); + } catch (SQLException ex) { + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), false, getInfoArray())); + throw new SwingBenchException(ex); + } + } + + public void close() { + } +} diff --git a/src/com/dom/benchmarking/swingbench/dsstransactions/SalesRollupByMonth.java b/src/com/dom/benchmarking/swingbench/dsstransactions/SalesRollupByMonth.java new file mode 100644 index 0000000..0576481 --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/dsstransactions/SalesRollupByMonth.java @@ -0,0 +1,78 @@ +package com.dom.benchmarking.swingbench.dsstransactions; + + +import com.dom.benchmarking.swingbench.event.JdbcTaskEvent; +import com.dom.benchmarking.swingbench.kernel.SwingBenchException; +import com.dom.benchmarking.swingbench.kernel.SwingBenchTask; +import com.dom.util.OracleUtilities; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; + +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + + +public class SalesRollupByMonth extends SalesHistory { + + private static final Logger logger = Logger.getLogger(SalesRollupByMonth.class.getName()); + + public SalesRollupByMonth() { + } + + public void init(Map param) throws SwingBenchException { + try { + if (!isDataCached()) { + synchronized (lock) { + if (!isDataCached()) { + Connection connection = (Connection) param.get(SwingBenchTask.JDBC_CONNECTION); + cacheData(connection); + } + } + } + } catch (SQLException e) { + logger.log(Level.SEVERE, "Failed to cache data with the following exception : ", e); + throw new SwingBenchException(e); + } + } + + public void execute(Map param) throws SwingBenchException { + Connection connection = (Connection) param.get(SwingBenchTask.JDBC_CONNECTION); + initJdbcTask(); + long executeStart = System.nanoTime(); + try { + OracleUtilities.setModuleInfo(connection, "SalesRollupByMonth"); + Statement st = connection.createStatement(); + String sql = + "SELECT channels.channel_desc, calendar_month_desc, \n" + + " countries.country_iso_code,\n" + + " TO_CHAR(SUM(amount_sold), '9,999,999,999') SALES$\n" + + "FROM sales, customers, times, channels, countries\n" + + "WHERE sales.time_id=times.time_id \n" + + " AND sales.cust_id=customers.cust_id \n" + + " AND customers.country_id = countries.country_id\n" + + " AND sales.channel_id = channels.channel_id \n" + + " AND channels.channel_desc IN (" + getRandomStringData(1, 3, getChannels(), "'") + ") \n" + + " AND times.calendar_month_desc IN (" + getRandomStringData(2, 6, getMonths(), "'") + ") \n" + + " AND countries.country_iso_code IN (" + getRandomStringData(1, 4, getCountries(), "'") + ")\n" + + "GROUP BY \n" + + " ROLLUP(channels.channel_desc, calendar_month_desc, countries.country_iso_code)"; + logger.finest(sql); + ResultSet rs = st.executeQuery(sql); + rs.next(); + rs.close(); + st.close(); + addSelectStatements(1); + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), true, getInfoArray())); + } catch (SQLException ex) { + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), false, getInfoArray())); + throw new SwingBenchException(ex); + } + } + + public void close() { + } +} diff --git a/src/com/dom/benchmarking/swingbench/dsstransactions/SalesRollupByWeek.java b/src/com/dom/benchmarking/swingbench/dsstransactions/SalesRollupByWeek.java new file mode 100644 index 0000000..53d9c3f --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/dsstransactions/SalesRollupByWeek.java @@ -0,0 +1,79 @@ +package com.dom.benchmarking.swingbench.dsstransactions; + + +import com.dom.benchmarking.swingbench.event.JdbcTaskEvent; +import com.dom.benchmarking.swingbench.kernel.SwingBenchException; +import com.dom.benchmarking.swingbench.kernel.SwingBenchTask; +import com.dom.util.OracleUtilities; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; + +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + + +public class SalesRollupByWeek extends SalesHistory { + + private static final Logger logger = Logger.getLogger(SalesRollupByWeek.class.getName()); + + public SalesRollupByWeek() { + } + + public void init(Map param) throws SwingBenchException { + try { + if (!isDataCached()) { + synchronized (lock) { + if (!isDataCached()) { + Connection connection = (Connection) param.get(SwingBenchTask.JDBC_CONNECTION); + cacheData(connection); + } + } + } + } catch (SQLException e) { + logger.log(Level.SEVERE, "Failed to cache data with the following exception : ", e); + throw new SwingBenchException(e); + } + } + + public void execute(Map param) throws SwingBenchException { + Connection connection = (Connection) param.get(SwingBenchTask.JDBC_CONNECTION); + initJdbcTask(); + long executeStart = System.nanoTime(); + try { + OracleUtilities.setModuleInfo(connection, "SalesRollupByWeek"); + Statement st = connection.createStatement(); + String sql = + "SELECT channels.channel_desc, calendar_week_number, \n" + + " countries.country_iso_code,\n" + + " TO_CHAR(SUM(amount_sold), '9,999,999,999') SALES$\n" + + "FROM sales, customers, times, channels, countries\n" + + "WHERE sales.time_id=times.time_id \n" + + " AND sales.cust_id=customers.cust_id \n" + + " AND customers.country_id = countries.country_id\n" + + " AND sales.channel_id = channels.channel_id \n" + + " AND channels.channel_desc IN (" + getRandomStringData(1, 3, getChannels(), "'") + ") \n" + + " AND times.calendar_year = " + getRandomStringData(1, 2, getYears(), "'") + " \n" + + " AND times.calendar_week_number IN (" + getRandomStringData(2, 4, getWeeks(), "'") + ") \n" + + " AND countries.country_iso_code IN (" + getRandomStringData(1, 4, getCountries(), "'") + ")\n" + + "GROUP BY \n" + + " ROLLUP(channels.channel_desc, calendar_week_number, countries.country_iso_code)"; + logger.finest(sql); + ResultSet rs = st.executeQuery(sql); + rs.next(); + rs.close(); + st.close(); + addSelectStatements(1); + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), true, getInfoArray())); + } catch (SQLException ex) { + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), false, getInfoArray())); + throw new SwingBenchException(ex); + } + } + + public void close() { + } +} diff --git a/src/com/dom/benchmarking/swingbench/dsstransactions/SimpleLookUp.java b/src/com/dom/benchmarking/swingbench/dsstransactions/SimpleLookUp.java new file mode 100644 index 0000000..dfda4ec --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/dsstransactions/SimpleLookUp.java @@ -0,0 +1,54 @@ +package com.dom.benchmarking.swingbench.dsstransactions; + + +import com.dom.benchmarking.swingbench.event.JdbcTaskEvent; +import com.dom.benchmarking.swingbench.kernel.DatabaseTransaction; +import com.dom.benchmarking.swingbench.kernel.SwingBenchException; +import com.dom.benchmarking.swingbench.kernel.SwingBenchTask; +import com.dom.benchmarking.swingbench.utilities.RandomGenerator; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +import java.util.Map; + + +public class SimpleLookUp extends DatabaseTransaction { + + private PreparedStatement ps = null; + + public SimpleLookUp() { + } + + public void init(Map params) { + } + + public void execute(Map params) throws SwingBenchException { + Connection connection = (Connection) params.get(SwingBenchTask.JDBC_CONNECTION); + initJdbcTask(); + long executeStart = System.nanoTime(); + try { + if (ps == null) { + ps = connection.prepareStatement("select count(quantity_sold) from sales where cust_id = ?"); + } + + int ci = RandomGenerator.randomInteger(1, 1549999992); + ps.setInt(1, ci); + + ResultSet rs = ps.executeQuery(); + rs.next(); + rs.close(); + addSelectStatements(1); + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), true, getInfoArray())); + } catch (SQLException ex) { + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), false, getInfoArray())); + throw new SwingBenchException(ex); + } + } + + public void close() { + } + +} diff --git a/src/com/dom/benchmarking/swingbench/dsstransactions/TopSalesWithinQuarter.java b/src/com/dom/benchmarking/swingbench/dsstransactions/TopSalesWithinQuarter.java new file mode 100644 index 0000000..dc0d0e3 --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/dsstransactions/TopSalesWithinQuarter.java @@ -0,0 +1,87 @@ +package com.dom.benchmarking.swingbench.dsstransactions; + + +import com.dom.benchmarking.swingbench.event.JdbcTaskEvent; +import com.dom.benchmarking.swingbench.kernel.SwingBenchException; +import com.dom.benchmarking.swingbench.kernel.SwingBenchTask; +import com.dom.util.OracleUtilities; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; + +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + + +public class TopSalesWithinQuarter extends SalesHistory { + private static final Logger logger = Logger.getLogger(TopSalesWithinQuarter.class.getName()); + + public TopSalesWithinQuarter() { + } + + public void init(Map param) throws SwingBenchException { + try { + if (!isDataCached()) { + synchronized (lock) { + if (!isDataCached()) { + Connection connection = (Connection) param.get(SwingBenchTask.JDBC_CONNECTION); + cacheData(connection); + } + } + } + } catch (SQLException e) { + logger.log(Level.SEVERE, "Failed to cache data with the following exception : ", e); + throw new SwingBenchException(e); + } + } + + public void execute(Map param) throws SwingBenchException { + Connection connection = (Connection) param.get(SwingBenchTask.JDBC_CONNECTION); + initJdbcTask(); + long executeStart = System.nanoTime(); + try { + OracleUtilities.setModuleInfo(connection, "TopSalesWithinQuarter"); + String quarter = getRandomStringData(1, 2, getQuarters(), "'"); + Statement st = connection.createStatement(); + String sql = + "SELECT *\n" + + "FROM\n" + + " (SELECT times.calendar_quarter_desc,\n" + + " customers.cust_first_name,\n" + + " customers.cust_last_name,\n" + + " customers.cust_id,\n" + + " SUM(sales.amount_sold),\n" + + " rank() over(PARTITION BY times.calendar_quarter_desc\n" + + " ORDER BY SUM(amount_sold) DESC) AS\n" + + " rank_within_quarter\n" + + " FROM sales,\n" + + " customers,\n" + + " times\n" + + " WHERE sales.cust_id = customers.cust_id\n" + + " AND times.calendar_quarter_desc = " + quarter + "\n" + + " AND times.time_id = sales.time_id\n" + + " GROUP BY customers.cust_id,\n" + + " customers.cust_first_name,\n" + + " customers.cust_last_name,\n" + + " customers.cust_id,\n" + + " times.calendar_quarter_desc)\n" + + "WHERE rank_within_quarter < 16"; + logger.finest(sql); + ResultSet rs = st.executeQuery(sql); + rs.next(); + rs.close(); + st.close(); + addSelectStatements(1); + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), true, getInfoArray())); + } catch (SQLException ex) { + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), false, getInfoArray())); + throw new SwingBenchException(ex); + } + } + + public void close() { + } +} diff --git a/src/com/dom/benchmarking/swingbench/dsstransactions/TopSalesWithinWeek.java b/src/com/dom/benchmarking/swingbench/dsstransactions/TopSalesWithinWeek.java new file mode 100644 index 0000000..5fc5336 --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/dsstransactions/TopSalesWithinWeek.java @@ -0,0 +1,88 @@ +package com.dom.benchmarking.swingbench.dsstransactions; + + +import com.dom.benchmarking.swingbench.event.JdbcTaskEvent; +import com.dom.benchmarking.swingbench.kernel.SwingBenchException; +import com.dom.benchmarking.swingbench.kernel.SwingBenchTask; +import com.dom.util.OracleUtilities; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; + +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + + +public class TopSalesWithinWeek extends SalesHistory { + private static final Logger logger = Logger.getLogger(TopSalesWithinWeek.class.getName()); + + public TopSalesWithinWeek() { + } + + public void init(Map param) throws SwingBenchException { + try { + if (!isDataCached()) { + synchronized (lock) { + if (!isDataCached()) { + Connection connection = (Connection) param.get(SwingBenchTask.JDBC_CONNECTION); + cacheData(connection); + } + } + } + } catch (SQLException e) { + logger.log(Level.SEVERE, "Failed to cache data with the following exception : ", e); + throw new SwingBenchException(e); + } + } + + public void execute(Map param) throws SwingBenchException { + Connection connection = (Connection) param.get(SwingBenchTask.JDBC_CONNECTION); + initJdbcTask(); + long executeStart = System.nanoTime(); + try { + OracleUtilities.setModuleInfo(connection, "TopSalesWithinWeek"); + String quarter = getRandomStringData(1, 2, getWeeks(), "'"); + Statement st = connection.createStatement(); + String sql = + "SELECT *\n" + + "FROM\n" + + " (SELECT times.Calendar_Week_Number,\n" + + " customers.cust_first_name,\n" + + " customers.cust_last_name,\n" + + " customers.cust_id,\n" + + " SUM(sales.amount_sold),\n" + + " rank() over(PARTITION BY times.Calendar_Week_Number\n" + + " ORDER BY SUM(amount_sold) DESC) AS\n" + + " rank_within_week\n" + + " FROM sales,\n" + + " customers,\n" + + " times\n" + + " WHERE sales.cust_id = customers.cust_id\n" + + " AND times.calendar_week_number = " + getRandomStringData(1, 2, getWeeks(), "'") + " \n" + + " AND times.calendar_year = " + getRandomStringData(1, 2, getYears(), "'") + " \n" + + " AND times.time_id = sales.time_id\n" + + " GROUP BY customers.cust_id,\n" + + " customers.cust_first_name,\n" + + " customers.cust_last_name,\n" + + " customers.cust_id,\n" + + " times.Calendar_Week_Number)\n" + + "WHERE rank_within_week < 16"; + logger.finest(sql); + ResultSet rs = st.executeQuery(sql); + rs.next(); + rs.close(); + st.close(); + addSelectStatements(1); + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), true, getInfoArray())); + } catch (SQLException ex) { + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), false, getInfoArray())); + throw new SwingBenchException(ex); + } + } + + public void close() { + } +} diff --git a/src/com/dom/benchmarking/swingbench/dsstransactions/WeekToWeekComparison.java b/src/com/dom/benchmarking/swingbench/dsstransactions/WeekToWeekComparison.java new file mode 100644 index 0000000..e5c5b2b --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/dsstransactions/WeekToWeekComparison.java @@ -0,0 +1,125 @@ +package com.dom.benchmarking.swingbench.dsstransactions; + + +import com.dom.benchmarking.swingbench.event.JdbcTaskEvent; +import com.dom.benchmarking.swingbench.kernel.SwingBenchException; +import com.dom.benchmarking.swingbench.kernel.SwingBenchTask; +import com.dom.benchmarking.swingbench.utilities.RandomGenerator; +import com.dom.util.OracleUtilities; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; + +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + + +public class WeekToWeekComparison extends SalesHistory { + private static final Logger logger = Logger.getLogger(WeekToWeekComparison.class.getName()); + + public WeekToWeekComparison() { + } + + public void init(Map param) throws SwingBenchException { + try { + if (!isDataCached()) { + synchronized (lock) { + if (!isDataCached()) { + Connection connection = (Connection) param.get(SwingBenchTask.JDBC_CONNECTION); + cacheData(connection); + } + } + } + } catch (SQLException e) { + logger.log(Level.SEVERE, "Failed to cache data with the following exception : ", e); + throw new SwingBenchException(e); + } + } + + public void execute(Map param) throws SwingBenchException { + Connection connection = (Connection) param.get(SwingBenchTask.JDBC_CONNECTION); + initJdbcTask(); + long executeStart = System.nanoTime(); + try { + OracleUtilities.setModuleInfo(connection, "WeekToWeekComparison"); + Statement st = connection.createStatement(); + String yearRange = getRandomStringData(2, 3, getYears(), null); + String lastYear = yearRange.substring(yearRange.indexOf(",") + 1, yearRange.length()); + int minWeek = RandomGenerator.randomInteger(1, 51); + + String selectedProduct = getRandomStringData(1, 2, getProducts(), "'"); + + String sql = + "WITH v AS\n" + + " (SELECT p.Prod_Name Product_Name,\n" + + " t.Calendar_Year YEAR,\n" + + " t.Calendar_Week_Number Week,\n" + + " SUM(Amount_Sold) Sales\n" + + " FROM Sales s,\n" + + " Times t,\n" + + " Products p\n" + + " WHERE s.Time_id = t.Time_id\n" + + " AND s.Prod_id = p.Prod_id\n" + + " AND p.Prod_name IN (" + selectedProduct + ")\n" + + " and T.CALENDAR_YEAR IN (" + yearRange + ")\n" + + " AND t.Calendar_Week_Number = " + minWeek + "\n" + + " GROUP BY p.Prod_Name,\n" + + " t.Calendar_Year,\n" + + " t.Calendar_Week_Number\n" + + " )\n" + + "SELECT Product_Name Prod,\n" + + " YEAR,\n" + + " Week,\n" + + " Sales,\n" + + " Weekly_ytd_sales,\n" + + " Weekly_ytd_sales_prior_year\n" + + "FROM\n" + + " (SELECT --Start of year_over_year sales\n" + + " Product_Name,\n" + + " YEAR,\n" + + " Week,\n" + + " Sales,\n" + + " Weekly_ytd_sales,\n" + + " LAG(Weekly_ytd_sales, 1) OVER (PARTITION BY Product_Name, Week ORDER BY YEAR) Weekly_ytd_sales_prior_year\n" + + " FROM\n" + + " (SELECT -- Start of dense_sales\n" + + " v.Product_Name Product_Name,\n" + + " t.Year YEAR,\n" + + " t.Week Week,\n" + + " NVL(v.Sales,0) Sales,\n" + + " SUM(NVL(v.Sales,0)) OVER (PARTITION BY v.Product_Name, t.Year ORDER BY t.week) weekly_ytd_sales\n" + + " FROM v PARTITION BY (v.Product_Name)\n" + + " RIGHT OUTER JOIN\n" + + " (SELECT DISTINCT Calendar_Week_Number Week,\n" + + " Calendar_Year YEAR\n" + + " FROM Times\n" + + " WHERE Calendar_Year IN (" + yearRange + ")\n" + + " ) t\n" + + " ON (v.week = t.week\n" + + " AND v.Year = t.Year)\n" + + " ) dense_sales\n" + + " ) year_over_year_sales\n" + + "where year = " + lastYear + "\n" + + "AND WEEK = " + minWeek + "\n" + + "ORDER BY 1,2,3"; + + + logger.finest(sql); + ResultSet rs = st.executeQuery(sql); + rs.next(); + rs.close(); + st.close(); + addSelectStatements(1); + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), true, getInfoArray())); + } catch (SQLException ex) { + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), false, getInfoArray())); + throw new SwingBenchException(ex); + } + } + + public void close() { + } +} diff --git a/src/com/dom/benchmarking/swingbench/plsqltransactions/BrowseAndUpdateOrders.java b/src/com/dom/benchmarking/swingbench/plsqltransactions/BrowseAndUpdateOrders.java new file mode 100644 index 0000000..1530b75 --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/plsqltransactions/BrowseAndUpdateOrders.java @@ -0,0 +1,75 @@ +package com.dom.benchmarking.swingbench.plsqltransactions; + + +import com.dom.benchmarking.swingbench.event.JdbcTaskEvent; +import com.dom.benchmarking.swingbench.kernel.SwingBenchException; +import com.dom.benchmarking.swingbench.kernel.SwingBenchTask; +import com.dom.benchmarking.swingbench.utilities.RandomGenerator; + +import java.sql.CallableStatement; +import java.sql.Connection; +import java.sql.SQLException; + +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + +import oracle.jdbc.OracleTypes; + + +public class BrowseAndUpdateOrders extends OrderEntryProcess { + private static final Logger logger = Logger.getLogger(BrowseAndUpdateOrders.class.getName()); + + public BrowseAndUpdateOrders() { + } + + public void close() { + } + + public void init(Map params) { + Connection connection = (Connection) params.get(SwingBenchTask.JDBC_CONNECTION); + try { + this.parseCommitClientSide(params); + this.setCommitClientSide(connection, commitClientSide); + this.getMaxandMinCustID(connection, params); + } catch (SQLException se) { + logger.log(Level.SEVERE, "Unable to get max and min customer id", se); + } + } + + public void execute(Map params) throws SwingBenchException { + Connection connection = (Connection) params.get(SwingBenchTask.JDBC_CONNECTION); + + int queryTimeOut = 60; + + if (params.get(SwingBenchTask.QUERY_TIMEOUT) != null) { + queryTimeOut = (Integer) (params.get(SwingBenchTask.QUERY_TIMEOUT)); + } + + long executeStart = System.nanoTime(); + initJdbcTask(); + try { + try (CallableStatement cs = connection.prepareCall("{? = call orderentry.browseandupdateorders(?,?,?)}")) { + cs.registerOutParameter(1, OracleTypes.VARCHAR); + cs.setLong(2, RandomGenerator.randomLong(MIN_CUSTID, MAX_CUSTID)); + cs.setInt(3, (int) this.getMinSleepTime()); + cs.setInt(4, (int) this.getMaxSleepTime()); + cs.setQueryTimeout(queryTimeOut); + cs.executeUpdate(); + parseInfoArray(cs.getString(1)); + this.commit(connection); + } catch (Exception se) { + throw new SwingBenchException(se); + } + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), true, getInfoArray())); + } catch (SwingBenchException ex) { + addRollbackStatements(1); + try { + connection.rollback(); + } catch (SQLException ignored) { + } + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), false, getInfoArray())); + throw ex; + } + } +} diff --git a/src/com/dom/benchmarking/swingbench/plsqltransactions/BrowseProducts.java b/src/com/dom/benchmarking/swingbench/plsqltransactions/BrowseProducts.java new file mode 100644 index 0000000..43905b3 --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/plsqltransactions/BrowseProducts.java @@ -0,0 +1,76 @@ +package com.dom.benchmarking.swingbench.plsqltransactions; + + +import com.dom.benchmarking.swingbench.event.JdbcTaskEvent; +import com.dom.benchmarking.swingbench.kernel.SwingBenchException; +import com.dom.benchmarking.swingbench.kernel.SwingBenchTask; +import com.dom.benchmarking.swingbench.utilities.RandomGenerator; +import oracle.jdbc.OracleTypes; + +import java.sql.CallableStatement; +import java.sql.Connection; +import java.sql.SQLException; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + + +public class BrowseProducts extends OrderEntryProcess { + private static final Logger logger = Logger.getLogger(BrowseProducts.class.getName()); + + public BrowseProducts() { + } + + public void init(Map params) throws SwingBenchException { + + Connection connection = (Connection) params.get(SwingBenchTask.JDBC_CONNECTION); + Boolean commitClientSide = Boolean.parseBoolean((String) params.get(SwingBenchTask.COMMIT_CLIENT_SIDE)); + try { + this.setCommitClientSide(connection, commitClientSide); + this.getMaxandMinCustID(connection, params); + } catch (SQLException se) { + logger.log(Level.SEVERE, "Unable to get max and min customer id", se); + } + } + + public void execute(Map params) throws SwingBenchException { + Connection connection = (Connection) params.get(SwingBenchTask.JDBC_CONNECTION); + + int queryTimeOut = 60; + + if (params.get(SwingBenchTask.QUERY_TIMEOUT) != null) { + queryTimeOut = ((Integer) (params.get(SwingBenchTask.QUERY_TIMEOUT))).intValue(); + } + + long executeStart = System.nanoTime(); + initJdbcTask(); + + try { + try (CallableStatement cs = connection.prepareCall("{? = call orderentry.browseproducts(?,?,?)}")) { + cs.registerOutParameter(1, OracleTypes.VARCHAR); + cs.setLong(2, RandomGenerator.randomLong(MIN_CUSTID, MAX_CUSTID)); + cs.setInt(3, (int) this.getMinSleepTime()); + cs.setInt(4, (int) this.getMaxSleepTime()); + cs.setQueryTimeout(queryTimeOut); + cs.executeUpdate(); + parseInfoArray(cs.getString(1)); + this.commit(connection); + } catch (Exception se) { + throw new SwingBenchException(se); + } + + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), true, getInfoArray())); //infoArray)); + } catch (SwingBenchException ex) { + addRollbackStatements(1); + try { + connection.rollback(); + } catch (SQLException ignored) { + } + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), false, getInfoArray())); + throw ex; + } + } + + public void close() { + } +} diff --git a/src/com/dom/benchmarking/swingbench/plsqltransactions/NewCustomerProcess.java b/src/com/dom/benchmarking/swingbench/plsqltransactions/NewCustomerProcess.java new file mode 100644 index 0000000..85e2ebb --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/plsqltransactions/NewCustomerProcess.java @@ -0,0 +1,152 @@ +package com.dom.benchmarking.swingbench.plsqltransactions; + + +import com.dom.benchmarking.swingbench.event.JdbcTaskEvent; +import com.dom.benchmarking.swingbench.kernel.SwingBenchException; +import com.dom.benchmarking.swingbench.kernel.SwingBenchTask; +import com.dom.benchmarking.swingbench.utilities.RandomGenerator; +import oracle.jdbc.OracleTypes; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.sql.CallableStatement; +import java.sql.Connection; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Map; +import java.util.StringTokenizer; +import java.util.logging.Level; +import java.util.logging.Logger; + + +public class NewCustomerProcess extends OrderEntryProcess { + + private static final Logger logger = Logger.getLogger(NewCustomerProcess.class.getName()); + private static final String NAMES_FILE = "data/names.txt"; + private static final String NLS_FILE = "data/nls.txt"; + private static ArrayList firstNames = null; + private static ArrayList lastNames = null; + private static ArrayList nlsInfo = null; + private static final Object lock = new Object(); + + public NewCustomerProcess() { + } + + public void init(Map params) throws SwingBenchException { + Connection connection = (Connection) params.get(SwingBenchTask.JDBC_CONNECTION); + + + boolean initCompleted = false; + + if ((firstNames == null) || !initCompleted) { // load any data you might need (in this case only once) + synchronized (lock) { + if (firstNames == null) { + firstNames = new ArrayList<>(); + lastNames = new ArrayList<>(); + nlsInfo = new ArrayList<>(); + + String value = (String) params.get("SOE_NAMESDATA_LOC"); + File namesFile = new File((value == null) ? NAMES_FILE : value); + value = (String) params.get("SOE_NLSDATA_LOC"); + File nlsFile = new File((value == null) ? NLS_FILE : value); + + try { + BufferedReader br = new BufferedReader(new FileReader(namesFile)); + String data = null; + String firstName = null; + String lastName = null; + + while ((data = br.readLine()) != null) { + StringTokenizer st = new StringTokenizer(data, ","); + firstName = st.nextToken(); + lastName = st.nextToken(); + firstNames.add(firstName); + lastNames.add(lastName); + } + br.close(); + value = (String) params.get("SOE_NLSDATA_LOC"); + br = new BufferedReader(new FileReader(nlsFile)); + + while ((data = br.readLine()) != null) { + NLSSupport nls = new NLSSupport(); + StringTokenizer st = new StringTokenizer(data, ","); + nls.language = st.nextToken(); + nls.territory = st.nextToken(); + nlsInfo.add(nls); + } + br.close(); + this.parseCommitClientSide(params); + this.setCommitClientSide(connection, commitClientSide); + logger.fine("Successfully loaded transaction data"); + } catch (java.io.FileNotFoundException fne) { + logger.log(Level.SEVERE, "Unable to open file : " + namesFile.getAbsolutePath() + " : " + nlsFile.getAbsolutePath(), fne); + throw new SwingBenchException(fne); + } catch (java.io.IOException ioe) { + logger.log(Level.SEVERE, "IO problems opening " + namesFile.getAbsolutePath(), ioe); + throw new SwingBenchException(ioe); + } catch (SQLException se) { + logger.log(Level.SEVERE, "Failed while attempting to set commit profile", se); + throw new SwingBenchException(se); + } + logger.fine("Completed initialisation of NewCustomerProcess"); + } + + initCompleted = true; + } + } + } + + public void execute(Map params) throws SwingBenchException { + Connection connection = (Connection) params.get(SwingBenchTask.JDBC_CONNECTION); + int queryTimeOut = 60; + + if (params.get(SwingBenchTask.QUERY_TIMEOUT) != null) { + queryTimeOut = (Integer) (params.get(SwingBenchTask.QUERY_TIMEOUT)); + } + + String firstName = firstNames.get(RandomGenerator.randomInteger(0, firstNames.size())); + String lastName = lastNames.get(RandomGenerator.randomInteger(0, lastNames.size())); + NLSSupport nls = nlsInfo.get(RandomGenerator.randomInteger(0, nlsInfo.size())); + + long executeStart = System.nanoTime(); + initJdbcTask(); + try { + try (CallableStatement cs = connection.prepareCall("{? = call orderentry.newcustomer(?,?,?,?,?,?)}")) { + cs.registerOutParameter(1, OracleTypes.VARCHAR); + cs.setString(2, firstName); + cs.setString(3, lastName); + cs.setString(4, nls.language); + cs.setString(5, nls.territory); + cs.setInt(6, (int) this.getMinSleepTime()); + cs.setInt(7, (int) this.getMaxSleepTime()); + cs.setQueryTimeout(queryTimeOut); + cs.executeUpdate(); + parseInfoArray(cs.getString(1)); + this.commit(connection); + } catch (Exception se) { + throw new SwingBenchException(se); + } + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), true, getInfoArray())); + } catch (SwingBenchException ex) { + addRollbackStatements(1); + try { + connection.rollback(); + } catch (SQLException ignore) { + } + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), false, getInfoArray())); + throw ex; + } + } + + public void close() { + } + + private class NLSSupport { + + String language = null; + String territory = null; + + } + +} diff --git a/src/com/dom/benchmarking/swingbench/plsqltransactions/NewCustomerProcessV2.java b/src/com/dom/benchmarking/swingbench/plsqltransactions/NewCustomerProcessV2.java new file mode 100644 index 0000000..3ebfe3b --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/plsqltransactions/NewCustomerProcessV2.java @@ -0,0 +1,168 @@ +package com.dom.benchmarking.swingbench.plsqltransactions; + + +import com.dom.benchmarking.swingbench.event.JdbcTaskEvent; +import com.dom.benchmarking.swingbench.kernel.SwingBenchException; +import com.dom.benchmarking.swingbench.kernel.SwingBenchTask; +import com.dom.benchmarking.swingbench.utilities.RandomGenerator; +import com.dom.util.Utilities; + +import java.io.File; + +import java.sql.CallableStatement; +import java.sql.Connection; +import java.sql.SQLException; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.StringTokenizer; +import java.util.logging.Level; +import java.util.logging.Logger; + +import oracle.jdbc.OracleTypes; + + +public class NewCustomerProcessV2 extends OrderEntryProcess { + + private static final Logger logger = Logger.getLogger(NewCustomerProcessV2.class.getName()); + private static final String COUNTIES_FILE = "data/counties.txt"; + private static final String COUNTRIES_FILE = "data/countries.txt"; + private static final String FIRST_NAMES_FILE = "data/lowerfirstnames.txt"; + private static final String LAST_NAMES_FILE = "data/lowerlastnames.txt"; + private static final String NLS_FILE = "data/nls.txt"; + private static final String TOWNS_FILE = "data/towns.txt"; + private static List nlsInfo = new ArrayList<>(); + private static List counties = null; + private static List countries = null; + private static List firstNames = null; + private static List lastNames = null; + private static List nlsInfoRaw = null; + private static List towns = null; + private static final Object lock = new Object(); + + public NewCustomerProcessV2() { + } + + public void init(Map params) throws SwingBenchException { + boolean initCompleted = false; + + if ((firstNames == null) || !initCompleted) { // load any data you might need (in this case only once) + + synchronized (lock) { + if (firstNames == null) { + + String value = (String) params.get("SOE_FIRST_NAMES_LOC"); + File firstNamesFile = new File((value == null) ? FIRST_NAMES_FILE : value); + value = (String) params.get("SOE_LAST_NAMES_LOC"); + File lastNamesFile = new File((value == null) ? LAST_NAMES_FILE : value); + value = (String) params.get("SOE_NLSDATA_LOC"); + File nlsFile = new File((value == null) ? NLS_FILE : value); + value = (String) params.get("SOE_TOWNS_LOC"); + File townsFile = new File((value == null) ? TOWNS_FILE : value); + value = (String) params.get("SOE_COUNTIES_LOC"); + File countiesFile = new File((value == null) ? COUNTIES_FILE : value); + value = (String) params.get("SOE_COUNTRIES_LOC"); + File countriesFile = new File((value == null) ? COUNTRIES_FILE : value); + + try { + firstNames = Utilities.cacheFile(firstNamesFile); + lastNames = Utilities.cacheFile(lastNamesFile); + nlsInfoRaw = Utilities.cacheFile(nlsFile); + counties = Utilities.cacheFile(countiesFile); + towns = Utilities.cacheFile(townsFile); + countries = Utilities.cacheFile(countriesFile); + + for (String rawData : nlsInfoRaw) { + NLSSupport nls = new NLSSupport(); + StringTokenizer st = new StringTokenizer(rawData, ","); + nls.language = st.nextToken(); + nls.territory = st.nextToken(); + nlsInfo.add(nls); + } + logger.fine("Completed reading files needed for initialisation of NewCustomerProcess()"); + Connection connection = (Connection) params.get(SwingBenchTask.JDBC_CONNECTION); + this.parseCommitClientSide(params); + this.setCommitClientSide(connection, commitClientSide); + initCompleted = true; + } catch (SQLException se) { + logger.log(Level.SEVERE, "Unable to get connection : ", se); + throw new SwingBenchException(se); + } catch (java.io.FileNotFoundException fne) { + logger.log(Level.SEVERE, "Unable to open data seed files : ", fne); + throw new SwingBenchException(fne); + } catch (java.io.IOException ioe) { + logger.log(Level.SEVERE, "IO problem opening seed files : ", ioe); + throw new SwingBenchException(ioe); + } + } + + + } + } + } + + public void execute(Map params) throws SwingBenchException { + + Connection connection = (Connection) params.get(SwingBenchTask.JDBC_CONNECTION); + int queryTimeOut = 60; + + if (params.get(SwingBenchTask.QUERY_TIMEOUT) != null) { + queryTimeOut = (Integer) (params.get(SwingBenchTask.QUERY_TIMEOUT)); + } + + String firstName = firstNames.get(RandomGenerator.randomInteger(0, firstNames.size())); + String lastName = lastNames.get(RandomGenerator.randomInteger(0, lastNames.size())); + String town = towns.get(RandomGenerator.randomInteger(0, towns.size())); + String county = counties.get(RandomGenerator.randomInteger(0, counties.size())); + String country = countries.get(RandomGenerator.randomInteger(0, countries.size())); + NLSSupport nls = nlsInfo.get(RandomGenerator.randomInteger(0, nlsInfo.size())); + + long executeStart = System.nanoTime(); + initJdbcTask(); + boolean sucessfulTransaction = true; + try { + try (CallableStatement cs = connection.prepareCall("{? = call orderentry.newcustomer(?,?,?,?,?,?,?,?,?)}")) { + cs.registerOutParameter(1, OracleTypes.VARCHAR); + cs.setString(2, firstName); + cs.setString(3, lastName); + cs.setString(4, nls.language); + cs.setString(5, nls.territory); + cs.setString(6, town); + cs.setString(7, county); + cs.setString(8, country); + cs.setInt(9, (int) this.getMinSleepTime()); + cs.setInt(10, (int) this.getMaxSleepTime()); + cs.setQueryTimeout(queryTimeOut); + cs.executeUpdate(); + parseInfoArray(cs.getString(1)); + if (getRollbackStatements() != 0) + sucessfulTransaction = false; + this.commit(connection); + } catch (Exception se) { + throw new SwingBenchException(se); + } + + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), sucessfulTransaction, getInfoArray())); + } catch (SwingBenchException ex) { + addRollbackStatements(1); + try { + connection.rollback(); + } catch (SQLException ignored) { + } + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), false, getInfoArray())); + throw ex; + } + } + + public void close() { + } + + private class NLSSupport { + + String language = null; + String territory = null; + + } + +} diff --git a/src/com/dom/benchmarking/swingbench/plsqltransactions/NewOrderProcess.java b/src/com/dom/benchmarking/swingbench/plsqltransactions/NewOrderProcess.java new file mode 100644 index 0000000..bf45c68 --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/plsqltransactions/NewOrderProcess.java @@ -0,0 +1,79 @@ +package com.dom.benchmarking.swingbench.plsqltransactions; + + +import com.dom.benchmarking.swingbench.event.JdbcTaskEvent; +import com.dom.benchmarking.swingbench.kernel.SwingBenchException; +import com.dom.benchmarking.swingbench.kernel.SwingBenchTask; +import com.dom.benchmarking.swingbench.utilities.RandomGenerator; +import oracle.jdbc.OracleTypes; + +import java.sql.CallableStatement; +import java.sql.Connection; +import java.sql.SQLException; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + + +public class NewOrderProcess extends OrderEntryProcess { + private static final Logger logger = Logger.getLogger(NewOrderProcess.class.getName()); + + public NewOrderProcess() { + } + + public void init(Map params) throws SwingBenchException { + Connection connection = (Connection) params.get(SwingBenchTask.JDBC_CONNECTION); + String param = (String) params.get("SOE_IS_STATIC"); + boolean isStatic = (param != null) ? Boolean.valueOf(param) : false; + try { + this.parseCommitClientSide(params); + this.setCommitClientSide(connection, commitClientSide); + this.setIsStatic(isStatic, connection); + } catch (SQLException se) { + logger.log(Level.SEVERE, "Unable to get max and min customer id", se); + } + } + + public void execute(Map params) throws SwingBenchException { + Connection connection = (Connection) params.get(SwingBenchTask.JDBC_CONNECTION); + int queryTimeOut = 60; + + if (params.get(SwingBenchTask.QUERY_TIMEOUT) != null) { + queryTimeOut = (Integer) (params.get(SwingBenchTask.QUERY_TIMEOUT)); + } + + long executeStart = System.nanoTime(); + initJdbcTask(); + boolean sucessfulTransaction = true; + + try { + try (CallableStatement cs = connection.prepareCall("{? = call orderentry.neworder(?,?,?)}")) { + cs.registerOutParameter(1, OracleTypes.VARCHAR); + cs.setLong(2, RandomGenerator.randomLong(MIN_CUSTID, MAX_CUSTID)); + cs.setInt(3, (int) this.getMinSleepTime()); + cs.setInt(4, (int) this.getMaxSleepTime()); + cs.setQueryTimeout(queryTimeOut); + cs.executeUpdate(); + parseInfoArray(cs.getString(1)); + if (getRollbackStatements() != 0) + sucessfulTransaction = false; + this.commit(connection); + } catch (Exception se) { + throw new SwingBenchException(se); + } + processTransactionEvent(new JdbcTaskEvent(this, getId(), System.nanoTime() - executeStart, sucessfulTransaction, getInfoArray())); + } catch (SwingBenchException ex) { + addRollbackStatements(1); + try { + connection.rollback(); + } catch (SQLException ignored) { + } + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), false, getInfoArray())); + throw ex; + } + + } + + public void close() { + } +} diff --git a/src/com/dom/benchmarking/swingbench/plsqltransactions/OrderEntryProcess.java b/src/com/dom/benchmarking/swingbench/plsqltransactions/OrderEntryProcess.java new file mode 100644 index 0000000..a4bd71d --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/plsqltransactions/OrderEntryProcess.java @@ -0,0 +1,188 @@ +package com.dom.benchmarking.swingbench.plsqltransactions; + + +import com.dom.benchmarking.swingbench.constants.Constants; +import com.dom.benchmarking.swingbench.kernel.DatabaseTransaction; +import com.dom.benchmarking.swingbench.kernel.SwingBenchTask; + +import java.sql.*; +import java.util.Map; +import java.util.StringTokenizer; +import java.util.logging.Logger; + + +public abstract class OrderEntryProcess extends DatabaseTransaction { + + private static final Logger logger = Logger.getLogger(OrderEntryProcess.class.getName()); + // static final String NEW_CUSTOMER = "New Customer"; +// static final String CUTOMER_ORDER = "Customer Order"; +// static final String CUSTOMER_BROWSE = "Customer Browse"; +// static final String GET_CUSTOMER_SEQ_TX = "Get Customer Sequence"; +// static final String GET_ORDER_SEQ_TX = "Get Order Sequence"; +// static final String INSERT_CUSTOMER_TX = "Insert New Customer"; +// static final String INSERT_ITEM_TX = "Insert Order Item"; +// static final String INSERT_ORDER_TX = "Insert Order"; +// static final String UPDATE_ORDER_TX = "Update Order"; +// static final String UPDATE_WAREHOUSE_TX = "Update Warehouse"; +// static final String GET_CUSTOMER_DETAILS_TX = "Get Customer Details"; +// static final String BROWSE_PENDING_ORDERS = "Browse Pending Orders"; +// static final String BROWSE_BY_PROD_ID = "Browse Product by ID"; +// static final String BROWSE_BY_CATEGORY_TX = "Browse Products by Category"; +// static final String BROWSE_BY_CAT_QUAN_TX = "Browse Products by Quantity"; +// static final String BROWSE_BY_ORDER_ID = "Browse Orders by ID"; +// static final String BROWSE_ORDER_DETAILS = "Browse Order Details"; +// static final String UPDATE_PENDING_ORDERS = "Update Pending Orders"; +// static final String GET_ORDER_BY_CUSTOMER_TX = "Browse Order by Customer"; +// static final int MIN_CATEGORY = 11; +// static final int MAX_CATEGORY = 39; +// static final int MAX_BROWSE_CATEGORY = 6; +// static final int MAX_CREDITLIMIT = 5000; +// static final int MIN_CREDITLIMIT = 100; +// static final int MIN_SALESID = 145; +// static final int MAX_SALESID = 171; +// static final int MIN_PRODS_TO_BUY = 2; +// static final int MAX_PRODS_TO_BUY = 6; +// static final int MIN_PROD_ID = 1726; +// static final int MAX_PROD_ID = 3515; + static final int MIN_WAREHOUSE_ID = 1; + static final int MAX_WAREHOUSE_ID = 1000; + // static final int AWAITING_PROCESSING = 4; +// static final int ORDER_PROCESSED = 10; + static long MIN_CUSTID = 0; + static long MAX_CUSTID = 0; + static long MIN_ORDERID = 0; + static long MAX_ORDERID = 0; + + private static boolean isInitCompleted = false; + static boolean commitClientSide = false; + private final static Object lock = new Object(); + + public void commit(Connection connection) throws SQLException { + if (commitClientSide) { + connection.commit(); + addCommitStatements(1); + } + } + + void setCommitClientSide(Connection connection, boolean commitClientSide) throws SQLException { + CallableStatement cs = connection.prepareCall("{call orderentry.setPLSQLCOMMIT(?)}"); + cs.setString(1, Boolean.toString(!commitClientSide)); + cs.executeUpdate(); + cs.close(); + } + + void parseCommitClientSide(Map params) { + this.commitClientSide = Boolean.parseBoolean((String) params.get(SwingBenchTask.COMMIT_CLIENT_SIDE)); + } + + public void getMaxandMinCustID(Connection connection, Map params) throws SQLException { + + if (MAX_CUSTID == 0) { // load any data you might need (in this case only once) + + synchronized (lock) { + if (MAX_CUSTID == 0) { + String minCI = (String) params.get(Constants.SOEMINCUSTOMERID); + String maxCI = (String) params.get(Constants.SOEMAXCUSTOMERID); + if ((minCI != null) && (maxCI != null)) { + logger.fine("Acquiring customer counts from environment variables"); + MIN_CUSTID = Long.parseLong(minCI); + MAX_CUSTID = Long.parseLong(maxCI); + } else { + PreparedStatement ps = connection.prepareStatement("select 1 from user_tables where table_name = 'ORDERENTRY_METADATA'"); + ResultSet trs = ps.executeQuery(); + if (trs.next()) { + logger.fine("Acquiring customer counts from metadata table"); + PreparedStatement vps = connection.prepareStatement("select metadata_key, metadata_value from ORDERENTRY_METADATA"); + ResultSet vrs = vps.executeQuery(); + while (vrs.next()) { + if (vrs.getString(1).equals("SOE_MIN_ORDER_ID")) { + MIN_ORDERID = Long.parseLong(vrs.getString(2)); + } else if (vrs.getString(1).equals("SOE_MAX_ORDER_ID")) { + MAX_ORDERID = Long.parseLong(vrs.getString(2)); + } else if (vrs.getString(1).equals("SOE_MIN_CUSTOMER_ID")) { + MIN_CUSTID = Long.parseLong(vrs.getString(2)); + } else if (vrs.getString(1).equals("SOE_MAX_CUSTOMER_ID")) { + MAX_CUSTID = Long.parseLong(vrs.getString(2)); + } + } + vrs.close(); + vps.close(); + } else { + logger.fine("Acquiring customer counts from database"); + + PreparedStatement mmPs = connection.prepareStatement("select min(customer_id), max(customer_id) from customers"); + ResultSet rs = mmPs.executeQuery(); + + if (rs.next()) { + MIN_CUSTID = rs.getInt(1); + MAX_CUSTID = rs.getInt(2); + } + logger.fine("Min CustomerID = " + MIN_CUSTID + ", Max CustomerID = " + MAX_CUSTID); + rs.close(); + mmPs.close(); //should be called only once; + + mmPs = connection.prepareStatement("select min(order_id), max(order_id) from orders"); + rs = mmPs.executeQuery(); + + if (rs.next()) { + MIN_ORDERID = rs.getInt(1); + MAX_ORDERID = rs.getInt(2); + } + logger.fine("Min CustomerID = " + MIN_CUSTID + ", Max CustomerID = " + MAX_CUSTID); + rs.close(); + mmPs.close(); //should be called only once; + } + + trs.close(); + ps.close(); + } + } + } + + } + } + + + public int[] parseInfoArray(String data) throws Exception { + int[] result = new int[7]; + try { + StringTokenizer st = new StringTokenizer(data, ","); + result[SELECT_STATEMENTS] = Integer.parseInt(st.nextToken()); + result[INSERT_STATEMENTS] = Integer.parseInt(st.nextToken()); + result[UPDATE_STATEMENTS] = Integer.parseInt(st.nextToken()); + result[DELETE_STATEMENTS] = Integer.parseInt(st.nextToken()); + result[COMMIT_STATEMENTS] = Integer.parseInt(st.nextToken()); + result[ROLLBACK_STATEMENTS] = Integer.parseInt(st.nextToken()); + result[SLEEP_TIME_LOC] = Integer.parseInt(st.nextToken()); + setDMLArray(result); + return result; + } catch (Exception e) { + throw new Exception("Unable to parse string returned from OrderEntry Package. String = " + data, e); + } + } + + void setIsStatic(boolean isStatic, Connection connection) throws SQLException { + if (isStatic) { + synchronized (lock) { + if (!isInitCompleted) { + logger.fine("Runing OrderEntry benchmark in constant mode" + isInitCompleted); + CallableStatement cs = connection.prepareCall("{call orderentry.setIsStatic(?)}"); + cs.setString(1, Boolean.toString(isStatic)); + cs.execute(); + cs.close(); + isInitCompleted = true; + } + } + } + } + +// public void setDMLstatements(int[] dmlArray) { +// addSelectStatements(dmlArray[SELECT_STATEMENTS]); +// addInsertStatements(dmlArray[INSERT_STATEMENTS]); +// addUpdateStatements(dmlArray[UPDATE_STATEMENTS]); +// addDeleteStatements(dmlArray[DELETE_STATEMENTS]); +// addCommitStatements(dmlArray[COMMIT_STATEMENTS]); +// addRollbackStatements(dmlArray[ROLLBACK_STATEMENTS]); +// } + +} diff --git a/src/com/dom/benchmarking/swingbench/plsqltransactions/OrdersByCountyQuery.java b/src/com/dom/benchmarking/swingbench/plsqltransactions/OrdersByCountyQuery.java new file mode 100644 index 0000000..7f52dd1 --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/plsqltransactions/OrdersByCountyQuery.java @@ -0,0 +1,64 @@ +package com.dom.benchmarking.swingbench.plsqltransactions; + + +import com.dom.benchmarking.swingbench.event.JdbcTaskEvent; +import com.dom.benchmarking.swingbench.kernel.SwingBenchException; +import com.dom.benchmarking.swingbench.kernel.SwingBenchTask; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.Map; +import java.util.logging.Logger; + + +public class OrdersByCountyQuery extends OrderEntryProcess { + private static final Logger logger = Logger.getLogger(OrdersByCountyQuery.class.getName()); + + public OrdersByCountyQuery() { + super(); + } + + public void init(Map params) { + } + + public void execute(Map params) throws SwingBenchException { + + Connection connection = (Connection) params.get(SwingBenchTask.JDBC_CONNECTION); + initJdbcTask(); + + long executeStart = System.nanoTime(); + + try { + try (PreparedStatement ps = connection.prepareStatement("SELECT COUNT(1),\n" + + " county\n" + + "FROM orders,\n" + + " addresses\n" + + "WHERE orders.DELIVERY_ADDRESS_ID = addresses.ADDRESS_ID\n" + + "GROUP BY county")) { + try (ResultSet rs = ps.executeQuery()) { + rs.next(); + } + addSelectStatements(1); + + } catch (Exception se) { + logger.fine(String.format("Exception when calling store procedure orderentry.WarehouseActivityQuery in database : %s", se)); + throw new SwingBenchException(se); + } + + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), true, getInfoArray())); + } catch (SwingBenchException ex) { + addRollbackStatements(1); + try { + connection.rollback(); + } catch (SQLException ignored) { + } + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), false, getInfoArray())); + throw ex; + } + } + + public void close() { + } +} diff --git a/src/com/dom/benchmarking/swingbench/plsqltransactions/ProcessOrders.java b/src/com/dom/benchmarking/swingbench/plsqltransactions/ProcessOrders.java new file mode 100644 index 0000000..47e6597 --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/plsqltransactions/ProcessOrders.java @@ -0,0 +1,73 @@ +package com.dom.benchmarking.swingbench.plsqltransactions; + + +import com.dom.benchmarking.swingbench.event.JdbcTaskEvent; +import com.dom.benchmarking.swingbench.kernel.SwingBenchException; +import com.dom.benchmarking.swingbench.kernel.SwingBenchTask; +import com.dom.benchmarking.swingbench.utilities.RandomGenerator; + +import java.sql.CallableStatement; +import java.sql.Connection; +import java.sql.SQLException; + +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + +import oracle.jdbc.OracleTypes; + + +public class ProcessOrders extends OrderEntryProcess { + + private static final Logger logger = Logger.getLogger(ProcessOrders.class.getName()); + + public ProcessOrders() { + } + + public void close() { + } + + public void init(Map params) { + Connection connection = (Connection) params.get(SwingBenchTask.JDBC_CONNECTION); + try { + this.parseCommitClientSide(params); + this.setCommitClientSide(connection, commitClientSide); + } catch (SQLException se) { + logger.log(Level.SEVERE, "Unable to set commit location", se); + } + } + + public void execute(Map params) throws SwingBenchException { + Connection connection = (Connection) params.get(SwingBenchTask.JDBC_CONNECTION); + int queryTimeOut = 60; + + if (params.get(SwingBenchTask.QUERY_TIMEOUT) != null) { + queryTimeOut = (Integer) (params.get(SwingBenchTask.QUERY_TIMEOUT)); + } + + long executeStart = System.nanoTime(); + initJdbcTask(); + + try { + try (CallableStatement cs = connection.prepareCall("{? = call orderentry.processorders(?,?,?)}")) { + cs.registerOutParameter(1, OracleTypes.VARCHAR); + cs.setInt(2, (int) RandomGenerator.randomInteger(MIN_WAREHOUSE_ID, MAX_WAREHOUSE_ID)); + cs.setInt(3, (int) this.getMinSleepTime()); + cs.setInt(4, (int) this.getMaxSleepTime()); + cs.setQueryTimeout(queryTimeOut); + cs.executeUpdate(); + parseInfoArray(cs.getString(1)); + this.commit(connection); + } catch (Exception se) { + throw new SwingBenchException(se); + } + + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), true, getInfoArray())); + } catch (SwingBenchException ex) { + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), false, getInfoArray())); + // throw new SwingBenchException(ex); + throw ex; + } + } + +} diff --git a/src/com/dom/benchmarking/swingbench/plsqltransactions/SalesRepsOrdersQuery.java b/src/com/dom/benchmarking/swingbench/plsqltransactions/SalesRepsOrdersQuery.java new file mode 100644 index 0000000..f666beb --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/plsqltransactions/SalesRepsOrdersQuery.java @@ -0,0 +1,64 @@ +package com.dom.benchmarking.swingbench.plsqltransactions; + + +import com.dom.benchmarking.swingbench.event.JdbcTaskEvent; +import com.dom.benchmarking.swingbench.kernel.SwingBenchException; +import com.dom.benchmarking.swingbench.kernel.SwingBenchTask; +import com.dom.benchmarking.swingbench.utilities.RandomGenerator; + +import java.sql.CallableStatement; +import java.sql.Connection; +import java.sql.SQLException; + +import java.util.Map; +import java.util.logging.Logger; + +import oracle.jdbc.OracleTypes; + + +public class SalesRepsOrdersQuery extends OrderEntryProcess { + private static final Logger logger = Logger.getLogger(SalesRepsOrdersQuery.class.getName()); + + public SalesRepsOrdersQuery() { + super(); + } + + public void init(Map params) { + } + + public void execute(Map params) throws SwingBenchException { + + Connection connection = (Connection) params.get(SwingBenchTask.JDBC_CONNECTION); + initJdbcTask(); + + int salesRepId = RandomGenerator.randomInteger(1, 1000); + + long executeStart = System.nanoTime(); + initJdbcTask(); + + try { + try (CallableStatement cs = connection.prepareCall("{? = call orderentry.SalesRepsQuery(?,?,?)}")) { + cs.registerOutParameter(1, OracleTypes.VARCHAR); + cs.setInt(2, salesRepId); + cs.setInt(3, (int) this.getMinSleepTime()); + cs.setInt(4, (int) this.getMaxSleepTime()); + cs.executeUpdate(); + parseInfoArray(cs.getString(1)); + } catch (Exception se) { + throw new SwingBenchException(se); + } + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), true, getInfoArray())); + } catch (SwingBenchException ex) { + addRollbackStatements(1); + try { + connection.rollback(); + } catch (SQLException ignored) { + } + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), false, getInfoArray())); + throw ex; + } + } + + public void close() { + } +} diff --git a/src/com/dom/benchmarking/swingbench/plsqltransactions/UpdateCustomerDetailsV2.java b/src/com/dom/benchmarking/swingbench/plsqltransactions/UpdateCustomerDetailsV2.java new file mode 100644 index 0000000..8ce8dbc --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/plsqltransactions/UpdateCustomerDetailsV2.java @@ -0,0 +1,157 @@ +package com.dom.benchmarking.swingbench.plsqltransactions; + + +import com.dom.benchmarking.swingbench.event.JdbcTaskEvent; +import com.dom.benchmarking.swingbench.kernel.SwingBenchException; +import com.dom.benchmarking.swingbench.kernel.SwingBenchTask; +import com.dom.benchmarking.swingbench.utilities.RandomGenerator; +import com.dom.util.Utilities; +import oracle.jdbc.OracleTypes; + +import java.io.File; +import java.sql.CallableStatement; +import java.sql.Connection; +import java.sql.SQLException; +import java.util.List; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + + +public class UpdateCustomerDetailsV2 extends OrderEntryProcess { + + private static final Logger logger = Logger.getLogger(UpdateCustomerDetailsV2.class.getName()); + private static final String COUNTIES_FILE = "data/counties.txt"; + private static final String COUNTRIES_FILE = "data/countries.txt"; + private static final String FIRST_NAMES_FILE = "data/lowerfirstnames.txt"; + private static final String LAST_NAMES_FILE = "data/lowerlastnames.txt"; + private static final String TOWNS_FILE = "data/towns.txt"; + private static List counties = null; + private static List countries = null; + private static List firstNames = null; + private static List lastNames = null; + private static List towns = null; + private static final Object lock = new Object(); + + public UpdateCustomerDetailsV2() { + } + + public void close() { + } + + @Override + public void init(Map params) throws SwingBenchException { + boolean initCompleted = false; + Connection connection = (Connection) params.get(SwingBenchTask.JDBC_CONNECTION); + try { + this.parseCommitClientSide(params); + this.setCommitClientSide(connection, commitClientSide); + } catch (SQLException se) { + throw new SwingBenchException("Unable to set commit location"); + } + + if ((firstNames == null) || !initCompleted) { // load any data you might need (in this case only once) + + synchronized (lock) { + if (firstNames == null) { + + String value = (String) params.get("SOE_FIRST_NAMES_LOC"); + File firstNamesFile = new File((value == null) ? FIRST_NAMES_FILE : value); + value = (String) params.get("SOE_LAST_NAMES_LOC"); + File lastNamesFile = new File((value == null) ? LAST_NAMES_FILE : value); + + value = (String) params.get("SOE_TOWNS_LOC"); + File townsFile = new File((value == null) ? TOWNS_FILE : value); + value = (String) params.get("SOE_COUNTIES_LOC"); + File countiesFile = new File((value == null) ? COUNTIES_FILE : value); + value = (String) params.get("SOE_COUNTRIES_LOC"); + File countriesFile = new File((value == null) ? COUNTRIES_FILE : value); + + try { + firstNames = Utilities.cacheFile(firstNamesFile); + lastNames = Utilities.cacheFile(lastNamesFile); + counties = Utilities.cacheFile(countiesFile); + towns = Utilities.cacheFile(townsFile); + countries = Utilities.cacheFile(countriesFile); + + + logger.fine("Completed reading files needed for initialisation of NewCustomerProcess()"); + + } catch (java.io.FileNotFoundException fne) { + logger.log(Level.SEVERE, "Unable to open data seed files : ", fne); + throw new SwingBenchException(fne); + } catch (java.io.IOException ioe) { + logger.log(Level.SEVERE, "IO problem opening seed files : ", ioe); + throw new SwingBenchException(ioe); + } + } + + initCompleted = true; + } + } + } + + @Override + public void execute(Map params) throws SwingBenchException { + // FUNCTION updateCustomerDetails( + // p_fname customers.cust_first_name%type, + // p_lname customers.cust_last_name%type, + // p_town addresses.town%type, + // p_county addresses.county%type, + // p_country addresses.country%type, + // min_sleep INTEGER, + // max_sleep INTEGER) + // RETURN VARCHAR; + + Connection connection = (Connection) params.get(SwingBenchTask.JDBC_CONNECTION); + int queryTimeOut = 60; + + if (params.get(SwingBenchTask.QUERY_TIMEOUT) != null) { + queryTimeOut = (Integer) (params.get(SwingBenchTask.QUERY_TIMEOUT)); + } + + String firstName = firstNames.get(RandomGenerator.randomInteger(0, firstNames.size())); + String lastName = lastNames.get(RandomGenerator.randomInteger(0, lastNames.size())); + String town = towns.get(RandomGenerator.randomInteger(0, towns.size())); + String county = counties.get(RandomGenerator.randomInteger(0, counties.size())); + String country = countries.get(RandomGenerator.randomInteger(0, countries.size())); + + long executeStart = System.nanoTime(); + initJdbcTask(); + try { + try (CallableStatement cs = connection.prepareCall("{? = call orderentry.updateCustomerDetails(?,?,?,?,?,?,?)}")) { + cs.registerOutParameter(1, OracleTypes.VARCHAR); + cs.setString(2, firstName); + cs.setString(3, lastName); + cs.setString(4, town); + cs.setString(5, county); + cs.setString(6, country); + cs.setInt(7, (int) this.getMinSleepTime()); + cs.setInt(8, (int) this.getMaxSleepTime()); + cs.setQueryTimeout(queryTimeOut); + cs.executeUpdate(); + parseInfoArray(cs.getString(1)); + this.commit(connection); + } catch (Exception se) { + throw new SwingBenchException(se); + } + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), true, getInfoArray())); + } catch (SwingBenchException ex) { + addRollbackStatements(1); + try { + connection.rollback(); + } catch (SQLException ignored) { + } + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), false, getInfoArray())); + throw ex; + } + } + + private class NLSSupport { + + String language = null; + String territory = null; + + } + +} diff --git a/src/com/dom/benchmarking/swingbench/plsqltransactions/WarehouseActivityQuery.java b/src/com/dom/benchmarking/swingbench/plsqltransactions/WarehouseActivityQuery.java new file mode 100644 index 0000000..c4c3d77 --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/plsqltransactions/WarehouseActivityQuery.java @@ -0,0 +1,65 @@ +package com.dom.benchmarking.swingbench.plsqltransactions; + + +import com.dom.benchmarking.swingbench.event.JdbcTaskEvent; +import com.dom.benchmarking.swingbench.kernel.SwingBenchException; +import com.dom.benchmarking.swingbench.kernel.SwingBenchTask; +import com.dom.benchmarking.swingbench.utilities.RandomGenerator; + +import java.sql.CallableStatement; +import java.sql.Connection; +import java.sql.SQLException; + +import java.util.Map; +import java.util.logging.Logger; + +import oracle.jdbc.OracleTypes; + + +public class WarehouseActivityQuery extends OrderEntryProcess { + private static final Logger logger = Logger.getLogger(WarehouseActivityQuery.class.getName()); + + public WarehouseActivityQuery() { + super(); + } + + public void init(Map params) { + } + + public void execute(Map params) throws SwingBenchException { + + Connection connection = (Connection) params.get(SwingBenchTask.JDBC_CONNECTION); + initJdbcTask(); + + int warehouseID = RandomGenerator.randomInteger(1, 1000); + + initJdbcTask(); + long executeStart = System.nanoTime(); + try { + try (CallableStatement cs = connection.prepareCall("{? = call orderentry.WarehouseActivityQuery(?,?,?)}")) { + cs.registerOutParameter(1, OracleTypes.VARCHAR); + cs.setInt(2, warehouseID); + cs.setInt(3, (int) this.getMinSleepTime()); + cs.setInt(4, (int) this.getMaxSleepTime()); + cs.executeUpdate(); + parseInfoArray(cs.getString(1)); + } catch (Exception se) { + logger.fine(String.format("Exception when calling store procedure orderentry.WarehouseActivityQuery in database : %s", se)); + throw new SwingBenchException(se); + } + + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), true, getInfoArray())); + } catch (SwingBenchException ex) { + addRollbackStatements(1); + try { + connection.rollback(); + } catch (SQLException ignored) { + } + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), false, getInfoArray())); + throw ex; + } + } + + public void close() { + } +} diff --git a/src/com/dom/benchmarking/swingbench/plsqltransactions/WarehouseOrdersQuery.java b/src/com/dom/benchmarking/swingbench/plsqltransactions/WarehouseOrdersQuery.java new file mode 100644 index 0000000..f75ae14 --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/plsqltransactions/WarehouseOrdersQuery.java @@ -0,0 +1,63 @@ +package com.dom.benchmarking.swingbench.plsqltransactions; + + +import com.dom.benchmarking.swingbench.event.JdbcTaskEvent; +import com.dom.benchmarking.swingbench.kernel.SwingBenchException; +import com.dom.benchmarking.swingbench.kernel.SwingBenchTask; +import com.dom.benchmarking.swingbench.utilities.RandomGenerator; + +import java.sql.CallableStatement; +import java.sql.Connection; +import java.sql.SQLException; + +import java.util.Map; +import java.util.logging.Logger; + +import oracle.jdbc.OracleTypes; + + +public class WarehouseOrdersQuery extends OrderEntryProcess { + private static final Logger logger = Logger.getLogger(WarehouseOrdersQuery.class.getName()); + + public WarehouseOrdersQuery() { + super(); + } + + public void init(Map params) { + } + + public void execute(Map params) throws SwingBenchException { + + Connection connection = (Connection) params.get(SwingBenchTask.JDBC_CONNECTION); + initJdbcTask(); + + int warehouseID = RandomGenerator.randomInteger(1, 1000); + + long executeStart = System.nanoTime(); + initJdbcTask(); + try { + try (CallableStatement cs = connection.prepareCall("{? = call orderentry.WarehouseOrdersQuery(?,?,?)}")) { + cs.registerOutParameter(1, OracleTypes.VARCHAR); + cs.setInt(2, warehouseID); + cs.setInt(3, (int) this.getMinSleepTime()); + cs.setInt(4, (int) this.getMaxSleepTime()); + cs.executeUpdate(); + parseInfoArray(cs.getString(1)); + } catch (Exception se) { + throw new SwingBenchException(se); + } + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), true, getInfoArray())); + } catch (SwingBenchException ex) { + addRollbackStatements(1); + try { + connection.rollback(); + } catch (SQLException ignored) { + } + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), false, getInfoArray())); + throw ex; + } + } + + public void close() { + } +} diff --git a/src/com/dom/benchmarking/swingbench/storedprocedures/StoredProcedure1.java b/src/com/dom/benchmarking/swingbench/storedprocedures/StoredProcedure1.java new file mode 100644 index 0000000..1e6518c --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/storedprocedures/StoredProcedure1.java @@ -0,0 +1,66 @@ +package com.dom.benchmarking.swingbench.storedprocedures; + + +import com.dom.benchmarking.swingbench.event.JdbcTaskEvent; +import com.dom.benchmarking.swingbench.kernel.DatabaseTransaction; +import com.dom.benchmarking.swingbench.kernel.SwingBenchException; +import com.dom.benchmarking.swingbench.kernel.SwingBenchTask; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.sql.CallableStatement; +import java.sql.Connection; +import java.sql.SQLException; + +import java.util.Arrays; +import java.util.DoubleSummaryStatistics; +import java.util.Map; + +import oracle.jdbc.OracleTypes; + + +public class StoredProcedure1 extends DatabaseTransaction { + public StoredProcedure1() { + } + + public void close() { + } + + public void init(Map params) { + } + + public void execute(Map params) throws SwingBenchException { + Connection connection = (Connection) params.get(SwingBenchTask.JDBC_CONNECTION); + int queryTimeOut = 60; + + if (params.get(SwingBenchTask.QUERY_TIMEOUT) != null) { + queryTimeOut = ((Integer) (params.get(SwingBenchTask.QUERY_TIMEOUT))).intValue(); + } + + long executeStart = System.nanoTime(); + int[] dmlArray = null; + + try { + try { + CallableStatement cs = connection.prepareCall("{? = call swingbench.storedprocedure1(?,?)}"); + cs.registerOutParameter(1, OracleTypes.ARRAY, "INTEGER_RETURN_ARRAY"); + cs.setInt(2, (int) this.getMinSleepTime()); + cs.setInt(3, (int) this.getMaxSleepTime()); + cs.setQueryTimeout(queryTimeOut); + cs.executeUpdate(); + BigDecimal[] dmlArrayResult = (BigDecimal[]) cs.getArray(1).getArray(); + // Oddly the array is an array of BigDecimals. Expected int[]. + dmlArray = Arrays.stream(dmlArrayResult).map(d -> d.intValueExact()).mapToInt(i -> i).toArray(); + cs.close(); + } catch (SQLException se) { + throw new SwingBenchException(se.getMessage()); + } + + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), true, dmlArray)); + } catch (SwingBenchException ex) { + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), false, dmlArray)); + throw new SwingBenchException(ex); + } finally { + } + } +} diff --git a/src/com/dom/benchmarking/swingbench/storedprocedures/StoredProcedure2.java b/src/com/dom/benchmarking/swingbench/storedprocedures/StoredProcedure2.java new file mode 100644 index 0000000..a906ce7 --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/storedprocedures/StoredProcedure2.java @@ -0,0 +1,66 @@ +package com.dom.benchmarking.swingbench.storedprocedures; + + +import com.dom.benchmarking.swingbench.event.JdbcTaskEvent; +import com.dom.benchmarking.swingbench.kernel.DatabaseTransaction; +import com.dom.benchmarking.swingbench.kernel.SwingBenchException; +import com.dom.benchmarking.swingbench.kernel.SwingBenchTask; + +import java.math.BigDecimal; +import java.sql.CallableStatement; +import java.sql.Connection; +import java.sql.SQLException; + +import java.util.Arrays; +import java.util.Map; + +import oracle.jdbc.OracleTypes; + + +public class StoredProcedure2 extends DatabaseTransaction { + public StoredProcedure2() { + } + + public void close() { + } + + public void init(Map params) { + } + + public void execute(Map params) throws SwingBenchException { + Connection connection = (Connection) params.get(SwingBenchTask.JDBC_CONNECTION); + int queryTimeOut = 60; + + if (params.get(SwingBenchTask.QUERY_TIMEOUT) != null) { + queryTimeOut = ((Integer) (params.get(SwingBenchTask.QUERY_TIMEOUT))).intValue(); + } + + long executeStart = System.nanoTime(); + int[] dmlArray = null; + + try { + long start = System.nanoTime(); + + try { + CallableStatement cs = connection.prepareCall("{? = call swingbench.storedprocedure2(?,?)}"); + cs.registerOutParameter(1, OracleTypes.ARRAY, "INTEGER_RETURN_ARRAY"); + cs.setInt(2, (int) this.getMinSleepTime()); + cs.setInt(3, (int) this.getMaxSleepTime()); + cs.setQueryTimeout(queryTimeOut); + cs.executeUpdate(); + BigDecimal[] dmlArrayResult = (BigDecimal[]) cs.getArray(1).getArray(); + // Oddly the array is an array of BigDecimals. Expected int[]. + dmlArray = Arrays.stream(dmlArrayResult).map(d -> d.intValueExact()).mapToInt(i -> i).toArray(); + cs.close(); + } catch (SQLException se) { + throw new SwingBenchException(se.getMessage()); + } + + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), true, dmlArray)); + } catch (SwingBenchException ex) { + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), false, dmlArray)); + throw new SwingBenchException(ex); + } finally { + } + } +} diff --git a/src/com/dom/benchmarking/swingbench/storedprocedures/StoredProcedure3.java b/src/com/dom/benchmarking/swingbench/storedprocedures/StoredProcedure3.java new file mode 100644 index 0000000..cc0c29f --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/storedprocedures/StoredProcedure3.java @@ -0,0 +1,61 @@ +package com.dom.benchmarking.swingbench.storedprocedures; + + +import com.dom.benchmarking.swingbench.event.JdbcTaskEvent; +import com.dom.benchmarking.swingbench.kernel.DatabaseTransaction; +import com.dom.benchmarking.swingbench.kernel.SwingBenchException; +import com.dom.benchmarking.swingbench.kernel.SwingBenchTask; + +import java.math.BigDecimal; +import java.sql.CallableStatement; +import java.sql.Connection; +import java.sql.SQLException; + +import java.util.Arrays; +import java.util.Map; + +import oracle.jdbc.OracleTypes; + + +public class StoredProcedure3 extends DatabaseTransaction { + public StoredProcedure3() { + } + + public void close() { + } + + public void init(Map params) { + } + + public void execute(Map params) throws SwingBenchException { + Connection connection = (Connection) params.get(SwingBenchTask.JDBC_CONNECTION); + int queryTimeOut = ((Integer) params.get(SwingBenchTask.QUERY_TIMEOUT)).intValue(); + long executeStart = System.nanoTime(); + int[] dmlArray = null; + + try { + long start = System.nanoTime(); + + try { + CallableStatement cs = connection.prepareCall("{? = call swingbench.storedprocedure3(?,?)}"); + cs.registerOutParameter(1, OracleTypes.ARRAY, "INTEGER_RETURN_ARRAY"); + cs.setInt(2, (int) this.getMinSleepTime()); + cs.setInt(3, (int) this.getMaxSleepTime()); + cs.setQueryTimeout(queryTimeOut); + cs.executeUpdate(); + BigDecimal[] dmlArrayResult = (BigDecimal[]) cs.getArray(1).getArray(); + // Oddly the array is an array of BigDecimals. Expected int[]. + dmlArray = Arrays.stream(dmlArrayResult).map(d -> d.intValueExact()).mapToInt(i -> i).toArray(); + cs.close(); + } catch (SQLException se) { + throw new SwingBenchException(se.getMessage()); + } + + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), true, dmlArray)); + } catch (SwingBenchException ex) { + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), false, dmlArray)); + throw new SwingBenchException(ex); + } finally { + } + } +} diff --git a/src/com/dom/benchmarking/swingbench/storedprocedures/StoredProcedure4.java b/src/com/dom/benchmarking/swingbench/storedprocedures/StoredProcedure4.java new file mode 100644 index 0000000..7923f26 --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/storedprocedures/StoredProcedure4.java @@ -0,0 +1,66 @@ +package com.dom.benchmarking.swingbench.storedprocedures; + + +import com.dom.benchmarking.swingbench.event.JdbcTaskEvent; +import com.dom.benchmarking.swingbench.kernel.DatabaseTransaction; +import com.dom.benchmarking.swingbench.kernel.SwingBenchException; +import com.dom.benchmarking.swingbench.kernel.SwingBenchTask; + +import java.math.BigDecimal; +import java.sql.CallableStatement; +import java.sql.Connection; +import java.sql.SQLException; + +import java.util.Arrays; +import java.util.Map; + +import oracle.jdbc.OracleTypes; + + +public class StoredProcedure4 extends DatabaseTransaction { + public StoredProcedure4() { + } + + public void close() { + } + + public void init(Map params) { + } + + public void execute(Map params) throws SwingBenchException { + Connection connection = (Connection) params.get(SwingBenchTask.JDBC_CONNECTION); + int queryTimeOut = 60; + + if (params.get(SwingBenchTask.QUERY_TIMEOUT) != null) { + queryTimeOut = ((Integer) (params.get(SwingBenchTask.QUERY_TIMEOUT))).intValue(); + } + + long executeStart = System.nanoTime(); + int[] dmlArray = null; + + try { + long start = System.nanoTime(); + + try { + CallableStatement cs = connection.prepareCall("{? = call swingbench.storedprocedure4(?,?)}"); + cs.registerOutParameter(1, OracleTypes.ARRAY, "INTEGER_RETURN_ARRAY"); + cs.setInt(2, (int) this.getMinSleepTime()); + cs.setInt(3, (int) this.getMaxSleepTime()); + cs.setQueryTimeout(queryTimeOut); + cs.executeUpdate(); + BigDecimal[] dmlArrayResult = (BigDecimal[]) cs.getArray(1).getArray(); + // Oddly the array is an array of BigDecimals. Expected int[]. + dmlArray = Arrays.stream(dmlArrayResult).map(d -> d.intValueExact()).mapToInt(i -> i).toArray(); + cs.close(); + } catch (SQLException se) { + throw new SwingBenchException(se.getMessage()); + } + + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), true, dmlArray)); + } catch (SwingBenchException ex) { + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), false, dmlArray)); + throw new SwingBenchException(ex); + } finally { + } + } +} diff --git a/src/com/dom/benchmarking/swingbench/storedprocedures/StoredProcedure5.java b/src/com/dom/benchmarking/swingbench/storedprocedures/StoredProcedure5.java new file mode 100644 index 0000000..adfdbc4 --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/storedprocedures/StoredProcedure5.java @@ -0,0 +1,66 @@ +package com.dom.benchmarking.swingbench.storedprocedures; + + +import com.dom.benchmarking.swingbench.event.JdbcTaskEvent; +import com.dom.benchmarking.swingbench.kernel.DatabaseTransaction; +import com.dom.benchmarking.swingbench.kernel.SwingBenchException; +import com.dom.benchmarking.swingbench.kernel.SwingBenchTask; + +import java.math.BigDecimal; +import java.sql.CallableStatement; +import java.sql.Connection; +import java.sql.SQLException; + +import java.util.Arrays; +import java.util.Map; + +import oracle.jdbc.OracleTypes; + + +public class StoredProcedure5 extends DatabaseTransaction { + public StoredProcedure5() { + } + + public void close() { + } + + public void init(Map params) { + } + + public void execute(Map params) throws SwingBenchException { + Connection connection = (Connection) params.get(SwingBenchTask.JDBC_CONNECTION); + int queryTimeOut = 60; + + if (params.get(SwingBenchTask.QUERY_TIMEOUT) != null) { + queryTimeOut = ((Integer) (params.get(SwingBenchTask.QUERY_TIMEOUT))).intValue(); + } + + long executeStart = System.nanoTime(); + int[] dmlArray = null; + + try { + long start = System.nanoTime(); + + try { + CallableStatement cs = connection.prepareCall("{? = call swingbench.storedprocedure5(?,?)}"); + cs.registerOutParameter(1, OracleTypes.ARRAY, "INTEGER_RETURN_ARRAY"); + cs.setInt(2, (int) this.getMinSleepTime()); + cs.setInt(3, (int) this.getMaxSleepTime()); + cs.setQueryTimeout(queryTimeOut); + cs.executeUpdate(); + BigDecimal[] dmlArrayResult = (BigDecimal[]) cs.getArray(1).getArray(); + // Oddly the array is an array of BigDecimals. Expected int[]. + dmlArray = Arrays.stream(dmlArrayResult).map(d -> d.intValueExact()).mapToInt(i -> i).toArray(); + cs.close(); + } catch (SQLException se) { + throw new SwingBenchException(se.getMessage()); + } + + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), true, dmlArray)); + } catch (SwingBenchException ex) { + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), false, dmlArray)); + throw new SwingBenchException(ex); + } finally { + } + } +} diff --git a/src/com/dom/benchmarking/swingbench/storedprocedures/StoredProcedure6.java b/src/com/dom/benchmarking/swingbench/storedprocedures/StoredProcedure6.java new file mode 100644 index 0000000..63e7f70 --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/storedprocedures/StoredProcedure6.java @@ -0,0 +1,63 @@ +package com.dom.benchmarking.swingbench.storedprocedures; + + +import com.dom.benchmarking.swingbench.event.JdbcTaskEvent; +import com.dom.benchmarking.swingbench.kernel.DatabaseTransaction; +import com.dom.benchmarking.swingbench.kernel.SwingBenchException; +import com.dom.benchmarking.swingbench.kernel.SwingBenchTask; + +import java.math.BigDecimal; +import java.sql.CallableStatement; +import java.sql.Connection; +import java.sql.SQLException; + +import java.util.Arrays; +import java.util.Map; + +import oracle.jdbc.OracleTypes; + +public class StoredProcedure6 extends DatabaseTransaction { + public StoredProcedure6() { + } + + public void close() { + } + + public void init(Map params) { + } + + public void execute(Map params) throws SwingBenchException { + Connection connection = (Connection) params.get(SwingBenchTask.JDBC_CONNECTION); + int queryTimeOut = 60; + + if (params.get(SwingBenchTask.QUERY_TIMEOUT) != null) { + queryTimeOut = ((Integer) (params.get(SwingBenchTask.QUERY_TIMEOUT))).intValue(); + } + + long executeStart = System.nanoTime(); + int[] dmlArray = null; + + try { + try { + CallableStatement cs = connection.prepareCall("{? = call swingbench.storedprocedure6(?,?)}"); + cs.registerOutParameter(1, OracleTypes.ARRAY, "INTEGER_RETURN_ARRAY"); + cs.setInt(2, (int) this.getMinSleepTime()); + cs.setInt(3, (int) this.getMaxSleepTime()); + cs.setQueryTimeout(queryTimeOut); + cs.executeUpdate(); + BigDecimal[] dmlArrayResult = (BigDecimal[]) cs.getArray(1).getArray(); + // Oddly the array is an array of BigDecimals. Expected int[]. Need to find a way to stop this being required. + dmlArray = Arrays.stream(dmlArrayResult).map(d -> d.intValueExact()).mapToInt(i -> i).toArray(); + cs.close(); + } catch (SQLException se) { + throw new SwingBenchException(se.getMessage()); + } + + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), true, dmlArray)); + } catch (SwingBenchException ex) { + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), false, dmlArray)); + throw new SwingBenchException(ex); + } finally { + } + } +} diff --git a/src/com/dom/benchmarking/swingbench/stresstest/StressTest.java b/src/com/dom/benchmarking/swingbench/stresstest/StressTest.java new file mode 100644 index 0000000..e90ba94 --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/stresstest/StressTest.java @@ -0,0 +1,76 @@ +package com.dom.benchmarking.swingbench.stresstest; + + +import com.dom.benchmarking.swingbench.kernel.DatabaseTransaction; +import com.dom.benchmarking.swingbench.kernel.SwingBenchException; +import com.dom.benchmarking.swingbench.kernel.SwingBenchTask; + +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.Statement; + +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.locks.Condition; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; + + +public abstract class StressTest extends DatabaseTransaction { + + private static boolean initRunning = false; + private static boolean initCompleted = false; + private static Lock lock = new ReentrantLock(); + private static Condition initFinished = lock.newCondition(); + private static AtomicInteger sequence = new AtomicInteger(1); + + + public StressTest() { + } + + public void init(Map parameters) throws SwingBenchException { + try { + lock.lock(); //No real need to use explicit locking, I simply prefer it + while (initRunning) { + initFinished.await(); + } + if (!initRunning && !initCompleted) { + initRunning = true; + Connection connection = (Connection) parameters.get(SwingBenchTask.JDBC_CONNECTION); + Statement st = connection.createStatement(); + try { + st.execute("drop table stressTestTable"); + } catch (SQLException ex) { // ignore the exception + } + st.execute( + "create table stressTestTable(\n" + + "id integer not null primary key,\n" + + "aint integer,\n" + + "afloat float,\n" + + "asmallvarchar varchar(10),\n" + + "abigvarchar varchar(1000),\n" + + "adate date)"); + st.execute("create index stbtidx on stressTestTable(asmallvarchar)"); + initRunning = false; + initCompleted = true; + initFinished.signalAll(); + } + lock.unlock(); + + } catch (InterruptedException e) { + + } catch (SQLException se) { + SwingBenchException sbe = new SwingBenchException("Couldn't initialise the benchmark : " + se.getMessage()); + sbe.setSeverity(SwingBenchException.UNRECOVERABLEERROR); + throw sbe; + } + } + + protected int getSequence() { + return sequence.getAndIncrement(); + } + + protected int getCurrentSequence() { + return sequence.get(); + } +} diff --git a/src/com/dom/benchmarking/swingbench/stresstest/StressTestDelete.java b/src/com/dom/benchmarking/swingbench/stresstest/StressTestDelete.java new file mode 100644 index 0000000..5544aa9 --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/stresstest/StressTestDelete.java @@ -0,0 +1,52 @@ +package com.dom.benchmarking.swingbench.stresstest; + + +import com.dom.benchmarking.swingbench.event.JdbcTaskEvent; +import com.dom.benchmarking.swingbench.kernel.SwingBenchException; +import com.dom.benchmarking.swingbench.kernel.SwingBenchTask; +import com.dom.util.RandomUtilities; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; + +import java.util.Map; + + +public final class StressTestDelete extends StressTest { + public StressTestDelete() { + } + + public void execute(Map parameters) throws SwingBenchException { + Connection connection = (Connection) parameters.get(SwingBenchTask.JDBC_CONNECTION); + PreparedStatement insPs = null; + boolean success = true; + + initJdbcTask(); + + long executeStart = System.nanoTime(); + try { + int selectId = RandomUtilities.randomInteger(1, getCurrentSequence()); + insPs = connection.prepareStatement("delete from stressTestTable where id = ?"); + insPs.setInt(1, selectId); + insPs.execute(); + connection.commit(); + addDeleteStatements(1); + addCommitStatements(1); + } catch (SQLException ex) { + success = false; + System.out.println(ex); + } finally { + try { + insPs.close(); + } catch (SQLException e) { + } + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - + executeStart), success, getSelectStatements(), getInsertStatements(), getUpdateStatements(), getDeleteStatements(), getCommitStatements(), getRollbackStatements())); + } + } + + public void close() { + + } +} diff --git a/src/com/dom/benchmarking/swingbench/stresstest/StressTestInsert.java b/src/com/dom/benchmarking/swingbench/stresstest/StressTestInsert.java new file mode 100644 index 0000000..0b870d3 --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/stresstest/StressTestInsert.java @@ -0,0 +1,58 @@ +package com.dom.benchmarking.swingbench.stresstest; + + +import com.dom.benchmarking.swingbench.event.JdbcTaskEvent; +import com.dom.benchmarking.swingbench.kernel.SwingBenchException; +import com.dom.benchmarking.swingbench.kernel.SwingBenchTask; +import com.dom.util.RandomUtilities; + +import java.sql.Connection; +import java.sql.Date; +import java.sql.PreparedStatement; +import java.sql.SQLException; + +import java.util.Map; + + +public final class StressTestInsert extends StressTest { + public StressTestInsert() { + } + + public void execute(Map parameters) throws SwingBenchException { + Connection connection = (Connection) parameters.get(SwingBenchTask.JDBC_CONNECTION); + PreparedStatement insPs = null; + boolean success = true; + + initJdbcTask(); + + long executeStart = System.nanoTime(); + try { + insPs = connection.prepareStatement("insert into stressTestTable(id, aint, afloat, asmallvarchar, abigvarchar, adate) values (?,?,?,?,?,?)"); + + insPs.setInt(1, getSequence()); + insPs.setInt(2, RandomUtilities.randomInteger(1, 9999999)); + insPs.setDouble(3, RandomUtilities.randomDouble(1, 1000)); + insPs.setString(4, RandomUtilities.randomAlpha(1, 10)); + insPs.setString(5, RandomUtilities.randomAlpha(1, 999)); + insPs.setDate(6, new Date(RandomUtilities.randomLong(System.currentTimeMillis(), System.currentTimeMillis() + 10000000))); + insPs.execute(); + connection.commit(); + addInsertStatements(1); + addCommitStatements(1); + } catch (SQLException ex) { + success = false; + System.out.println(ex); + } finally { + try { + insPs.close(); + } catch (SQLException e) { + } + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - + executeStart), success, getSelectStatements(), getInsertStatements(), getUpdateStatements(), getDeleteStatements(), getCommitStatements(), getRollbackStatements())); + } + } + + public void close() { + + } +} diff --git a/src/com/dom/benchmarking/swingbench/stresstest/StressTestSelect.java b/src/com/dom/benchmarking/swingbench/stresstest/StressTestSelect.java new file mode 100644 index 0000000..b97cdd3 --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/stresstest/StressTestSelect.java @@ -0,0 +1,53 @@ +package com.dom.benchmarking.swingbench.stresstest; + + +import com.dom.benchmarking.swingbench.event.JdbcTaskEvent; +import com.dom.benchmarking.swingbench.kernel.SwingBenchException; +import com.dom.benchmarking.swingbench.kernel.SwingBenchTask; +import com.dom.util.RandomUtilities; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +import java.util.Map; + + +public final class StressTestSelect extends StressTest { + public StressTestSelect() { + } + + public void execute(Map parameters) throws SwingBenchException { + Connection connection = (Connection) parameters.get(SwingBenchTask.JDBC_CONNECTION); + PreparedStatement selPs = null; + ResultSet rs = null; + boolean success = true; + + initJdbcTask(); + + long executeStart = System.nanoTime(); + try { + int selectId = RandomUtilities.randomInteger(1, getCurrentSequence()); + selPs = connection.prepareStatement("select * from stressTestTable where id = ?"); + selPs.setInt(1, selectId); + rs = selPs.executeQuery(); + addSelectStatements(1); + } catch (SQLException ex) { + success = false; + System.out.println(ex); + } finally { + try { + rs.close(); + selPs.close(); + } catch (SQLException e) { + } + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - + executeStart), success, getSelectStatements(), getInsertStatements(), getUpdateStatements(), getDeleteStatements(), getCommitStatements(), getRollbackStatements())); + } + } + + public void close() { + + } +} diff --git a/src/com/dom/benchmarking/swingbench/stresstest/StressTestUpdate.java b/src/com/dom/benchmarking/swingbench/stresstest/StressTestUpdate.java new file mode 100644 index 0000000..e795bf4 --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/stresstest/StressTestUpdate.java @@ -0,0 +1,52 @@ +package com.dom.benchmarking.swingbench.stresstest; + + +import com.dom.benchmarking.swingbench.event.JdbcTaskEvent; +import com.dom.benchmarking.swingbench.kernel.SwingBenchException; +import com.dom.benchmarking.swingbench.kernel.SwingBenchTask; +import com.dom.util.RandomUtilities; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; + +import java.util.Map; + + +public final class StressTestUpdate extends StressTest { + public StressTestUpdate() { + } + + public void execute(Map parameters) throws SwingBenchException { + Connection connection = (Connection) parameters.get(SwingBenchTask.JDBC_CONNECTION); + PreparedStatement insPs = null; + boolean success = true; + + initJdbcTask(); + + long executeStart = System.nanoTime(); + try { + int selectId = RandomUtilities.randomInteger(1, getCurrentSequence()); + insPs = connection.prepareStatement("update stressTestTable set aint = aint + 1 where id = ?"); + insPs.setInt(1, selectId); + insPs.execute(); + connection.commit(); + addUpdateStatements(1); + addCommitStatements(1); + } catch (SQLException ex) { + success = false; + System.out.println(ex); + } finally { + try { + insPs.close(); + } catch (SQLException e) { + } + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - + executeStart), success, getSelectStatements(), getInsertStatements(), getUpdateStatements(), getDeleteStatements(), getCommitStatements(), getRollbackStatements())); + } + } + + public void close() { + + } +} diff --git a/src/com/dom/benchmarking/swingbench/transactions/BrowseAndUpdateOrders.java b/src/com/dom/benchmarking/swingbench/transactions/BrowseAndUpdateOrders.java new file mode 100644 index 0000000..fea65d7 --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/transactions/BrowseAndUpdateOrders.java @@ -0,0 +1,123 @@ +package com.dom.benchmarking.swingbench.transactions; + + +import com.dom.benchmarking.swingbench.event.JdbcTaskEvent; +import com.dom.benchmarking.swingbench.kernel.SwingBenchException; +import com.dom.benchmarking.swingbench.kernel.SwingBenchTask; +import com.dom.benchmarking.swingbench.utilities.RandomGenerator; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +import java.util.List; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + + +public class BrowseAndUpdateOrders extends OrderEntryProcess { + private static final Logger logger = Logger.getLogger(BrowseAndUpdateOrders.class.getName()); + private PreparedStatement liPs = null; + private PreparedStatement upPs = null; + private PreparedStatement upPs2 = null; + + public BrowseAndUpdateOrders() { + } + + public void init(Map params) { + Connection connection = (Connection) params.get(SwingBenchTask.JDBC_CONNECTION); + try { + this.getMaxandMinCustID(connection, params); + } catch (SQLException se) { + logger.log(Level.SEVERE, "Unable to get max and min customer id", se); + } + } + + public void execute(Map params) throws SwingBenchException { + Connection connection = (Connection) params.get(SwingBenchTask.JDBC_CONNECTION); + long custID = RandomGenerator.randomLong(MIN_CUSTID, MAX_CUSTID); + ResultSet rs = null; + initJdbcTask(); + + long executeStart = System.nanoTime(); + + try { + try { + logon(connection, custID); + addInsertStatements(1); + addCommitStatements(1); + getCustomerDetails(connection, custID); + getAddressDetails(connection, custID); + List orders = getOrdersByCustomer(connection, custID); + addSelectStatements(3); + if (orders.size() > 0) { + Long selectedOrder = orders.get(RandomGenerator.randomInteger(0, orders.size())); + liPs = connection.prepareStatement( + "select ORDER_ID, \n" + + " LINE_ITEM_ID, \n" + + " PRODUCT_ID, \n" + + " UNIT_PRICE, \n" + + " QUANTITY,DISPATCH_DATE, \n" + + " RETURN_DATE, \n" + + " GIFT_WRAP, \n" + + " CONDITION, \n" + + " SUPPLIER_ID, \n" + + " ESTIMATED_DELIVERY \n" + + " from order_items \n" + + " where order_id = ? \n" + + " and rownum < 5"); + liPs.setLong(1, selectedOrder); + rs = liPs.executeQuery(); + addSelectStatements(1); + if (rs.next()) { + Long lit = rs.getLong(2); + Float up = rs.getFloat(4); + upPs = connection.prepareStatement( + "update order_items \n" + + " set quantity = quantity + 1 \n" + + " where order_items.ORDER_Id = ? \n" + + " and order_items.LINE_ITEM_ID = ?"); + upPs.setLong(1, selectedOrder); + upPs.setLong(2, lit); + upPs.executeUpdate(); + upPs2 = connection.prepareStatement( + "update orders \n" + + " set order_total = order_total + ? \n" + + " where order_Id = ?"); + upPs2.setFloat(1, up); + upPs2.setLong(2, selectedOrder); + addUpdateStatements(2); + connection.commit(); + addCommitStatements(1); + } + } + addSelectStatements(1); + } catch (SQLException se) { + logger.log(Level.FINE, String.format("Exception : ", se.getMessage())); + logger.log(Level.FINEST, "SQLException thrown : ", se); + throw new SwingBenchException(se); + } finally { + hardClose(rs); + hardClose(liPs); + hardClose(upPs); + hardClose(upPs2); + } + + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), true, getInfoArray())); + } catch (SwingBenchException sbe) { + try { + addRollbackStatements(1); + connection.rollback(); + } catch (SQLException er) { + logger.log(Level.FINE, "Unable to rollback transaction"); + } + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), false, getInfoArray())); + throw new SwingBenchException(sbe.getMessage()); + } + } + + public void close() { + } +} diff --git a/src/com/dom/benchmarking/swingbench/transactions/BrowseProducts.java b/src/com/dom/benchmarking/swingbench/transactions/BrowseProducts.java new file mode 100644 index 0000000..2b6686b --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/transactions/BrowseProducts.java @@ -0,0 +1,73 @@ +package com.dom.benchmarking.swingbench.transactions; + + +import com.dom.benchmarking.swingbench.event.JdbcTaskEvent; +import com.dom.benchmarking.swingbench.kernel.SwingBenchException; +import com.dom.benchmarking.swingbench.kernel.SwingBenchTask; +import com.dom.benchmarking.swingbench.utilities.RandomGenerator; + +import java.sql.Connection; +import java.sql.SQLException; + +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + + +public class BrowseProducts extends OrderEntryProcess { + private static final Logger logger = Logger.getLogger(com.dom.benchmarking.swingbench.plsqltransactions.BrowseProducts.class.getName()); + private long custID = 0; + + public BrowseProducts() { + } + + public void init(Map params) { + Connection connection = (Connection) params.get(SwingBenchTask.JDBC_CONNECTION); + try { + this.getMaxandMinCustID(connection, params); + } catch (SQLException se) { + logger.log(Level.SEVERE, "Unable to get max and min customer id", se); + } + } + + public void execute(Map params) throws SwingBenchException { + + Connection connection = (Connection) params.get(SwingBenchTask.JDBC_CONNECTION); + initJdbcTask(); + + long executeStart = System.nanoTime(); + + try { + try { + custID = RandomGenerator.randomLong(MIN_CUSTID, MAX_CUSTID); + logon(connection, custID); + addInsertStatements(1); + addCommitStatements(1); + getCustomerDetails(connection, custID); + addSelectStatements(1); + thinkSleep(); + + int numOfBrowseCategorys = RandomGenerator.randomInteger(1, MAX_BROWSE_CATEGORY); + + for (int i = 0; i < numOfBrowseCategorys; i++) { + getProductDetailsByID(connection, RandomGenerator.randomInteger(MIN_PROD_ID, MAX_PROD_ID)); + addSelectStatements(1); + thinkSleep(); + } + + } catch (SQLException se) { + logger.log(Level.FINE, String.format("Exception : ", se.getMessage())); + logger.log(Level.FINEST, "SQLException thrown : ", se); + throw new SwingBenchException(se); + } + + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), true, getInfoArray())); + } catch (SwingBenchException sbe) { + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), false, getInfoArray())); + throw new SwingBenchException(sbe.getMessage()); + } + } + + public void close() { + } +} diff --git a/src/com/dom/benchmarking/swingbench/transactions/JobTest.java b/src/com/dom/benchmarking/swingbench/transactions/JobTest.java new file mode 100644 index 0000000..01b18c2 --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/transactions/JobTest.java @@ -0,0 +1,7 @@ +package com.dom.benchmarking.swingbench.transactions; + +/** + * Created by dgiles on 10/03/2016. + */ +public class JobTest { +} diff --git a/src/com/dom/benchmarking/swingbench/transactions/NewCustomerProcess.java b/src/com/dom/benchmarking/swingbench/transactions/NewCustomerProcess.java new file mode 100644 index 0000000..a9f3374 --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/transactions/NewCustomerProcess.java @@ -0,0 +1,242 @@ +package com.dom.benchmarking.swingbench.transactions; + + +import com.dom.benchmarking.swingbench.event.JdbcTaskEvent; +import com.dom.benchmarking.swingbench.kernel.SwingBenchException; +import com.dom.benchmarking.swingbench.kernel.SwingBenchTask; +import com.dom.benchmarking.swingbench.utilities.RandomGenerator; +import com.dom.util.Utilities; + +import java.io.File; +import java.sql.*; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.StringTokenizer; +import java.util.logging.Level; +import java.util.logging.Logger; + + +public class NewCustomerProcess extends OrderEntryProcess { + + private static final Logger logger = Logger.getLogger(NewCustomerProcess.class.getName()); + private static final String COUNTIES_FILE = "data/counties.txt"; + private static final String COUNTRIES_FILE = "data/countries.txt"; + private static final String FIRST_NAMES_FILE = "data/lowerfirstnames.txt"; + private static final String LAST_NAMES_FILE = "data/lowerlastnames.txt"; + private static final String NLS_FILE = "data/nls.txt"; + private static final String TOWNS_FILE = "data/towns.txt"; + private static final int HOUSE_NO_RANGE = 200; + private static List nlsInfo = new ArrayList<>(); + private static List counties = null; + private static List countries = null; + private static List firstNames = null; + private static List lastNames = null; + private static List nlsInfoRaw = null; + private static List towns = null; + private static final Object lock = new Object(); + + public NewCustomerProcess() { + } + + + public void init(Map params) throws SwingBenchException { + boolean initCompleted = false; + + if ((firstNames == null) || !initCompleted) { // load any data you might need (in this case only once) + + synchronized (lock) { + if (firstNames == null) { + + String value = (String) params.get("SOE_FIRST_NAMES_LOC"); + File firstNamesFile = new File((value == null) ? FIRST_NAMES_FILE : value); + value = (String) params.get("SOE_LAST_NAMES_LOC"); + File lastNamesFile = new File((value == null) ? LAST_NAMES_FILE : value); + value = (String) params.get("SOE_NLSDATA_LOC"); + File nlsFile = new File((value == null) ? NLS_FILE : value); + value = (String) params.get("SOE_TOWNS_LOC"); + File townsFile = new File((value == null) ? TOWNS_FILE : value); + value = (String) params.get("SOE_COUNTIES_LOC"); + File countiesFile = new File((value == null) ? COUNTIES_FILE : value); + value = (String) params.get("SOE_COUNTRIES_LOC"); + File countriesFile = new File((value == null) ? COUNTRIES_FILE : value); + + try { + firstNames = Utilities.cacheFile(firstNamesFile); + lastNames = Utilities.cacheFile(lastNamesFile); + nlsInfoRaw = Utilities.cacheFile(nlsFile); + counties = Utilities.cacheFile(countiesFile); + towns = Utilities.cacheFile(townsFile); + countries = Utilities.cacheFile(countriesFile); + + for (String rawData : nlsInfoRaw) { + NLSSupport nls = new NLSSupport(); + StringTokenizer st = new StringTokenizer(rawData, ","); + nls.language = st.nextToken(); + nls.territory = st.nextToken(); + nlsInfo.add(nls); + } + logger.fine("Completed reading files needed for initialisation of NewCustomerProcess()"); + + } catch (java.io.FileNotFoundException fne) { + logger.log(Level.SEVERE, "Unable to open data seed files : ", fne); + throw new SwingBenchException(fne); + } catch (java.io.IOException ioe) { + logger.log(Level.SEVERE, "IO problem opening seed files : ", ioe); + throw new SwingBenchException(ioe); + } + } + + initCompleted = true; + } + } + } + + public void execute(Map params) throws SwingBenchException { + Connection connection = (Connection) params.get(SwingBenchTask.JDBC_CONNECTION); + long custID; + long addressID; + long cardID; + String firstName = firstNames.get(RandomGenerator.randomInteger(0, firstNames.size())); + String lastName = lastNames.get(RandomGenerator.randomInteger(0, lastNames.size())); + String town = towns.get(RandomGenerator.randomInteger(0, towns.size())); + String county = counties.get(RandomGenerator.randomInteger(0, counties.size())); + String country = countries.get(RandomGenerator.randomInteger(0, countries.size())); + NLSSupport nls = nlsInfo.get(RandomGenerator.randomInteger(0, nlsInfo.size())); + initJdbcTask(); + + long executeStart = System.nanoTime(); + try { + try (PreparedStatement seqPs = connection.prepareStatement("select customer_seq.nextval, address_seq.nextval, card_details_seq.nextval from dual"); + PreparedStatement insPs1 = connection.prepareStatement("insert into customers (customer_id,\n" + + " cust_first_name,\n" + + " cust_last_name,\n" + + " nls_language,\n" + + " nls_territory,\n" + + " credit_limit,\n" + + " cust_email,\n" + + " account_mgr_id,\n" + + " customer_since,\n" + + " customer_class,\n" + + " suggestions,\n" + + " dob,\n" + + " mailshot,\n" + + " partner_mailshot,\n" + + " preferred_address,\n" + + " preferred_card)\n" + + "values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); + PreparedStatement insPs2 = connection.prepareStatement("INSERT INTO ADDRESSES (address_id,\n" + + " customer_id,\n" + + " date_created,\n" + + " house_no_or_name,\n" + + " street_name,\n" + + " town,\n" + + " county,\n" + + " country,\n" + + " post_code,\n" + + " zip_code)\n" + + "VALUES (?, ?, TRUNC(SYSDATE, 'MI'), ?, ?, ?, ?, ?, ?, NULL)"); + PreparedStatement insPs3 = connection.prepareStatement("INSERT INTO CARD_DETAILS (card_id,\n" + + " customer_id,\n" + + " card_type,\n" + + " card_number,\n" + + " expiry_date,\n" + + " is_valid,\n" + + " security_code)\n" + + "VALUES (?, ?, ?, ?, trunc(SYSDATE + ?), ?, ?)"); + ResultSet rs = seqPs.executeQuery()) { + + rs.next(); + custID = rs.getLong(1); + addressID = rs.getLong(2); + cardID = rs.getLong(3); + + addSelectStatements(1); + thinkSleep(); + + Date dob = new Date(System.currentTimeMillis() - (RandomGenerator.randomLong(18, 65) * 31556952000L)); + Date custSince = new Date(System.currentTimeMillis() - (RandomGenerator.randomLong(1, 4) * 31556952000L)); + + insPs1.setLong(1, custID); + insPs1.setString(2, firstName); + insPs1.setString(3, lastName); + insPs1.setString(4, nls.language); + insPs1.setString(5, nls.territory); + insPs1.setInt(6, RandomGenerator.randomInteger(MIN_CREDITLIMIT, MAX_CREDITLIMIT)); + insPs1.setString(7, firstName + "." + lastName + "@" + "oracle.com"); + insPs1.setInt(8, RandomGenerator.randomInteger(MIN_SALESID, MAX_SALESID)); + insPs1.setDate(9, custSince); + insPs1.setString(10, "Ocasional"); + insPs1.setString(11, "Music"); + insPs1.setDate(12, dob); + insPs1.setString(13, "Y"); + insPs1.setString(14, "N"); + insPs1.setLong(15, addressID); + insPs1.setLong(16, custID); + + insPs1.execute(); + addInsertStatements(1); + + insPs2.setLong(1, addressID); + insPs2.setLong(2, custID); + insPs2.setInt(3, RandomGenerator.randomInteger(1, HOUSE_NO_RANGE)); + insPs2.setString(4, "Street Name"); + insPs2.setString(5, town); + insPs2.setString(6, county); + insPs2.setString(7, country); + insPs2.setString(8, "Postcode"); + insPs2.execute(); + insPs2.close(); + addInsertStatements(1); + + + insPs3.setLong(1, cardID); + insPs3.setLong(2, custID); + insPs3.setString(3, "Visa (Debit)"); + insPs3.setLong(4, RandomGenerator.randomLong(1111111111L, 9999999999L)); + insPs3.setInt(5, RandomGenerator.randomInteger(365, 1460)); + insPs3.setString(6, "Y"); + insPs3.setInt(7, RandomGenerator.randomInteger(1111, 9999)); + insPs3.execute(); + insPs3.close(); + addInsertStatements(1); + + connection.commit(); + addCommitStatements(1); + thinkSleep(); + logon(connection, custID); + addInsertStatements(1); + addCommitStatements(1); + getCustomerDetails(connection, custID); + addSelectStatements(1); + + } catch (SQLException se) { + logger.log(Level.FINE, String.format("Exception : %s", se.getMessage())); + logger.log(Level.FINEST, "SQLException thrown : %s", se); + throw new SwingBenchException(se); + } + + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), true, getInfoArray())); + } catch (SwingBenchException sbe) { + try { + addRollbackStatements(1); + connection.rollback(); + } catch (SQLException er) { + logger.log(Level.FINE, "Unable to rollback transaction"); + } + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), false, getInfoArray())); + throw new SwingBenchException(sbe); + } + } + + public void close() { + } + + private class NLSSupport { + + String language = null; + String territory = null; + + } + +} diff --git a/src/com/dom/benchmarking/swingbench/transactions/NewOrderProcess.java b/src/com/dom/benchmarking/swingbench/transactions/NewOrderProcess.java new file mode 100644 index 0000000..8b46a99 --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/transactions/NewOrderProcess.java @@ -0,0 +1,268 @@ +package com.dom.benchmarking.swingbench.transactions; + + +import com.dom.benchmarking.swingbench.event.JdbcTaskEvent; +import com.dom.benchmarking.swingbench.kernel.SwingBenchException; +import com.dom.benchmarking.swingbench.kernel.SwingBenchTask; +import com.dom.benchmarking.swingbench.utilities.RandomGenerator; + +import java.sql.*; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + + +public class NewOrderProcess extends OrderEntryProcess { + private static final Logger logger = Logger.getLogger(NewOrderProcess.class.getName()); + private static final String PRODUCTS_FILE = "data/productids.txt"; + private static final int STATICLINEITEMSIZE = 3; + private static Object lock = new Object(); + private PreparedStatement insIPs = null; + private PreparedStatement insOPs = null; + private PreparedStatement seqPs = null; + private PreparedStatement updIns = null; + private PreparedStatement updOPs = null; + private long custID; + private long orderID; + + public NewOrderProcess() { + } + + public void init(Map params) throws SwingBenchException { + Connection connection = (Connection) params.get(SwingBenchTask.JDBC_CONNECTION); + boolean initCompleted = false; + + if (!initCompleted) { // load any data you might need (in this case only once) + + synchronized (lock) { + try { + this.getMaxandMinCustID(connection, params); + this.getMaxandMinWarehouseID(connection); + } catch (SQLException se) { + logger.log(Level.SEVERE, "Failed to get max and min customer id", se); + } + } + initCompleted = true; + } + } + + + public void execute(Map params) throws SwingBenchException { + List productOrders = new ArrayList(); + Connection connection = (Connection) params.get(SwingBenchTask.JDBC_CONNECTION); + initJdbcTask(); + + long executeStart = System.nanoTime(); + + try { + try { + custID = RandomGenerator.randomLong(MIN_CUSTID, MAX_CUSTID); + logon(connection, custID); + addInsertStatements(1); + addCommitStatements(1); + getCustomerDetails(connection, custID); + getAddressDetails(connection, custID); + getCardDetails(connection, custID); + addSelectStatements(3); + thinkSleep(); + + int numOfBrowseCategorys = RandomGenerator.randomInteger(1, MAX_BROWSE_CATEGORY); + + for (int i = 0; i < numOfBrowseCategorys; i++) { // Look at a randomn number of products + productOrders = getProductDetailsByCategory(connection, RandomGenerator.randomInteger(MIN_CATEGORY, MAX_CATEGORY)); + addSelectStatements(1); + thinkSleep(); + } + if (productOrders.size() > 0) { + try (PreparedStatement seqPs = connection.prepareStatement("select orders_seq.nextval from dual"); + ResultSet rs = seqPs.executeQuery()) { + rs.next(); + orderID = rs.getLong(1); + } catch (Exception se) { + throw new SwingBenchException(se); + } + addSelectStatements(1); + thinkSleep(); + int wareHouseId = RandomGenerator.randomInteger(MIN_WAREHOUSE_ID, MAX_WAREHOUSE_ID); + Date orderDate = new Date(System.currentTimeMillis()); + // TODO: Add insert columns to provide equivalence to PL/SQL version + try (PreparedStatement insOPs = + connection.prepareStatement("insert into orders(ORDER_ID, ORDER_DATE, CUSTOMER_ID, WAREHOUSE_ID, DELIVERY_TYPE, COST_OF_DELIVERY, WAIT_TILL_ALL_AVAILABLE) " + + "values (?, ?, ?, ?, ?, ?, ?)");) { + insOPs.setLong(1, orderID); + insOPs.setDate(2, orderDate); + insOPs.setLong(3, custID); + insOPs.setInt(4, wareHouseId); + insOPs.setString(5, "Standard"); + insOPs.setInt(6, RandomGenerator.randomInteger(MIN_COST_DELIVERY, MAX_COST_DELIVERY)); + insOPs.setString(7, "ship_asap"); + insOPs.execute(); + } catch (Exception se) { + throw new SwingBenchException(se); + } + addInsertStatements(1); + thinkSleep(); + + int numOfProductsToBuy = RandomGenerator.randomInteger(MIN_PRODS_TO_BUY, productOrders.size()); + double totalOrderCost = 0; + List itemsOrdered = new ArrayList(); + + for (int lineItemID = 0; lineItemID < numOfProductsToBuy; lineItemID++) { + //int prodID = ((Integer)products.get(RandomGenerator.randomInteger(0, products.size()))).intValue(); + int prodID = productOrders.get(lineItemID).getProductID(); + int quantity; + double price = + productOrders.get(lineItemID).getProductID(); + quantity = productOrders.get(lineItemID).getQuantityAvailable(); // check to see if its in stock + + if (quantity > 0) { + try (PreparedStatement insIPs = + connection.prepareStatement("insert into order_items(ORDER_ID, LINE_ITEM_ID, PRODUCT_ID, UNIT_PRICE, QUANTITY, GIFT_WRAP, CONDITION, ESTIMATED_DELIVERY) " + + "values (?, ?, ?, ?, ?, ?, ?, (SYSDATE+ 3))")) { + insIPs.setLong(1, orderID); + insIPs.setInt(2, lineItemID); + insIPs.setInt(3, prodID); + insIPs.setDouble(4, price); + insIPs.setInt(5, 1); + insIPs.setString(6, "None"); + insIPs.setString(7, "New"); + insIPs.execute(); + } catch (Exception se) { + throw new SwingBenchException(se); + } + addInsertStatements(1); + } + + thinkSleep(); + + ProductDetails inventoryUpdate = new ProductDetails(prodID, wareHouseId, 1); + itemsOrdered.add(inventoryUpdate); + totalOrderCost = totalOrderCost + price; + } + + try (PreparedStatement updOPs = connection.prepareStatement("update orders " + "set order_mode = ?, " + "order_status = ?, " + "order_total = ? " + "where order_id = ?")) { + updOPs.setString(1, "online"); + updOPs.setInt(2, RandomGenerator.randomInteger(0, AWAITING_PROCESSING)); + updOPs.setDouble(3, totalOrderCost); + updOPs.setLong(4, orderID); + updOPs.execute(); + } catch (SQLException se) { + throw new SwingBenchException(se); + } + + addUpdateStatements(1); + thinkSleep(); + //getOrderDetailsByOrderID(connection, orderID); + //addSelectStatements(1); + thinkSleep(); + + for (int i = 0; i < itemsOrdered.size(); i++) { + ProductDetails inventoryUpdate = itemsOrdered.get(i); + try (PreparedStatement updIns = connection.prepareStatement("update inventories " + "set quantity_on_hand = quantity_on_hand - ? " + "where product_id = ? " + "and warehouse_id = ?")) { + updIns.setInt(1, inventoryUpdate.quantityAvailable); + updIns.setInt(2, inventoryUpdate.productID); + updIns.setInt(3, inventoryUpdate.warehouseID); + updIns.execute(); + updIns.close(); + addUpdateStatements(1); + } catch (SQLException se) { + throw new SwingBenchException(se); + } + } + + + connection.commit(); + addCommitStatements(1); + } + } catch (SQLException e) { + logger.log(Level.FINE, String.format("Exception : ", e.getMessage())); + logger.log(Level.FINEST, "SQLException thrown : ", e); + throw new SwingBenchException(e); // shouldn't happen + } + + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), true, getInfoArray())); + } catch (SwingBenchException sbe) { + try { + addRollbackStatements(1); + connection.rollback(); + } catch (SQLException er) { + logger.log(Level.FINE, "Unable to rollback transaction"); + } + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), false, getInfoArray())); + throw new SwingBenchException(sbe); + } + } + + /*public void populate(int numToPopulate, boolean isRandomSizes, Connection connection) throws SQLException { // used for initial population + + ((OracleConnection)connection).setDefaultExecuteBatch(100); + seqPs = connection.prepareStatement("select orders_seq.nextval from dual"); //insert a order + insOPs = connection.prepareStatement("insert into orders(ORDER_ID, ORDER_DATE, ORDER_TOTAL, CUSTOMER_ID) " + "values (?, SYSTIMESTAMP, ?, ?)"); + insIPs = connection.prepareStatement("insert into order_items(ORDER_ID, LINE_ITEM_ID, PRODUCT_ID, UNIT_PRICE, QUANTITY) " + "values (?, ?, ?, ?, ?)"); + ResultSet rs = seqPs.executeQuery(); + rs.next(); + orderID = rs.getInt(1); + rs.close(); + + Map selectedProducts = null; + + for (int x = 0; x < numToPopulate; x++) { + int numOfProductsToBuy = (isRandomSizes) ? RandomGenerator.randomInteger(MIN_PRODS_TO_BUY, MAX_PRODS_TO_BUY) + 1 : STATICLINEITEMSIZE; + double totalOrderCost = 0; + selectedProducts = new HashMap(numOfProductsToBuy); + for (int i = 1; i < numOfProductsToBuy; i++) { + Integer randProdID = null; + while (true) { + randProdID = RandomGenerator.randomInteger(MIN_PROD_ID, MAX_PROD_ID); + if (selectedProducts.get(randProdID) == null) { + selectedProducts.put(randProdID, randProdID); + break; + } + } + + // int prodID = ((Integer)products.get(randProdID.intValue())).intValue(); + // int prodID = RandomGenerator.randomInteger(MIN_PROD_ID, MAX_PROD_ID); + int quantity = 1; + + double price = RandomGenerator.randomInteger(2, 15); + totalOrderCost += price; + insIPs.setLong(1, orderID); + insIPs.setInt(2, i); + insIPs.setInt(3, randProdID); + insIPs.setDouble(4, price); + insIPs.setInt(5, quantity); + insIPs.executeUpdate(); + } + + custID = RandomGenerator.randomLong(MIN_CUSTID, MAX_CUSTID); + insOPs.setLong(1, orderID); + //insOPs.setDate(2, new Date(System.nanoTime())); + insOPs.setDouble(2, totalOrderCost); + insOPs.setLong(3, custID); + insOPs.execute(); + + if ((orderID % 10000) == 0) { + connection.commit(); + } + + orderID++; + } + + Statement st = connection.createStatement(); + st.execute("alter sequence orders_seq increment by " + numToPopulate); + rs = seqPs.executeQuery(); + st.execute("alter sequence orders_seq increment by 1"); + st.close(); + seqPs.close(); + insOPs.close(); + insIPs.close(); + ((OracleConnection)connection).setDefaultExecuteBatch(1); + }*/ + + public void close() { + } + + +} diff --git a/src/com/dom/benchmarking/swingbench/transactions/OrderEntryProcess.java b/src/com/dom/benchmarking/swingbench/transactions/OrderEntryProcess.java new file mode 100644 index 0000000..599fe5e --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/transactions/OrderEntryProcess.java @@ -0,0 +1,494 @@ +package com.dom.benchmarking.swingbench.transactions; + + +import com.dom.benchmarking.swingbench.constants.Constants; +import com.dom.benchmarking.swingbench.kernel.DatabaseTransaction; +import com.dom.util.RandomUtilities; + +import java.sql.Connection; +import java.sql.Date; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.logging.Logger; + + +public abstract class OrderEntryProcess extends DatabaseTransaction { + + static final String NEW_CUSTOMER = "New Customer"; + static final String CUTOMER_ORDER = "Customer Order"; + static final String CUSTOMER_BROWSE = "Customer Browse"; + static final String GET_CUSTOMER_SEQ_TX = "Get Customer Sequence"; + static final String GET_ORDER_SEQ_TX = "Get Order Sequence"; + static final String INSERT_CUSTOMER_TX = "Insert New Customer"; + static final String INSERT_ITEM_TX = "Insert Order Item"; + static final String INSERT_ORDER_TX = "Insert Order"; + static final String UPDATE_ORDER_TX = "Update Order"; + static final String UPDATE_WAREHOUSE_TX = "Update Warehouse"; + static final String GET_CUSTOMER_DETAILS_TX = "Get Customer Details"; + static final String BROWSE_PENDING_ORDERS = "Browse Pending Orders"; + static final String BROWSE_BY_PROD_ID = "Browse Product by ID"; + static final String BROWSE_BY_CATEGORY_TX = "Browse Products by Category"; + static final String BROWSE_BY_CAT_QUAN_TX = "Browse Products by Quantity"; + static final String BROWSE_BY_ORDER_ID = "Browse Orders by ID"; + static final String BROWSE_ORDER_DETAILS = "Browse Order Details"; + static final String UPDATE_PENDING_ORDERS = "Update Pending Orders"; + static final String GET_ORDER_BY_CUSTOMER_TX = "Browse Order by Customer"; + static final int MIN_CATEGORY = 1; + static final int MAX_CATEGORY = 199; + static final int MAX_BROWSE_CATEGORY = 24; + static final int MAX_CREDITLIMIT = 5000; + static final int MIN_CREDITLIMIT = 100; + static final int MIN_SALESID = 145; + static final int MAX_SALESID = 171; + static final int MIN_PRODS_TO_BUY = 2; + static final int MAX_PRODS_TO_BUY = 6; + static final int MIN_PROD_ID = 1; + static final int HOUSE_NO_RANGE = 200; + static final int MAX_PROD_ID = 1000; + static final int MIN_COST_DELIVERY = 1; + static final int MAX_COST_DELIVERY = 5; + static int MIN_WAREHOUSE_ID = 1; + static int MAX_WAREHOUSE_ID = 1000; + static long MIN_ORDERID = 1; + static long MAX_ORDERID = 146610; + static final int AWAITING_PROCESSING = 4; + static final int ORDER_PROCESSED = 10; + static long MIN_CUSTID = 0; + static long MAX_CUSTID = 0; + private PreparedStatement catPs = null; + private PreparedStatement cardPs = null; + private PreparedStatement catqPs = null; + private PreparedStatement custPs = null; + private PreparedStatement addPs = null; + private PreparedStatement insLogon = null; + private PreparedStatement orderPs = null; + private PreparedStatement orderPs2 = null; + private PreparedStatement orderPs3 = null; + private PreparedStatement prodPs = null; + private PreparedStatement prodqPs = null; + private static final Logger logger = Logger.getLogger(OrderEntryProcess.class.getName()); + private static Object lock = new Object(); + + + public void logon(Connection connection, long custid) throws SQLException { + Date currentTime = new Date(System.currentTimeMillis()); + try (PreparedStatement insLogon = connection.prepareStatement("insert into logon (logon_id, customer_id, logon_date) values(logon_seq.nextval,?,?)")) { + insLogon.setLong(1, custid); + insLogon.setDate(2, currentTime); + insLogon.executeUpdate(); + connection.commit(); + insLogon.close(); + } + } + + public void getMaxandMinCustID(Connection connection, Map params) throws SQLException { + + + if (MAX_CUSTID == 0) { // load any data you might need (in this case only once) + + synchronized (lock) { + if (MAX_CUSTID == 0) { + + + String minCI = (String) params.get(Constants.SOEMINCUSTOMERID); + String maxCI = (String) params.get(Constants.SOEMAXCUSTOMERID); + if ((minCI != null) && (maxCI != null)) { + logger.fine("Acquiring customer counts from environment variables"); + MIN_CUSTID = Long.parseLong(minCI); + MAX_CUSTID = Long.parseLong(maxCI); + } else { + PreparedStatement ps = connection.prepareStatement("select 1 from user_tables where table_name = 'ORDERENTRY_METADATA'"); + ResultSet trs = ps.executeQuery(); + if (trs.next()) { + logger.fine("Acquiring customer counts from metadata table"); + PreparedStatement vps = connection.prepareStatement("select metadata_key, metadata_value from ORDERENTRY_METADATA"); + ResultSet vrs = vps.executeQuery(); + while (vrs.next()) { + if (vrs.getString(1).equals("SOE_MIN_ORDER_ID")) { + MIN_ORDERID = Long.parseLong(vrs.getString(2)); + } else if (vrs.getString(1).equals("SOE_MAX_ORDER_ID")) { + MAX_ORDERID = Long.parseLong(vrs.getString(2)); + } else if (vrs.getString(1).equals("SOE_MIN_CUSTOMER_ID")) { + MIN_CUSTID = Long.parseLong(vrs.getString(2)); + } else if (vrs.getString(1).equals("SOE_MAX_CUSTOMER_ID")) { + MAX_CUSTID = Long.parseLong(vrs.getString(2)); + } + } + logger.fine("Min CustomerID = " + MIN_CUSTID + ", Max CustomerID = " + MAX_CUSTID); + vrs.close(); + vps.close(); + } else { + logger.fine("Acquiring customer counts from database"); + + PreparedStatement mmPs = connection.prepareStatement("select min(customer_id), max(customer_id) from customers"); + ResultSet rs = mmPs.executeQuery(); + + if (rs.next()) { + MIN_CUSTID = rs.getLong(1); + MAX_CUSTID = rs.getLong(2); + } + logger.fine("Min CustomerID = " + MIN_CUSTID + ", Max CustomerID = " + MAX_CUSTID); + rs.close(); + mmPs.close(); //should be called only once; + + mmPs = connection.prepareStatement("select min(order_id), max(order_id) from orders"); + rs = mmPs.executeQuery(); + + if (rs.next()) { + MIN_ORDERID = rs.getLong(1); + MAX_ORDERID = rs.getLong(2); + } + logger.fine("Min CustomerID = " + MIN_CUSTID + ", Max CustomerID = " + MAX_CUSTID); + rs.close(); + mmPs.close(); //should be called only once; + } + + trs.close(); + ps.close(); + } + } + } + + } + } + + // public void getMaxandMinCustID(Connection connection) throws SQLException { + // PreparedStatement mmPs = null; + // ResultSet rs = null; + // try { + // mmPs = connection.prepareStatement("select min(customer_id), max(customer_id) from customers"); + // rs = mmPs.executeQuery(); + // if (rs.next()) { + // MIN_CUSTID = rs.getInt(1); + // MAX_CUSTID = rs.getInt(2); + // } + // } finally { + // rs.close(); + // mmPs.close(); + // } + // + // //should be called only once; + // } + + public void getMaxandMinWarehouseID(Connection connection) throws SQLException { + PreparedStatement mmPs = null; + ResultSet rs = null; + try { + mmPs = connection.prepareStatement("select min(warehouse_id), max(warehouse_id) from warehouses"); + rs = mmPs.executeQuery(); + if (rs.next()) { + MIN_WAREHOUSE_ID = rs.getInt(1); + MAX_WAREHOUSE_ID = rs.getInt(2); + } + } finally { + rs.close(); + mmPs.close(); + } + + } + + public void insertAdditionalWarehouses(Connection connection, int numWarehouses) throws SQLException { + PreparedStatement iaw = null; + try { + iaw = connection.prepareStatement("insert into warehouses(warehouse_id, warehouse_name, location_id) values (?,?,?)"); + + for (int i = 0; i < numWarehouses; i++) { + int whid = (MAX_WAREHOUSE_ID + i) + 1; + iaw.setInt(1, whid); + iaw.setString(2, "Warehouse Number " + whid); + iaw.setInt(3, RandomUtilities.randomInteger(1, 9999)); + iaw.executeUpdate(); + } + connection.commit(); + + } finally { + iaw.close(); + } + } + + public List getCustomerDetailsByName(Connection connection, String firstname, String lastName) throws SQLException { + List result = new ArrayList(); + ResultSet rs = null; + try { + custPs = connection.prepareStatement( + "SELECT CUSTOMER_ID, \n" + + " CUST_FIRST_NAME, \n" + + " CUST_LAST_NAME, \n" + + " NLS_LANGUAGE, \n" + + " NLS_TERRITORY, \n" + + " CREDIT_LIMIT, \n" + + " CUST_EMAIL, \n" + + " ACCOUNT_MGR_ID, \n" + + " CUSTOMER_SINCE, \n" + + " CUSTOMER_CLASS, \n" + + " SUGGESTIONS, \n" + + " DOB, \n" + + " MAILSHOT, \n" + + " PARTNER_MAILSHOT, \n" + + " PREFERRED_ADDRESS,\n" + + " PREFERRED_CARD\n" + + " FROM CUSTOMERS \n" + + " WHERE lower(cust_last_name) = lower(?) \n" + + " AND lower(cust_first_name) = lower(?) \n" + + " AND rownum < 5"); + custPs.setString(2, firstname); + custPs.setString(1, lastName); + rs = custPs.executeQuery(); + while (rs.next()) { + result.add(rs.getLong(1)); + } + } finally { + hardClose(rs); + hardClose(custPs); + } + return result; + } + + public void getCustomerDetails(Connection connection, long custId) throws SQLException { + ResultSet rs = null; + try { + custPs = connection.prepareStatement( + "SELECT CUSTOMER_ID, CUST_FIRST_NAME, CUST_LAST_NAME, NLS_LANGUAGE, \n" + + " NLS_TERRITORY, CREDIT_LIMIT, CUST_EMAIL, ACCOUNT_MGR_ID, CUSTOMER_SINCE, \n" + + " CUSTOMER_CLASS, SUGGESTIONS, DOB, MAILSHOT, PARTNER_MAILSHOT, \n" + + " PREFERRED_ADDRESS, PREFERRED_CARD \n" + + "FROM\n" + + " CUSTOMERS WHERE CUSTOMER_ID = ? AND ROWNUM < 5"); + custPs.setLong(1, custId); + + rs = custPs.executeQuery(); + rs.next(); + } finally { + hardClose(rs); + hardClose(custPs); + } + + } + + public void getAddressDetails(Connection connection, long custId) throws SQLException { + ResultSet rs = null; + try { + addPs = connection.prepareStatement( + "SELECT ADDRESS_ID, \n" + + " CUSTOMER_ID, \n" + + " DATE_CREATED, \n" + + " HOUSE_NO_OR_NAME, \n" + + " STREET_NAME, \n" + + " TOWN, \n" + + " COUNTY, \n" + + " COUNTRY, \n" + + " POST_CODE, \n" + + " ZIP_CODE \n" + + " FROM ADDRESSES \n" + + " WHERE customer_id = ? \n" + + " AND rownum < 5"); + addPs.setLong(1, custId); + rs = addPs.executeQuery(); + rs.next(); + } finally { + hardClose(rs); + hardClose(addPs); + } + } + + public void getCardDetails(Connection connection, long custId) throws SQLException { + ResultSet rs = null; + try { + cardPs = connection.prepareStatement( + "SELECT CARD_ID,\n" + + " CUSTOMER_ID,\n" + + " CARD_TYPE,\n" + + " CARD_NUMBER,\n" + + " EXPIRY_DATE,\n" + + " IS_VALID,\n" + + " SECURITY_CODE\n" + + " FROM card_details \n" + + " WHERE CUSTOMER_ID = ? \n" + + " AND rownum < 5"); + cardPs.setLong(1, custId); + rs = cardPs.executeQuery(); + rs.next(); + } finally { + hardClose(rs); + hardClose(cardPs); + } + } + + public List getOrdersByCustomer(Connection connection, long custId) throws SQLException { + List orders = new ArrayList(); + ResultSet rs = null; + try { + orderPs3 = connection.prepareStatement( + "SELECT ORDER_ID, \n" + + " ORDER_DATE, \n" + + " ORDER_MODE, \n" + + " CUSTOMER_ID, \n" + + " ORDER_STATUS, \n" + + " ORDER_TOTAL, \n" + + " SALES_REP_ID, \n" + + " PROMOTION_ID, \n" + + " WAREHOUSE_ID, \n" + + " DELIVERY_TYPE, \n" + + " COST_OF_DELIVERY, \n" + + " WAIT_TILL_ALL_AVAILABLE, \n" + + " DELIVERY_ADDRESS_ID, \n" + + " CUSTOMER_CLASS, \n" + + " CARD_ID, \n" + + " INVOICE_ADDRESS_ID \n" + + " from orders \n" + + " where customer_id = ? \n" + + " and rownum < 5"); + orderPs3.setLong(1, custId); + rs = orderPs3.executeQuery(); + while (rs.next()) { // Will only ever be a maximum of 5 + orders.add(rs.getLong(1)); + } + } finally { + hardClose(rs); + hardClose(orderPs3); + } + return orders; + } + + + public double getProductDetailsByID(Connection connection, int prodID) throws SQLException { + ResultSet rs = null; + double price = 0; + + try { + prodPs = + connection.prepareStatement(" select product_id, product_name, product_description, category_id, weight_class, supplier_id, product_status, list_price, min_price, catalog_url from product_information where product_id = ?"); + prodPs.setInt(1, prodID); + rs = prodPs.executeQuery(); + while (rs.next()) { + price = rs.getDouble(8); + } + } catch (SQLException se) { + throw se; + } finally { + hardClose(rs); + hardClose(prodPs); + } + + return price; + } + + public List getProductDetailsByCategory(Connection connection, int catID) throws SQLException { + List result = new ArrayList(); + ResultSet rs = null; + int warehouseId = RandomUtilities.randomInteger(MIN_WAREHOUSE_ID, MAX_WAREHOUSE_ID); + try { + catPs = connection.prepareStatement( + "select products.PRODUCT_ID, \n" + + " PRODUCT_NAME, \n" + + " PRODUCT_DESCRIPTION, \n" + + " CATEGORY_ID, \n" + + " WEIGHT_CLASS, \n" + + " WARRANTY_PERIOD, \n" + + " SUPPLIER_ID, \n" + + " PRODUCT_STATUS, \n" + + " LIST_PRICE, \n" + + " MIN_PRICE, \n" + + " CATALOG_URL, \n" + + " QUANTITY_ON_HAND \n" + + " from products, \n" + + " inventories \n" + + " where products.category_id = ? \n" + + " and inventories.product_id = products.product_id \n" + + " and inventories.warehouse_id = ? \n" + + " and rownum < 5"); + catPs.setInt(1, catID); + catPs.setInt(2, warehouseId); + + rs = catPs.executeQuery(); + while (rs.next()) { + result.add(new ProductDetails(rs.getInt(1), warehouseId, rs.getInt(12))); + } + } finally { + hardClose(rs); + hardClose(catPs); + } + return result; + } + + public int getProductQuantityByID(Connection connection, int ID) throws SQLException { + int quantity = 0; + ResultSet rs = null; + try { + prodqPs = + connection.prepareStatement(" select p.product_id, product_name, product_description, category_id, weight_class, supplier_id, product_status, list_price, min_price, catalog_url, quantity_on_hand, warehouse_id from product_information p, inventories i where i.product_id = ? and i.product_id = p.product_id"); + prodqPs.setInt(1, ID); + + rs = prodqPs.executeQuery(); + if (rs.next()) { + quantity = rs.getInt(11); + } + } finally { + hardClose(rs); + hardClose(prodqPs); + } + return quantity; + } + + public void getProductQuantityByCategory(Connection connection, int catID) throws SQLException { + ResultSet rs = null; + try { + catqPs = + connection.prepareStatement(" select p.product_id, product_name, product_description, category_id, weight_class, supplier_id, product_status, list_price, min_price, catalog_url, quantity_on_hand, warehouse_id from product_information p, inventories i where category_id = ? and i.product_id = p.product_id"); + catqPs.setInt(1, catID); + + rs = catqPs.executeQuery(); + rs.next(); + } finally { + hardClose(rs); + hardClose(catqPs); + } + + } + + public void getOrderByID(Connection connection, int orderID) throws SQLException { + ResultSet rs = null; + try { + orderPs = + connection.prepareStatement(" select order_id, order_date, order_mode, customer_id, order_status, order_total, sales_rep_id, promotion_id from orders where order_id = ?"); + orderPs.setInt(1, orderID); + + rs = orderPs.executeQuery(); + rs.next(); + } finally { + hardClose(rs); + hardClose(orderPs); + } + + } + + public void getOrderDetailsByOrderID(Connection connection, long orderID) throws SQLException { + ResultSet rs = null; + try { + orderPs2 = + connection.prepareStatement(" SELECT o.order_id, line_item_id, product_id, unit_price, quantity, order_mode, order_status, order_total, sales_rep_id, promotion_id, c.customer_id, cust_first_name, cust_last_name, credit_limit, cust_email FROM orders o , order_items oi, customers c WHERE o.order_id = oi.order_id and o.customer_id = c.customer_id and o.order_id = ?"); + orderPs2.setLong(1, orderID); + + rs = orderPs2.executeQuery(); + rs.next(); + } finally { + hardClose(rs); + hardClose(orderPs2); + } + + } + + /*public void setMaxSleepTime(long newMaxSleepTime) { + maxSleepTime = newMaxSleepTime; + } + + public void setMinSleepTime(long newMinSleepTime) { + minSleepTime = newMinSleepTime; + }*/ + +} diff --git a/src/com/dom/benchmarking/swingbench/transactions/ProcessOrders.java b/src/com/dom/benchmarking/swingbench/transactions/ProcessOrders.java new file mode 100644 index 0000000..0fbd0d1 --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/transactions/ProcessOrders.java @@ -0,0 +1,114 @@ +package com.dom.benchmarking.swingbench.transactions; + + +import com.dom.benchmarking.swingbench.event.JdbcTaskEvent; +import com.dom.benchmarking.swingbench.kernel.SwingBenchException; +import com.dom.benchmarking.swingbench.kernel.SwingBenchTask; +import com.dom.benchmarking.swingbench.utilities.RandomGenerator; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + + +public class ProcessOrders extends OrderEntryProcess { + + private static final Logger logger = Logger.getLogger(ProcessOrders.class.getName()); + private PreparedStatement orderPs3 = null; + private PreparedStatement updoPs = null; + private int orderID; + + public ProcessOrders() { + } + + public void close() { + } + + public void init(Map parameters) { + } + + public void execute(Map params) throws SwingBenchException { + Connection connection = (Connection) params.get(SwingBenchTask.JDBC_CONNECTION); + initJdbcTask(); + ResultSet rs = null; + + long executeStart = System.nanoTime(); + + try { + try { + orderPs3 = connection.prepareStatement( + "WITH need_to_process AS \n" + + " (SELECT order_id, \n" + + " /* we're only looking for unprocessed orders */ \n" + + " customer_id \n" + + " FROM orders \n" + + " WHERE order_status <= 4 \n" + + " AND rownum < 10 \n" + + " ) \n" + + " SELECT o.order_id, \n" + + " oi.line_item_id, \n" + + " oi.product_id, \n" + + " oi.unit_price, \n" + + " oi.quantity, \n" + + " o.order_mode, \n" + + " o.order_status, \n" + + " o.order_total, \n" + + " o.sales_rep_id, \n" + + " o.promotion_id, \n" + + " c.customer_id, \n" + + " c.cust_first_name, \n" + + " c.cust_last_name, \n" + + " c.credit_limit, \n" + + " c.cust_email, \n" + + " o.order_date \n" + + " FROM orders o, \n" + + " need_to_process ntp, \n" + + " customers c, \n" + + " order_items oi \n" + + " WHERE ntp.order_id = o.order_id \n" + + " AND c.customer_id = o.customer_id \n" + + " and oi.order_id (+) = o.order_id"); + + rs = orderPs3.executeQuery(); + rs.next(); + orderID = rs.getInt(1); + addSelectStatements(1); + thinkSleep(); //update the order + updoPs = connection.prepareStatement("update /*+ index(orders, order_pk) */ " + "orders " + "set order_status = ? " + "where order_id = ?"); + updoPs.setInt(1, RandomGenerator.randomInteger(AWAITING_PROCESSING + 1, ORDER_PROCESSED)); + updoPs.setInt(2, orderID); + updoPs.execute(); + addUpdateStatements(1); + connection.commit(); + addCommitStatements(1); + } catch (SQLException se) { + logger.log(Level.FINE, String.format("Exception : ", se.getMessage())); + logger.log(Level.FINEST, "SQLException thrown : ", se); + throw new SwingBenchException(se); + } finally { + hardClose(rs); + hardClose(orderPs3); + hardClose(updoPs); + } + + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), true, getInfoArray())); + } catch (SwingBenchException sbe) { + try { + addRollbackStatements(1); + connection.rollback(); + } catch (SQLException er) { + logger.log(Level.FINE, "Unable to rollback transaction"); + } + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), false, getInfoArray())); + + + throw new SwingBenchException(sbe.getMessage()); + } + } + +} diff --git a/src/com/dom/benchmarking/swingbench/transactions/ProductDetails.java b/src/com/dom/benchmarking/swingbench/transactions/ProductDetails.java new file mode 100644 index 0000000..24b6490 --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/transactions/ProductDetails.java @@ -0,0 +1,34 @@ +package com.dom.benchmarking.swingbench.transactions; + + +public class ProductDetails { + + double price; + int productID; + int quantityAvailable; + int warehouseID; + + public double getPrice() { + return price; + } + + public int getProductID() { + return productID; + } + + public int getQuantityAvailable() { + return quantityAvailable; + } + + public int getWarehouseID() { + return warehouseID; + } + + + public ProductDetails(int pid, int wid, int qo) { + productID = pid; + warehouseID = wid; + quantityAvailable = qo; + } + +} diff --git a/src/com/dom/benchmarking/swingbench/transactions/SalesRepsOrdersQuery.java b/src/com/dom/benchmarking/swingbench/transactions/SalesRepsOrdersQuery.java new file mode 100644 index 0000000..5773fa0 --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/transactions/SalesRepsOrdersQuery.java @@ -0,0 +1,83 @@ +package com.dom.benchmarking.swingbench.transactions; + + +import com.dom.benchmarking.swingbench.event.JdbcTaskEvent; +import com.dom.benchmarking.swingbench.kernel.SwingBenchException; +import com.dom.benchmarking.swingbench.kernel.SwingBenchTask; +import com.dom.benchmarking.swingbench.utilities.RandomGenerator; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + + +public class SalesRepsOrdersQuery extends OrderEntryProcess { + private static final Logger logger = Logger.getLogger(SalesRepsOrdersQuery.class.getName()); + private PreparedStatement ps = null; + + public SalesRepsOrdersQuery() { + super(); + } + + public void init(Map params) { + } + + public void execute(Map params) throws SwingBenchException { + + Connection connection = (Connection) params.get(SwingBenchTask.JDBC_CONNECTION); + initJdbcTask(); + + int salesRepId = RandomGenerator.randomInteger(1, 1000); + + long executeStart = System.nanoTime(); + + try { + try { + ResultSet rs = null; + try { + ps = connection.prepareStatement( + "SELECT tt.ORDER_TOTAL,\n" + + " tt.SALES_REP_ID,\n" + + " tt.ORDER_DATE,\n" + + " customers.CUST_FIRST_NAME,\n" + + " customers.CUST_LAST_NAME\n" + + "FROM\n" + + " (SELECT orders.ORDER_TOTAL,\n" + + " orders.SALES_REP_ID,\n" + + " orders.ORDER_DATE,\n" + + " orders.customer_id,\n" + + " rank() Over (Order By orders.ORDER_TOTAL DESC) sal_rank\n" + + " FROM orders\n" + + " WHERE orders.SALES_REP_ID = ?\n" + + " ) tt,\n" + + " customers\n" + + "WHERE tt.sal_rank <= 10\n" + + "and customers.customer_id = tt.customer_id"); + ps.setInt(1, salesRepId); + rs = ps.executeQuery(); + rs.next(); + } finally { + hardClose(rs); + hardClose(ps); + } + } catch (SQLException se) { + logger.log(Level.FINE, String.format("Exception : ", se.getMessage())); + logger.log(Level.FINEST, "SQLException thrown : ", se); + throw new SwingBenchException(se.getMessage()); + } + + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), true, getInfoArray())); + } catch (SwingBenchException sbe) { + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), false, getInfoArray())); + throw new SwingBenchException(sbe.getMessage()); + } + } + + public void close() { + } +} diff --git a/src/com/dom/benchmarking/swingbench/transactions/UpdateCustomerDetails.java b/src/com/dom/benchmarking/swingbench/transactions/UpdateCustomerDetails.java new file mode 100644 index 0000000..539d3bf --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/transactions/UpdateCustomerDetails.java @@ -0,0 +1,176 @@ +package com.dom.benchmarking.swingbench.transactions; + +import com.dom.benchmarking.swingbench.event.JdbcTaskEvent; +import com.dom.benchmarking.swingbench.kernel.SwingBenchException; +import com.dom.benchmarking.swingbench.kernel.SwingBenchTask; +import com.dom.benchmarking.swingbench.utilities.RandomGenerator; +import com.dom.util.Utilities; + +import java.io.File; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +import java.util.List; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + +public class UpdateCustomerDetails extends OrderEntryProcess { + + private static final String COUNTIES_FILE = "data/counties.txt"; + private static final String COUNTRIES_FILE = "data/countries.txt"; + private static final String FIRST_NAMES_FILE = "data/lowerfirstnames.txt"; + private static final String LAST_NAMES_FILE = "data/lowerlastnames.txt"; + private static final String TOWNS_FILE = "data/towns.txt"; + private static List counties = null; + private static List countries = null; + private static List firstNames = null; + private static List lastNames = null; + private static List towns = null; + private static Object lock = new Object(); + private PreparedStatement addSeqPs = null; + private PreparedStatement insAddPs = null; + private PreparedStatement updAddPs = null; + private static final Logger logger = Logger.getLogger(UpdateCustomerDetails.class.getName()); + + public UpdateCustomerDetails() { + super(); + } + + @Override + public void init(Map params) throws SwingBenchException { + boolean initCompleted = false; + Connection connection = (Connection) params.get(SwingBenchTask.JDBC_CONNECTION); + + if ((firstNames == null) || !initCompleted) { // load any data you might need (in this case only once) + + synchronized (lock) { + if (firstNames == null) { + + String value = (String) params.get("SOE_FIRST_NAMES_LOC"); + File firstNamesFile = new File((value == null) ? FIRST_NAMES_FILE : value); + value = (String) params.get("SOE_LAST_NAMES_LOC"); + File lastNamesFile = new File((value == null) ? LAST_NAMES_FILE : value); + + value = (String) params.get("SOE_TOWNS_LOC"); + File townsFile = new File((value == null) ? TOWNS_FILE : value); + value = (String) params.get("SOE_COUNTIES_LOC"); + File countiesFile = new File((value == null) ? COUNTIES_FILE : value); + value = (String) params.get("SOE_COUNTRIES_LOC"); + File countriesFile = new File((value == null) ? COUNTRIES_FILE : value); + + try { + firstNames = Utilities.cacheFile(firstNamesFile); + lastNames = Utilities.cacheFile(lastNamesFile); + counties = Utilities.cacheFile(countiesFile); + towns = Utilities.cacheFile(townsFile); + countries = Utilities.cacheFile(countriesFile); + + + logger.fine("Completed reading files needed for initialisation of NewCustomerProcess()"); + + } catch (java.io.FileNotFoundException fne) { + logger.log(Level.SEVERE, "Unable to open data seed files : ", fne); + throw new SwingBenchException(fne); + } catch (java.io.IOException ioe) { + logger.log(Level.SEVERE, "IO problem opening seed files : ", ioe); + throw new SwingBenchException(ioe); + } + } + + initCompleted = true; + } + } + } + + @Override + public void execute(Map params) throws SwingBenchException { + Connection connection = (Connection) params.get(SwingBenchTask.JDBC_CONNECTION); + initJdbcTask(); + ResultSet rs = null; + + String firstName = firstNames.get(RandomGenerator.randomInteger(0, firstNames.size())); + String lastName = lastNames.get(RandomGenerator.randomInteger(0, lastNames.size())); + String town = towns.get(RandomGenerator.randomInteger(0, towns.size())); + String county = counties.get(RandomGenerator.randomInteger(0, counties.size())); + String country = countries.get(RandomGenerator.randomInteger(0, countries.size())); + long executeStart = System.nanoTime(); + + + try { + try { + List custIDLists = getCustomerDetailsByName(connection, firstName, lastName); + addSelectStatements(1); + thinkSleep(); + if (custIDLists.size() > 0) { + addSeqPs = connection.prepareStatement("select address_seq.nextval from dual"); + rs = addSeqPs.executeQuery(); + + rs.next(); + Long addId = rs.getLong(1); + insAddPs = connection.prepareStatement( + "INSERT INTO ADDRESSES \n" + + " ( address_id, \n" + + " customer_id, \n" + + " date_created, \n" + + " house_no_or_name, \n" + + " street_name, \n" + + " town, \n" + + " county, \n" + + " country, \n" + + " post_code, \n" + + " zip_code \n" + + " ) \n" + + " VALUES \n" + + " ( ?, ?, TRUNC(SYSDATE,'MI'), ?, 'Street Name', ?, ?, ?, 'Postcode', NULL)"); + insAddPs.setLong(1, addId); + insAddPs.setLong(2, custIDLists.get(0)); + insAddPs.setInt(3, RandomGenerator.randomInteger(1, HOUSE_NO_RANGE)); + insAddPs.setString(4, town); + insAddPs.setString(5, county); + insAddPs.setString(6, country); + insAddPs.execute(); + addInsertStatements(1); + + updAddPs = connection.prepareStatement(" UPDATE CUSTOMERS SET PREFERRED_ADDRESS = ? WHERE customer_id = ?"); + updAddPs.setLong(1, addId); + updAddPs.setLong(2, custIDLists.get(0)); + updAddPs.execute(); + addUpdateStatements(1); + connection.commit(); + addCommitStatements(1); + } + + } catch (SQLException se) { + logger.log(Level.FINE, String.format("Exception : ", se.getMessage())); + logger.log(Level.FINEST, "SQLException thrown : ", se); + throw new SwingBenchException(se); + } finally { + hardClose(rs); + hardClose(addSeqPs); + hardClose(insAddPs); + hardClose(updAddPs); + } + + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), true, getInfoArray())); + } catch (SwingBenchException sbe) { + try { + addRollbackStatements(1); + connection.rollback(); + } catch (SQLException er) { + logger.log(Level.FINE, "Unable to rollback transaction"); + } + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), false, getInfoArray())); + throw new SwingBenchException(sbe.getMessage()); + } + + } + + @Override + public void close() { + // TODO Implement this method + } +} diff --git a/src/com/dom/benchmarking/swingbench/transactions/WarehouseActivityQuery.java b/src/com/dom/benchmarking/swingbench/transactions/WarehouseActivityQuery.java new file mode 100644 index 0000000..263b2ef --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/transactions/WarehouseActivityQuery.java @@ -0,0 +1,100 @@ +package com.dom.benchmarking.swingbench.transactions; + + +import com.dom.benchmarking.swingbench.event.JdbcTaskEvent; +import com.dom.benchmarking.swingbench.kernel.SwingBenchException; +import com.dom.benchmarking.swingbench.kernel.SwingBenchTask; +import com.dom.benchmarking.swingbench.utilities.RandomGenerator; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + + +public class WarehouseActivityQuery extends OrderEntryProcess { + private static final Logger logger = Logger.getLogger(WarehouseActivityQuery.class.getName()); + private PreparedStatement ps = null; + + public WarehouseActivityQuery() { + super(); + } + + public void init(Map params) { + } + + public void execute(Map params) throws SwingBenchException { + + Connection connection = (Connection) params.get(SwingBenchTask.JDBC_CONNECTION); + initJdbcTask(); + + int warehouseID = RandomGenerator.randomInteger(1, 1000); + + long executeStart = System.nanoTime(); + + try { + try { + + ResultSet rs = null; + try { + ps = connection.prepareStatement( + "WITH stage1 AS -- get 12 rows of 5mins\n" + + " (SELECT\n" + + " /*+ materialize CARDINALITY(12) */\n" + + " (rownum*(1/288)) offset\n" + + " FROM dual\n" + + " CONNECT BY rownum <= 12\n" + + " ),\n" + + " stage2 AS -- get 12 rows with 2 columns, 1 col lagged behind the other\n" + + " (SELECT\n" + + " /*+ materialize CARDINALITY(12) */\n" + + " lag(offset, 1, 0) over (order by rownum) ostart,\n" + + " offset oend\n" + + " FROM stage1\n" + + " ),\n" + + " stage3 AS -- transform them to timestamps\n" + + " (SELECT\n" + + " /*+ materialize CARDINALITY(12) */\n" + + " (systimestamp - ostart) date1,\n" + + " (systimestamp - oend) date2\n" + + " FROM stage2\n" + + " )\n" + + "SELECT warehouse_id, date1,\n" + + " date2,\n" + + " SUM(orders.order_total) \"Value of Orders\",\n" + + " Count(1) \"Number of Orders\"\n" + + "FROM stage3,\n" + + " orders\n" + + "WHERE order_date BETWEEN date2 AND date1\n" + + "and warehouse_id = ?\n" + + "GROUP BY warehouse_id, date1,\n" + + " date2\n" + + "ORDER BY date1,\n" + + " date2 DESC"); + ps.setInt(1, warehouseID); + rs = ps.executeQuery(); + rs.next(); + } finally { + hardClose(rs); + hardClose(ps); + } + } catch (SQLException se) { + logger.log(Level.FINE, String.format("Exception : ", se.getMessage())); + logger.log(Level.FINEST, "SQLException thrown : ", se); + throw new SwingBenchException(se); + } + + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), true, getInfoArray())); + } catch (SwingBenchException sbe) { + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), false, getInfoArray())); + throw new SwingBenchException(sbe.getMessage()); + } + } + + public void close() { + } +} diff --git a/src/com/dom/benchmarking/swingbench/transactions/WarehouseOrdersQuery.java b/src/com/dom/benchmarking/swingbench/transactions/WarehouseOrdersQuery.java new file mode 100644 index 0000000..6ae127f --- /dev/null +++ b/src/com/dom/benchmarking/swingbench/transactions/WarehouseOrdersQuery.java @@ -0,0 +1,76 @@ +package com.dom.benchmarking.swingbench.transactions; + + +import com.dom.benchmarking.swingbench.event.JdbcTaskEvent; +import com.dom.benchmarking.swingbench.kernel.SwingBenchException; +import com.dom.benchmarking.swingbench.kernel.SwingBenchTask; +import com.dom.benchmarking.swingbench.utilities.RandomGenerator; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + + +public class WarehouseOrdersQuery extends OrderEntryProcess { + private static final Logger logger = Logger.getLogger(WarehouseOrdersQuery.class.getName()); + private PreparedStatement ps = null; + + public WarehouseOrdersQuery() { + super(); + } + + public void init(Map params) { + } + + public void execute(Map params) throws SwingBenchException { + + Connection connection = (Connection) params.get(SwingBenchTask.JDBC_CONNECTION); + initJdbcTask(); + + int warehouseID = RandomGenerator.randomInteger(1, 1000); + + long executeStart = System.nanoTime(); + + try { + try { + + ResultSet rs = null; + try { + ps = connection.prepareStatement( + "SELECT order_mode,\n" + + " orders.warehouse_id,\n" + + " SUM(order_total),\n" + + " COUNT(1)\n" + + "FROM orders,\n" + + " warehouses\n" + + "WHERE orders.warehouse_id = warehouses.warehouse_id\n" + + "AND warehouses.warehouse_id = ?\n" + + "GROUP BY cube(orders.order_mode, orders.warehouse_id)"); + ps.setInt(1, warehouseID); + rs = ps.executeQuery(); + rs.next(); + } finally { + hardClose(rs); + hardClose(ps); + } + } catch (SQLException se) { + logger.log(Level.FINE, String.format("Exception : ", se.getMessage())); + logger.log(Level.FINEST, "SQLException thrown : ", se); + throw new SwingBenchException(se); + } + + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), true, getInfoArray())); + } catch (SwingBenchException sbe) { + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), false, getInfoArray())); + throw new SwingBenchException(sbe.getMessage()); + } + } + + public void close() { + } +} diff --git a/src/com/mike/CallingCircle/CallingCircleLineIdentifier.java b/src/com/mike/CallingCircle/CallingCircleLineIdentifier.java new file mode 100644 index 0000000..f2efd70 --- /dev/null +++ b/src/com/mike/CallingCircle/CallingCircleLineIdentifier.java @@ -0,0 +1,55 @@ +package com.mike.CallingCircle; + +import com.mike.CallingCircle.*; + + +public class CallingCircleLineIdentifier { + private CallingLineIdentifier callingLineIdentifier; + private String rowId; + private String validFrom; + private String validTo; + private long indexId; + + public CallingCircleLineIdentifier() { + } + + public CallingLineIdentifier getCallingLineIdentifier() { + return callingLineIdentifier; + } + + public void setCallingLineIdentifier(CallingLineIdentifier newCallingLineIdentifier) { + callingLineIdentifier = newCallingLineIdentifier; + } + + public long getIndexId() { + return indexId; + } + + public void setIndexId(long newIndexId) { + indexId = newIndexId; + } + + public String getRowId() { + return rowId; + } + + public void setRowId(String newRowId) { + rowId = newRowId; + } + + public String getValidFrom() { + return validFrom; + } + + public void setValidFrom(String newValidFrom) { + validFrom = newValidFrom; + } + + public String getValidTo() { + return validTo; + } + + public void setValidTo(String newValidTo) { + validTo = newValidTo; + } +} diff --git a/src/com/mike/CallingCircle/CallingCircleProcess.java b/src/com/mike/CallingCircle/CallingCircleProcess.java new file mode 100644 index 0000000..4338d36 --- /dev/null +++ b/src/com/mike/CallingCircle/CallingCircleProcess.java @@ -0,0 +1,205 @@ +package com.mike.CallingCircle; + +import com.dom.benchmarking.swingbench.kernel.DatabaseTransaction; +import com.dom.benchmarking.swingbench.kernel.SwingBenchException; + + +import java.sql.CallableStatement; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.Types; + +import java.util.logging.*; + + +public abstract class CallingCircleProcess extends DatabaseTransaction { + private static final Logger logger = Logger.getLogger(CallingCircleProcess.class.getName()); + public static final String NEW_CC_PROCESS = "New Customer"; + public static final String UPDATE_CC_PROCESS = "Update Customer Details"; + public static final String RETRIEVE_HISTORY = "Retrieve Customer Details"; + public static final String NEW_CUSTOMER_TX = "Register New Account"; + public static final String GET_CUSTOMER_TX = "Account Login"; + public static final String NEW_CUSTOMER_CLI_TX = "Register Line"; + public static final String GET_CUSTOMER_CLI_TX = "Choose Line"; + public static final String SET_CIRCLE_CLI_TX = "Update Calling Circle"; + public static final String GET_CIRCLE_CLIS_TX = "Query Calling Circle"; + public static final String QRY_CLIS_CURRENT_TX = "Report Current Calling Circle"; + public static final String QRY_CLIS_HISTORY_TX = "Report Calling Circle History"; + public static final String DEFAULT_PROP_FILE = "callingcircle.prop"; + protected CallableStatement getCallingCircleLineIdentifiersCs = null; + protected CallableStatement getCustomerAccountCs = null; + protected CallableStatement getCustomerCallingLineIdentifierCs = null; + protected CallableStatement newCustomerAccountCs = null; + protected CallableStatement newCustomerCallingLineIdentifierCs = null; + protected CallableStatement qryCallingCircleCurrentCs = null; + protected CallableStatement qryCallingCircleHistoryCs = null; + protected CallableStatement setCallingCircleLineIdentifierCs = null; + protected CallingCircleLineIdentifier callingCircleLineIdentifier; + protected CustomerAccount customerAccount; + protected CustomerCallingLineIdentifier customerCallingLineIdentifier; + + public void newCustomerAccount(Connection connection) throws SwingBenchException { + try { + // if (newCustomerAccountCs == null) { + newCustomerAccountCs = connection.prepareCall("{call ccAppPkg.newCustAccount(?,?)}"); + // } + + newCustomerAccountCs.setString(1, customerAccount.getName()); + newCustomerAccountCs.setString(2, customerAccount.getPin()); + newCustomerAccountCs.execute(); + + newCustomerAccountCs.close(); + } catch (SQLException se) { + throw new SwingBenchException(se); + } + } + + public void getCustomerAccount(Connection connection) throws SwingBenchException { + try { + // if (getCustomerAccountCs == null) { + getCustomerAccountCs = connection.prepareCall("{call ccAppPkg.getCustAccount(?,?,?,?,?,?)}"); + // } + + getCustomerAccountCs.setString(1, customerAccount.getName()); + getCustomerAccountCs.setString(2, customerAccount.getPin()); + getCustomerAccountCs.registerOutParameter(3, Types.INTEGER); + getCustomerAccountCs.registerOutParameter(4, Types.DATE); + getCustomerAccountCs.registerOutParameter(5, Types.INTEGER); + getCustomerAccountCs.registerOutParameter(6, Types.DATE); + getCustomerAccountCs.execute(); + customerAccount.setId(getCustomerAccountCs.getLong(3)); + customerAccount.setLastLogin(getCustomerAccountCs.getDate(4)); + customerAccount.setFailedLogins(getCustomerAccountCs.getLong(5)); + customerAccount.setLastFailedLogin(getCustomerAccountCs.getDate(6)); + getCustomerAccountCs.close(); + } catch (SQLException se) { + throw new SwingBenchException(se); + } + } + + public void newCustomerCallingLineIdentifier(Connection connection) throws SwingBenchException { + try { + // if (newCustomerCallingLineIdentifierCs == null) { + newCustomerCallingLineIdentifierCs = connection.prepareCall("{call ccAppPkg.newCustCLI(?,?,?,?,?)}"); + // } + + newCustomerCallingLineIdentifierCs.setString(1, customerCallingLineIdentifier.getCallingLineIdentifier().getRegionValue()); + newCustomerCallingLineIdentifierCs.setString(2, customerCallingLineIdentifier.getCallingLineIdentifier().getCountryValue()); + newCustomerCallingLineIdentifierCs.setString(3, customerCallingLineIdentifier.getCallingLineIdentifier().getCallingLineIdentifier()); + newCustomerCallingLineIdentifierCs.setLong(4, customerCallingLineIdentifier.getCallingCircleId()); + newCustomerCallingLineIdentifierCs.setLong(5, customerAccount.getId()); + newCustomerCallingLineIdentifierCs.execute(); + newCustomerCallingLineIdentifierCs.close(); + } catch (SQLException se) { + throw new SwingBenchException(se); + } + } + + public void getCustomerCallingLineIdentifier(Connection connection) throws SwingBenchException { + try { + // if (getCustomerCallingLineIdentifierCs == null) { + getCustomerCallingLineIdentifierCs = connection.prepareCall("{call ccAppPkg.getCustCLI(?,?,?,?,?,?,?,?,?,?,?,?)}"); + // } + + getCustomerCallingLineIdentifierCs.setLong(1, customerAccount.getId()); + getCustomerCallingLineIdentifierCs.setString(2, customerCallingLineIdentifier.getCallingLineIdentifier().getCountryValue()); + getCustomerCallingLineIdentifierCs.setString(3, customerCallingLineIdentifier.getCallingLineIdentifier().getRegionValue()); + getCustomerCallingLineIdentifierCs.setString(4, customerCallingLineIdentifier.getCallingLineIdentifier().getCallingLineIdentifier()); + getCustomerCallingLineIdentifierCs.registerOutParameter(5, Types.INTEGER); + getCustomerCallingLineIdentifierCs.registerOutParameter(6, Types.VARCHAR); + getCustomerCallingLineIdentifierCs.registerOutParameter(7, Types.VARCHAR); + getCustomerCallingLineIdentifierCs.registerOutParameter(8, Types.VARCHAR); + getCustomerCallingLineIdentifierCs.registerOutParameter(9, Types.VARCHAR); + getCustomerCallingLineIdentifierCs.registerOutParameter(10, Types.INTEGER); + getCustomerCallingLineIdentifierCs.registerOutParameter(11, Types.INTEGER); + getCustomerCallingLineIdentifierCs.registerOutParameter(12, Types.VARCHAR); + getCustomerCallingLineIdentifierCs.execute(); + customerCallingLineIdentifier.setId(getCustomerCallingLineIdentifierCs.getLong(5)); + + { + CallingLineIdentifier myCallingLineIdentifier = new CallingLineIdentifier(); + myCallingLineIdentifier.setRegionType(getCustomerCallingLineIdentifierCs.getString(6)); + myCallingLineIdentifier.setRegionText(getCustomerCallingLineIdentifierCs.getString(7)); + myCallingLineIdentifier.setCountryType(getCustomerCallingLineIdentifierCs.getString(8)); + myCallingLineIdentifier.setCountryText(getCustomerCallingLineIdentifierCs.getString(9)); + customerCallingLineIdentifier.setCallingLineIdentifier(myCallingLineIdentifier); + } + + customerCallingLineIdentifier.setUpdates(getCustomerCallingLineIdentifierCs.getLong(10)); + customerCallingLineIdentifier.setUpdatesAllowed(getCustomerCallingLineIdentifierCs.getLong(11)); + customerCallingLineIdentifier.setCallingCircleName(getCustomerCallingLineIdentifierCs.getString(12)); + getCustomerCallingLineIdentifierCs.close(); + } catch (SQLException se) { + throw new SwingBenchException(se); + } + } + + public void setCallingCircleLineIdentifier(Connection connection) throws SwingBenchException { + try { + // if (setCallingCircleLineIdentifierCs == null) { + setCallingCircleLineIdentifierCs = connection.prepareCall("{call ccAppPkg.setPackageCLI(?,?,?,?,?,?)}"); + // } + + setCallingCircleLineIdentifierCs.setLong(1, callingCircleLineIdentifier.getIndexId()); + setCallingCircleLineIdentifierCs.setString(2, callingCircleLineIdentifier.getCallingLineIdentifier().getRegionValue()); + setCallingCircleLineIdentifierCs.setString(3, callingCircleLineIdentifier.getCallingLineIdentifier().getCountryValue()); + setCallingCircleLineIdentifierCs.setString(4, callingCircleLineIdentifier.getCallingLineIdentifier().getCallingLineIdentifier()); + setCallingCircleLineIdentifierCs.registerOutParameter(5, Types.INTEGER); + setCallingCircleLineIdentifierCs.registerOutParameter(6, Types.VARCHAR); + setCallingCircleLineIdentifierCs.execute(); + + setCallingCircleLineIdentifierCs.close(); + } catch (SQLException se) { + logger.fine("Failed in setCallingCircleLineIdentifier() : with the following parameters"); + logger.fine("IndexId = " + callingCircleLineIdentifier.getIndexId()); + logger.fine("RegionValue = " + callingCircleLineIdentifier.getCallingLineIdentifier().getRegionValue()); + logger.fine("CountryValue = " + callingCircleLineIdentifier.getCallingLineIdentifier().getCountryValue()); + logger.fine("CallingLineIdentifier = " + callingCircleLineIdentifier.getCallingLineIdentifier().getCallingLineIdentifier()); + throw new SwingBenchException(se); + } + } + + public void getCallingCircleLineIdentifiers(Connection connection) throws SwingBenchException { + try { + // if (getCallingCircleLineIdentifiersCs == null) { + getCallingCircleLineIdentifiersCs = connection.prepareCall("{call ccAppPkg.getPackageCLIs(?)}"); + // } + + getCallingCircleLineIdentifiersCs.setLong(1, customerCallingLineIdentifier.getId()); + getCallingCircleLineIdentifiersCs.execute(); + + getCallingCircleLineIdentifiersCs.close(); + } catch (SQLException se) { + throw new SwingBenchException(se); + } + } + + public void qryCallingCircleCurrent(Connection connection) throws SwingBenchException { + try { + // if (qryCallingCircleCurrentCs == null) { + qryCallingCircleCurrentCs = connection.prepareCall("{call ccAppPkg.qryPackageCLIsCurrent(?)}"); + // } + + qryCallingCircleCurrentCs.setLong(1, customerCallingLineIdentifier.getId()); + qryCallingCircleCurrentCs.execute(); + qryCallingCircleCurrentCs.close(); + } catch (SQLException se) { + throw new SwingBenchException(se); + } + } + + public void qryCallingCircleHistory(Connection connection) throws SwingBenchException { + try { + // if (qryCallingCircleHistoryCs == null) { + qryCallingCircleHistoryCs = connection.prepareCall("{call ccAppPkg.qryPackageCLIsHistory(?)}"); + // } + + qryCallingCircleHistoryCs.setLong(1, customerCallingLineIdentifier.getId()); + qryCallingCircleHistoryCs.execute(); + qryCallingCircleHistoryCs.close(); + } catch (SQLException se) { + throw new SwingBenchException(se); + } + } + +} diff --git a/src/com/mike/CallingCircle/CallingLineIdentifier.java b/src/com/mike/CallingCircle/CallingLineIdentifier.java new file mode 100644 index 0000000..73710d6 --- /dev/null +++ b/src/com/mike/CallingCircle/CallingLineIdentifier.java @@ -0,0 +1,79 @@ +package com.mike.CallingCircle; + +public class CallingLineIdentifier { + private String CountryText; + private String CountryType; + private String CountryValue; + private String RegionText; + private String callingLineIdentifier; + private String regionType; + private String regionValue; + private long id; + + public CallingLineIdentifier() { + } + + public String getCountryText() { + return CountryText; + } + + public void setCountryText(String newCountryText) { + CountryText = newCountryText; + } + + public String getCountryType() { + return CountryType; + } + + public void setCountryType(String newCountryType) { + CountryType = newCountryType; + } + + public String getCountryValue() { + return CountryValue; + } + + public void setCountryValue(String newCountryValue) { + CountryValue = newCountryValue; + } + + public String getRegionText() { + return RegionText; + } + + public void setRegionText(String newRegionText) { + RegionText = newRegionText; + } + + public String getCallingLineIdentifier() { + return callingLineIdentifier; + } + + public void setCallingLineIdentifier(String newCallingLineIdentifier) { + callingLineIdentifier = newCallingLineIdentifier; + } + + public long getId() { + return id; + } + + public void setId(long newId) { + id = newId; + } + + public String getRegionType() { + return regionType; + } + + public void setRegionType(String newRegionType) { + regionType = newRegionType; + } + + public String getRegionValue() { + return regionValue; + } + + public void setRegionValue(String newRegionValue) { + regionValue = newRegionValue; + } +} diff --git a/src/com/mike/CallingCircle/CustomerAccount.java b/src/com/mike/CallingCircle/CustomerAccount.java new file mode 100644 index 0000000..e66112a --- /dev/null +++ b/src/com/mike/CallingCircle/CustomerAccount.java @@ -0,0 +1,91 @@ +package com.mike.CallingCircle; + +import java.sql.Date; + + +public class CustomerAccount { + private Date lastFailedLogin; + private Date lastLogin; + private String name; + private String pin; + private String rowID; + private String validFrom; + private String validTo; + private long failedLogins; + private long id; + + public CustomerAccount() { + } + + public long getFailedLogins() { + return failedLogins; + } + + public void setFailedLogins(long newFailedLogins) { + failedLogins = newFailedLogins; + } + + public long getId() { + return id; + } + + public void setId(long newId) { + id = newId; + } + + public java.sql.Date getLastFailedLogin() { + return lastFailedLogin; + } + + public java.sql.Date getLastLogin() { + return lastLogin; + } + + public String getName() { + return name; + } + + public void setName(String newName) { + name = newName; + } + + public String getPin() { + return pin; + } + + public void setPin(String newPin) { + pin = newPin; + } + + public String getRowID() { + return rowID; + } + + public void setRowID(String newRowID) { + rowID = newRowID; + } + + public String getValidFrom() { + return validFrom; + } + + public void setValidFrom(String newValidFrom) { + validFrom = newValidFrom; + } + + public String getValidTo() { + return validTo; + } + + public void setValidTo(String newValidTo) { + validTo = newValidTo; + } + + public void setLastFailedLogin(Date newLastFailedLogin) { + lastFailedLogin = newLastFailedLogin; + } + + public void setLastLogin(Date newLastLogin) { + lastLogin = newLastLogin; + } +} diff --git a/src/com/mike/CallingCircle/CustomerCallingLineIdentifier.java b/src/com/mike/CallingCircle/CustomerCallingLineIdentifier.java new file mode 100644 index 0000000..b6b8779 --- /dev/null +++ b/src/com/mike/CallingCircle/CustomerCallingLineIdentifier.java @@ -0,0 +1,97 @@ +package com.mike.CallingCircle; + +public class CustomerCallingLineIdentifier extends Object { + private CallingLineIdentifier callingLineIdentifier; + private String callingCircleName; + private String callingCircleRulesPLSQL; + private String rowId; + private String validFrom; + private String validTo; + private long callingCircleId; + private long id; + private long updates; + private long updatesAllowed; + + public CustomerCallingLineIdentifier() { + } + + public CallingLineIdentifier getCallingLineIdentifier() { + return callingLineIdentifier; + } + + public void setCallingLineIdentifier(CallingLineIdentifier newCallingLineIdentifier) { + callingLineIdentifier = newCallingLineIdentifier; + } + + public long getCallingCircleId() { + return callingCircleId; + } + + public void setCallingCircleId(long newCallingCircleId) { + callingCircleId = newCallingCircleId; + } + + public String getCallingCircleName() { + return callingCircleName; + } + + public void setCallingCircleName(String newCallingCircleName) { + callingCircleName = newCallingCircleName; + } + + public String getCallingCircleRulesPLSQL() { + return callingCircleRulesPLSQL; + } + + public void setCpPLSQL(String newCallingCircleRulesPLSQL) { + callingCircleRulesPLSQL = newCallingCircleRulesPLSQL; + } + + public long getId() { + return id; + } + + public void setId(long newId) { + id = newId; + } + + public String getRowId() { + return rowId; + } + + public void setRowId(String newRowId) { + rowId = newRowId; + } + + public long getUpdates() { + return updates; + } + + public void setUpdates(long newUpdates) { + updates = newUpdates; + } + + public long getUpdatesAllowed() { + return updatesAllowed; + } + + public void setUpdatesAllowed(long newUpdatesAllowed) { + updatesAllowed = newUpdatesAllowed; + } + + public String getValidFrom() { + return validFrom; + } + + public void setValidFrom(String newValidFrom) { + validFrom = newValidFrom; + } + + public String getValidTo() { + return validTo; + } + + public void setValidTo(String newValidTo) { + validTo = newValidTo; + } +} diff --git a/src/com/mike/CallingCircle/NewCallingCircleProcess.java b/src/com/mike/CallingCircle/NewCallingCircleProcess.java new file mode 100644 index 0000000..454fb6a --- /dev/null +++ b/src/com/mike/CallingCircle/NewCallingCircleProcess.java @@ -0,0 +1,298 @@ +package com.mike.CallingCircle; + +import com.dom.benchmarking.swingbench.constants.Constants; +import com.dom.benchmarking.swingbench.event.JdbcTaskEvent; +import com.dom.benchmarking.swingbench.kernel.SwingBenchException; +import com.dom.benchmarking.swingbench.kernel.SwingBenchTask; + + +import java.io.BufferedReader; +import java.io.FileReader; + + +import java.sql.Connection; +import java.sql.SQLException; + + +import java.util.ArrayList; +import java.util.List; +import java.util.logging.*; +import java.util.Map; +import java.util.StringTokenizer; + + +public class NewCallingCircleProcess extends CallingCircleProcess { + + private static final Logger logger = Logger.getLogger(NewCallingCircleProcess.class.getName()); + private static String dataFile = "newccprocess.txt"; + private static ArrayList transactionParams = null; + private static int tpPointer = 0; + private static Object lock = new Object(); + + public NewCallingCircleProcess() { + } + + public void init(Map params) throws SwingBenchException { + String fileName = null; + setId(NEW_CC_PROCESS); + customerAccount = new CustomerAccount(); + customerCallingLineIdentifier = new CustomerCallingLineIdentifier(); + callingCircleLineIdentifier = new CallingCircleLineIdentifier(); + + boolean initCompleted = false; + + if ((transactionParams == null) || !initCompleted) { // load any data you might need (in this case only once) + + synchronized (lock) { + if (transactionParams == null) { + transactionParams = new ArrayList(); + + try { + fileName = (String)params.get(Constants.CCDATADIRLOC); + + if (fileName == null) { + fileName = (String)params.get(Constants.CCNEWPROCESSFILELOC); + + if (fileName == null) { + fileName = "data/" + dataFile; + } + } else { + fileName += dataFile; + } + + logger.log(Level.SEVERE, "Attempting to read : " + fileName); + + BufferedReader br = new BufferedReader(new FileReader(fileName)); + String data = null; + + List paramList = null; + while ((data = br.readLine()) != null) { + StringTokenizer st = new StringTokenizer(data, ","); + paramList = new ArrayList(10); + + while (st.hasMoreTokens()) { + paramList.add(st.nextToken()); + } + + transactionParams.add(paramList); + } + + br.close(); + logger.log(Level.SEVERE, "Loaded NewCallingCircleProcess() data into memory, transactionParams[] count =" + transactionParams.size()); + } catch (java.io.FileNotFoundException fne) { + SwingBenchException sbe = new SwingBenchException("Swingbench can't find the datafile specified in the environement variables : " + fileName); + sbe.setSeverity(SwingBenchException.UNRECOVERABLEERROR); + throw sbe; + } catch (java.io.IOException ioe) { + SwingBenchException sbe = new SwingBenchException("An I/O error occured, see the following message : " + ioe.getMessage()); + sbe.setSeverity(SwingBenchException.UNRECOVERABLEERROR); + throw sbe; + } + } + + initCompleted = true; + } + } + } + + public ArrayList getParameterSet() throws SwingBenchException { + ArrayList parameterSet = new ArrayList(); + + try { + synchronized (lock) { // don't let all the threads access transactionParams at same time + + boolean notEndOfSet = true; + boolean firstRecord = true; + + while (notEndOfSet) { + ArrayList paramList = (ArrayList)transactionParams.get(tpPointer); + String param = (String)paramList.get(0); + + if (param.equals("New")) { + if (firstRecord) { + firstRecord = false; + parameterSet.add(paramList); + tpPointer++; + } else { + notEndOfSet = false; + } + } else { + parameterSet.add(paramList); + tpPointer++; + } + } + } + } catch (Exception e) { + SwingBenchException sbe = new SwingBenchException("Probably run out of transactions to process. Generate a new transaction load"); + sbe.setSeverity(SwingBenchException.UNRECOVERABLEERROR); + throw sbe; + } + + return parameterSet; + } + + public void execute(Map params) throws SwingBenchException { + Connection connection = (Connection)params.get(SwingBenchTask.JDBC_CONNECTION); + initJdbcTask(); + + long executeStart = System.nanoTime(); + + try { + ArrayList paramSet = getParameterSet(); // get a chunk of parameters + ArrayList parameters = (ArrayList)paramSet.get(0); // get the first set + + if (!((String)parameters.get(0)).equals("New")) { + throw new SwingBenchException("Parameters out of sequence"); + } + + customerAccount.setName((String)parameters.get(1)); + customerAccount.setPin((String)parameters.get(2)); + + CallingLineIdentifier myCallingLineIdentifier = new CallingLineIdentifier(); + myCallingLineIdentifier.setCountryValue((String)parameters.get(3)); + myCallingLineIdentifier.setRegionValue((String)parameters.get(4)); + myCallingLineIdentifier.setCallingLineIdentifier((String)parameters.get(5)); + customerCallingLineIdentifier.setCallingLineIdentifier(myCallingLineIdentifier); + customerCallingLineIdentifier.setCallingCircleId(Integer.parseInt((String)parameters.get(6))); + + long start = System.nanoTime(); + + try { + newCustomerAccount(connection); + processTransactionEvent(true, (System.nanoTime() - start), NEW_CUSTOMER_TX); + } catch (SwingBenchException sbe) { + processTransactionEvent(false, (System.nanoTime() - start), NEW_CUSTOMER_TX); + throw new SwingBenchException(sbe); + } + + addDML(1, 1, 0, 0, 1, 0); + start = System.nanoTime(); + + try { + getCustomerAccount(connection); + processTransactionEvent(true, (System.nanoTime() - start), GET_CUSTOMER_TX); + } catch (SwingBenchException sbe) { + processTransactionEvent(false, (System.nanoTime() - start), GET_CUSTOMER_TX); + throw new SwingBenchException(sbe); + } + + addDML(1, 0, 1, 0, 1, 0); + + try { + newCustomerCallingLineIdentifier(connection); + processTransactionEvent(true, (System.nanoTime() - start), NEW_CUSTOMER_CLI_TX); + } catch (SwingBenchException sbe) { + processTransactionEvent(false, (System.nanoTime() - start), NEW_CUSTOMER_CLI_TX); + throw new SwingBenchException(sbe); + } + + addDML(2, 2, 0, 0, 1, 0); + + try { + getCustomerCallingLineIdentifier(connection); + processTransactionEvent(true, (System.nanoTime() - start), GET_CUSTOMER_CLI_TX); + } catch (SwingBenchException sbe) { + processTransactionEvent(false, (System.nanoTime() - start), GET_CUSTOMER_CLI_TX); + throw new SwingBenchException(sbe); + } + + addDML(2, 0, 0, 0, 0, 0); + + try { + qryCallingCircleCurrent(connection); + processTransactionEvent(true, (System.nanoTime() - start), GET_CIRCLE_CLIS_TX); + } catch (SwingBenchException sbe) { + processTransactionEvent(false, (System.nanoTime() - start), GET_CIRCLE_CLIS_TX); + throw new SwingBenchException(sbe); + } + + addDML(11, 0, 0, 0, 0, 0); + + for (int i = 1; i < paramSet.size(); i++) { //there should be 10, but lets make it dynamic + parameters = (ArrayList)paramSet.get(i); // get the first set + + if (!((String)parameters.get(0)).equals("Upd")) { + throw new SwingBenchException("Parameters out of sequence"); + } + + customerAccount.setName((String)parameters.get(1)); //set the parameters again, we're stateless + customerAccount.setPin((String)parameters.get(2)); + myCallingLineIdentifier = new CallingLineIdentifier(); + myCallingLineIdentifier.setCountryValue((String)parameters.get(3)); + myCallingLineIdentifier.setRegionValue((String)parameters.get(4)); + myCallingLineIdentifier.setCallingLineIdentifier((String)parameters.get(5)); + customerCallingLineIdentifier.setCallingLineIdentifier(myCallingLineIdentifier); + callingCircleLineIdentifier.setIndexId(Integer.parseInt((String)parameters.get(6))); + myCallingLineIdentifier = new CallingLineIdentifier(); + myCallingLineIdentifier.setCountryValue((String)parameters.get(7)); + myCallingLineIdentifier.setRegionValue((String)parameters.get(8)); + myCallingLineIdentifier.setCallingLineIdentifier((String)parameters.get(9)); + callingCircleLineIdentifier.setCallingLineIdentifier(myCallingLineIdentifier); + thinkSleep(); + + try { + getCustomerAccount(connection); + processTransactionEvent(true, (System.nanoTime() - start), GET_CUSTOMER_TX); + } catch (SwingBenchException sbe) { + processTransactionEvent(false, (System.nanoTime() - start), GET_CUSTOMER_TX); + throw new SwingBenchException(sbe); + } + + addDML(1, 0, 1, 0, 1, 0); + + try { + getCustomerCallingLineIdentifier(connection); + processTransactionEvent(true, (System.nanoTime() - start), GET_CUSTOMER_CLI_TX); + } catch (SwingBenchException sbe) { + processTransactionEvent(false, (System.nanoTime() - start), GET_CUSTOMER_CLI_TX); + throw new SwingBenchException(sbe); + } + + addDML(2, 0, 0, 0, 0, 0); + + try { + getCallingCircleLineIdentifiers(connection); + processTransactionEvent(true, (System.nanoTime() - start), GET_CIRCLE_CLIS_TX); + } catch (SwingBenchException sbe) { + processTransactionEvent(false, (System.nanoTime() - start), GET_CIRCLE_CLIS_TX); + throw new SwingBenchException(sbe); + } + + addDML(11, 0, 0, 0, 0, 0); + + try { + setCallingCircleLineIdentifier(connection); + processTransactionEvent(true, (System.nanoTime() - start), SET_CIRCLE_CLI_TX); + } catch (SwingBenchException sbe) { + processTransactionEvent(false, (System.nanoTime() - start), SET_CIRCLE_CLI_TX); + throw new SwingBenchException(sbe); + } + + addDML(2, 2, 2, 0, 1, 0); + + try { + qryCallingCircleCurrent(connection); + processTransactionEvent(true, (System.nanoTime() - start), QRY_CLIS_CURRENT_TX); + } catch (SwingBenchException sbe) { + processTransactionEvent(false, (System.nanoTime() - start), QRY_CLIS_CURRENT_TX); + throw new SwingBenchException(sbe); + } + } + + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), true, getInfoArray())); + } catch (SwingBenchException sbe) { + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), false, getInfoArray())); + + try { + connection.rollback(); + } catch (SQLException se) { + } + + throw new SwingBenchException(sbe); + } + } + + public void close() { + } + +} diff --git a/src/com/mike/CallingCircle/RetrieveHistoryProcess.java b/src/com/mike/CallingCircle/RetrieveHistoryProcess.java new file mode 100644 index 0000000..910ce99 --- /dev/null +++ b/src/com/mike/CallingCircle/RetrieveHistoryProcess.java @@ -0,0 +1,204 @@ +package com.mike.CallingCircle; + + +import com.dom.benchmarking.swingbench.constants.Constants; +import com.dom.benchmarking.swingbench.event.JdbcTaskEvent; +import com.dom.benchmarking.swingbench.kernel.SwingBenchException; +import com.dom.benchmarking.swingbench.kernel.SwingBenchTask; + +import java.io.BufferedReader; +import java.io.FileReader; + +import java.sql.Connection; +import java.sql.SQLException; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.StringTokenizer; +import java.util.logging.Logger; + + +public class RetrieveHistoryProcess extends CallingCircleProcess { + private static final Logger logger = Logger.getLogger(RetrieveHistoryProcess.class.getName()); + private static String dataFile = "qryccprocess.txt"; + private static ArrayList transactionParams = null; + private static int tpPointer = 0; + private static Object lock = new Object(); + + public RetrieveHistoryProcess() { + } + + public void init(Map params) throws SwingBenchException { + String fileName = null; + setId(RETRIEVE_HISTORY); + customerAccount = new CustomerAccount(); + customerCallingLineIdentifier = new CustomerCallingLineIdentifier(); + callingCircleLineIdentifier = new CallingCircleLineIdentifier(); + + boolean initCompleted = false; + + if ((transactionParams == null) || !initCompleted) { // load any data you might need (in this case only once) + + synchronized (lock) { + if (transactionParams == null) { + transactionParams = new ArrayList(); + + try { + fileName = (String)params.get(Constants.CCDATADIRLOC); + + if (fileName == null) { + fileName = (String)params.get(Constants.CCQUERYPROCESSFILELOC); + + if (fileName == null) { + fileName = "data/" + dataFile; + } + } else { + fileName += dataFile; + } + + logger.fine("Attempting to read : " + fileName); + + BufferedReader br = new BufferedReader(new FileReader(fileName)); + String data = null; + List paramList = null; + while ((data = br.readLine()) != null) { + StringTokenizer st = new StringTokenizer(data, ","); + paramList = new ArrayList(6); + while (st.hasMoreTokens()) { + paramList.add(st.nextToken()); + } + + transactionParams.add(paramList); + } + + br.close(); + logger.fine("Loaded RetrieveHistoryProcess() data into memory, transactionParams[] count =" + transactionParams.size()); + } catch (java.io.FileNotFoundException fne) { + SwingBenchException sbe = new SwingBenchException("Swingbench can't find the datafile specified in the environement variables : " + fileName); + sbe.setSeverity(SwingBenchException.UNRECOVERABLEERROR); + throw sbe; + } catch (java.io.IOException ioe) { + SwingBenchException sbe = new SwingBenchException("An I/O error occured, see the following message : " + ioe.getMessage()); + sbe.setSeverity(SwingBenchException.UNRECOVERABLEERROR); + throw sbe; + } catch (Exception e) { + SwingBenchException sbe = new SwingBenchException("An Unexpected error occured in init() of RetrieveHistoryProcess, see the following message : " + e.getMessage()); + sbe.setSeverity(SwingBenchException.UNRECOVERABLEERROR); + throw sbe; + } + } + + initCompleted = true; + } + } + } + + public ArrayList getParameterSet() throws SwingBenchException { + ArrayList parameterSet = new ArrayList(); + + try { + synchronized (lock) { // don't let all the threads access transactionParams at same time + + boolean notEndOfSet = true; + boolean firstRecord = true; + + while (notEndOfSet) { + ArrayList paramList = (ArrayList)transactionParams.get(tpPointer); + String param = (String)paramList.get(0); + + if (param.equals("Qry")) { + if (firstRecord) { + firstRecord = false; + parameterSet.add(paramList); + tpPointer++; + } else { + notEndOfSet = false; + } + } else { + parameterSet.add(paramList); + tpPointer++; + } + } + } + } catch (Exception e) { + SwingBenchException sbe = new SwingBenchException("Probably run out of transactions to process. Generate a new transaction load"); + sbe.setSeverity(SwingBenchException.UNRECOVERABLEERROR); + throw sbe; + } + + return parameterSet; + } + + public void execute(Map params) throws SwingBenchException { + Connection connection = (Connection)params.get(SwingBenchTask.JDBC_CONNECTION); + initJdbcTask(); + + long executeStart = System.nanoTime(); + + try { + ArrayList paramSet = getParameterSet(); // get a chunk of parameters + ArrayList parameters = (ArrayList)paramSet.get(0); // get the first set + + if (!((String)parameters.get(0)).equals("Qry")) { + throw new SwingBenchException("Parameters out of sequence"); + } + + customerAccount.setName((String)parameters.get(1)); + customerAccount.setPin((String)parameters.get(2)); + + CallingLineIdentifier myCallingLineIdentifier = new CallingLineIdentifier(); + myCallingLineIdentifier.setCountryValue((String)parameters.get(3)); + myCallingLineIdentifier.setRegionValue((String)parameters.get(4)); + myCallingLineIdentifier.setCallingLineIdentifier((String)parameters.get(5)); + customerCallingLineIdentifier.setCallingLineIdentifier(myCallingLineIdentifier); + + long start = System.nanoTime(); + + try { + getCustomerAccount(connection); + processTransactionEvent(true, (System.nanoTime() - start), GET_CUSTOMER_TX); + } catch (SwingBenchException sbe) { + processTransactionEvent(false, (System.nanoTime() - start), GET_CUSTOMER_TX); + throw new SwingBenchException(sbe); + } + + addDML(1, 0, 1, 0, 1, 0); + start = System.nanoTime(); + + try { + getCustomerCallingLineIdentifier(connection); + processTransactionEvent(true, (System.nanoTime() - start), GET_CUSTOMER_CLI_TX); + } catch (SwingBenchException sbe) { + processTransactionEvent(false, (System.nanoTime() - start), GET_CUSTOMER_CLI_TX); + throw new SwingBenchException(sbe); + } + + addDML(2, 0, 0, 0, 0, 0); + start = System.nanoTime(); + + try { + qryCallingCircleHistory(connection); + processTransactionEvent(true, (System.nanoTime() - start), QRY_CLIS_CURRENT_TX); + } catch (SwingBenchException sbe) { + processTransactionEvent(false, (System.nanoTime() - start), QRY_CLIS_CURRENT_TX); + throw new SwingBenchException(sbe); + } + + addDML(11, 0, 0, 0, 0, 0); + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), true, getInfoArray())); + } catch (SwingBenchException sbe) { + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), false, getInfoArray())); + + try { + connection.rollback(); + } catch (SQLException se) { + } + + throw new SwingBenchException(sbe); + } + } + + public void close() { + } +} diff --git a/src/com/mike/CallingCircle/UpdateCallingCircleProcess.java b/src/com/mike/CallingCircle/UpdateCallingCircleProcess.java new file mode 100644 index 0000000..0175312 --- /dev/null +++ b/src/com/mike/CallingCircle/UpdateCallingCircleProcess.java @@ -0,0 +1,280 @@ +package com.mike.CallingCircle; + + +import com.dom.benchmarking.swingbench.constants.Constants; +import com.dom.benchmarking.swingbench.event.JdbcTaskEvent; +import com.dom.benchmarking.swingbench.kernel.SwingBenchException; +import com.dom.benchmarking.swingbench.kernel.SwingBenchTask; + +import java.io.BufferedReader; +import java.io.FileReader; + +import java.sql.Connection; +import java.sql.SQLException; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.StringTokenizer; +import java.util.logging.Logger; + + +public class UpdateCallingCircleProcess extends CallingCircleProcess { + + private static final Logger logger = Logger.getLogger(UpdateCallingCircleProcess.class.getName()); + private static String dataFile = "updccprocess.txt"; + private static ArrayList transactionParams = null; + private static int tpPointer = 0; + private static Object lock = new Object(); + + public UpdateCallingCircleProcess() { + } + + public void init(Map params) throws SwingBenchException { + String fileName = null; + setId(UPDATE_CC_PROCESS); + customerAccount = new CustomerAccount(); + customerCallingLineIdentifier = new CustomerCallingLineIdentifier(); + callingCircleLineIdentifier = new CallingCircleLineIdentifier(); + + boolean initCompleted = false; + + if ((transactionParams == null) || !initCompleted) { // load any data you might need (in this case only once) + + synchronized (lock) { + if (transactionParams == null) { + transactionParams = new ArrayList(); + + try { + fileName = (String)params.get(Constants.CCDATADIRLOC); + + if (fileName == null) { + fileName = (String)params.get(Constants.CCUPDATEPROCESSFILELOC); + + if (fileName == null) { + fileName = "data/" + dataFile; + } + } else { + fileName += dataFile; + } + + logger.fine("Attempting to read : " + fileName); + + BufferedReader br = new BufferedReader(new FileReader(fileName)); + String data = null; + + List paramList = null; + while ((data = br.readLine()) != null) { + StringTokenizer st = new StringTokenizer(data, ","); + paramList = new ArrayList(10); + + while (st.hasMoreTokens()) { + paramList.add(st.nextToken()); + } + + transactionParams.add(paramList); + } + + br.close(); + logger.fine("Loaded UpdateCallingCircleProcess() data into memory, transactionParams[] count =" + transactionParams.size()); + } catch (java.io.FileNotFoundException fne) { + SwingBenchException sbe = new SwingBenchException("Swingbench can't find the datafile specified in the environement variables : " + fileName); + sbe.setSeverity(SwingBenchException.UNRECOVERABLEERROR); + throw sbe; + } catch (java.io.IOException ioe) { + SwingBenchException sbe = new SwingBenchException("An I/O error occured, see the following message : " + ioe.getMessage()); + sbe.setSeverity(SwingBenchException.UNRECOVERABLEERROR); + throw sbe; + } catch (Exception e) { + SwingBenchException sbe = new SwingBenchException("An Unexpected error occured in init() of UpdateCallingCircleProcess, see the following message : " + e.getMessage()); + sbe.setSeverity(SwingBenchException.UNRECOVERABLEERROR); + throw sbe; + } + } + + initCompleted = true; + } + } + } + + public ArrayList getParameterSet() throws SwingBenchException { + ArrayList parameterSet = new ArrayList(); + + try { + synchronized (lock) { // don't let all the threads access transactionParams at same time + + boolean notEndOfSet = true; + boolean firstRecord = true; + + while (notEndOfSet) { + ArrayList paramList = (ArrayList)transactionParams.get(tpPointer); + String param = (String)paramList.get(0); + + if (param.equals("Get")) { + if (firstRecord) { + firstRecord = false; + parameterSet.add(paramList); + tpPointer++; + } else { + notEndOfSet = false; + } + } else { + parameterSet.add(paramList); + tpPointer++; + } + } + } + } catch (Exception e) { + SwingBenchException sbe = new SwingBenchException("Probably run out of transactions to process. Generate a new transaction load"); + sbe.setSeverity(SwingBenchException.UNRECOVERABLEERROR); + throw sbe; + } + + return parameterSet; + } + + public void execute(Map params) throws SwingBenchException { + Connection connection = (Connection)params.get(SwingBenchTask.JDBC_CONNECTION); + initJdbcTask(); + + long executeStart = System.nanoTime(); + + try { + ArrayList paramSet = getParameterSet(); // get a chunk of parameters + ArrayList parameters = (ArrayList)paramSet.get(0); // get the first set + + if (!((String)parameters.get(0)).equals("Get")) { + throw new SwingBenchException("Parameters out of sequence"); + } + + customerAccount.setName((String)parameters.get(1)); //set the parameters again, we're stateless + customerAccount.setPin((String)parameters.get(2)); + + CallingLineIdentifier myCallingLineIdentifier = new CallingLineIdentifier(); + myCallingLineIdentifier = new CallingLineIdentifier(); + myCallingLineIdentifier.setCountryValue((String)parameters.get(3)); + myCallingLineIdentifier.setRegionValue((String)parameters.get(4)); + myCallingLineIdentifier.setCallingLineIdentifier((String)parameters.get(5)); + customerCallingLineIdentifier.setCallingLineIdentifier(myCallingLineIdentifier); + + long start = System.nanoTime(); + + try { + getCustomerAccount(connection); + processTransactionEvent(true, (System.nanoTime() - start), GET_CUSTOMER_TX); + } catch (SwingBenchException sbe) { + processTransactionEvent(false, (System.nanoTime() - start), GET_CUSTOMER_TX); + throw new SwingBenchException(sbe); + } + + addDML(1, 0, 1, 0, 1, 0); + + try { + getCustomerCallingLineIdentifier(connection); + processTransactionEvent(true, (System.nanoTime() - start), GET_CUSTOMER_CLI_TX); + } catch (SwingBenchException sbe) { + processTransactionEvent(false, (System.nanoTime() - start), GET_CUSTOMER_CLI_TX); + throw new SwingBenchException(sbe); + } + + addDML(2, 0, 0, 0, 0, 0); + + try { + qryCallingCircleCurrent(connection); + processTransactionEvent(true, (System.nanoTime() - start), GET_CIRCLE_CLIS_TX); + } catch (SwingBenchException sbe) { + processTransactionEvent(false, (System.nanoTime() - start), GET_CIRCLE_CLIS_TX); + throw new SwingBenchException(sbe); + } + + addDML(11, 0, 0, 0, 0, 0); + + for (int i = 1; i < paramSet.size(); i++) { //there should be 10, but lets make it dynamic + parameters = (ArrayList)paramSet.get(i); // get the first set + + if (!((String)parameters.get(0)).equals("Upd")) { + throw new SwingBenchException("Parameters out of sequence"); + } + + customerAccount.setName((String)parameters.get(1)); //set the parameters again, we're stateless + customerAccount.setPin((String)parameters.get(2)); + myCallingLineIdentifier = new CallingLineIdentifier(); + myCallingLineIdentifier.setCountryValue((String)parameters.get(3)); + myCallingLineIdentifier.setRegionValue((String)parameters.get(4)); + myCallingLineIdentifier.setCallingLineIdentifier((String)parameters.get(5)); + customerCallingLineIdentifier.setCallingLineIdentifier(myCallingLineIdentifier); + callingCircleLineIdentifier.setIndexId(Integer.parseInt((String)parameters.get(6))); + myCallingLineIdentifier = new CallingLineIdentifier(); + myCallingLineIdentifier.setCountryValue((String)parameters.get(7)); + myCallingLineIdentifier.setRegionValue((String)parameters.get(8)); + myCallingLineIdentifier.setCallingLineIdentifier((String)parameters.get(9)); + callingCircleLineIdentifier.setCallingLineIdentifier(myCallingLineIdentifier); + thinkSleep(); + + try { + getCustomerAccount(connection); + processTransactionEvent(true, (System.nanoTime() - start), GET_CUSTOMER_TX); + } catch (SwingBenchException sbe) { + processTransactionEvent(false, (System.nanoTime() - start), GET_CUSTOMER_TX); + throw new SwingBenchException(sbe); + } + + addDML(1, 0, 1, 0, 1, 0); + + try { + getCustomerCallingLineIdentifier(connection); + processTransactionEvent(true, (System.nanoTime() - start), GET_CUSTOMER_CLI_TX); + } catch (SwingBenchException sbe) { + processTransactionEvent(false, (System.nanoTime() - start), GET_CUSTOMER_CLI_TX); + throw new SwingBenchException(sbe); + } + + addDML(2, 0, 0, 0, 0, 0); + + try { + getCallingCircleLineIdentifiers(connection); + processTransactionEvent(true, (System.nanoTime() - start), GET_CIRCLE_CLIS_TX); + } catch (SwingBenchException sbe) { + processTransactionEvent(false, (System.nanoTime() - start), GET_CIRCLE_CLIS_TX); + throw new SwingBenchException(sbe); + } + + addDML(11, 0, 0, 0, 0, 0); + + try { + setCallingCircleLineIdentifier(connection); + processTransactionEvent(true, (System.nanoTime() - start), SET_CIRCLE_CLI_TX); + } catch (SwingBenchException sbe) { + processTransactionEvent(false, (System.nanoTime() - start), SET_CIRCLE_CLI_TX); + throw new SwingBenchException(sbe); + } + + addDML(2, 2, 2, 0, 1, 0); + + try { + qryCallingCircleCurrent(connection); + processTransactionEvent(true, (System.nanoTime() - start), QRY_CLIS_CURRENT_TX); + } catch (SwingBenchException sbe) { + processTransactionEvent(false, (System.nanoTime() - start), QRY_CLIS_CURRENT_TX); + throw new SwingBenchException(sbe); + } + + addDML(11, 0, 0, 0, 0, 0); + } + + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), true, getInfoArray())); + } catch (SwingBenchException sbe) { + processTransactionEvent(new JdbcTaskEvent(this, getId(), (System.nanoTime() - executeStart), false, getInfoArray())); + + try { + connection.rollback(); + } catch (SQLException se) { + } + + throw new SwingBenchException(sbe); + } + } + + public void close() { + } +}