· 9 years ago · Mar 18, 2017, 12:32 PM
1package task4;
2
3import java.sql.Connection;
4import java.sql.DriverManager;
5import java.sql.SQLException;
6import java.sql.Statement;
7import java.text.ParseException;
8import java.text.SimpleDateFormat;
9import java.util.Date;
10import java.util.HashMap;
11import java.util.Scanner;
12
13public class TransactionTask {
14
15 //Scanner init
16 private static Scanner scan;
17 static String input;
18
19 // SQL Connection inits
20 private static Connection connection = null;
21 public static Statement statement = null;
22 static final String dbuser = "root";
23 static final String dbpassword = "";
24 static final String dbname = "school";
25 static final String dbport = "3306";
26
27 public static void main(String[] args) {
28
29 scan = new Scanner(System.in);
30
31 HashMap<String, String> transactionDetails = new HashMap<String, String>();
32
33 System.out.println("Please fill in all the fields required:");
34 System.out.println("(TERMINAL ID ~ CARD NUMBER ~ EXP DATE ~ PIN BLOCK ~ AMOUNT ~ PROMO CODE)");
35 System.out.println("<-==============================================->");
36
37 String input = scan.nextLine();
38 String[] fields = input.split("~");
39
40 transactionDetails.put("TerminalID", fields[0].trim());
41 transactionDetails.put("Card NR", fields[1]);
42 transactionDetails.put("Expiration Date", fields[2]);
43 transactionDetails.put("PinBlock", fields[3]);
44 transactionDetails.put("Amount", fields[4]);
45 transactionDetails.put("PromoCode", fields[5]);
46
47 System.out.println("<-==============================================->");
48
49 // Assigning variables to use for validation
50 String cardnr = transactionDetails.get("Card NR");
51 String promocode = transactionDetails.get("PromoCode");
52 String expdate = transactionDetails.get("Expiration Date");
53 String amount = transactionDetails.get("Amount");
54 String pin = transactionDetails.get("PinBlock");
55
56 // Validation begin
57 if (cardnr.length() < 12 && cardnr.length() > 18 && !cardnr.matches("^-?\\d+$")) {
58 System.out.println("Card number should be between 12 and 18 numbers.");
59 return;
60 } else if (promocode.length() > 13) {
61 System.out.println("Invalid promotion code");
62 return;
63 } else if (expdate.length() > 0 && !validateDate(expdate)) {
64 System.out.println("Expiration date is not in valid format or has expired.");
65 return;
66 } else if (amount.length() > 0 && !isFloat(amount)) {
67 System.out.println("Invalid amount entered.");
68 return;
69 } else if (pin.length() > 0 && !isHex(pin)) {
70 System.out.println("You have entered an invalid PIN Block");
71 return;
72 } else
73 System.out.println("Everything is valid!");
74
75 UpdateDB(transactionDetails);
76 }
77
78
79
80 // Checking if a value is HEX
81 public static boolean isHex(String hex) {
82 try {
83 Long.parseLong(hex, 16);
84 return true;
85 } catch (NumberFormatException ex) {
86 return false;
87 }
88 }
89
90
91 // Checking if value is float
92 public static boolean isFloat(String f) {
93 try {
94 Float.parseFloat(f);
95 return true;
96 } catch (NumberFormatException ex) {
97 return false;
98 }
99 }
100
101 // Method for validating date if its in correct format
102 public static boolean validateDate(String expdate) {
103 SimpleDateFormat sdf = new SimpleDateFormat("MM/yy");
104 Date date = new Date();
105
106 try {
107 Date date1 = sdf.parse(expdate);
108 return date1.after(date);
109 } catch (ParseException ex) {
110 return false;
111 }
112 }
113
114 // Method for checking if String is Integer
115 // Not going to use parseInt, cuz this is simpler and doesnt throw anything.
116
117 static boolean isInt(String s) {
118
119 if (s.matches("^[+-]?\\d+$"))
120 return true;
121 else
122 return false;
123 }
124
125 //SQL Connection
126 private static void connect()
127 {
128 try {
129 Class.forName("com.mysql.jdbc.Driver");
130 connection = DriverManager.getConnection("jdbc:mysql://localhost:" + dbport + "/" + dbname, dbuser, dbpassword);
131 }
132 catch (Exception e){
133 System.out.println(e);
134 }
135 }
136
137 private static void disconnect()
138 {
139 try
140 {
141 connection.close();
142 connection = null;
143 }
144 catch (Exception e)
145 {
146 System.out.println(e);
147 }
148 }
149
150 private static void UpdateDB(HashMap<String, String> data)
151 {
152 // try to create table if not exists
153 initTable();
154
155 connect();
156 try {
157 statement = connection.createStatement();
158
159 String sql = String.format("INSERT INTO `transactions` (`terminal_id`, `cardnr`, `expdate`, `pinblock`, `amount`, `promocode`) VALUES "
160 + "('%s', '%s', '%s', '%s', '%s', '%s');",
161 data.get("TerminalID"),
162 data.get("Card NR"),
163 data.get("Expiration Date"),
164 data.get("PinBlock"),
165 data.get("Amount"),
166 data.get("PromoCode")
167 );
168 System.out.println(sql);
169
170 statement.executeUpdate(sql);
171
172 }
173 catch(SQLException e)
174 {
175 // Custom error handling for 1062 (sql - duplicate entry)
176 // Just for example how to handle and output custom error messages :D
177 if (e.getErrorCode() == 1062)
178 {
179 System.out.println("This transaction already exists!");
180 }
181 else
182 {
183 System.out.println(e);
184 }
185 }
186
187 disconnect();
188 }
189
190 // initialize if the table transactions doesnt exist
191 private static void initTable()
192 {
193 connect();
194
195 try{
196 statement = connection.createStatement();
197
198 String sql = "CREATE TABLE IF NOT EXISTS `transactions` ( `terminal_id` VARCHAR(12) NOT NULL , `cardnr` VARCHAR(16) NOT NULL , `expdate` VARCHAR(12) NOT NULL , `pinblock` VARCHAR(12) NOT NULL , `amount` VARCHAR(12) NOT NULL , `promocode` VARCHAR(12) NOT NULL , PRIMARY KEY (`terminal_id`)) ENGINE = InnoDB;";
199
200 statement.execute(sql);
201 }
202 catch(Exception e)
203 {
204 System.out.println(e);
205 }
206
207 disconnect();
208 }
209}