Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // COMP28112 Exercise 22 - Dainius Varanauskas
- package uk.ac.manchester.cs.comp28112.lab2;
- import java.io.IOException;
- import org.apache.commons.httpclient.methods.PutMethod;
- import org.apache.commons.httpclient.methods.RequestEntity;
- import org.apache.commons.httpclient.methods.StringRequestEntity;
- import org.apache.commons.httpclient.*;
- import org.apache.commons.httpclient.HttpClient;
- import org.apache.commons.httpclient.HttpStatus;
- import org.apache.commons.httpclient.methods.GetMethod;
- // Client Class to book a hotel and a band.
- public class Client {
- // Client fields.
- private static String my_username = "8dv141";
- private static String my_password = "TiLQGq";
- private static PutMethod putMethodHotel = new PutMethod("http://jewel.cs.man.ac.uk:3010/queue/enqueue");
- private static PutMethod putMethodBand = new PutMethod("http://jewel.cs.man.ac.uk:3020/queue/enqueue");
- // Main
- public static void main(String[] args) {
- // Manual cancel request.
- if (args.length > 0 && args[0].equals("Cancel")) {
- System.out.println("---------------| Canceling Hotel |---------------");
- String request_id = Long.toString(System.currentTimeMillis()); // Generate a request id.
- cancel_slot(my_username, my_password, Integer.parseInt(args[1]), putMethodHotel); // Cancel Hotel booking.
- System.out.println("---------------| Canceling Bands |---------------");
- request_id = Long.toString(System.currentTimeMillis()); // Generate a request id.
- cancel_slot(my_username, my_password, Integer.parseInt(args[1]), putMethodBand); // Cancel Band booking.
- System.exit(1); // Exit program.
- }
- // Attempt to reserve the slot id for band. Continue until output is a non-negative result.
- // If the result is negative, reset slot id and make hotel look for a new one.
- int my_slot_id = -1;
- do {
- // Cancel the slot booked by the hotel if the slot id is positive.
- if (my_slot_id > 0) {
- System.out.println("---------------| Canceling Hotel |---------------");
- String request_id = Long.toString(System.currentTimeMillis()); // Generate a request id.
- cancel_slot(my_username, my_password, my_slot_id, putMethodHotel); // Cancel Hotel booking.
- }
- // Attempt to reserve the slot id for hotel. Continue until output is a non-negative result.
- do {
- // Find the earliest slot id. Continue until a valid (positive) slot id is found.
- System.out.println("-------------| Looking for slot id |-------------");
- while (my_slot_id < 0) {
- my_slot_id = find_slot_id(get_availability_list(my_username, my_password, putMethodHotel),
- get_availability_list(my_username, my_password, putMethodBand));
- }
- // Reset put methods to build different requests using XMLStrings.
- reset_putMethods();
- System.out.println("---------------| Reserving Hotel |---------------");
- } while (reserve_slot(my_username, my_password, 0, putMethodHotel) != 0);
- System.out.println("---------------| Reserving Bands |---------------");
- } 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.
- } // main
- // Reset the putMethod objects.
- private static void reset_putMethods() {
- putMethodHotel = new PutMethod("http://jewel.cs.man.ac.uk:3010/queue/enqueue");
- putMethodBand = new PutMethod("http://jewel.cs.man.ac.uk:3020/queue/enqueue");
- } // reset_putMethods
- // Check if input string contains value.
- private static void check_for_null(String string, String method) {
- if (string == null) { // Check if input string is null.
- System.err.println("Resulting string in " + method + " was null."); // Print what method it originated from.
- System.exit(1); // Exit the program.
- }
- } // check_for_null
- // Build a uri using given username and password.
- private static String msg_uri_builder(String msg_uri, String username, String password) {
- return msg_uri += "?username=" + username + "&password=" + password;
- } // msg_uri_builder
- // Cancel a slot for an event.
- private static int cancel_slot(String username, String password, int slot_id, PutMethod putMethod) {
- String request_id = Long.toString(System.currentTimeMillis()); // Generate a request id.
- String xmlString = cancelation(request_id, username, password, slot_id); // Build a cancelation XML string.
- Pair <String, Integer> response = send_message(xmlString, putMethod); // Send a cancel request and get a response.
- String msg_uri = response.getKey(); // Get the response body.
- msg_uri = msg_uri_builder(msg_uri, username, password); // Build a string with username and password.
- String response_msg_cancelation = get_message(msg_uri); // Request a cancel response message.
- return response.getValue(); // Return response code.
- } // cancel_slot
- // Build a cancel request in XML.
- private static String cancelation(String request_id, String username, String password, int slot_id) {
- String xmlString = null; // Create a string to hold XML.
- try {
- xmlString = XMLRequest.Cancel(request_id, username, password, slot_id); // Build the reservation request.
- } catch (Exception e) {
- System.err.println("Failed to build XML string."); // Catch exceptions.
- e.printStackTrace();
- }
- check_for_null(xmlString, "cancelation"); // Check for error.
- return xmlString;
- }
- // Reserve a slot for an event.
- private static int reserve_slot(String username, String password, int slot_id, PutMethod putMethod) {
- String request_id = Long.toString(System.currentTimeMillis()); // Generate a request id.
- String xmlString = reservation(request_id, username, password, slot_id); // Build a reservation XML string.
- Pair <String, Integer> response = send_message(xmlString, putMethod); // Send a reservation request and get a response.
- String msg_uri = response.getKey(); // Get the response body.
- msg_uri = msg_uri_builder(msg_uri, username, password); // Build a string with username and password.
- String response_msg_reservation = get_message(msg_uri); // Request a reservation response message.
- return response.getValue(); // Return response code.
- } // reserve_slot
- // Build a reservation request in XML.
- private static String reservation(String request_id, String username, String password, int slot_id) {
- String xmlString = null; // Create a string to hold XML.
- try {
- xmlString = XMLRequest.Reservation(request_id, username, password, slot_id); // Build the reservation request.
- } catch (Exception e) {
- System.err.println("Failed to build XML string."); // Catch exceptions.
- e.printStackTrace();
- }
- check_for_null(xmlString, "reservation"); // Check for error.
- return xmlString;
- } // reservation
- // Find the earliest matching slot id.
- private static int find_slot_id(int[] availableHotels, int[]availableBands) {
- for (int i = 0; i < availableHotels.length; i++) { // Poly. search O(n^2)
- for (int j = 0; j < availableBands.length; j++) {
- if (availableHotels[i] == availableBands[j]) {
- System.out.println("Found slot: " + availableHotels[i]);
- return availableHotels[i];
- }
- }
- }
- System.out.println("No slot found. Retrying.");
- return -1; // Return negative value if no slot found.
- } // find_slot_id
- private static int[] get_availability_list(String username, String password, PutMethod putMethod) {
- String request_id = Long.toString(System.currentTimeMillis()); // Generate a request id.
- String xmlString = availability(request_id, username, password); // Build an availability XML string.
- Pair <String, Integer> response = send_message(xmlString, putMethod); // Send a availability request and get a response.
- String msg_uri = response.getKey(); // Get the response body.
- msg_uri = msg_uri_builder(msg_uri, username, password); // Build a string with username and password.
- String response_msg_availability = get_message(msg_uri); // Request an availability response message.
- return availability_parser(response_msg_availability); // Get and return the availability list as a list of integers.
- } // get_availability_list
- // Build an availability request in XML.
- private static String availability(String request_id, String username, String password) {
- String xmlString = null; // Create a string to hold XML.
- try {
- xmlString = XMLRequest.Availability(request_id, username, password); // Build the availability request.
- } catch (Exception e) {
- System.err.println("Failed to build XML string."); // Catch exceptions.
- e.printStackTrace();
- }
- check_for_null(xmlString, "availability"); // Check for error.
- return xmlString; // Return result.
- } // availability
- // Parse the availability list.
- private static int[] availability_parser(String availability) {
- String[] digits = availability.replaceAll("\\[|\\]|\\s", "").split(","); // Split the string into set of substrings with only numbers.
- int[] availableHotels = new int[digits.length]; // Create a list for numbers.
- for (int i = 0; i < digits.length; i++) { // Parse each digit.
- try {
- availableHotels[i] = Integer.parseInt(digits[i]);
- } catch (Exception err) {
- System.out.println("Digits array length: " + digits.length); // Catch exceptions.
- System.out.println("Error whilst parsing availability list");
- err.printStackTrace();
- }
- }
- return availableHotels; // Return the list.
- } // availability_parser
- // Send a message to the server.
- private static Pair<String, Integer> send_message(String xmlString, PutMethod putMethod) {
- String msg_uri = null; // Create message to return.
- RequestEntity entity = new StringRequestEntity(xmlString); // Set the request's entity (body).
- putMethod.setRequestEntity(entity);
- putMethod.addRequestHeader("Content-Type", "application/xml"); // Set the put method's headers
- putMethod.addRequestHeader("Accept", "application/xml");
- HttpClient client = new HttpClient(); // Create a client and the execute the put method.
- int responseCode = -1; // Initialise the temporary values.
- int delay = 3000; // n second delay (1000 = 1s).
- long p_time = System.currentTimeMillis(); // Set previous time.
- long c_time = System.currentTimeMillis(); // Set current time.
- do {
- if (c_time - p_time > delay) { // If delta between times exceeds delay, execute request.
- try {
- responseCode = client.executeMethod(putMethod); // Get reseponse code.
- if (responseCode == HttpStatus.SC_OK) { // Check the response code and react accordingly.
- System.out.println("Message uri: " + Response.getMsgURI(putMethod.getResponseBodyAsString()));
- msg_uri = Response.getMsgURI(putMethod.getResponseBodyAsString());
- } else if (responseCode == HttpStatus.SC_CONFLICT) {
- System.out.println("Message uri: " + Response.getMsgURI(putMethod.getResponseBodyAsString()));
- System.out.println("Error: Slot is not free");
- System.out.println("Error code:" + responseCode);
- System.out.println("Error message:" + putMethod.getResponseBodyAsString());
- } else if (responseCode == HttpStatus.SC_UNAUTHORIZED) {
- System.out.println("Message uri: " + Response.getMsgURI(putMethod.getResponseBodyAsString()));
- System.out.println("Error: request requires authorisation");
- System.out.println("Error code:" + responseCode);
- System.out.println("Error message:" + putMethod.getResponseBodyAsString());
- } else if (responseCode == HttpStatus.SC_FORBIDDEN) {
- System.out.println("Message uri: " + Response.getMsgURI(putMethod.getResponseBodyAsString()));
- System.out.println("Error: request forbidden");
- System.out.println("Error code:" + responseCode);
- System.out.println("Error message:" + putMethod.getResponseBodyAsString());
- } else if (responseCode == 510) {
- System.out.println("Message uri: " + Response.getMsgURI(putMethod.getResponseBodyAsString()));
- System.out.println("Error: Invalid request");
- System.out.println("Error code:" + responseCode);
- System.out.println("Error message:" + putMethod.getResponseBodyAsString());
- } else if (responseCode == HttpStatus.SC_NOT_FOUND) {
- System.out.println("Message uri: " + Response.getMsgURI(putMethod.getResponseBodyAsString()));
- System.out.println("Error: Not found");
- System.out.println("Error code:" + responseCode);
- System.out.println("Error message:" + putMethod.getResponseBodyAsString());
- } else {
- System.out.println("Error code:" + responseCode);
- System.out.println("Error message:" + putMethod.getResponseBodyAsString());
- }
- } catch (HttpException e) { // Catch exceptions.
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } catch (ParseException e) {
- e.printStackTrace();
- }
- p_time = c_time; // Set previous time to current (previous).
- }
- c_time = System.currentTimeMillis(); // Advance the current time to present (current).
- } while (responseCode != HttpStatus.SC_OK); // If the code is 200 (OK) continue.
- check_for_null(msg_uri, "send_message"); // Check for error.
- return new Pair<String, Integer>(msg_uri, responseCode); // Return the URI of the received msg.
- } // send_message
- // Get a response from the server.
- private static Pair<String, Integer> get_message(String msg_uri) {
- int responseCode = -1; // Initialise the temporary values.
- int delay = 3000; // n second delay (1000 = 1s).
- long p_time = System.currentTimeMillis(); // Set previous time.
- long c_time = System.currentTimeMillis(); // Set current time.
- String responseBody = null; // Response string containing the result.
- do {
- if (c_time - p_time > delay) { // If delta between times exceeds delay, execute request.
- try {
- GetMethod getMethod = null; // Create a get method.
- getMethod = new GetMethod(msg_uri);
- getMethod.addRequestHeader("Content-Type", "application/xml"); // Setup get method.
- getMethod.addRequestHeader("Accept", "application/xml");
- HttpClient client = new HttpClient(); // Create a client and the execute the method.
- responseCode = client.executeMethod(getMethod);
- if (responseCode == HttpStatus.SC_OK) { // Check the response code and react accordingly.
- Response response = Response.parseGetResponse(getMethod.getResponseBodyAsString());
- responseBody = response.toString(); // Save the responsebody from response.
- System.out.println("Response type: " + response.getResponseType());
- System.out.println(response.toString());
- } else if (responseCode == HttpStatus.SC_CONFLICT) {
- System.out.println("Slot is not free: " + responseCode);
- System.out.println("Error message: " + getMethod.getResponseBodyAsString());
- } else if (responseCode == HttpStatus.SC_NOT_FOUND){
- System.out.println("Message not found: " + responseCode);
- System.out.println("Error message: " + getMethod.getResponseBodyAsString());
- } else if (responseCode == HttpStatus.SC_UNAUTHORIZED) {
- System.out.println("Invalid username/password to retrieve message: " + responseCode);
- System.out.println("Error message: " + getMethod.getResponseBodyAsString());
- } else {
- System.out.println("Error code: " + responseCode);
- System.out.println("Error message: " + getMethod.getResponseBodyAsString());
- }
- } catch (Exception err) { // Catch exceptions.
- System.out.println("Usage: 'java ClientRecMsg msg_uri'");
- err.printStackTrace();
- }
- p_time = c_time; // Set previous time to current (previous).
- }
- c_time = System.currentTimeMillis(); // Advance the current time to present (current).
- } while (responseCode != HttpStatus.SC_OK); // If the code is 200 (OK) continue.
- check_for_null(responseBody, "request_message"); // Check for error.
- return new Pair<String, Integer>(responseBody, response); // Return response body string.
- } // get_message
- } // Client
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement