Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedReader;
- import java.io.InputStreamReader;
- import java.io.PrintWriter;
- import java.net.Socket;
- //Server client
- public class Client {
- private static BufferedReader input;
- private static PrintWriter output;
- private boolean connected = false;
- public void clientOptions(int choice) {
- int userInput = choice;//scanner.nextInt();
- try(Socket socket = new Socket("212.159.23.21",4444/*"localhost", 40450*/)){
- input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
- output = new PrintWriter(socket.getOutputStream(), true);
- connected = true;
- switch (userInput) {
- case 1:
- String cabinNo = "57";
- String email = "George@live.com";
- String userpw = "Georgina";
- String cruise = "50";
- output.println("Hello there, Mr.Ross. Would you like some tea?");
- //output.println(1+","+cabinNo+","+email+","+userpw+","+cruise);
- break;
- case 2:
- cabinNo = "57";
- userpw = "Georgina";
- output.println(2+","+cabinNo+","+userpw);
- break;
- case 3:
- cabinNo = "57";
- output.println(3+","+cabinNo);
- break;
- case 4:
- cabinNo = "57";
- output.println(4+","+cabinNo);
- break;
- case 5:
- cabinNo = "57";
- String excursionId = "971156";
- String numberOfPeople = "3";
- output.println(5+","+cabinNo+","+excursionId+","+numberOfPeople);
- break;
- }
- }
- catch(Exception e){
- System.out.println("Exception: "+e);
- }
- /*catch(SocketTimeoutException e){
- System.out.println("The socket has timed out");
- }
- catch(IOException e) {
- System.out.println("Client error: " + e.getMessage());
- }*/
- }
- public void registerUser(){
- System.out.println("Made it");
- String cabinNo = "57";
- String email = "George@live.com";
- String userpw = "Georgina";
- output.println(1+","+cabinNo+","+email+","+userpw);
- }
- public void logIn(){
- String cabinNo = "57";
- String userpw = "Georgina";
- output.println(2+","+cabinNo+","+userpw);
- }
- public void logOut(){
- String rndm = "random";
- output.println(3+","+"57");
- }
- public static void bookings(){
- }
- public void excursions(){
- System.out.println("yay");
- }
- }
- ========================================================================
- import javax.swing.*;
- import java.awt.*;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import java.awt.event.WindowAdapter;
- import java.awt.event.WindowEvent;
- public class Test extends JFrame {
- JButton regButton;
- JButton logButton;
- public Test() {
- Client client = new Client();
- regButton = new JButton("Register");
- logButton = new JButton("Login");
- JPanel panel = new JPanel();
- setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
- addWindowListener(new WindowAdapter() {
- @Override
- public void windowClosing(WindowEvent e) {
- super.windowClosing(e);
- client.excursions();
- System.exit(0);
- }
- });
- panel.add(regButton);
- panel.add(logButton);
- getContentPane().add(panel);
- regButton.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- client.clientOptions(1);
- }
- });
- logButton.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- client.clientOptions(5);
- }
- });
- setSize(new Dimension(500, 400));
- setTitle("Welcome!");
- setVisible(true);
- }
- public static void main(String[] args) {
- Test t = new Test();
- }
- }
- ========================================================================
- import java.io.IOException;
- import java.net.ServerSocket;
- import java.net.Socket;
- public class Main {
- public static void main(String[] args) throws IOException {
- try {
- int portNumber = 40450;
- ServerSocket serverSocket = new ServerSocket(40450);
- while (true) {
- Socket clientSocket = serverSocket.accept();
- DataServer dataserver = new DataServer(clientSocket);
- dataserver.start();
- }
- }
- catch(Exception e){
- System.out.println("Exception: "+e.getMessage());
- }
- }
- }
- =======================================================================
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.PrintWriter;
- import java.net.Socket;
- import java.sql.*;
- import java.util.ArrayList;
- //Database server
- public class DataServer extends Thread {
- private String cabinNo;
- private Socket socket;
- private BufferedReader readInput;
- private PrintWriter writeOutput;
- private static ArrayList <String> usersOnline = new ArrayList<>();
- private static ArrayList <ArrayList> cruises = new ArrayList<>();
- private static ArrayList <String> cruise10 = new ArrayList<>();
- private static ArrayList <String> cruise20 = new ArrayList<>();
- public DataServer(Socket socket) {
- this.socket = socket;
- }
- @Override
- public void run() {
- boolean b = true;
- while (b) {
- try {
- //Declare new reader and writer to communicate with the client
- readInput = new BufferedReader((new InputStreamReader(socket.getInputStream())));
- writeOutput = new PrintWriter(socket.getOutputStream(), true);
- String storeInput = readInput.readLine();
- if(storeInput != null) {
- connectToDb(storeInput);
- }
- socket.getInputStream().read();
- //b = false;
- }
- catch (IOException e) {
- System.out.println("IO exception: "+e.getMessage());
- }
- catch (NullPointerException e){
- System.out.println("nullpointer exception: "+e.getMessage());
- }
- catch (SQLException e){
- System.out.println("SQL Exception: "+e.getMessage());
- }
- }
- }
- //Method that takes the readInput string and sorts it into a String array in String chunks
- public String [] processInput(String input){
- String [] processedInput = input.split(",");
- return processedInput;
- }
- //Method that checks if a user account is logged in
- public boolean checkUsersOnline(String input){
- for(int i = 0; i < usersOnline.size(); i++){
- //System.out.println(usersOnline.get(i));
- if(usersOnline.get(i).equals(input)){//readInput.equals(usersOnline.get(i))
- System.out.println("input is: "+input);
- return true;
- }
- }
- return false;
- }
- //Connection method that connects to a DB and performs tasks on behalf of a client
- public void connectToDb(String input) throws SQLException{
- //First line takes a String and cuts it into chunks using processInput method
- //The first chunk in every message is a key that is later used by a switch statement
- //The key is essential for the program to know which action to perform
- String [] storeInput = processInput(input);
- String username = "Client";
- String password = "ClientAccess";
- String databaseName = "Cruise";
- String databasePath = "jdbc:mysql://localhost:3306/"+databaseName+"?autoReconnect=true&useSSL=false";
- //String schoolDataBase = studentnet.cst.beds.ac.uk; //school DB
- //localhost:3306 //local DB
- //Try to make a connection to DB
- java.sql.Connection connection = null;
- Statement statement = null;
- ResultSet results = null;
- ResultSet results2=null;
- try {
- Class.forName("com.mysql.jdbc.Driver");
- connection = DriverManager.getConnection(databasePath, username, password);
- statement = connection.createStatement();
- //Creating a switch statement that processes the incoming message from the client
- //Using the value of the first element of the Array, the switch statement takes appropriate action
- switch (storeInput[0]) {
- case "1":
- //Register user
- //statement.executeUpdate("INSERT INTO customer (cabinNo, email, userpw) VALUE ("+storeInput[1]+",'"+storeInput[2]+"','"+storeInput[3]+"');");
- boolean exists = false;
- results = statement.executeQuery("SELECT * FROM customers;");
- while(results.next()) {
- if (storeInput[1].equals(results.getString("cabinNo"))) {
- System.out.println("Cabin number has already been used");
- exists = true;
- }
- }
- if(!exists) {
- PreparedStatement prepStatementRegister = connection.prepareStatement
- ("INSERT INTO customers (cabinNo, email, userpw, selectedCruise) VALUE (?, ?, ?, ?)");
- prepStatementRegister.setString(1, storeInput[1]);
- prepStatementRegister.setString(2, storeInput[2]);
- prepStatementRegister.setString(3, storeInput[3]);
- prepStatementRegister.setString(4, storeInput[4]);
- prepStatementRegister.executeUpdate();
- System.out.println("Cabin registered successfully.");
- }
- break;
- case "2":
- //Log in
- //PreparedStatement prepStatementLogIn = connection.prepareStatement("SELECT * FROM customer;");
- results = statement.executeQuery("SELECT * FROM customer;");
- while(results.next()){
- if(storeInput[1].equals(results.getString("cabinNo"))){
- if(storeInput[2].equals(results.getString("userpw")) && checkUsersOnline(storeInput[1])==false){
- System.out.println("val: "+storeInput[1]);
- usersOnline.add(storeInput[1]);
- for(int x= 0; x < usersOnline.size();x++){
- System.out.println(usersOnline.get(x));
- }
- System.out.println("logged in");
- }
- else{
- System.out.println("user already online");
- }
- }
- }
- break;
- case "3":
- //Log out
- cabinNo = storeInput[1];
- usersOnline.remove(cabinNo);
- System.out.println("User logged out");
- break;
- case "4":
- //View available excursions
- String cruiseId;
- results = statement.executeQuery("SELECT * FROM customers WHERE cabinNo = "+storeInput[1]);
- while(results.next()) {
- cruiseId = results.getString(5);
- results = statement.executeQuery("SELECT * FROM excursions WHERE cruiseId = " + cruiseId);
- while (results.next()) {
- System.out.println("Excursion ID - " + results.getString(1) + " | Excursion name - " + results.getString(4));
- }
- }
- break;
- case "5":
- //Book excursions
- String excursionId;
- String excursionNames;
- int excursionBookings;
- results = statement.executeQuery("SELECT * FROM excursions WHERE excursionId = "+storeInput[2]);
- while(results.next()){
- excursionId = results.getString(1);
- excursionNames = results.getString(4);
- excursionBookings = results.getInt(5);
- if(excursionId.equals(storeInput[2])) {
- System.out.println(excursionId);
- PreparedStatement updateBookings = connection.prepareStatement("UPDATE excursions SET excursionBookings = ? WHERE excursionId = ?");
- updateBookings.setString(1, String.valueOf((excursionBookings + Integer.parseInt(storeInput[3]))));
- updateBookings.setString(2, excursionId);
- updateBookings.executeUpdate();
- PreparedStatement updateCustomerBookings = connection.prepareStatement("UPDATE customers SET bookings = ? WHERE cabinNo = ?");
- updateCustomerBookings.setString(1,(excursionId));
- updateCustomerBookings.setString(2, storeInput[1]);
- System.out.println("updated");
- }
- else{
- System.out.println("Invalid Excursion ID");
- }
- }
- //Booking excursions
- break;
- case "6":
- //Update bookings
- System.out.println("case 6");
- //Updating excursions
- }
- }
- catch(SQLException e){
- System.out.println("SQL exception"+e);
- }
- catch(ClassNotFoundException e){
- System.out.println("Class not found exception");
- }
- catch(ArrayIndexOutOfBoundsException e){
- System.out.println("Array Index out of bounds");
- }
- finally{
- if(statement!=null){
- try{
- statement.close();
- }
- catch (SQLException e){
- System.out.println("Exception at statemnet.close()");
- }
- }
- if(results!=null){
- try{
- results.close();
- }
- catch(SQLException e){
- System.out.println("Exception at results.close()");
- }
- }
- if(connection!=null){
- try{
- connection.close();
- }
- catch(SQLException e){
- System.out.println("Exception at connection.close()");
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement