Advertisement
Guest User

Untitled

a guest
Jun 23rd, 2017
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 22.50 KB | None | 0 0
  1. package com.pax.testyadb2;
  2.  
  3.  
  4. import ch.vorburger.exec.ManagedProcessException;
  5. import ch.vorburger.mariadb4j.DB;
  6. import ch.vorburger.mariadb4j.DBConfigurationBuilder;
  7.  
  8. import java.awt.event.KeyEvent;
  9. import java.awt.event.KeyListener;
  10. import java.io.BufferedReader;
  11. import java.io.IOException;
  12. import java.io.InputStreamReader;
  13. import java.sql.*;
  14. import java.util.Random;
  15. import java.util.Timer;
  16. import java.util.TimerTask;
  17.  
  18. public class Main {
  19.     private static String DB_PATH = "";
  20.     private static String DB_NAME = "db10";
  21.     private static Boolean FIRST_START = true;
  22.     private static int USERS_COUNT = 10;
  23.     private static int START_RECORDS = 10;
  24.     private static int QUERY_PERIOD = 1000;
  25.     private static DBConfigurationBuilder configBuilder;
  26.     private static Connection conn;
  27.     private static Timer usersTimer;
  28.     private static Timer messageTimer;
  29.  
  30.     public static void main(String[] args) throws SQLException, IOException, ManagedProcessException {
  31.         DB_PATH = args[0];
  32.         DB_NAME = args[1];
  33.         System.out.println("Welcome!");
  34.         System.out.println("This is test MariaDB");
  35.         System.out.println("first time?(y or n)");
  36.         System.out.println("Enter 'h' for get help");
  37.  
  38.         BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
  39. //        String line = in.readLine();
  40.         String line = "";
  41.  
  42.         while (line.equalsIgnoreCase("quit") == false) {
  43.             line = in.readLine();
  44.             switch (line) {
  45.                 case "y":
  46.                     initialize();
  47.                     break;
  48.                 case "n":
  49.                     configBuilder = DBConfigurationBuilder.newBuilder();
  50.                     configBuilder.setPort(3306); // OR, default: setPort(0); => autom. detect free port
  51.                     configBuilder.setDataDir(DB_PATH + DB_NAME); // just an example
  52.                     DB db = DB.newEmbeddedDB(configBuilder.build());
  53.                     db.start();
  54.                     try {
  55.                         Class.forName("com.mysql.jdbc.Driver");
  56.                     } catch (ClassNotFoundException e) {
  57.                         e.printStackTrace();
  58.                     }
  59.                     conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "");
  60.                     break;
  61.                 case "au":
  62.                     addNewUser(conn);
  63.                     break;
  64.                 case "h":
  65.                     help();
  66.                     break;
  67.                 case "su":
  68.                     showUsers(conn);
  69.                     break;
  70.                 case "sup":
  71.                     showUserPoints(conn);
  72.                     break;
  73.                 case "nm":
  74.                     addNewMessage(conn);
  75.                     break;
  76.                 case "sm":
  77.                     showMessages(conn);
  78.                     break;
  79.                 case "stm":
  80.                     messageTimer.cancel();
  81.                     break;
  82.                 case "stu":
  83.                     usersTimer.cancel();
  84.                     break;
  85.             }
  86.             if (line.contains("mau")) {
  87.                 String[] number = line.split(" ");
  88.                 int iMax = Integer.parseInt(number[1]);
  89.                 for (int i = 0; i < iMax; i++) {
  90.                     addNewUser(conn);
  91.                 }
  92.             }
  93.             if (line.contains("tnm")) {
  94.                 int countInteger;
  95.                 int period;
  96.                 String[] count = line.split(" ");
  97.                 if (count.length < 2) {
  98.                     countInteger = 1;
  99.                     period = 1000;
  100.                 } else {
  101.                     countInteger = Integer.parseInt(count[1]);
  102.                     period = Integer.parseInt(count[2]);
  103.                 }
  104.                 class message extends TimerTask {
  105.                     public void run() {
  106.                         for (int i = 0; i < countInteger; i++) {
  107.                             try {
  108.                                 addNewMessage(conn);
  109.                             } catch (SQLException e) {
  110.                                 e.printStackTrace();
  111.                             }
  112.                         }
  113.                     }
  114.                 }
  115.                 messageTimer = new Timer();
  116.                 messageTimer.schedule(new message(), 0, period);
  117.             }
  118.             if (line.contains("tnu")) {
  119.                 int countInteger;
  120.                 int period;
  121.                 String[] count = line.split(" ");
  122.                 if (count.length < 2) {
  123.                     countInteger = 1;
  124.                     period = 1000;
  125.                 } else {
  126.                     countInteger = Integer.parseInt(count[1]);
  127.                     period = Integer.parseInt(count[2]);
  128.                 }
  129.                 class user extends TimerTask {
  130.                     public void run() {
  131.                         for (int i = 0; i < countInteger; i++) {
  132.                             addNewUser(conn);
  133.                         }
  134.                     }
  135.                 }
  136.                 usersTimer = new Timer();
  137.                 usersTimer.schedule(new user(), 0, period);
  138.             }
  139.         }
  140. //        String[] values = line.split(" ");
  141. //        FIRST_START = values[0].equals("y");
  142. //        START_RECORDS = Integer.parseInt(values[1]);
  143. //        USERS_COUNT = Integer.parseInt(values[2]);
  144. //        QUERY_PERIOD = Integer.parseInt(values[3]);
  145. //        if (FIRST_START) {
  146. //            System.out.println("y");
  147. //            initialize();
  148. //        } else {
  149. ////            configBuilder = DBConfigurationBuilder.newBuilder();
  150. ////            configBuilder.setPort(3306); // OR, default: setPort(0); => autom. detect free port
  151. ////            configBuilder.setDataDir("/Volumes/secondary/projects/java/yadb/db"); // just an example
  152. ////            DB db = DB.newEmbeddedDB(configBuilder.build());
  153. ////            db.start();
  154. ////            try {
  155. ////                Class.forName("com.mysql.jdbc.Driver");
  156. ////            } catch (ClassNotFoundException e) {
  157. ////                e.printStackTrace();
  158. ////            }
  159. ////            conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "");
  160. //
  161. //        }
  162.  
  163.  
  164. //        if (START_RECORDS > 0) {
  165. ////            setStartRecords(conn);
  166. //        } else {
  167. ////            randomInsert(conn);
  168. //        }
  169.  
  170.  
  171.     }
  172.  
  173.     private static void showMessages(Connection connection) throws SQLException {
  174.         final Statement statement = connection.createStatement();
  175.         int i = 1;
  176.         String q = ("SELECT * FROM chat_history");
  177.         ResultSet rs = statement.executeQuery(q);
  178.         while (rs.next()) {
  179.             System.out.print("(" + i + ") - (");
  180.             System.out.print(rs.getString("id"));
  181.             System.out.print(",");
  182.             System.out.print(rs.getString("origin"));
  183.             System.out.print(",");
  184.             System.out.print(rs.getString("sender"));
  185.             System.out.print(",");
  186.             System.out.print(rs.getString("message"));
  187.             System.out.print(",");
  188.             System.out.print(rs.getString("timestamp"));
  189.             System.out.print(")");
  190.             i++;
  191.             System.out.println();
  192.         }
  193.     }
  194.  
  195.     private static void addNewMessage(Connection connection) throws SQLException {
  196.         Random random = new Random();
  197.         String origin = "";
  198.         String sender = "";
  199.         String message = "";
  200.         Timestamp timestamp = new Timestamp(System.currentTimeMillis());
  201. //        System.out.println(timestamp);
  202.         final Statement statement = connection.createStatement();
  203.         int i = 0;
  204.         String q = ("SELECT * FROM user_stats");
  205.         ResultSet rs = statement.executeQuery(q);
  206.         while (rs.next()) {
  207.             i++;
  208.         }
  209.         int userId = random.nextInt() % i;
  210.         if (userId < 0) {
  211.             userId = userId * (-1);
  212.         }
  213.         String q2 = ("SELECT * FROM user_stats WHERE id=" + userId);
  214.         ResultSet rs2 = statement.executeQuery(q2);
  215.         while (rs2.next()) {
  216.             origin = rs2.getString("origin");
  217.             sender = rs2.getString("username");
  218.             message = String.valueOf(random.nextDouble() % 1000000.0);
  219. //            System.out.println("new Message:" + timestamp + " " + origin + "-" + sender + ":" + message);
  220.         }
  221.         connection.createStatement().
  222.                 execute("INSERT INTO chat_history " +
  223.                         "(origin, sender, " +
  224.                         "message, timestamp) VALUES (" +
  225.                         "'" + origin + "'," +
  226.                         "'" + sender + "'," +
  227.                         "'" + message + "'," +
  228.                         "'" + timestamp + "');");
  229.  
  230.     }
  231.  
  232.     private static void showUserPoints(Connection connection) throws SQLException {
  233.         Random random = new Random();
  234.         final Statement statement = connection.createStatement();
  235.         int i = 0;
  236.         String q = ("SELECT * FROM user_stats");
  237.         ResultSet rs = statement.executeQuery(q);
  238.         while (rs.next()) {
  239.             i++;
  240.         }
  241.         int userId = random.nextInt() % i;
  242.         if (userId < 0) {
  243.             userId = userId * (-1);
  244.         }
  245.         String q2 = ("SELECT * FROM user_stats WHERE id =" + userId);
  246.         ResultSet rs2 = statement.executeQuery(q2);
  247.         System.out.println(userId);
  248.         while (rs2.next()) {
  249.             System.out.println(rs2.getString("points"));
  250.         }
  251.     }
  252.  
  253.     private static void showUsers(Connection connection) throws SQLException {
  254.         final Statement statement = connection.createStatement();
  255.         int i = 1;
  256.         String q = ("SELECT * FROM user_stats");
  257.         ResultSet rs = statement.executeQuery(q);
  258.         while (rs.next()) {
  259.             System.out.print("(" + i + ") - (");
  260.             System.out.print(rs.getString("id"));
  261.             System.out.print(",");
  262.             System.out.print(rs.getString("origin"));
  263.             System.out.print(",");
  264.             System.out.print(rs.getString("username"));
  265.             System.out.print(",");
  266.             System.out.print(rs.getString("level"));
  267.             System.out.print(",");
  268.             System.out.print(rs.getString("points"));
  269.             System.out.print(",");
  270.             System.out.print(rs.getString("position"));
  271.             System.out.print(",");
  272.             System.out.print(rs.getString("online"));
  273.             System.out.print(",");
  274.             System.out.print(rs.getString("total_points"));
  275.             System.out.print(")");
  276.             i++;
  277.             System.out.println();
  278.         }
  279. //        System.out.println("count:" + (i - 1));
  280.     }
  281.  
  282.     private static void help() {
  283.         System.out.println("au - add new user");
  284.         System.out.println("ac - add new chat config N'\\'A");
  285.         System.out.println("ach - add new chat history N'\\'A");
  286.         System.out.println("acc - add new chat command N'\\'A");
  287.         System.out.println("asm - add new scheduled message N'\\'A");
  288.         System.out.println("---------------------------------");
  289.         System.out.println("su - show users");
  290.         System.out.println("sc - show chat configs N'\\'A");
  291.         System.out.println("sch - show chat histories N'\\'A");
  292.         System.out.println("scc - show chat commands N'\\'A");
  293.         System.out.println("sm - show messages");
  294.         System.out.println("ssm - show scheduled messages N'\\'A");
  295.         System.out.println("---------------------------------");
  296.         System.out.println("mau - multi adding users");
  297.         System.out.println("mac - multi adding new chat configs N'\\'A");
  298.         System.out.println("mach - multi adding new chat histories N'\\'A");
  299.         System.out.println("macc - multi adding new chat commands N'\\'A");
  300.         System.out.println("masm - multi adding new scheduled messages N'\\'A");
  301.         System.out.println("---------------------------------");
  302.         System.out.println("sup - show user points");
  303.         System.out.println("nw - new message");
  304.         System.out.println("tnm - timer new messages (two values count and period)");
  305.         System.out.println("tnu - timer new users (two values count and period)");
  306.         System.out.println("stm - stop timer messages");
  307.         System.out.println("stu - stop timer users");
  308.     }
  309.  
  310.     private static void addNewUser(Connection connection) {
  311.         Random random = new Random();
  312.         try {
  313.             connection.createStatement().
  314.                     execute("INSERT INTO user_stats " +
  315.                             "(origin, username, " +
  316.                             "level, points," +
  317.                             " position, online, " +
  318.                             "total_points ) VALUES (" +
  319.                             "'" + getRandomOrigin(random.nextBoolean()) + "'," +
  320.                             "'" + random.nextDouble() % 1000000 + "'," +
  321.                             "'" + Math.abs(random.nextInt() % 10) + "'," +
  322.                             "'" + random.nextFloat() % 10000.0 + "'," +
  323.                             "'" + Math.abs(random.nextInt() % 3) + "'," +
  324.                             "'" + Math.abs(random.nextInt() % 2) + "'," +
  325.                             "'" + Math.abs(random.nextFloat() % 10000.0) + "');");
  326.         } catch (SQLException e) {
  327.             e.printStackTrace();
  328.         }
  329.     }
  330.  
  331.     private static String getRandomOrigin(boolean b) {
  332.         if (b) {
  333.             return "twitch";
  334.         } else {
  335.             return "goodgame";
  336.         }
  337.     }
  338.  
  339.  
  340.     private static void initialize() throws ManagedProcessException, SQLException {
  341.         configBuilder = DBConfigurationBuilder.newBuilder();
  342.         configBuilder.setPort(3306); // OR, default: setPort(0); => autom. detect free port
  343.         configBuilder.setDataDir(DB_PATH + DB_NAME); // just an example
  344.         DB db = DB.newEmbeddedDB(configBuilder.build());
  345.         db.start();
  346.         try {
  347.             Class.forName("com.mysql.jdbc.Driver");
  348.         } catch (ClassNotFoundException e) {
  349.             e.printStackTrace();
  350.         }
  351.         conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "");
  352.         try {
  353.             String chatCommandsSql = "CREATE TABLE chat_commands(\n" +
  354.                     "id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,\n" +
  355.                     "command VARCHAR(32) ,\n" +
  356.                     "description VARCHAR(255) ,\n" +
  357.                     "target BOOLEAN ,\n" +
  358.                     "kind BOOLEAN DEFAULT 0 ,\n" +
  359.                     "type TINYINT(2) ,\n" +
  360.                     "personal BOOLEAN,\n" +
  361.                     "action VARCHAR(255),\n" +
  362.                     "cost FLOAT,\n" +
  363.                     "enabled BOOLEAN,\n" +
  364.                     "error_cost VARCHAR(255),\n" +
  365.                     "error_command VARCHAR(255),\n" +
  366.                     "PRIMARY KEY (id)\n" +
  367.                     ") ENGINE=InnoDB;";
  368.             String chatHistorySql = "CREATE TABLE chat_history(\n" +
  369.                     "id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,\n" +
  370.                     "origin VARCHAR(32) ,\n" +
  371.                     "sender VARCHAR(255) ,\n" +
  372.                     "message TEXT ,\n" +
  373.                     "timestamp DATETIME,\n" +
  374.                     "PRIMARY KEY (id)\n" +
  375.                     ") ENGINE=InnoDB;";
  376.             String configSql = "CREATE TABLE config(\n" +
  377.                     "`key` VARCHAR(255),\n" +
  378.                     "`value` VARCHAR(255),\n" +
  379.                     "PRIMARY KEY (`key`)\n" +
  380.                     ") ENGINE=InnoDB;";
  381.             String scheduledMessagesSql = "CREATE TABLE scheduled_messages(\n" +
  382.                     "id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,\n" +
  383.                     "target VARCHAR(32) ,\n" +
  384.                     "schedule TIME ,\n" +
  385.                     "starter_schedule TIME ,\n" +
  386.                     "text TEXT ,\n" +
  387.                     "enabled BOOLEAN,\n" +
  388.                     "PRIMARY KEY (id)\n" +
  389.                     ") ENGINE=InnoDB;";
  390.             String userStatsSql = "CREATE TABLE user_stats(\n" +
  391.                     "id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,\n" +
  392.                     "origin VARCHAR(32) NOT NULL,\n" +
  393.                     "username VARCHAR(255) NOT NULL,\n" +
  394.                     "level INT(3) NOT NULL,\n" +
  395.                     "points FLOAT NOT NULL DEFAULT 0.0,\n" +
  396.                     "position INT(2) NOT NULL DEFAULT 2,\n" +
  397.                     "online BOOLEAN NOT NULL DEFAULT 0,\n" +
  398.                     "total_points FLOAT NOT NULL DEFAULT 0.0,\n" +
  399.                     "PRIMARY KEY (id)\n" +
  400.                     ") ENGINE=InnoDB;";
  401. //            String sql3 = "CREATE TABLE users2(\n" +
  402. //                    "userid INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,\n" +
  403. //                    "name VARCHAR(80) NOT NULL,\n" +
  404. //                    "surname VARCHAR(80) NOT NULL,\n" +
  405. //                    "PRIMARY KEY (userid)\n" +
  406. //                    ") ENGINE=InnoDB;";
  407. //            String sql = "PRAGMA foreign_keys = false;\n" +
  408. //                    "CREATE TABLE \"chat_commands\"(\n" +
  409. //                    "\"id\"  INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\n" +
  410. //                    "\"command\"  TEXT(32),\n" +
  411. //                    "\"description\"  TEXT(256),\n" +
  412. //                    "\"target\" INTEGER,\n" +
  413. //                    "\"kind\"  INTEGER DEFAULT 0,\n" +
  414. //                    "\"type\"  INTEGER,\n" +
  415. //                    "\"personal\" INTEGER,\n" +
  416. //                    "\"action\"  TEXT(256),\n" +
  417. //                    "\"cost\" INTEGER,\n" +
  418. //                    "\"enabled\"  INTEGER,\n" +
  419. //                    "\"error_cost\"  TEXT(256),\n" +
  420. //                    "\"error_cost_test\"  TEXT(256),\n" +
  421. //                    "\"error_command\"  TEXT(256)\n" +
  422. //                    ")\n" +
  423. //                    " ENGINE=InnoDB;" +
  424. //                    "CREATE TABLE \"chat_history\" (\n" +
  425. //                    "\t \"id\" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\n" +
  426. //                    "\t \"origin\" TEXT(16,0) NOT NULL,\n" +
  427. //                    "\t \"sender\" TEXT(64,0) NOT NULL,\n" +
  428. //                    "\t \"message\" TEXT(1024,0) NOT NULL,\n" +
  429. //                    "\t \"timestamp\" integer\n" +
  430. //                    ")\n" +
  431. //                    " ENGINE=InnoDB;" +
  432. //                    "CREATE TABLE \"config\" (\n" +
  433. //                    "\t \"key\" TEXT(255,0) NOT NULL,\n" +
  434. //                    "\t \"value\" TEXT(65536,0) NOT NULL,\n" +
  435. //                    "\tPRIMARY KEY(\"key\")\n" +
  436. //                    ")\n" +
  437. //                    " ENGINE=InnoDB;" +
  438. //                    "CREATE TABLE \"scheduled_messages\" (\n" +
  439. //                    "\"id\"  INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\n" +
  440. //                    "\"target\"  TEXT(16),\n" +
  441. //                    "\"schedule\"  TEXT(32),\n" +
  442. //                    "\"starter_schedule\" TEXT(32),\n" +
  443. //                    "\"text\"  TEXT(128),\n" +
  444. //                    "\"enabled\"  INTEGER\n" +
  445. //                    ")" +
  446. //                    " ENGINE=InnoDB;\n" +
  447. //                    "CREATE TABLE \"user_stats\" (\n" +
  448. //                    "\t \"id\" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\n" +
  449. //                    "\t \"origin\" TEXT(32,0) NOT NULL,\n" +
  450. //                    "\t \"username\" TEXT(128,0) NOT NULL,\n" +
  451. //                    "\t \"level\" integer NOT NULL,\n" +
  452. //                    "\t \"points\" real NOT NULL DEFAULT 0,\n" +
  453. //                    "\t \"position\" integer NOT NULL DEFAULT 2,\n" +
  454. //                    "\t \"online\" integer NOT NULL DEFAULT 0,\n" +
  455. //                    "\t \"total_points\" real NOT NULL DEFAULT 0\n" +
  456. //                    ")\n" +
  457. //                    " ENGINE=InnoDB;" +
  458. //                    "INSERT INTO config (key, value) VALUES (\"version\", \"1\")\n" +
  459. //                    "PRAGMA foreign_keys = true;";
  460. //            conn.createStatement().execute(
  461. //                    "CREATE TABLE users(\n" +
  462. //                            "userid INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,\n" +
  463. //                            "name VARCHAR(80) NOT NULL,\n" +
  464. //                            "surname VARCHAR(80) NOT NULL,\n" +
  465. //                            "PRIMARY KEY (userid)\n" +
  466. //                            ") ENGINE=InnoDB;");
  467.             conn.createStatement().execute(
  468.                     chatCommandsSql);
  469.             conn.createStatement().execute(
  470.                     chatHistorySql);
  471.             conn.createStatement().execute(
  472.                     configSql);
  473.             conn.createStatement().execute(
  474.                     scheduledMessagesSql);
  475.             conn.createStatement().execute(
  476.                     userStatsSql);
  477. //            conn.createStatement().execute(
  478. //                    sql3);
  479.         } catch (SQLException e) {
  480.             e.printStackTrace();
  481.         }
  482.     }
  483.  
  484.  
  485.     private static void randomInsert(Connection connection) {
  486.         try {
  487.             connection.createStatement().execute("INSERT INTO user_stats VALUES ('" + getRandomNumber() + "');");
  488.         } catch (SQLException e) {
  489.             e.printStackTrace();
  490.         }
  491.     }
  492.  
  493.     private static void setStartRecords(Connection conn) {
  494.         for (int i = 0; i < START_RECORDS; i++) {
  495.             randomInsert(conn);
  496.         }
  497.     }
  498.  
  499.     private static void randomSelect(Connection connection) throws Exception {
  500.         int i = 0;
  501.         final Statement statement = connection.createStatement();
  502.         String q = ("SELECT code FROM sk");
  503.         ResultSet rs = statement.executeQuery(q);
  504.         while (rs.next()) {
  505.             i++;
  506.             System.out.println(rs.getString("code"));
  507.         }
  508.         System.out.println("count:" + (i - 1));
  509.     }
  510.  
  511.     private static int getRandomNumber() {
  512.         Random random = new Random();
  513.         return Math.abs(random.nextInt() % 1000 + 1);
  514.     }
  515.  
  516.     private static int getRandomOfUserCountNumber() {
  517.         Random random = new Random();
  518.         return Math.abs(random.nextInt() % USERS_COUNT + 1);
  519.     }
  520.  
  521.     private static void randomTask(Connection connection) {
  522.         Random random = new Random();
  523.         if (random.nextBoolean()) {
  524.             System.out.println("============INSERT=============");
  525.             randomInsert(connection);
  526.         } else {
  527.             try {
  528.                 System.out.println("============SELECT=============");
  529.                 randomSelect(connection);
  530.             } catch (Exception e) {
  531.                 e.printStackTrace();
  532.             }
  533.         }
  534.     }
  535. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement