Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2019
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 17.33 KB | None | 0 0
  1.  
  2. // COMP28112 Exercise 22 - Dainius Varanauskas
  3.  
  4. package uk.ac.manchester.cs.comp28112.lab2;
  5.  
  6. import java.io.IOException;
  7.  
  8. import org.apache.commons.httpclient.methods.PutMethod;
  9. import org.apache.commons.httpclient.methods.RequestEntity;
  10. import org.apache.commons.httpclient.methods.StringRequestEntity;
  11.  
  12. import org.apache.commons.httpclient.*;
  13. import org.apache.commons.httpclient.HttpClient;
  14. import org.apache.commons.httpclient.HttpStatus;
  15. import org.apache.commons.httpclient.methods.GetMethod;
  16.  
  17. // Client Class to book a hotel and a band.
  18. public class Client {
  19.  
  20. // Client fields.
  21. private static String my_username = "8dv141";
  22. private static String my_password = "TiLQGq";
  23. private static PutMethod putMethodHotel = new PutMethod("http://jewel.cs.man.ac.uk:3010/queue/enqueue");
  24. private static PutMethod putMethodBand = new PutMethod("http://jewel.cs.man.ac.uk:3020/queue/enqueue");
  25.  
  26. // Main
  27. public static void main(String[] args) {
  28.  
  29. // Manual cancel request.
  30. if (args.length > 0 && args[0].equals("Cancel")) {
  31. System.out.println("---------------| Canceling Hotel |---------------");
  32. String request_id = Long.toString(System.currentTimeMillis()); // Generate a request id.
  33. cancel_slot(my_username, my_password, Integer.parseInt(args[1]), putMethodHotel); // Cancel Hotel booking.
  34. System.out.println("---------------| Canceling Bands |---------------");
  35. request_id = Long.toString(System.currentTimeMillis()); // Generate a request id.
  36. cancel_slot(my_username, my_password, Integer.parseInt(args[1]), putMethodBand); // Cancel Band booking.
  37. System.exit(1); // Exit program.
  38. }
  39.  
  40. // Attempt to reserve the slot id for band. Continue until output is a non-negative result.
  41. // If the result is negative, reset slot id and make hotel look for a new one.
  42. int my_slot_id = -1;
  43. do {
  44. // Cancel the slot booked by the hotel if the slot id is positive.
  45. if (my_slot_id > 0) {
  46. System.out.println("---------------| Canceling Hotel |---------------");
  47. String request_id = Long.toString(System.currentTimeMillis()); // Generate a request id.
  48. cancel_slot(my_username, my_password, my_slot_id, putMethodHotel); // Cancel Hotel booking.
  49. }
  50. // Attempt to reserve the slot id for hotel. Continue until output is a non-negative result.
  51. do {
  52. // Find the earliest slot id. Continue until a valid (positive) slot id is found.
  53. System.out.println("-------------| Looking for slot id |-------------");
  54. while (my_slot_id < 0) {
  55. my_slot_id = find_slot_id(get_availability_list(my_username, my_password, putMethodHotel),
  56. get_availability_list(my_username, my_password, putMethodBand));
  57. }
  58. // Reset put methods to build different requests using XMLStrings.
  59. reset_putMethods();
  60. System.out.println("---------------| Reserving Hotel |---------------");
  61. } while (reserve_slot(my_username, my_password, 0, putMethodHotel) != 0);
  62. System.out.println("---------------| Reserving Bands |---------------");
  63. } while (reserve_slot(my_username, my_password, my_slot_id, putMethodBand) != 0); // TODO :: WHILE IS NOT LOOPING CAUSE THE return value is not properly returned.
  64. } // main
  65.  
  66. // Reset the putMethod objects.
  67. private static void reset_putMethods() {
  68. putMethodHotel = new PutMethod("http://jewel.cs.man.ac.uk:3010/queue/enqueue");
  69. putMethodBand = new PutMethod("http://jewel.cs.man.ac.uk:3020/queue/enqueue");
  70. } // reset_putMethods
  71.  
  72. // Check if input string contains value.
  73. private static void check_for_null(String string, String method) {
  74. if (string == null) { // Check if input string is null.
  75. System.err.println("Resulting string in " + method + " was null."); // Print what method it originated from.
  76. System.exit(1); // Exit the program.
  77. }
  78. } // check_for_null
  79.  
  80. // Build a uri using given username and password.
  81. private static String msg_uri_builder(String msg_uri, String username, String password) {
  82. return msg_uri += "?username=" + username + "&password=" + password;
  83. } // msg_uri_builder
  84.  
  85. // Cancel a slot for an event.
  86. private static int cancel_slot(String username, String password, int slot_id, PutMethod putMethod) {
  87. String request_id = Long.toString(System.currentTimeMillis()); // Generate a request id.
  88. String xmlString = cancelation(request_id, username, password, slot_id); // Build a cancelation XML string.
  89. Pair <String, Integer> response = send_message(xmlString, putMethod); // Send a cancel request and get a response.
  90. String msg_uri = response.getKey(); // Get the response body.
  91. msg_uri = msg_uri_builder(msg_uri, username, password); // Build a string with username and password.
  92. String response_msg_cancelation = get_message(msg_uri); // Request a cancel response message.
  93. return response.getValue(); // Return response code.
  94. } // cancel_slot
  95.  
  96. // Build a cancel request in XML.
  97. private static String cancelation(String request_id, String username, String password, int slot_id) {
  98. String xmlString = null; // Create a string to hold XML.
  99. try {
  100. xmlString = XMLRequest.Cancel(request_id, username, password, slot_id); // Build the reservation request.
  101. } catch (Exception e) {
  102. System.err.println("Failed to build XML string."); // Catch exceptions.
  103. e.printStackTrace();
  104. }
  105. check_for_null(xmlString, "cancelation"); // Check for error.
  106. return xmlString;
  107. }
  108.  
  109. // Reserve a slot for an event.
  110. private static int reserve_slot(String username, String password, int slot_id, PutMethod putMethod) {
  111. String request_id = Long.toString(System.currentTimeMillis()); // Generate a request id.
  112. String xmlString = reservation(request_id, username, password, slot_id); // Build a reservation XML string.
  113. Pair <String, Integer> response = send_message(xmlString, putMethod); // Send a reservation request and get a response.
  114. String msg_uri = response.getKey(); // Get the response body.
  115. msg_uri = msg_uri_builder(msg_uri, username, password); // Build a string with username and password.
  116. String response_msg_reservation = get_message(msg_uri); // Request a reservation response message.
  117. return response.getValue(); // Return response code.
  118. } // reserve_slot
  119.  
  120. // Build a reservation request in XML.
  121. private static String reservation(String request_id, String username, String password, int slot_id) {
  122. String xmlString = null; // Create a string to hold XML.
  123. try {
  124. xmlString = XMLRequest.Reservation(request_id, username, password, slot_id); // Build the reservation request.
  125. } catch (Exception e) {
  126. System.err.println("Failed to build XML string."); // Catch exceptions.
  127. e.printStackTrace();
  128. }
  129. check_for_null(xmlString, "reservation"); // Check for error.
  130. return xmlString;
  131. } // reservation
  132.  
  133. // Find the earliest matching slot id.
  134. private static int find_slot_id(int[] availableHotels, int[]availableBands) {
  135. for (int i = 0; i < availableHotels.length; i++) { // Poly. search O(n^2)
  136. for (int j = 0; j < availableBands.length; j++) {
  137. if (availableHotels[i] == availableBands[j]) {
  138. System.out.println("Found slot: " + availableHotels[i]);
  139. return availableHotels[i];
  140. }
  141. }
  142. }
  143. System.out.println("No slot found. Retrying.");
  144. return -1; // Return negative value if no slot found.
  145. } // find_slot_id
  146.  
  147. private static int[] get_availability_list(String username, String password, PutMethod putMethod) {
  148. String request_id = Long.toString(System.currentTimeMillis()); // Generate a request id.
  149. String xmlString = availability(request_id, username, password); // Build an availability XML string.
  150. Pair <String, Integer> response = send_message(xmlString, putMethod); // Send a availability request and get a response.
  151. String msg_uri = response.getKey(); // Get the response body.
  152. msg_uri = msg_uri_builder(msg_uri, username, password); // Build a string with username and password.
  153. String response_msg_availability = get_message(msg_uri); // Request an availability response message.
  154. return availability_parser(response_msg_availability); // Get and return the availability list as a list of integers.
  155. } // get_availability_list
  156.  
  157. // Build an availability request in XML.
  158. private static String availability(String request_id, String username, String password) {
  159. String xmlString = null; // Create a string to hold XML.
  160. try {
  161. xmlString = XMLRequest.Availability(request_id, username, password); // Build the availability request.
  162. } catch (Exception e) {
  163. System.err.println("Failed to build XML string."); // Catch exceptions.
  164. e.printStackTrace();
  165. }
  166. check_for_null(xmlString, "availability"); // Check for error.
  167. return xmlString; // Return result.
  168. } // availability
  169.  
  170. // Parse the availability list.
  171. private static int[] availability_parser(String availability) {
  172. String[] digits = availability.replaceAll("\\[|\\]|\\s", "").split(","); // Split the string into set of substrings with only numbers.
  173. int[] availableHotels = new int[digits.length]; // Create a list for numbers.
  174. for (int i = 0; i < digits.length; i++) { // Parse each digit.
  175. try {
  176. availableHotels[i] = Integer.parseInt(digits[i]);
  177. } catch (Exception err) {
  178. System.out.println("Digits array length: " + digits.length); // Catch exceptions.
  179. System.out.println("Error whilst parsing availability list");
  180. err.printStackTrace();
  181. }
  182. }
  183. return availableHotels; // Return the list.
  184. } // availability_parser
  185.  
  186. // Send a message to the server.
  187. private static Pair<String, Integer> send_message(String xmlString, PutMethod putMethod) {
  188. String msg_uri = null; // Create message to return.
  189. RequestEntity entity = new StringRequestEntity(xmlString); // Set the request's entity (body).
  190. putMethod.setRequestEntity(entity);
  191. putMethod.addRequestHeader("Content-Type", "application/xml"); // Set the put method's headers
  192. putMethod.addRequestHeader("Accept", "application/xml");
  193. HttpClient client = new HttpClient(); // Create a client and the execute the put method.
  194. int responseCode = -1; // Initialise the temporary values.
  195. int delay = 3000; // n second delay (1000 = 1s).
  196. long p_time = System.currentTimeMillis(); // Set previous time.
  197. long c_time = System.currentTimeMillis(); // Set current time.
  198. do {
  199. if (c_time - p_time > delay) { // If delta between times exceeds delay, execute request.
  200. try {
  201. responseCode = client.executeMethod(putMethod); // Get reseponse code.
  202. if (responseCode == HttpStatus.SC_OK) { // Check the response code and react accordingly.
  203. System.out.println("Message uri: " + Response.getMsgURI(putMethod.getResponseBodyAsString()));
  204. msg_uri = Response.getMsgURI(putMethod.getResponseBodyAsString());
  205. } else if (responseCode == HttpStatus.SC_CONFLICT) {
  206. System.out.println("Message uri: " + Response.getMsgURI(putMethod.getResponseBodyAsString()));
  207. System.out.println("Error: Slot is not free");
  208. System.out.println("Error code:" + responseCode);
  209. System.out.println("Error message:" + putMethod.getResponseBodyAsString());
  210. } else if (responseCode == HttpStatus.SC_UNAUTHORIZED) {
  211. System.out.println("Message uri: " + Response.getMsgURI(putMethod.getResponseBodyAsString()));
  212. System.out.println("Error: request requires authorisation");
  213. System.out.println("Error code:" + responseCode);
  214. System.out.println("Error message:" + putMethod.getResponseBodyAsString());
  215. } else if (responseCode == HttpStatus.SC_FORBIDDEN) {
  216. System.out.println("Message uri: " + Response.getMsgURI(putMethod.getResponseBodyAsString()));
  217. System.out.println("Error: request forbidden");
  218. System.out.println("Error code:" + responseCode);
  219. System.out.println("Error message:" + putMethod.getResponseBodyAsString());
  220. } else if (responseCode == 510) {
  221. System.out.println("Message uri: " + Response.getMsgURI(putMethod.getResponseBodyAsString()));
  222. System.out.println("Error: Invalid request");
  223. System.out.println("Error code:" + responseCode);
  224. System.out.println("Error message:" + putMethod.getResponseBodyAsString());
  225. } else if (responseCode == HttpStatus.SC_NOT_FOUND) {
  226. System.out.println("Message uri: " + Response.getMsgURI(putMethod.getResponseBodyAsString()));
  227. System.out.println("Error: Not found");
  228. System.out.println("Error code:" + responseCode);
  229. System.out.println("Error message:" + putMethod.getResponseBodyAsString());
  230. } else {
  231. System.out.println("Error code:" + responseCode);
  232. System.out.println("Error message:" + putMethod.getResponseBodyAsString());
  233. }
  234. } catch (HttpException e) { // Catch exceptions.
  235. e.printStackTrace();
  236. } catch (IOException e) {
  237. e.printStackTrace();
  238. } catch (ParseException e) {
  239. e.printStackTrace();
  240. }
  241. p_time = c_time; // Set previous time to current (previous).
  242. }
  243. c_time = System.currentTimeMillis(); // Advance the current time to present (current).
  244. } while (responseCode != HttpStatus.SC_OK); // If the code is 200 (OK) continue.
  245. check_for_null(msg_uri, "send_message"); // Check for error.
  246. return new Pair<String, Integer>(msg_uri, responseCode); // Return the URI of the received msg.
  247. } // send_message
  248.  
  249. // Get a response from the server.
  250. private static Pair<String, Integer> get_message(String msg_uri) {
  251. int responseCode = -1; // Initialise the temporary values.
  252. int delay = 3000; // n second delay (1000 = 1s).
  253. long p_time = System.currentTimeMillis(); // Set previous time.
  254. long c_time = System.currentTimeMillis(); // Set current time.
  255. String responseBody = null; // Response string containing the result.
  256. do {
  257. if (c_time - p_time > delay) { // If delta between times exceeds delay, execute request.
  258. try {
  259. GetMethod getMethod = null; // Create a get method.
  260. getMethod = new GetMethod(msg_uri);
  261. getMethod.addRequestHeader("Content-Type", "application/xml"); // Setup get method.
  262. getMethod.addRequestHeader("Accept", "application/xml");
  263. HttpClient client = new HttpClient(); // Create a client and the execute the method.
  264. responseCode = client.executeMethod(getMethod);
  265. if (responseCode == HttpStatus.SC_OK) { // Check the response code and react accordingly.
  266. Response response = Response.parseGetResponse(getMethod.getResponseBodyAsString());
  267. responseBody = response.toString(); // Save the responsebody from response.
  268. System.out.println("Response type: " + response.getResponseType());
  269. System.out.println(response.toString());
  270. } else if (responseCode == HttpStatus.SC_CONFLICT) {
  271. System.out.println("Slot is not free: " + responseCode);
  272. System.out.println("Error message: " + getMethod.getResponseBodyAsString());
  273. } else if (responseCode == HttpStatus.SC_NOT_FOUND){
  274. System.out.println("Message not found: " + responseCode);
  275. System.out.println("Error message: " + getMethod.getResponseBodyAsString());
  276. } else if (responseCode == HttpStatus.SC_UNAUTHORIZED) {
  277. System.out.println("Invalid username/password to retrieve message: " + responseCode);
  278. System.out.println("Error message: " + getMethod.getResponseBodyAsString());
  279. } else {
  280. System.out.println("Error code: " + responseCode);
  281. System.out.println("Error message: " + getMethod.getResponseBodyAsString());
  282. }
  283. } catch (Exception err) { // Catch exceptions.
  284. System.out.println("Usage: 'java ClientRecMsg msg_uri'");
  285. err.printStackTrace();
  286. }
  287. p_time = c_time; // Set previous time to current (previous).
  288. }
  289. c_time = System.currentTimeMillis(); // Advance the current time to present (current).
  290. } while (responseCode != HttpStatus.SC_OK); // If the code is 200 (OK) continue.
  291. check_for_null(responseBody, "request_message"); // Check for error.
  292. return new Pair<String, Integer>(responseBody, response); // Return response body string.
  293. } // get_message
  294. } // Client
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement