Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Here is a incomplete pos server program, receiving input from posclient, inserting traction detail data into sql database. create a database Client Server Program Search

Here is a incomplete pos server program, receiving input from posclient, inserting traction detail data into sql database.

create a database

Client Server Program

  1. Search TMA02 in POSServer.java, to locate the code instruction that require you to change the code

  2. The behaviour is the same as TMA01, except following listed

  3. Add corresponding library (e.g. JPA) into project

  4. Add the persistence unit into project

  5. Add entities needed into project (You can right click the project -> New -> Other -> Persistence -> Entity Classes from Database

  1. Change the writeTransaction method in POSSever.java so that it writes transaction into database table transactions and transactionDetails table. Add transaction protection as it is multi-thread

  2. Change the loadItemData method in POSSever.java so that it reads items data from database table items. In the class SharedSocketPool, set the HashMap items with key equals to the item code, value equals to the items object itself.

  3. Change the prepareFileWriter method in POSServer.java so that it will create the EntityManager object.

  4. In ClientHandler, the command R and X has something to change

https://codeshare.io/2j9wwM

update on a sql server

create table transactionDetails(

transDetailId bigint not null primary key auto_increment,

transId bigint not null,

itemId int not null,

qty int not null,

constraint fk_transactionDetails_transId_transactions foreign key (transId)

references transactions (transId),

constraint fk_transactionDetails_transId_items foreign key (itemId)

references items (itemId)

);

client side

https://www.chegg.com/homework-help/questions-and-answers/create-table-transactiondetails-transdetailid-bigint-null-primary-key-autoincrement-transi-q68897179?trackid=e0U6foKK

pos

server

image text in transcribed

image text in transcribedimage text in transcribedimage text in transcribedimage text in transcribedimage text in transcribedimage text in transcribedimage text in transcribed

image text in transcribedimage text in transcribedimage text in transcribed

8) Click "Detail" button of that row. It should redirect to a page, showing 3 records. Each row shows the item input in step 5. run: C Client Id : 2 R:123:2 R: 456:2 R:999:2 R:AAA:2 Invalid Command X 31.56 Connection Closed BUILD SUCCESSFUL (total time: 25 seconds) Items - Transactions Transaction id Client id Transaction Date Time of items Total Amount 1 1 2020-12-06 17:56:32.0 6 Details 2020-12-13 02:02:14.0 31.560000000002 Details Items Transactions Item Code Item Name Unit Price 123 123 1 /* 2 * To change this license header, choose License Headers in Project Properties. 3 * To change this template file, choose Tools | Templates 4 * and open the template in the editor. 5 */ 6 package tma02.pos; 7 8 import java.io.*; 9 import java.net. *; 10 import java.util.*; import java.util.concurrent.locks.*; 12 13 public class POSServer{ 14 15 //Define the constants 16 private final static int MAX_NO_OF_CONNECTION = 5; 17 private final static String ITEMCODE_FILE_PATH = "itemcode.csv"; 18 private final static String TRANS_HIST_FILE_PATH = "transaction.csv"; 19 A. 20 public static void main(String args[]){ tryl 21 22 //1. Declare variables /* la. Server Socket */ ServerSocket ssk; SharedSocketPool pool;/* Shared object */ 1/2. instantize the variable // 2a instantize server socket ssk = new ServerSocket( 12345); // instantize shared object for all client, pass 3 constants as parameters pool = new Shared SocketPool MAX_NO_OF_CONNECTION, ITEMCODE_FILE_PATH, TRANS_HIST_FILE_PATH); 31 33 34 35 37 1* You can ignore this part. This is to flush the File output stream and close the stream when this program close */ Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { try pool cleanup(); }catch( Exception e){ e.printStackTrace(); 38 39 SA 41 42 43 }); 44 45 46 47 48 //3. receive the client Connection while(true){ 1/4. Get the Client Socket from server socket by accepting client connection Socket skt = ssk.accept(); new. Thread new ClientHandler(pool.skt)...start 175. Create the clientHandler object, pass the Shared Object and Client Socket to it //6. Create and start the thread 50 51 52 }catch(Exception e) { e.printStackTrace(); }//end of try-catch block }//end of main thread 55 56 57 58 }//end of class POSServer 59 private int maxlo0fConnection:- private String itemCodeFilePath: private ReentrantLock lock; private Condition hasEmptySlot; private ArrayListclientHandler handlers Llinaluthalmstoremantive clientubandleuchiert. 1/private HashMap itemPrice; private FileWriter.wr. 65 67 private HashMap(); 87 88 89 1/call the method so that it will create/append and open the "transaction.csv" file output stream this.prepareFileWriteri transFilepath); 91 92 //call the method so that it will load the "itemCode.csv" file into the itemPrice Hashlap this loadItemData 95 96 98 /* Client will call this method to get client id. PLEASE implement the thread safe coding. */ public BaShouldeisesgachionized here2 Revalermitawateededuint getclientId ClientHandler caller) int clientid -1; try 1/8b. Should we use lock & Condition here? Beware, it may not needed! = 100 101 102 Hints : 103 If lock & Condition needed here, what should we check? And what should we do if the checking is true? Line 56-58 may give you some insight * 104 105 106 107 108 109 110 111 112 113 114 /* Send the "Please wait message to client IF MAXIMUM NUMBER OF CONNECTIONS IS REACH! */ /* Be careful where to put this line. Try to test the program to see if max. no of Connection reach, will the waiting client show this message? */ _caller.WriteToClient("Please wait"); 116 /* IF THERE ARE LESS THAN 5 CONNECTIONS, look up the space that is free, and get that index as client id */ handlers.set(handlers.indexOf(null)caller); /* Assign the client (i.e. the caller) to that free slot */ clientid - handlers.indexOf( caller). catch(Exception e) e.printStackTrace(); finally. //8c. Anything need to write here? } return clientid; 119 121 122 123 O 125 126 128 129 130 131 /* Client will call this method when they send the command "Q" to server, to release a slot in the ArrayList */ public *.Shouldeisesgachionized here? Rena.lemmitawateededoid releaseClient(clientHandler caller) try{ 7/9b. Should we use lock here? Beware, it may not needed! // To free the slot, just assign a null to that slot. handlers.set(handlers.indexOf(_caller), null); catch(Exception e). e.printStackTrace(); finally 7/9c. Anything need to write here? } 133 135 136 137 138 } publici Shouldelsesmchionizedbere2 Bewalaituma notweeded double getUnitPrice intitenCode) 1796. Should we use lock here? Beware, it may not needed! 140 141 142 143 /* The following code is shortcut of if-else, if the itemCode parameter found in the Hashiap, then return the price, if no, return -1 */ return this.itemPrice.contains Key( itemCode) ? this. itemPrice.get(itemcode): -1; 145 147 public synchronized. Itens getItem( String itemcode) return this.items.getOrDefault(itemcode, null); 149 150 /* This is a method that allow client to pass in the client id + total and write in the "transaction.csv" */ public 11.Should we use "swchronized" bere2 Beware witman not needed void writeTransaction int clientId double total try { //TMAO2: Begin the entity manger transaction //THAO2: Create the Transactions entity object //TMAO2: Set the clientId into Transactions entity object //TMAO2: Set the TransDtm with current date time (i.e. new Date() into Transactions entity object 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 for(/* TMA12: Loop through the details (i.e. List) */){ //THAO2: set the "Transactions entity object" into each Transactiondetails entity } //TMAO2: Set the details (i.e. List) into Transactions entity object //THAO2: Persist this Transactions entity object into DB 170 171 172 // TMA12: Commit the entity manger transaction } catch (Exception e) { e.printStackTrace(); //TMA02: Rollback the entity manger transaction if error occur } 174 175 176 O 178 179 1/It will triggered before the main program close public void cleanup try this.fw.flush(); this fw.close() catch (Exceptionell e.printStackTrace(); 182 184 185 186 187 188 //This is a method to read the file content and load into the Item Price HashMap private void loadItemData(){ try{ Scanner fin = new Scanner(new File( this. itemCodeFilePath)); while( fin hasNextLine()){ String line = fin.nextLine(); 189 190 191 192 193 194 195 196 197 198 199 200 // Split the data String[] values /* 12a. Google => Java how to split the string with delimiter , *; //R:123:F try int itemCode = /* 12b. Google => java how to cast string to int */(values[0]); double price 1* 12c. Google => java how to cast string to double */(values[1]); itemPrice.put IfAbsent(itemcode, price); } catch(/* 12d. If the input is not a numeric value, what exception will throw? */ nfe) { System.out.println("Invalid data file data : " + line); Continue; } } fin.close(); // TMA12: Prepare a dynamic query to get all the items from DB // TMA02: Get a list of result from the query 201 202 203 204 205 206 207 208 209 210 211 for(/* THAO2: loop all the items in the list */){ /* TMAO2: Put them into items HashMap. Key is the item code, Value is the items object itself */ } }catch(Exception e) { e.printStackTrace(); 212 213 215 } 216 217 218 219 //This is a method to prepare and open the file output stream private void prepareFileWriter(String transFilePath){ tryl //TMAO2: Create the entity manager and assign to this em }catch(Exception ioe){ ioe.printStackTrace(); 220 221 222 224 226 227 class ClientHandler /* 14. how to make this class multithreading? *} { 228 229 231 232 233 234 235 236 237 238 private final String ERR_MSG = "Invalid Command"; private SharedSocketPool sharedPoolObj; private Socket skt; private BufferedReader in; private PrintWriter out; private char lastCommandCode, thisCndCode; private String Cod; private int clientid; private double myTotal; private ListTransactiondetalo details = new ArrayList (i.e. details) //Record this command code as last command code, so that you can check in next round of client input sequence validation break; 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 case 'X': //Check previous command code if(lastCommandCode != 'R'){ WriteToClient(ERR_MSG); } // send the myTotal to client //By using one of the Shared Object public method, write the clientId, myTotal to the "transaction.csv" 337 338 // Anything need to perform if the transaction end? Hints, related to a numeric variable //TMA02 : clear the List TransactionDetails> details 339 340 341 342 //Record this command code as last Command code, so that you can check in next round of client input sequence validation 343 lastCommandCode - thisCndCode; 344 break; 345 346 347 case 'Q': //Check previous command Code //Use the local private method to close the socket Connection + release a free slot in shared object arraylist is Running = false;//break the while loop // Record this Command code as last Command code, so that you can check in next round of client input sequence validation 348 349 350 351 352 353 354 355 356 357 358 359 360 break; default: // send error message to client // remember to use Continue to skip remaining code and get client next Command }//end of switch-case 361 362 363 }catch(Exception e){ System.out.println("Connection Closed"); //Use the local private method to close the socket Connection + release a free slot in shared object arraylist }//end of try-catch block }//end of run() 364 365 366 367 0 368 369 370 371 372 373 374 375 376 377 public void WriteToClient(String msg){ try this.out.println(msg); }catch( Exception e){ System.out.println("Connection Closed"); //Use the local private method to close the socket Connection + release a free slot in shared object arraylist } 378 379 380 //This is a local private method to close the socket Connection + release a free slot in shared object arraylist private void closeConn(){ tryl //20. use shared object public method to release a free slot in the ArrayList 1/21. close all input, output stream and socket }catch(Exception e) { System.out.println("Connection Closed"); 381 382 383 384 385 8) Click "Detail" button of that row. It should redirect to a page, showing 3 records. Each row shows the item input in step 5. run: C Client Id : 2 R:123:2 R: 456:2 R:999:2 R:AAA:2 Invalid Command X 31.56 Connection Closed BUILD SUCCESSFUL (total time: 25 seconds) Items - Transactions Transaction id Client id Transaction Date Time of items Total Amount 1 1 2020-12-06 17:56:32.0 6 Details 2020-12-13 02:02:14.0 31.560000000002 Details Items Transactions Item Code Item Name Unit Price 123 123 1 /* 2 * To change this license header, choose License Headers in Project Properties. 3 * To change this template file, choose Tools | Templates 4 * and open the template in the editor. 5 */ 6 package tma02.pos; 7 8 import java.io.*; 9 import java.net. *; 10 import java.util.*; import java.util.concurrent.locks.*; 12 13 public class POSServer{ 14 15 //Define the constants 16 private final static int MAX_NO_OF_CONNECTION = 5; 17 private final static String ITEMCODE_FILE_PATH = "itemcode.csv"; 18 private final static String TRANS_HIST_FILE_PATH = "transaction.csv"; 19 A. 20 public static void main(String args[]){ tryl 21 22 //1. Declare variables /* la. Server Socket */ ServerSocket ssk; SharedSocketPool pool;/* Shared object */ 1/2. instantize the variable // 2a instantize server socket ssk = new ServerSocket( 12345); // instantize shared object for all client, pass 3 constants as parameters pool = new Shared SocketPool MAX_NO_OF_CONNECTION, ITEMCODE_FILE_PATH, TRANS_HIST_FILE_PATH); 31 33 34 35 37 1* You can ignore this part. This is to flush the File output stream and close the stream when this program close */ Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { try pool cleanup(); }catch( Exception e){ e.printStackTrace(); 38 39 SA 41 42 43 }); 44 45 46 47 48 //3. receive the client Connection while(true){ 1/4. Get the Client Socket from server socket by accepting client connection Socket skt = ssk.accept(); new. Thread new ClientHandler(pool.skt)...start 175. Create the clientHandler object, pass the Shared Object and Client Socket to it //6. Create and start the thread 50 51 52 }catch(Exception e) { e.printStackTrace(); }//end of try-catch block }//end of main thread 55 56 57 58 }//end of class POSServer 59 private int maxlo0fConnection:- private String itemCodeFilePath: private ReentrantLock lock; private Condition hasEmptySlot; private ArrayListclientHandler handlers Llinaluthalmstoremantive clientubandleuchiert. 1/private HashMap itemPrice; private FileWriter.wr. 65 67 private HashMap(); 87 88 89 1/call the method so that it will create/append and open the "transaction.csv" file output stream this.prepareFileWriteri transFilepath); 91 92 //call the method so that it will load the "itemCode.csv" file into the itemPrice Hashlap this loadItemData 95 96 98 /* Client will call this method to get client id. PLEASE implement the thread safe coding. */ public BaShouldeisesgachionized here2 Revalermitawateededuint getclientId ClientHandler caller) int clientid -1; try 1/8b. Should we use lock & Condition here? Beware, it may not needed! = 100 101 102 Hints : 103 If lock & Condition needed here, what should we check? And what should we do if the checking is true? Line 56-58 may give you some insight * 104 105 106 107 108 109 110 111 112 113 114 /* Send the "Please wait message to client IF MAXIMUM NUMBER OF CONNECTIONS IS REACH! */ /* Be careful where to put this line. Try to test the program to see if max. no of Connection reach, will the waiting client show this message? */ _caller.WriteToClient("Please wait"); 116 /* IF THERE ARE LESS THAN 5 CONNECTIONS, look up the space that is free, and get that index as client id */ handlers.set(handlers.indexOf(null)caller); /* Assign the client (i.e. the caller) to that free slot */ clientid - handlers.indexOf( caller). catch(Exception e) e.printStackTrace(); finally. //8c. Anything need to write here? } return clientid; 119 121 122 123 O 125 126 128 129 130 131 /* Client will call this method when they send the command "Q" to server, to release a slot in the ArrayList */ public *.Shouldeisesgachionized here? Rena.lemmitawateededoid releaseClient(clientHandler caller) try{ 7/9b. Should we use lock here? Beware, it may not needed! // To free the slot, just assign a null to that slot. handlers.set(handlers.indexOf(_caller), null); catch(Exception e). e.printStackTrace(); finally 7/9c. Anything need to write here? } 133 135 136 137 138 } publici Shouldelsesmchionizedbere2 Bewalaituma notweeded double getUnitPrice intitenCode) 1796. Should we use lock here? Beware, it may not needed! 140 141 142 143 /* The following code is shortcut of if-else, if the itemCode parameter found in the Hashiap, then return the price, if no, return -1 */ return this.itemPrice.contains Key( itemCode) ? this. itemPrice.get(itemcode): -1; 145 147 public synchronized. Itens getItem( String itemcode) return this.items.getOrDefault(itemcode, null); 149 150 /* This is a method that allow client to pass in the client id + total and write in the "transaction.csv" */ public 11.Should we use "swchronized" bere2 Beware witman not needed void writeTransaction int clientId double total try { //TMAO2: Begin the entity manger transaction //THAO2: Create the Transactions entity object //TMAO2: Set the clientId into Transactions entity object //TMAO2: Set the TransDtm with current date time (i.e. new Date() into Transactions entity object 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 for(/* TMA12: Loop through the details (i.e. List) */){ //THAO2: set the "Transactions entity object" into each Transactiondetails entity } //TMAO2: Set the details (i.e. List) into Transactions entity object //THAO2: Persist this Transactions entity object into DB 170 171 172 // TMA12: Commit the entity manger transaction } catch (Exception e) { e.printStackTrace(); //TMA02: Rollback the entity manger transaction if error occur } 174 175 176 O 178 179 1/It will triggered before the main program close public void cleanup try this.fw.flush(); this fw.close() catch (Exceptionell e.printStackTrace(); 182 184 185 186 187 188 //This is a method to read the file content and load into the Item Price HashMap private void loadItemData(){ try{ Scanner fin = new Scanner(new File( this. itemCodeFilePath)); while( fin hasNextLine()){ String line = fin.nextLine(); 189 190 191 192 193 194 195 196 197 198 199 200 // Split the data String[] values /* 12a. Google => Java how to split the string with delimiter , *; //R:123:F try int itemCode = /* 12b. Google => java how to cast string to int */(values[0]); double price 1* 12c. Google => java how to cast string to double */(values[1]); itemPrice.put IfAbsent(itemcode, price); } catch(/* 12d. If the input is not a numeric value, what exception will throw? */ nfe) { System.out.println("Invalid data file data : " + line); Continue; } } fin.close(); // TMA12: Prepare a dynamic query to get all the items from DB // TMA02: Get a list of result from the query 201 202 203 204 205 206 207 208 209 210 211 for(/* THAO2: loop all the items in the list */){ /* TMAO2: Put them into items HashMap. Key is the item code, Value is the items object itself */ } }catch(Exception e) { e.printStackTrace(); 212 213 215 } 216 217 218 219 //This is a method to prepare and open the file output stream private void prepareFileWriter(String transFilePath){ tryl //TMAO2: Create the entity manager and assign to this em }catch(Exception ioe){ ioe.printStackTrace(); 220 221 222 224 226 227 class ClientHandler /* 14. how to make this class multithreading? *} { 228 229 231 232 233 234 235 236 237 238 private final String ERR_MSG = "Invalid Command"; private SharedSocketPool sharedPoolObj; private Socket skt; private BufferedReader in; private PrintWriter out; private char lastCommandCode, thisCndCode; private String Cod; private int clientid; private double myTotal; private ListTransactiondetalo details = new ArrayList (i.e. details) //Record this command code as last command code, so that you can check in next round of client input sequence validation break; 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 case 'X': //Check previous command code if(lastCommandCode != 'R'){ WriteToClient(ERR_MSG); } // send the myTotal to client //By using one of the Shared Object public method, write the clientId, myTotal to the "transaction.csv" 337 338 // Anything need to perform if the transaction end? Hints, related to a numeric variable //TMA02 : clear the List TransactionDetails> details 339 340 341 342 //Record this command code as last Command code, so that you can check in next round of client input sequence validation 343 lastCommandCode - thisCndCode; 344 break; 345 346 347 case 'Q': //Check previous command Code //Use the local private method to close the socket Connection + release a free slot in shared object arraylist is Running = false;//break the while loop // Record this Command code as last Command code, so that you can check in next round of client input sequence validation 348 349 350 351 352 353 354 355 356 357 358 359 360 break; default: // send error message to client // remember to use Continue to skip remaining code and get client next Command }//end of switch-case 361 362 363 }catch(Exception e){ System.out.println("Connection Closed"); //Use the local private method to close the socket Connection + release a free slot in shared object arraylist }//end of try-catch block }//end of run() 364 365 366 367 0 368 369 370 371 372 373 374 375 376 377 public void WriteToClient(String msg){ try this.out.println(msg); }catch( Exception e){ System.out.println("Connection Closed"); //Use the local private method to close the socket Connection + release a free slot in shared object arraylist } 378 379 380 //This is a local private method to close the socket Connection + release a free slot in shared object arraylist private void closeConn(){ tryl //20. use shared object public method to release a free slot in the ArrayList 1/21. close all input, output stream and socket }catch(Exception e) { System.out.println("Connection Closed"); 381 382 383 384 385

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image_2

Step: 3

blur-text-image_3

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Sams Teach Yourself Beginning Databases In 24 Hours

Authors: Ryan Stephens, Ron Plew

1st Edition

067232492X, 978-0672324925

More Books

Students also viewed these Databases questions

Question

Should you be allowed to surf the Web at work? Why or why not?

Answered: 1 week ago

Question

What is conservative approach ?

Answered: 1 week ago

Question

What are the basic financial decisions ?

Answered: 1 week ago

Question

What is Change Control and how does it operate?

Answered: 1 week ago

Question

How do Data Requirements relate to Functional Requirements?

Answered: 1 week ago