Server done
This commit is contained in:
@@ -0,0 +1,190 @@
|
||||
package com.andreicerbu;
|
||||
|
||||
import com.andreicerbu.exceptions.*;
|
||||
import com.andreicerbu.items.database.TableDeposit;
|
||||
import com.andreicerbu.json.JsonFields;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.sql.*;
|
||||
import java.util.*;
|
||||
|
||||
import static com.andreicerbu.json.JsonFields.listOfDeposits;
|
||||
|
||||
public class Algorithm {
|
||||
JSONObject order = null;
|
||||
Integer id_user = null;
|
||||
String name = null;
|
||||
Float lat_coord = null;
|
||||
Float long_coord = null;
|
||||
|
||||
JSONObject routeJson = null;
|
||||
JSONObject destination = null;
|
||||
JSONArray deposits = null;
|
||||
|
||||
List<TableDeposit> listOfDeposits = new ArrayList<>();
|
||||
Map<Integer, String> mapProductIdToName = new HashMap<>();
|
||||
|
||||
public Algorithm(JSONObject order) throws SQLException, ProductUnavailableAnymoreException {
|
||||
this.order = new JSONObject(order.toString());
|
||||
this.id_user = this.order.getInt(JsonFields.id_user);
|
||||
this.order.remove(JsonFields.id_user);
|
||||
|
||||
run();
|
||||
}
|
||||
|
||||
private void getUserInformation(Connection conn) throws SQLException{
|
||||
PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM users WHERE id = ?");
|
||||
pstmt.setInt(1, id_user);
|
||||
|
||||
ResultSet resultSet = pstmt.executeQuery();
|
||||
resultSet.next();
|
||||
|
||||
name = resultSet.getString("username");
|
||||
lat_coord = resultSet.getFloat(JsonFields.lat_coord);
|
||||
long_coord = resultSet.getFloat(JsonFields.long_coord);
|
||||
|
||||
destination = new JSONObject();
|
||||
destination.put(JsonFields.id_user, id_user);
|
||||
destination.put(JsonFields.name, name);
|
||||
destination.put(JsonFields.lat_coord, lat_coord);
|
||||
destination.put(JsonFields.long_coord, long_coord);
|
||||
}
|
||||
|
||||
private void getDeposits(Connection conn) throws SQLException{
|
||||
PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM deposits");
|
||||
ResultSet resultSet = pstmt.executeQuery();
|
||||
|
||||
while(resultSet.next()){
|
||||
listOfDeposits.add(new TableDeposit(
|
||||
resultSet.getInt("id"), resultSet.getString("name"),
|
||||
resultSet.getFloat("lat_coord"), resultSet.getFloat("long_coord")
|
||||
));
|
||||
}
|
||||
|
||||
listOfDeposits.sort(new Comparator<TableDeposit>() {
|
||||
@Override
|
||||
public int compare(TableDeposit d1, TableDeposit d2) {
|
||||
return (int) (findDistanceBetweenCoord(d2.getLat_coord(), d2.getLong_coord(), lat_coord, long_coord) -
|
||||
findDistanceBetweenCoord(d1.getLat_coord(), d1.getLong_coord(), lat_coord, long_coord));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private float findDistanceBetweenCoord(Float x1, Float y1, Float x2, Float y2){
|
||||
return (float) Math.sqrt(
|
||||
Math.pow((x2 - x1), 2) + Math.pow((y2 - y1), 2)
|
||||
);
|
||||
}
|
||||
|
||||
private void getProductNames(Connection conn) throws SQLException {
|
||||
JSONArray products = new JSONArray(order.get(JsonFields.listOfProducts).toString());
|
||||
Statement stmt = conn.createStatement();
|
||||
ResultSet resultSet = stmt.executeQuery("SELECT id, name FROM products");
|
||||
|
||||
while (resultSet.next()) {
|
||||
int id_product = resultSet.getInt("id");
|
||||
String name = resultSet.getString("name");
|
||||
|
||||
for (int index = 0; index < products.length(); index++) {
|
||||
JSONObject item = products.getJSONObject(index);
|
||||
|
||||
if(id_product == item.getInt(JsonFields.id_product)){
|
||||
mapProductIdToName.put(id_product, name);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void createRoute(Connection conn) throws SQLException, ProductUnavailableAnymoreException {
|
||||
deposits = new JSONArray();
|
||||
JSONArray products = new JSONArray(order.get(JsonFields.listOfProducts).toString());
|
||||
|
||||
PreparedStatement pstmt;
|
||||
for(TableDeposit deposit : listOfDeposits){//we take each deposit
|
||||
JSONObject depositJSON = new JSONObject(createDepositJSONForRoute(deposit).toString());
|
||||
JSONArray listOfProductsJSON = depositJSON.getJSONArray(JsonFields.listOfProducts);
|
||||
|
||||
pstmt = conn.prepareStatement("SELECT * FROM prod_in_depo WHERE id_deposit = ?");
|
||||
pstmt.setInt(1, deposit.getId_deposit());
|
||||
ResultSet resultSet = pstmt.executeQuery();//we take all the products that exists in a deposit
|
||||
|
||||
while(resultSet.next()){
|
||||
int id_product = resultSet.getInt("id_product");
|
||||
int quantity = resultSet.getInt("quantity");
|
||||
String name = mapProductIdToName.get(id_product);
|
||||
|
||||
for(int index = 0; index < products.length(); index++){//iterate through our order
|
||||
JSONObject item = products.getJSONObject(index);
|
||||
JSONObject itemForList = new JSONObject();
|
||||
|
||||
if(item.getInt(JsonFields.id_product) == id_product){
|
||||
itemForList.put(JsonFields.id_product, id_product);
|
||||
itemForList.put(JsonFields.name, name);
|
||||
int newQuantity = item.getInt(JsonFields.quantity) - quantity;
|
||||
|
||||
if(newQuantity > 0){
|
||||
item.put(JsonFields.quantity, newQuantity);
|
||||
itemForList.put(JsonFields.quantity, quantity);
|
||||
}else{
|
||||
itemForList.put(JsonFields.quantity, item.getInt(JsonFields.quantity));
|
||||
products.remove(index);
|
||||
}
|
||||
|
||||
listOfProductsJSON.put(itemForList);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if(!depositJSON.getJSONArray(JsonFields.listOfProducts).isEmpty()) {
|
||||
deposits.put(depositJSON);
|
||||
}
|
||||
|
||||
if(products.isEmpty()){
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if(!products.isEmpty()){
|
||||
throw new ProductUnavailableAnymoreException("One of the chosen products is not available anymore");
|
||||
}
|
||||
}
|
||||
|
||||
private JSONObject createDepositJSONForRoute(TableDeposit deposit){
|
||||
JSONObject depositJSON = new JSONObject();
|
||||
|
||||
depositJSON.put(JsonFields.id_deposit, deposit.getId_deposit());
|
||||
depositJSON.put(JsonFields.name, deposit.getName());
|
||||
depositJSON.put(JsonFields.lat_coord, deposit.getLat_coord());
|
||||
depositJSON.put(JsonFields.long_coord, deposit.getLong_coord());
|
||||
depositJSON.put(JsonFields.listOfProducts, new JSONArray());
|
||||
depositJSON.put(JsonFields.distance, findDistanceBetweenCoord(lat_coord, long_coord, deposit.getLat_coord(), deposit.getLong_coord()));
|
||||
|
||||
return depositJSON;
|
||||
}
|
||||
|
||||
|
||||
private void createJsonRoute(){
|
||||
routeJson = new JSONObject();
|
||||
|
||||
routeJson.put(JsonFields.destination, destination);
|
||||
routeJson.put(JsonFields.listOfDeposits, deposits);
|
||||
routeJson.put(JsonFields.listOfProducts, order.getJSONArray(JsonFields.listOfProducts));
|
||||
}
|
||||
|
||||
private synchronized void run() throws SQLException, ProductUnavailableAnymoreException{
|
||||
Connection conn = Database.getConnection();
|
||||
|
||||
getUserInformation(conn);
|
||||
getDeposits(conn);
|
||||
getProductNames(conn);
|
||||
|
||||
createRoute(conn);
|
||||
createJsonRoute();
|
||||
}
|
||||
|
||||
public JSONObject getRouteJson() {
|
||||
return routeJson;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package com.andreicerbu;
|
||||
|
||||
import com.andreicerbu.json.JsonFields;
|
||||
|
||||
import java.io.*;
|
||||
import java.net.Socket;
|
||||
import java.net.SocketTimeoutException;
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class ClientThread extends Thread{
|
||||
private final Socket socket;
|
||||
private boolean isRunning = true;
|
||||
private static final int TIME_OUT = 3000;
|
||||
|
||||
public ClientThread(Socket socket)throws IOException {
|
||||
this.socket = socket;
|
||||
socket.setSoTimeout(TIME_OUT);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run(){
|
||||
try {
|
||||
BufferedReader in = new BufferedReader(
|
||||
new InputStreamReader(socket.getInputStream()));
|
||||
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
|
||||
|
||||
SocketInput socketInput = new SocketInput();
|
||||
|
||||
while (isRunning) {
|
||||
try {
|
||||
if(!socket.isConnected()){
|
||||
throw new SocketTimeoutException();
|
||||
}
|
||||
String input = in.readLine();
|
||||
socketInput = new SocketInput(input);
|
||||
|
||||
Connection conn = Database.getConnection();
|
||||
socketInput.processInputJson(conn);
|
||||
|
||||
out.println(socketInput.getJsonResponse().toString());
|
||||
} catch (SocketTimeoutException ignored) {
|
||||
} catch (SQLException e) {
|
||||
socketInput.processOutputJson(JsonFields.responseError, "Internal server error.\nPlease try again later");
|
||||
out.println(socketInput.getJsonResponse().toString());
|
||||
} catch (IOException e){
|
||||
System.out.println("Closing Thread");
|
||||
System.out.flush();
|
||||
isRunning = false;
|
||||
}
|
||||
}
|
||||
|
||||
in.close();
|
||||
out.close();
|
||||
socket.close();
|
||||
}catch(IOException ignored){
|
||||
}
|
||||
}
|
||||
|
||||
public void endThread(){
|
||||
isRunning = false;
|
||||
}
|
||||
|
||||
public boolean isThreadNotAlive(){
|
||||
return !this.isAlive();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,650 @@
|
||||
package com.andreicerbu;
|
||||
|
||||
import com.andreicerbu.exceptions.*;
|
||||
import com.andreicerbu.items.AdminJson;
|
||||
import com.andreicerbu.items.BaseItem;
|
||||
import com.andreicerbu.json.JsonFields;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileWriter;
|
||||
import java.io.IOException;
|
||||
import java.sql.*;
|
||||
import java.util.Random;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class Database {
|
||||
private static final String URL =
|
||||
"jdbc:mysql://localhost:3306/java";
|
||||
private static final String USER = "root";
|
||||
private static final String PASSWORD = "";
|
||||
|
||||
private static Connection conn;
|
||||
|
||||
public static Connection getConnection() throws SQLException{
|
||||
conn = DriverManager.getConnection(URL, USER, PASSWORD);
|
||||
conn.setAutoCommit(false);
|
||||
return conn;
|
||||
}
|
||||
|
||||
|
||||
public static synchronized void placeOrder(Connection conn, JSONObject json, Integer id_user) throws SQLException, IOException {
|
||||
JSONArray listOfProducts = new JSONArray(json.getJSONArray(JsonFields.listOfProducts));
|
||||
json.remove(JsonFields.listOfProducts);
|
||||
|
||||
for(int index = 0; index < listOfProducts.length(); index++){
|
||||
JSONObject item = listOfProducts.getJSONObject(index);
|
||||
PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM products WHERE id = ?");
|
||||
pstmt.setInt(1, item.getInt(JsonFields.id_product));
|
||||
ResultSet resultSet = pstmt.executeQuery();
|
||||
resultSet.next();
|
||||
|
||||
item.put(JsonFields.name, resultSet.getString("name"));
|
||||
}
|
||||
|
||||
String pathToOrders = "D:\\Server Delivery Planner\\orders\\";
|
||||
String pathToRoutes = "D:\\Server Delivery Planner\\routes\\";
|
||||
String pathToOrderDatabase = "D:\\\\Server Delivery Planner\\\\orders\\\\";
|
||||
String pathToRouteDatabase = "D:\\\\Server Delivery Planner\\\\routes\\\\";
|
||||
|
||||
|
||||
String nameOfFile;
|
||||
while(true){
|
||||
nameOfFile = randomStringGenerator();
|
||||
|
||||
Statement pstmt = conn.createStatement();
|
||||
ResultSet resultSet = pstmt.executeQuery("SELECT * FROM orders WHERE path_to_file = '" + pathToOrderDatabase + nameOfFile + "'");
|
||||
if(!resultSet.next()){
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
String orderFileName = pathToOrders + nameOfFile + "_order.txt";
|
||||
String routeFileName = pathToRoutes + nameOfFile + "_route.txt";
|
||||
|
||||
PreparedStatement pstmt = conn.prepareStatement("INSERT INTO orders (path_to_file) VALUES (?)");
|
||||
pstmt.setString(1,pathToOrderDatabase + nameOfFile + "_order.txt" );
|
||||
pstmt.executeUpdate();
|
||||
|
||||
pstmt = conn.prepareStatement("INSERT INTO routes (path_to_file) VALUES (?)");
|
||||
pstmt.setString(1, pathToRouteDatabase + nameOfFile + "_route.txt");
|
||||
pstmt.executeUpdate();
|
||||
|
||||
conn.commit();
|
||||
|
||||
int idOrder;
|
||||
pstmt = conn.prepareStatement("SELECT id FROM orders WHERE path_to_file = ?");
|
||||
pstmt.setString(1,pathToOrderDatabase + nameOfFile + "_order.txt" );
|
||||
ResultSet resultSet = pstmt.executeQuery();
|
||||
resultSet.next();
|
||||
idOrder = resultSet.getInt("id");
|
||||
|
||||
pstmt = conn.prepareStatement("SELECT id FROM routes WHERE path_to_file = ?");
|
||||
pstmt.setString(1,pathToRouteDatabase + nameOfFile + "_route.txt" );
|
||||
resultSet = pstmt.executeQuery();
|
||||
resultSet.next();
|
||||
json.put(JsonFields.id_route, resultSet.getInt("id"));
|
||||
|
||||
File order = new File(orderFileName);
|
||||
File route = new File(routeFileName);
|
||||
|
||||
FileWriter writerOrder = new FileWriter(order);
|
||||
FileWriter writerRoute = new FileWriter(route);
|
||||
|
||||
writerOrder.write(listOfProducts.toString(4));
|
||||
writerRoute.write(json.toString(4));
|
||||
|
||||
writerOrder.close();
|
||||
writerRoute.close();
|
||||
|
||||
JSONArray array = new JSONArray(listOfProducts.toString());
|
||||
for(int index = 0; index < array.length(); index++){
|
||||
JSONObject item = array.getJSONObject(index);
|
||||
|
||||
pstmt = conn.prepareStatement("SELECT * FROM prod_in_depo");
|
||||
ResultSet products = pstmt.executeQuery();
|
||||
while(products.next()){
|
||||
int id_product = products.getInt(JsonFields.id_product);
|
||||
int quantity = products.getInt(JsonFields.quantity);
|
||||
int id_deposit = products.getInt(JsonFields.id_deposit);
|
||||
|
||||
if(item.getInt(JsonFields.id_product) == id_product && item.has(JsonFields.quantity)){
|
||||
if(quantity - item.getInt(JsonFields.quantity) > 0) {
|
||||
int newQuantity = quantity - item.getInt(JsonFields.quantity);
|
||||
item.put(JsonFields.quantity, newQuantity);
|
||||
pstmt = conn.prepareStatement(
|
||||
"UPDATE prod_in_depo SET quantity = ? WHERE id_product = ? AND id_deposit = ?");
|
||||
pstmt.setInt(1, item.getInt(JsonFields.quantity));
|
||||
pstmt.setInt(2, id_product);
|
||||
pstmt.setInt(3, id_deposit);
|
||||
|
||||
item.remove(JsonFields.quantity);
|
||||
|
||||
pstmt.executeUpdate();
|
||||
conn.commit();
|
||||
|
||||
|
||||
}else{
|
||||
int newQuantity = item.getInt(JsonFields.quantity) - quantity;
|
||||
item.put(JsonFields.quantity, newQuantity);
|
||||
pstmt = conn.prepareStatement("DELETE FROM prod_in_depo WHERE id_product = ? AND id_deposit = ?");
|
||||
pstmt.setInt(1, id_product);
|
||||
pstmt.setInt(2, id_deposit);
|
||||
|
||||
if(newQuantity == 0){
|
||||
item.remove(JsonFields.quantity);
|
||||
}else {
|
||||
item.put(JsonFields.quantity, newQuantity);
|
||||
}
|
||||
|
||||
pstmt.executeUpdate();
|
||||
conn.commit();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pstmt = conn.prepareStatement("INSERT INTO user_orders (id_user, id_order) VALUES (?, ?) ");
|
||||
pstmt.setInt(1, id_user);
|
||||
pstmt.setInt(2, idOrder);
|
||||
|
||||
pstmt.executeUpdate();
|
||||
conn.commit();
|
||||
}
|
||||
|
||||
private static String randomStringGenerator(){
|
||||
int leftLimit = 97; // letter 'a'
|
||||
int rightLimit = 122; // letter 'z'
|
||||
int targetStringLength = 10;
|
||||
Random random = new Random();
|
||||
|
||||
return random.ints(leftLimit, rightLimit + 1)
|
||||
.limit(targetStringLength)
|
||||
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
|
||||
.toString();
|
||||
}
|
||||
|
||||
public static JSONObject getUserOrders(Connection conn, Integer idUser) throws SQLException, IOException {
|
||||
JSONObject json = new JSONObject();
|
||||
JSONArray array = new JSONArray();
|
||||
PreparedStatement getUserOrders = conn.prepareStatement("SELECT id_order WHERE id_user = ?");
|
||||
getUserOrders.setInt(1, idUser);
|
||||
|
||||
ResultSet userOrders = getUserOrders.executeQuery();
|
||||
while(userOrders.next()){
|
||||
int id_order = userOrders.getInt("id_order");
|
||||
PreparedStatement getOrders = conn.prepareStatement("SELECT path_to_file FROM orders WHERE id = ?");
|
||||
getOrders.setInt(1, id_order);
|
||||
|
||||
ResultSet order = getOrders.executeQuery();
|
||||
if(!order.next()){
|
||||
continue;
|
||||
}
|
||||
|
||||
String path = order.getString("path_to_file");
|
||||
array.put(getDataFromFile(path));
|
||||
}
|
||||
|
||||
json.put(JsonFields.response, JsonFields.responseSuccess);
|
||||
json.put(JsonFields.responseMessage, array);
|
||||
|
||||
return json;
|
||||
}
|
||||
|
||||
private static String getDataFromFile(String path) throws IOException{
|
||||
Scanner myReader = new Scanner(new File(path));
|
||||
StringBuilder data = new StringBuilder();
|
||||
|
||||
while(myReader.hasNextLine()){
|
||||
data.append(myReader.nextLine());
|
||||
}
|
||||
|
||||
return data.toString();
|
||||
}
|
||||
|
||||
public static void registerUser(Connection conn, BaseItem user) throws SQLException, InvalidCredentialsException {
|
||||
PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM users where email = ?");
|
||||
pstmt.setString(1, user.getEmail());
|
||||
ResultSet resultSet = pstmt.executeQuery();
|
||||
|
||||
if(resultSet.isBeforeFirst()){
|
||||
throw new InvalidCredentialsException("User already exists");
|
||||
}
|
||||
|
||||
pstmt = conn.prepareStatement(
|
||||
"INSERT INTO users (username, email, password, lat_coord, long_coord) VALUES (?, ?, ?, ?, ?)");
|
||||
pstmt.setString(1, user.getName());
|
||||
pstmt.setString(2, user.getEmail());
|
||||
pstmt.setString(3, user.getPassword());
|
||||
pstmt.setFloat(4, user.getLat_coord());
|
||||
pstmt.setFloat(5, user.getLong_coord());
|
||||
|
||||
pstmt.executeUpdate();
|
||||
conn.commit();
|
||||
}
|
||||
|
||||
public static Integer loginUser(Connection conn, BaseItem user) throws SQLException, InvalidCredentialsException {
|
||||
Statement stmt = conn.createStatement();
|
||||
ResultSet resultSet = stmt.executeQuery("SELECT id, password FROM users WHERE email = '" + user.getEmail() + "'");
|
||||
|
||||
if(!resultSet.isBeforeFirst()){
|
||||
throw new InvalidCredentialsException("Incorrect credentials");
|
||||
}
|
||||
|
||||
resultSet.next();
|
||||
Integer id = resultSet.getInt("id");
|
||||
String password = resultSet.getString("password");
|
||||
|
||||
if(!user.getPassword().equals(password)){
|
||||
throw new InvalidCredentialsException("Incorrect credentials");
|
||||
}
|
||||
|
||||
return id;
|
||||
}
|
||||
|
||||
public static void alterTable(Connection conn, AdminJson adminJson) throws SQLException, ProcessDoneException,
|
||||
FieldToUpdateNotExistingException, FieldAlreadyExistsException {
|
||||
|
||||
switch (adminJson.getTable()){
|
||||
case JsonFields.tableRoutes -> alterTableRoutes(conn, adminJson);
|
||||
case JsonFields.tableDeposits -> alterTableDeposits(conn, adminJson);
|
||||
case JsonFields.tableProducts -> alterTableProducts(conn, adminJson);
|
||||
case JsonFields.tableProdInDepo -> alterTableProdInDepo(conn, adminJson);
|
||||
case JsonFields.tableUsers -> alterTableUsers(conn, adminJson);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
private static void alterTableRoutes(Connection conn, AdminJson adminJson) throws SQLException, ProcessDoneException {
|
||||
try {
|
||||
PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM routes WHERE id = ?");
|
||||
pstmt.setInt(1, adminJson.getListOfValues().get(0).getId_route());
|
||||
ResultSet resultSet = pstmt.executeQuery();
|
||||
|
||||
if(!resultSet.isBeforeFirst()){
|
||||
throw new SQLException();
|
||||
}
|
||||
|
||||
String nameOfFile = getNameOfFileRoute(conn, adminJson.getListOfValues().get(0).getId_route());
|
||||
|
||||
pstmt = conn.prepareStatement("DELETE FROM routes WHERE id = ?");
|
||||
pstmt.setInt(1, adminJson.getListOfValues().get(0).getId_route());
|
||||
pstmt.executeUpdate();
|
||||
|
||||
File routeFile = new File("D:\\Server Delivery Planner\\routes\\" + nameOfFile + "_route.txt");
|
||||
|
||||
System.gc();
|
||||
routeFile.delete();
|
||||
|
||||
conn.commit();
|
||||
throw new ProcessDoneException("Route successfully deleted");
|
||||
} catch (SQLException ignored){
|
||||
throw new SQLException("Route was already deleted");
|
||||
}
|
||||
}
|
||||
|
||||
private static void alterTableDeposits(Connection conn, AdminJson adminJson) throws SQLException, ProcessDoneException{
|
||||
switch (adminJson.getCommand()){
|
||||
case JsonFields.commandInsert -> {
|
||||
try {
|
||||
PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM deposits WHERE name = ?");
|
||||
pstmt.setString(1, adminJson.getListOfValues().get(0).getName());
|
||||
ResultSet resultSet = pstmt.executeQuery();
|
||||
|
||||
if(resultSet.isBeforeFirst()){
|
||||
throw new SQLException();
|
||||
}
|
||||
|
||||
pstmt = conn.prepareStatement("INSERT INTO deposits (name, lat_coord, long_coord) VALUES (?, ?, ?)");
|
||||
pstmt.setString(1, adminJson.getListOfValues().get(0).getName());
|
||||
pstmt.setFloat(2, adminJson.getListOfValues().get(0).getLat_coord());
|
||||
pstmt.setFloat(3, adminJson.getListOfValues().get(0).getLong_coord());
|
||||
|
||||
pstmt.executeUpdate();
|
||||
conn.commit();
|
||||
|
||||
throw new ProcessDoneException("Deposit " + adminJson.getListOfValues().get(0).getName() + " successfully inserted");
|
||||
} catch (SQLException ignored){
|
||||
throw new SQLException("Deposit " + adminJson.getListOfValues().get(0).getName() + " was already inserted");
|
||||
}
|
||||
}
|
||||
|
||||
case JsonFields.commandUpdate -> {
|
||||
try {
|
||||
PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM deposits WHERE lat_coord = ? AND long_coord = ? AND id <> ? ");
|
||||
pstmt.setString(1, adminJson.getListOfValues().get(0).getName());
|
||||
pstmt.setFloat(2, adminJson.getListOfValues().get(0).getLat_coord());
|
||||
pstmt.setFloat(3, adminJson.getListOfValues().get(0).getLong_coord());
|
||||
pstmt.setInt(4, adminJson.getListOfValues().get(0).getId_deposit());
|
||||
ResultSet resultSet = pstmt.executeQuery();
|
||||
|
||||
if(resultSet.isBeforeFirst()){
|
||||
throw new SQLException();
|
||||
}
|
||||
|
||||
pstmt = conn.prepareStatement("UPDATE deposits SET name = ?, lat_coord = ?, long_coord = ? WHERE id = ?");
|
||||
pstmt.setString(1, adminJson.getListOfValues().get(0).getName());
|
||||
pstmt.setFloat(2, adminJson.getListOfValues().get(0).getLat_coord());
|
||||
pstmt.setFloat(3, adminJson.getListOfValues().get(0).getLong_coord());
|
||||
pstmt.setInt(4, adminJson.getListOfValues().get(0).getId_deposit());
|
||||
|
||||
pstmt.executeUpdate();
|
||||
conn.commit();
|
||||
|
||||
throw new ProcessDoneException("Deposit successfully updated");
|
||||
} catch (SQLException ignored){
|
||||
throw new SQLException("Deposit was not updated");
|
||||
}
|
||||
}
|
||||
|
||||
case JsonFields.commandDelete -> {
|
||||
try {
|
||||
PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM deposits WHERE id = ?");
|
||||
pstmt.setInt(1, adminJson.getListOfValues().get(0).getId_deposit());
|
||||
ResultSet resultSet = pstmt.executeQuery();
|
||||
|
||||
if(!resultSet.isBeforeFirst()){
|
||||
throw new SQLException();
|
||||
}
|
||||
|
||||
int idDeposit = adminJson.getListOfValues().get(0).getId_deposit();
|
||||
pstmt = conn.prepareStatement("DELETE FROM prod_in_depo WHERE id_deposit = ?");
|
||||
pstmt.setInt(1, idDeposit);
|
||||
pstmt.executeUpdate();
|
||||
|
||||
pstmt = conn.prepareStatement("DELETE FROM deposits WHERE id = ?");
|
||||
pstmt.setInt(1, idDeposit);
|
||||
pstmt.executeUpdate();
|
||||
|
||||
conn.commit();
|
||||
|
||||
throw new ProcessDoneException("Deposit " + adminJson.getListOfValues().get(0).getName() + " successfully deleted");
|
||||
} catch (SQLException ignored){
|
||||
throw new SQLException("Deposit " + adminJson.getListOfValues().get(0).getName() + " was already deleted");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void alterTableProducts(Connection conn, AdminJson adminJson) throws SQLException, ProcessDoneException,
|
||||
FieldToUpdateNotExistingException, FieldAlreadyExistsException{
|
||||
switch (adminJson.getCommand()){
|
||||
case JsonFields.commandInsert -> {
|
||||
try {
|
||||
PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM products WHERE name = ?");
|
||||
pstmt.setString(1, adminJson.getListOfValues().get(0).getName());
|
||||
ResultSet resultSet = pstmt.executeQuery();
|
||||
|
||||
if(resultSet.isBeforeFirst()){
|
||||
throw new SQLException();
|
||||
}
|
||||
|
||||
pstmt = conn.prepareStatement("INSERT INTO products (name) VALUES (?)");
|
||||
pstmt.setString(1, adminJson.getListOfValues().get(0).getName());
|
||||
|
||||
pstmt.executeUpdate();
|
||||
conn.commit();
|
||||
|
||||
throw new ProcessDoneException("Product " + adminJson.getListOfValues().get(0).getName() + " successfully inserted");
|
||||
} catch (SQLException ignored){
|
||||
throw new SQLException("Product " + adminJson.getListOfValues().get(0).getName() + " was already inserted");
|
||||
}
|
||||
}
|
||||
|
||||
case JsonFields.commandUpdate -> {
|
||||
String oldName = null;
|
||||
try {
|
||||
PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM products WHERE id = ?");
|
||||
pstmt.setInt(1, adminJson.getListOfValues().get(0).getId_product());
|
||||
ResultSet resultSet = pstmt.executeQuery();
|
||||
|
||||
if(!resultSet.isBeforeFirst()){
|
||||
throw new FieldToUpdateNotExistingException("Product not existing anymore");
|
||||
}
|
||||
|
||||
resultSet.next();
|
||||
oldName = resultSet.getString("name");
|
||||
|
||||
pstmt = conn.prepareStatement("SELECT id FROM products WHERE name = ?");
|
||||
pstmt.setString(1, adminJson.getListOfValues().get(0).getName());
|
||||
resultSet = pstmt.executeQuery();
|
||||
|
||||
if(resultSet.isBeforeFirst()){
|
||||
throw new FieldAlreadyExistsException("New label can't be added because it already exists");
|
||||
}
|
||||
|
||||
pstmt = conn.prepareStatement("UPDATE products SET name = ? WHERE id = ?");
|
||||
pstmt.setString(1, adminJson.getListOfValues().get(0).getName());
|
||||
pstmt.setInt(2, adminJson.getListOfValues().get(0).getId_product());
|
||||
|
||||
pstmt.executeUpdate();
|
||||
conn.commit();
|
||||
|
||||
throw new ProcessDoneException("Product " + oldName + " successfully updated to " + adminJson.getListOfValues().get(0).getName());
|
||||
} catch (SQLException ignored){
|
||||
throw new SQLException( "Product " + oldName + " was not updated to " + adminJson.getListOfValues().get(0).getName());
|
||||
}
|
||||
}
|
||||
|
||||
case JsonFields.commandDelete -> {
|
||||
try {
|
||||
PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM products WHERE id = ?");
|
||||
pstmt.setInt(1, adminJson.getListOfValues().get(0).getId_product());
|
||||
ResultSet resultSet = pstmt.executeQuery();
|
||||
|
||||
if(!resultSet.isBeforeFirst()){
|
||||
throw new SQLException();
|
||||
}
|
||||
|
||||
pstmt = conn.prepareStatement("DELETE FROM prod_in_depo WHERE id_product = ?");
|
||||
pstmt.setInt(1, adminJson.getListOfValues().get(0).getId_product());
|
||||
pstmt.executeUpdate();
|
||||
|
||||
pstmt = conn.prepareStatement("DELETE FROM products WHERE id = ?");
|
||||
pstmt.setInt(1, adminJson.getListOfValues().get(0).getId_product());
|
||||
pstmt.executeUpdate();
|
||||
|
||||
conn.commit();
|
||||
|
||||
throw new ProcessDoneException("Product " + adminJson.getListOfValues().get(0).getName() + " successfully deleted");
|
||||
}catch (SQLException ignored){
|
||||
throw new SQLException("Product " + adminJson.getListOfValues().get(0).getName() + " was already deleted");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void alterTableProdInDepo(Connection conn, AdminJson adminJson) throws SQLException, ProcessDoneException, FieldToUpdateNotExistingException {
|
||||
switch (adminJson.getCommand()) {
|
||||
case JsonFields.commandInsert -> {
|
||||
try {
|
||||
String name = adminJson.getListOfValues().get(0).getName();
|
||||
PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM products WHERE name = ?");
|
||||
pstmt.setString(1, name);
|
||||
ResultSet resultSet = pstmt.executeQuery();
|
||||
|
||||
if(!resultSet.isBeforeFirst()){
|
||||
throw new FieldToUpdateNotExistingException("Product not existing anymore");
|
||||
}
|
||||
|
||||
resultSet.next();
|
||||
int idProduct = resultSet.getInt("id");
|
||||
|
||||
pstmt = conn.prepareStatement("SELECT * FROM prod_in_depo WHERE id_product = ? AND id_deposit = ?");
|
||||
pstmt.setInt(1, idProduct);
|
||||
pstmt.setInt(2, adminJson.getListOfValues().get(0).getId_deposit());
|
||||
resultSet = pstmt.executeQuery();
|
||||
|
||||
if(resultSet.isBeforeFirst()){
|
||||
throw new SQLException();
|
||||
}
|
||||
|
||||
pstmt = conn.prepareStatement("INSERT INTO prod_in_depo (id_product, id_deposit, quantity) VALUES (?, ?, ?)");
|
||||
pstmt.setInt(1, idProduct);
|
||||
pstmt.setInt(2, adminJson.getListOfValues().get(0).getId_deposit());
|
||||
pstmt.setInt(3, adminJson.getListOfValues().get(0).getQuantity());
|
||||
|
||||
pstmt.executeUpdate();
|
||||
conn.commit();
|
||||
|
||||
throw new ProcessDoneException("Product " + adminJson.getListOfValues().get(0).getName() + " successfully inserted in deposit");
|
||||
} catch (SQLException ignored){
|
||||
throw new SQLException("Product " + adminJson.getListOfValues().get(0).getName() + " was already inserted in deposit");
|
||||
}
|
||||
}
|
||||
|
||||
case JsonFields.commandUpdate -> {
|
||||
try {
|
||||
PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM prod_in_depo WHERE id_product = ? AND id_deposit = ?");
|
||||
pstmt.setInt(1, adminJson.getListOfValues().get(0).getId_product());
|
||||
pstmt.setInt(2, adminJson.getListOfValues().get(0).getId_deposit());
|
||||
ResultSet resultSet = pstmt.executeQuery();
|
||||
|
||||
if(!resultSet.isBeforeFirst()){
|
||||
throw new SQLException();
|
||||
}
|
||||
|
||||
pstmt = conn.prepareStatement("UPDATE prod_in_depo SET quantity = ? WHERE id_product = ? AND id_deposit = ?");
|
||||
|
||||
pstmt.setInt(1, adminJson.getListOfValues().get(0).getQuantity());
|
||||
pstmt.setInt(2, adminJson.getListOfValues().get(0).getId_product());
|
||||
pstmt.setInt(3, adminJson.getListOfValues().get(0).getId_deposit());
|
||||
|
||||
pstmt.executeUpdate();
|
||||
conn.commit();
|
||||
|
||||
throw new ProcessDoneException("Product " + adminJson.getListOfValues().get(0).getName() + " successfully updated");
|
||||
} catch (SQLException ignored){
|
||||
throw new SQLException("Product " + adminJson.getListOfValues().get(0).getName() + " was not updated");
|
||||
}
|
||||
}
|
||||
|
||||
case JsonFields.commandDelete -> {
|
||||
try {
|
||||
PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM prod_in_depo WHERE id_product = ? AND id_deposit = ?");
|
||||
pstmt.setInt(1, adminJson.getListOfValues().get(0).getId_product());
|
||||
pstmt.setInt(2, adminJson.getListOfValues().get(0).getId_deposit());
|
||||
ResultSet resultSet = pstmt.executeQuery();
|
||||
|
||||
if(!resultSet.isBeforeFirst()){
|
||||
throw new SQLException();
|
||||
}
|
||||
|
||||
pstmt = conn.prepareStatement("DELETE FROM prod_in_depo WHERE id_product = ? AND id_deposit = ?");
|
||||
pstmt.setInt(1, adminJson.getListOfValues().get(0).getId_product());
|
||||
pstmt.setInt(2, adminJson.getListOfValues().get(0).getId_deposit());
|
||||
|
||||
pstmt.executeUpdate();
|
||||
conn.commit();
|
||||
|
||||
throw new ProcessDoneException("Product " + adminJson.getListOfValues().get(0).getName() + " successfully deleted from deposit");
|
||||
} catch (SQLException ignored) {
|
||||
throw new SQLException("Product " + adminJson.getListOfValues().get(0).getName() + " was already deleted from deposit");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
private static void alterTableUsers(Connection conn, AdminJson adminJson) throws SQLException, ProcessDoneException{
|
||||
try {
|
||||
PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM users WHERE id = ?");//check for user existence
|
||||
pstmt.setInt(1, adminJson.getListOfValues().get(0).getId_user());
|
||||
ResultSet resultSet = pstmt.executeQuery();
|
||||
|
||||
if(!resultSet.isBeforeFirst()){
|
||||
throw new SQLException();
|
||||
}
|
||||
|
||||
pstmt = conn.prepareStatement("SELECT id_order FROM user_orders WHERE id_user = ?");//get all orders made by user
|
||||
pstmt.setInt(1, adminJson.getListOfValues().get(0).getId_user());
|
||||
resultSet = pstmt.executeQuery();
|
||||
|
||||
while(resultSet.next()){
|
||||
int id_order = resultSet.getInt("id_order");
|
||||
String nameOfOrder = getNameOfFile(conn, id_order);
|
||||
|
||||
String pathToFileRouteDatabase = "D:\\\\Server Delivery Planner\\\\routes\\\\" + nameOfOrder + "_route.txt";
|
||||
String pathToFileOrderDatabase = "D:\\\\Server Delivery Planner\\\\orders\\\\" + nameOfOrder + "_order.txt";
|
||||
String pathToFileOrder = "D:\\Server Delivery Planner\\orders\\" + nameOfOrder + "_order.txt";
|
||||
String pathToFileRoute = "D:\\Server Delivery Planner\\routes\\" + nameOfOrder + "_route.txt";
|
||||
|
||||
File orderFile = new File(pathToFileOrder);
|
||||
File routeFile = new File(pathToFileRoute);
|
||||
|
||||
System.gc();
|
||||
orderFile.delete();
|
||||
|
||||
System.gc();
|
||||
routeFile.delete();
|
||||
|
||||
pstmt = conn.prepareStatement("DELETE FROM user_orders WHERE id_order = ?");
|
||||
pstmt.setInt(1, id_order);
|
||||
pstmt.executeUpdate();
|
||||
|
||||
pstmt = conn.prepareStatement("DELETE FROM orders WHERE path_to_file = ?");
|
||||
pstmt.setString(1, pathToFileOrderDatabase);
|
||||
pstmt.executeUpdate();
|
||||
|
||||
pstmt = conn.prepareStatement("DELETE FROM routes WHERE path_to_file = ?");
|
||||
pstmt.setString(1, pathToFileRouteDatabase);
|
||||
pstmt.executeUpdate();
|
||||
|
||||
conn.commit();
|
||||
}
|
||||
|
||||
pstmt = conn.prepareStatement("DELETE FROM users WHERE id = ?");
|
||||
pstmt.setInt(1, adminJson.getListOfValues().get(0).getId_user());
|
||||
pstmt.executeUpdate();
|
||||
|
||||
conn.commit();
|
||||
|
||||
throw new ProcessDoneException("User " + adminJson.getListOfValues().get(0).getName() + " successfully deleted");
|
||||
} catch (SQLException ignored){
|
||||
throw new SQLException("User " + adminJson.getListOfValues().get(0).getName() + " was already deleted");
|
||||
}
|
||||
}
|
||||
|
||||
private static String getNameOfFile(Connection conn, int id_order)throws SQLException{
|
||||
PreparedStatement pstmt = conn.prepareStatement("SELECT path_to_file FROM orders WHERE id = ?");
|
||||
pstmt.setInt(1, id_order);
|
||||
ResultSet resultSet1 = pstmt.executeQuery();
|
||||
resultSet1.next();
|
||||
|
||||
String resultStringToProcess = resultSet1.getString("path_to_file");
|
||||
int left, right = resultStringToProcess.indexOf('_');
|
||||
left = right;
|
||||
|
||||
while(resultStringToProcess.charAt(left) != '\\'){
|
||||
left--;
|
||||
}
|
||||
left++;
|
||||
|
||||
return resultStringToProcess.substring(left, right);
|
||||
}
|
||||
|
||||
private static String getNameOfFileRoute(Connection conn, int id_route)throws SQLException{
|
||||
PreparedStatement pstmt = conn.prepareStatement("SELECT path_to_file FROM routes WHERE id = ?");
|
||||
pstmt.setInt(1, id_route);
|
||||
ResultSet resultSet1 = pstmt.executeQuery();
|
||||
resultSet1.next();
|
||||
|
||||
String resultStringToProcess = resultSet1.getString("path_to_file");
|
||||
int left, right = resultStringToProcess.indexOf('_');
|
||||
left = right;
|
||||
|
||||
while(resultStringToProcess.charAt(left) != '\\'){
|
||||
left--;
|
||||
}
|
||||
left++;
|
||||
|
||||
return resultStringToProcess.substring(left, right);
|
||||
}
|
||||
|
||||
|
||||
public static void closeConnection(Connection conn) throws SQLException{
|
||||
conn.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package com.andreicerbu;
|
||||
|
||||
import java.sql.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
public class InitializeDatabase {
|
||||
private static final String URL =
|
||||
"jdbc:mysql://localhost:3306/java";
|
||||
private static final String USER = "root";
|
||||
private static final String PASSWORD = "";
|
||||
private static Connection conn;
|
||||
|
||||
private final static String createProduct =
|
||||
"CREATE TABLE products( id INT AUTO_INCREMENT, name VARCHAR(256) NOT NULL, PRIMARY KEY(id) , UNIQUE(name))";
|
||||
private final static String createDeposit =
|
||||
"CREATE TABLE deposits( id INT AUTO_INCREMENT, name VARCHAR(256) NOT NULL, lat_coord FLOAT NOT NULL, long_coord FLOAT NOT NULL, PRIMARY KEY(id), UNIQUE (lat_coord), UNIQUE (long_coord) )";
|
||||
private final static String createProdInDepo =
|
||||
"CREATE TABLE prod_in_depo( id INT AUTO_INCREMENT, id_product INT NOT NULL, id_deposit INT NOT NULL, quantity INT NOT NULL, PRIMARY KEY(id), FOREIGN KEY (id_product) REFERENCES products(id), FOREIGN KEY (id_deposit) REFERENCES deposits(id), UNIQUE (id_product, id_deposit) )";
|
||||
private final static String createOrders =
|
||||
"CREATE TABLE orders( id INT AUTO_INCREMENT, path_to_file VARCHAR(512) NOT NULL, PRIMARY KEY(id), UNIQUE (path_to_file) )";
|
||||
private final static String createRoutes =
|
||||
"CREATE TABLE routes( id INT AUTO_INCREMENT, path_to_file VARCHAR(512) NOT NULL, PRIMARY KEY(id), UNIQUE (path_to_file) )";
|
||||
private final static String createUsers =
|
||||
"CREATE TABLE users( id INT AUTO_INCREMENT, username VARCHAR(256) NOT NULL, email VARCHAR(256) NOT NULL, password VARCHAR(256) NOT NULL, lat_coord FLOAT NOT NULL, long_coord FLOAT NOT NULL, PRIMARY KEY(id), UNIQUE(email) );";
|
||||
private final static String createUserOrders =
|
||||
"CREATE TABLE user_orders( id INT AUTO_INCREMENT, id_user INT NOT NULL, id_order INT NOT NULL, PRIMARY KEY (id), FOREIGN KEY (id_user) REFERENCES users(id), FOREIGN KEY (id_order) REFERENCES orders (id), UNIQUE (id_order) )";
|
||||
|
||||
private final static String dropProduct = "DROP TABLE products";
|
||||
private final static String dropDeposit = "DROP TABLE deposits";
|
||||
private final static String dropProdInDepo = "DROP TABLE prod_in_depo";
|
||||
private final static String dropOrders = "DROP TABLE orders";
|
||||
private final static String dropRoutes = "DROP TABLE routes";
|
||||
private final static String dropUsers = "DROP TABLE users";
|
||||
private final static String dropUserOrders = "DROP TABLE user_orders";
|
||||
|
||||
private final static List<String> dropTablesQueries = new ArrayList<>(Arrays.asList(dropProdInDepo, dropUserOrders, dropDeposit, dropProduct, dropRoutes, dropUsers, dropOrders));
|
||||
private final static List<String> createTablesQueries = new ArrayList<>(Arrays.asList(createDeposit, createOrders, createRoutes, createProduct, createProdInDepo, createUsers, createUserOrders));
|
||||
|
||||
public static void main(String[] args){
|
||||
createTables();
|
||||
//dropTables();
|
||||
}
|
||||
|
||||
private static void createTables(){
|
||||
try {
|
||||
conn = DriverManager.getConnection(URL, USER, PASSWORD);
|
||||
conn.setAutoCommit(false);
|
||||
|
||||
Statement stmt = conn.createStatement();
|
||||
|
||||
for(String query : createTablesQueries){
|
||||
try {
|
||||
stmt.executeUpdate(query);
|
||||
System.out.println("Table created successfully");
|
||||
}
|
||||
catch (SQLException tableExists){
|
||||
System.out.println(tableExists.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
conn.commit();
|
||||
}catch (SQLException e){
|
||||
try {
|
||||
System.err.println(e);
|
||||
conn.rollback();
|
||||
}catch(SQLException rollback){
|
||||
System.err.println(rollback);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void dropTables(){
|
||||
try {
|
||||
conn = DriverManager.getConnection(URL, USER, PASSWORD);
|
||||
conn.setAutoCommit(false);
|
||||
|
||||
Statement stmt = conn.createStatement();
|
||||
|
||||
for(String query : dropTablesQueries){
|
||||
try {
|
||||
stmt.executeUpdate(query);
|
||||
System.out.println("Dropped table");
|
||||
} catch (SQLException tableNotExisting) {
|
||||
System.out.println(tableNotExisting.getMessage());
|
||||
}
|
||||
}
|
||||
conn.commit();
|
||||
}catch (SQLException e){
|
||||
try {
|
||||
conn.rollback();
|
||||
}catch(SQLException ee){
|
||||
System.err.println(ee);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.andreicerbu;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public class Main {
|
||||
public static void main(String[] args){
|
||||
try {
|
||||
Server server = new Server();
|
||||
server.run();
|
||||
}catch (IOException e){
|
||||
System.out.println(e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.andreicerbu;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.InetAddress;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.Socket;
|
||||
import java.net.SocketTimeoutException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class Server {
|
||||
private static final int PORT = 8672;
|
||||
private static final int TIME_OUT = 10000;
|
||||
ServerSocket serverSocket = null;
|
||||
List<ClientThread> clients;
|
||||
|
||||
public Server()throws IOException {
|
||||
serverSocket = new ServerSocket(PORT);
|
||||
serverSocket.setSoTimeout(TIME_OUT);
|
||||
clients = new ArrayList<>();
|
||||
|
||||
InetAddress localaddr = InetAddress.getLocalHost();
|
||||
System.out.println("Local IP Address : " + localaddr);
|
||||
System.out.println("Local hostname : " + localaddr.getHostName());
|
||||
}
|
||||
|
||||
private void acceptConnection() throws IOException{
|
||||
Socket clientSocket = serverSocket.accept();
|
||||
System.out.println("Client Connected!");
|
||||
clients.add(new ClientThread(clientSocket));
|
||||
clients.get(clients.size() - 1).start();
|
||||
}
|
||||
|
||||
public void run(){
|
||||
while(true) {
|
||||
try {
|
||||
acceptConnection();
|
||||
}catch (SocketTimeoutException ignored){
|
||||
clients.removeIf(ClientThread::isThreadNotAlive);
|
||||
System.out.println("Waiting for client!");
|
||||
} catch (IOException e) {
|
||||
System.err.println(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
package com.andreicerbu;
|
||||
|
||||
import com.andreicerbu.exceptions.*;
|
||||
import com.andreicerbu.items.*;
|
||||
|
||||
import com.andreicerbu.json.JsonFields;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class SocketInput {
|
||||
private String input;
|
||||
private JSONObject jsonInput = null;
|
||||
private JSONObject jsonOutput = null;
|
||||
|
||||
private static final String registrationDone = "Registration done succesfully";
|
||||
private static final String orderDone = "Order placed successfully";
|
||||
|
||||
|
||||
private static final String genericError = "Internal server error. Please try again";
|
||||
|
||||
public SocketInput(){}
|
||||
|
||||
public SocketInput(String input){
|
||||
this.input = input;
|
||||
jsonInput = new JSONObject(input);
|
||||
}
|
||||
|
||||
public void processInputJson(Connection conn) throws IOException{
|
||||
jsonOutput = new JSONObject();
|
||||
AdminJson adminJson = new AdminJson();
|
||||
|
||||
switch(jsonInput.getString(JsonFields.command)) {
|
||||
case JsonFields.commandPlaceOrder -> {
|
||||
try {
|
||||
Algorithm algorithm = new Algorithm(jsonInput);
|
||||
Database.placeOrder(Database.getConnection(), algorithm.getRouteJson(), jsonInput.getInt(JsonFields.id_user));
|
||||
processOutputJson(JsonFields.responseSuccess, orderDone);
|
||||
} catch (ProductUnavailableAnymoreException e){
|
||||
processOutputJson(JsonFields.responseError, e.getMessage());
|
||||
} catch (SQLException ignored){
|
||||
processOutputJson(JsonFields.responseError, genericError);
|
||||
}
|
||||
}
|
||||
|
||||
case JsonFields.commandGetDatabase -> {
|
||||
try {
|
||||
DatabaseJson databaseJson = new DatabaseJson();
|
||||
databaseJson.createJSON();
|
||||
jsonOutput = databaseJson.getJSON();
|
||||
} catch (SQLException e){
|
||||
System.err.println(e);
|
||||
System.err.flush();
|
||||
processOutputJson(JsonFields.responseError, genericError);
|
||||
}
|
||||
}
|
||||
|
||||
case JsonFields.commandGetUserDatabase -> {
|
||||
try {
|
||||
adminJson.deserializeJSON(jsonInput);
|
||||
DatabaseClientJson databaseClientJson = new DatabaseClientJson(adminJson.getListOfValues().get(0).getId_user());
|
||||
databaseClientJson.createJSON();
|
||||
jsonOutput = databaseClientJson.getJSON();
|
||||
} catch (SQLException ignored){
|
||||
processOutputJson(JsonFields.responseError, genericError);
|
||||
}
|
||||
}
|
||||
|
||||
case JsonFields.commandGetOrders -> {
|
||||
try {
|
||||
jsonOutput = Database.getUserOrders(conn, adminJson.getListOfValues().get(0).getId_user());
|
||||
} catch (SQLException ignored){
|
||||
processOutputJson(JsonFields.responseError, genericError);
|
||||
}
|
||||
}
|
||||
|
||||
case JsonFields.commandRegister -> {
|
||||
try {
|
||||
adminJson.deserializeJSON(jsonInput);
|
||||
Database.registerUser(conn, adminJson.getListOfValues().get(0));
|
||||
processOutputJson(JsonFields.responseSuccess, registrationDone);
|
||||
} catch (InvalidCredentialsException e) {
|
||||
processOutputJson(JsonFields.responseError, e.getMessage());
|
||||
} catch (SQLException ignored){
|
||||
processOutputJson(JsonFields.responseError, genericError);
|
||||
}
|
||||
}
|
||||
|
||||
case JsonFields.commandLogin -> {
|
||||
try{
|
||||
adminJson.deserializeJSON(jsonInput);
|
||||
Integer userId = Database.loginUser(conn, adminJson.getListOfValues().get(0));
|
||||
processOutputJson(JsonFields.responseSuccess, String.valueOf(userId));
|
||||
} catch (InvalidCredentialsException e){
|
||||
processOutputJson(JsonFields.responseError, e.getMessage());
|
||||
} catch (SQLException ignored){
|
||||
processOutputJson(JsonFields.responseError, genericError);
|
||||
}
|
||||
}
|
||||
|
||||
default -> {
|
||||
try {
|
||||
adminJson.deserializeJSON(jsonInput);
|
||||
Database.alterTable(conn, adminJson);
|
||||
}catch(SQLException | FieldToUpdateNotExistingException | FieldAlreadyExistsException e){
|
||||
processOutputJson(JsonFields.responseError, e.getMessage());
|
||||
} catch(ProcessDoneException e){
|
||||
processOutputJson(JsonFields.responseSuccess, e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void processOutputJson(String response, String message){
|
||||
jsonOutput = new JSONObject();
|
||||
switch (response){
|
||||
case JsonFields.responseSuccess -> {
|
||||
jsonOutput.put(JsonFields.response, JsonFields.responseSuccess);
|
||||
jsonOutput.put(JsonFields.responseMessage, message);
|
||||
}
|
||||
|
||||
case JsonFields.responseError -> {
|
||||
jsonOutput.put(JsonFields.response, JsonFields.responseError);
|
||||
jsonOutput.put(JsonFields.responseMessage, message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public JSONObject getJsonResponse(){
|
||||
return jsonOutput;
|
||||
}
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package com.andreicerbu.exceptions;
|
||||
|
||||
public class FieldAlreadyExistsException extends Exception{
|
||||
public FieldAlreadyExistsException(String message){
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package com.andreicerbu.exceptions;
|
||||
|
||||
public class FieldToUpdateNotExistingException extends Exception{
|
||||
public FieldToUpdateNotExistingException(String message){
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package com.andreicerbu.exceptions;
|
||||
|
||||
public class InvalidCredentialsException extends Exception{
|
||||
public InvalidCredentialsException(String message){
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package com.andreicerbu.exceptions;
|
||||
|
||||
public class NotExistingUserException extends Exception{
|
||||
public NotExistingUserException(){
|
||||
super("Incorrect credentials");
|
||||
}
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package com.andreicerbu.exceptions;
|
||||
|
||||
public class ProcessDoneException extends Exception{
|
||||
public ProcessDoneException(String message){
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package com.andreicerbu.exceptions;
|
||||
|
||||
public class ProductUnavailableAnymoreException extends Exception{
|
||||
public ProductUnavailableAnymoreException(String message){
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.andreicerbu.interfaces;
|
||||
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.sql.SQLException;
|
||||
|
||||
public interface JSONMethods {
|
||||
void createJSON() throws SQLException;
|
||||
JSONObject getJSON();
|
||||
void deserializeJSON(JSONObject json);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.andreicerbu.items;
|
||||
|
||||
import com.andreicerbu.interfaces.JSONMethods;
|
||||
import com.andreicerbu.json.JsonFields;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class AdminJson extends BaseItem implements JSONMethods {
|
||||
private List<BaseItem> listOfValues = new ArrayList<>();
|
||||
private JSONArray listOfValuesJSON = new JSONArray();
|
||||
|
||||
public AdminJson(){}
|
||||
|
||||
|
||||
@Override
|
||||
public void createJSON() {
|
||||
json.put(JsonFields.table, table == null ? JSONObject.NULL : table);
|
||||
json.put(JsonFields.command, command == null ? JSONObject.NULL : command);
|
||||
}
|
||||
|
||||
@Override
|
||||
public JSONObject getJSON() {
|
||||
json.put(JsonFields.listOfValues,listOfValuesJSON);
|
||||
return json;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deserializeJSON(JSONObject json) {
|
||||
table = json.get(JsonFields.table) == JSONObject.NULL ? null : json.getString(JsonFields.table);
|
||||
command = json.getString(JsonFields.command) == JSONObject.NULL ? null : json.getString(JsonFields.command);
|
||||
|
||||
JSONArray listOfValuesJSON = json.getJSONArray(JsonFields.listOfValues);
|
||||
|
||||
for (int index = 0; index < listOfValuesJSON.length(); index++) {
|
||||
JSONObject value = listOfValuesJSON.getJSONObject(index);
|
||||
BaseItem item = deserializeBaseItemJSON(table, value);
|
||||
this.listOfValues.add(item);
|
||||
}
|
||||
}
|
||||
|
||||
public List<BaseItem> getListOfValues() {
|
||||
return listOfValues;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
package com.andreicerbu.items;
|
||||
|
||||
import org.json.JSONObject;
|
||||
import static com.andreicerbu.json.JsonFields.*;
|
||||
import com.andreicerbu.json.JsonFields;
|
||||
import com.andreicerbu.items.database.*;
|
||||
|
||||
public abstract class BaseItem {
|
||||
protected JSONObject json = new JSONObject();
|
||||
|
||||
protected Integer id_user_orders = null;
|
||||
protected Integer id_user = null;
|
||||
protected Integer id_order = null;
|
||||
protected Integer id_deposit = null;
|
||||
protected Integer id_prod_in_depo = null;
|
||||
protected Integer id_product = null;
|
||||
protected Integer id_route = null;
|
||||
|
||||
protected Integer quantity = null;
|
||||
protected String name = null;
|
||||
protected String email = null;
|
||||
protected String password = null;
|
||||
protected Float lat_coord = null;
|
||||
protected Float long_coord = null;
|
||||
|
||||
protected String command = null;
|
||||
protected String table = null;
|
||||
protected String jsonType = null;
|
||||
|
||||
|
||||
|
||||
protected BaseItem deserializeBaseItemJSON(String table, JSONObject json){
|
||||
BaseItem item;
|
||||
|
||||
switch(table){
|
||||
case tableOrders -> item = new TableOrder(
|
||||
json.get(JsonFields.id_order) == JSONObject.NULL ? null : json.getInt(JsonFields.id_order),
|
||||
json.get(JsonFields.name) == JSONObject.NULL ? null : json.getString(JsonFields.name)
|
||||
);
|
||||
case tableDeposits -> item = new TableDeposit(
|
||||
json.get(JsonFields.id_deposit) == JSONObject.NULL ? null : json.getInt(JsonFields.id_deposit),
|
||||
json.get(JsonFields.name) == JSONObject.NULL ? null : json.getString(JsonFields.name),
|
||||
json.get(JsonFields.lat_coord) == JSONObject.NULL ? null : json.getFloat(JsonFields.lat_coord),
|
||||
json.get(JsonFields.long_coord) == JSONObject.NULL ? null : json.getFloat(JsonFields.long_coord)
|
||||
);
|
||||
case tableProdInDepo -> item = new TableProdInDepo(
|
||||
json.get(JsonFields.id_prod_in_depo) == JSONObject.NULL ? null : json.getInt(JsonFields.id_prod_in_depo),
|
||||
json.get(JsonFields.id_product) == JSONObject.NULL ? null : json.getInt(JsonFields.id_product),
|
||||
json.get(JsonFields.id_deposit) == JSONObject.NULL ? null : json.getInt(JsonFields.id_deposit),
|
||||
json.get(JsonFields.name) == JSONObject.NULL ? null : json.getString(JsonFields.name),
|
||||
json.get(JsonFields.quantity) == JSONObject.NULL ? null : json.getInt(JsonFields.quantity)
|
||||
|
||||
);
|
||||
case tableProducts -> item = new TableProduct(
|
||||
json.get(JsonFields.id_product) == JSONObject.NULL ? null : json.getInt(JsonFields.id_product),
|
||||
json.get(JsonFields.name) == JSONObject.NULL ? null : json.getString(JsonFields.name)
|
||||
);
|
||||
case tableRoutes -> item = new TableRoute(
|
||||
json.get(JsonFields.id_route) == JSONObject.NULL ? null : json.getInt(JsonFields.id_route),
|
||||
json.get(JsonFields.name) == JSONObject.NULL ? null : json.getString(JsonFields.name),
|
||||
json.get(JsonFields.id_order) == JSONObject.NULL ? null : json.getInt(JsonFields.id_order)
|
||||
);
|
||||
|
||||
case tableUsers -> item = new TableUser(
|
||||
json.get(JsonFields.id_user) == JSONObject.NULL ? null : json.getInt(JsonFields.id_user),
|
||||
json.get(JsonFields.name) == JSONObject.NULL ? null : json.getString(JsonFields.name),
|
||||
json.get(JsonFields.email) == JSONObject.NULL ? null : json.getString(JsonFields.email),
|
||||
json.get(JsonFields.password) == JSONObject.NULL ? null : json.getString(JsonFields.password),
|
||||
json.get(JsonFields.lat_coord) == JSONObject.NULL ? null : json.getFloat(JsonFields.lat_coord),
|
||||
json.get(JsonFields.long_coord) == JSONObject.NULL ? null : json.getFloat(JsonFields.long_coord)
|
||||
);
|
||||
|
||||
case tableUserOrders -> item = new TableUserOrder (
|
||||
json.get(JsonFields.id_user_orders) == JSONObject.NULL ? null : json.getInt(JsonFields.id_user_orders),
|
||||
json.get(JsonFields.id_user) == JSONObject.NULL ? null : json.getInt(JsonFields.id_user),
|
||||
json.get(JsonFields.id_order) == JSONObject.NULL ? null : json.getInt(JsonFields.id_order)
|
||||
);
|
||||
|
||||
default -> item = null;
|
||||
}
|
||||
|
||||
return item;
|
||||
}
|
||||
|
||||
public Integer getId_user() {
|
||||
return id_user;
|
||||
}
|
||||
|
||||
public Integer getId_user_orders() {
|
||||
return id_user_orders;
|
||||
}
|
||||
|
||||
public Integer getId_prod_in_depo() {
|
||||
return id_prod_in_depo;
|
||||
}
|
||||
|
||||
public Integer getId_route() {
|
||||
return id_route;
|
||||
}
|
||||
|
||||
public Integer getId_product() {
|
||||
return id_product;
|
||||
}
|
||||
|
||||
public Integer getId_deposit() {
|
||||
return id_deposit;
|
||||
}
|
||||
|
||||
public Integer getId_order() {
|
||||
return id_order;
|
||||
}
|
||||
|
||||
public Integer getQuantity() {
|
||||
return quantity;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public Float getLat_coord() {
|
||||
return lat_coord;
|
||||
}
|
||||
|
||||
public Float getLong_coord() {
|
||||
return long_coord;
|
||||
}
|
||||
|
||||
public String getCommand() {
|
||||
return command;
|
||||
}
|
||||
|
||||
public String getTable() {
|
||||
return table;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
package com.andreicerbu.items;
|
||||
|
||||
import com.andreicerbu.Database;
|
||||
import com.andreicerbu.interfaces.JSONMethods;
|
||||
import com.andreicerbu.items.database.*;
|
||||
import com.andreicerbu.json.JsonFields;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.sql.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class DatabaseClientJson implements JSONMethods {
|
||||
JSONObject json = new JSONObject();
|
||||
Integer idUser;
|
||||
|
||||
JSONArray listTableOrderJson;
|
||||
JSONArray listTableProductJson;
|
||||
JSONArray listTableProdInDepoJson;
|
||||
JSONArray listTableUserJson;
|
||||
|
||||
public DatabaseClientJson(Integer idUser){
|
||||
this.idUser = idUser;
|
||||
}
|
||||
|
||||
public void readDatabase() throws SQLException {
|
||||
Connection conn = Database.getConnection();
|
||||
|
||||
listTableOrderJson = new JSONArray();
|
||||
listTableProductJson = new JSONArray();
|
||||
listTableUserJson = new JSONArray();
|
||||
listTableProdInDepoJson = new JSONArray();
|
||||
|
||||
populateListTableOrderJson(conn, idUser);
|
||||
populateListTableProductJson(conn);
|
||||
populateListTableUserJson(conn, idUser);
|
||||
populateListTableProdInDepoJson(conn);
|
||||
|
||||
Database.closeConnection(conn);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void createJSON() throws SQLException {
|
||||
readDatabase();
|
||||
}
|
||||
|
||||
@Override
|
||||
public JSONObject getJSON() {
|
||||
return json;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deserializeJSON(JSONObject json) {
|
||||
|
||||
}
|
||||
|
||||
private void populateListTableOrderJson(Connection conn, Integer idUser) throws SQLException{
|
||||
PreparedStatement pstmt = conn.prepareStatement("SELECT id_order FROM user_orders WHERE id_user = ?");
|
||||
pstmt.setInt(1, idUser);
|
||||
|
||||
ResultSet resultSet = pstmt.executeQuery();
|
||||
while(resultSet.next()){
|
||||
int id_order = resultSet.getInt("id_order");
|
||||
|
||||
Statement stmt = conn.createStatement();
|
||||
ResultSet resultSetPath = stmt.executeQuery("SELECT path_to_file FROM orders WHERE id = " + id_order);
|
||||
resultSetPath.next();
|
||||
|
||||
String path_to_file = resultSetPath.getString("path_to_file");
|
||||
StringBuilder content = new StringBuilder();
|
||||
|
||||
try {
|
||||
File myObj = new File(path_to_file);
|
||||
Scanner myReader = new Scanner(myObj);
|
||||
while (myReader.hasNextLine()) {
|
||||
content.append(myReader.nextLine());
|
||||
}
|
||||
}catch (IOException ignored){}
|
||||
|
||||
JSONArray order = new JSONArray(content.toString());
|
||||
listTableOrderJson.put(order);
|
||||
}
|
||||
|
||||
json.put(JsonFields.tableOrders, listTableOrderJson);
|
||||
}
|
||||
|
||||
private void populateListTableProdInDepoJson(Connection conn) throws SQLException{
|
||||
Statement stmt = conn.createStatement();
|
||||
ResultSet resultSet = stmt.executeQuery("SELECT * FROM prod_in_depo");
|
||||
while(resultSet.next()){
|
||||
JSONObject object = new JSONObject();
|
||||
object.put(JsonFields.id_prod_in_depo, resultSet.getInt("id"));
|
||||
object.put(JsonFields.id_product, resultSet.getInt("id_product"));
|
||||
object.put(JsonFields.id_deposit, resultSet.getInt("id_deposit"));
|
||||
object.put(JsonFields.quantity, resultSet.getInt("quantity"));
|
||||
|
||||
listTableProdInDepoJson.put(object);
|
||||
}
|
||||
|
||||
json.put(JsonFields.tableProdInDepo, listTableProdInDepoJson);
|
||||
}
|
||||
|
||||
private void populateListTableProductJson(Connection conn) throws SQLException{
|
||||
Statement stmt = conn.createStatement();
|
||||
ResultSet resultSet = stmt.executeQuery("SELECT * FROM products");
|
||||
while(resultSet.next()){
|
||||
JSONObject object = new JSONObject();
|
||||
object.put(JsonFields.id_product, resultSet.getInt("id"));
|
||||
object.put(JsonFields.name, resultSet.getString("name"));
|
||||
|
||||
listTableProductJson.put(object);
|
||||
}
|
||||
|
||||
json.put(JsonFields.tableProducts, listTableProductJson);
|
||||
}
|
||||
|
||||
private void populateListTableUserJson(Connection conn, Integer idUser) throws SQLException{
|
||||
PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM users WHERE id = ?");
|
||||
pstmt.setInt(1, idUser);
|
||||
|
||||
ResultSet resultSet = pstmt.executeQuery();
|
||||
while(resultSet.next()){
|
||||
JSONObject object = new JSONObject();
|
||||
object.put(JsonFields.id_user, resultSet.getInt("id"));
|
||||
object.put(JsonFields.name, resultSet.getString("username"));
|
||||
object.put(JsonFields.email, resultSet.getString("email"));
|
||||
object.put(JsonFields.password, resultSet.getString("password"));
|
||||
object.put(JsonFields.lat_coord, resultSet.getString("lat_coord"));
|
||||
object.put(JsonFields.long_coord, resultSet.getString("long_coord"));
|
||||
|
||||
listTableUserJson.put(object);
|
||||
}
|
||||
|
||||
json.put(JsonFields.tableUsers, listTableUserJson);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
package com.andreicerbu.items;
|
||||
|
||||
import com.andreicerbu.Database;
|
||||
import com.andreicerbu.interfaces.JSONMethods;
|
||||
import com.andreicerbu.items.database.*;
|
||||
import com.andreicerbu.json.JsonFields;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.sql.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class DatabaseJson implements JSONMethods {
|
||||
JSONObject json = new JSONObject();
|
||||
|
||||
JSONArray listTableDepositJson;
|
||||
JSONArray listTableOrderJson;
|
||||
JSONArray listTableProdInDepoJson;
|
||||
JSONArray listTableProductJson;
|
||||
JSONArray listTableRouteJson;
|
||||
JSONArray listTableUserJson;
|
||||
JSONArray listTableUserOrderJson;
|
||||
|
||||
public DatabaseJson() {
|
||||
}
|
||||
|
||||
public void readDatabase() throws SQLException {
|
||||
Connection conn = Database.getConnection();
|
||||
Statement stmt = conn.createStatement();
|
||||
|
||||
listTableDepositJson = new JSONArray();
|
||||
listTableOrderJson = new JSONArray();
|
||||
listTableProdInDepoJson = new JSONArray();
|
||||
listTableProductJson = new JSONArray();
|
||||
listTableRouteJson = new JSONArray();
|
||||
listTableUserJson = new JSONArray();
|
||||
listTableUserOrderJson = new JSONArray();
|
||||
|
||||
populateListTableDepositJson(stmt);
|
||||
populateListTableOrderJson(stmt);
|
||||
populateListTableProdInDepoJson(stmt);
|
||||
populateListTableProductJson(stmt);
|
||||
populateListTableRouteJson(stmt);
|
||||
populateListTableUserJson(stmt);
|
||||
populateListTableUserOrderJson(stmt);
|
||||
|
||||
Database.closeConnection(conn);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void createJSON() throws SQLException {
|
||||
readDatabase();
|
||||
}
|
||||
|
||||
@Override
|
||||
public JSONObject getJSON() {
|
||||
return json;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deserializeJSON(JSONObject json) {
|
||||
|
||||
}
|
||||
|
||||
private void populateListTableDepositJson(Statement stmt) throws SQLException {
|
||||
ResultSet resultSet = stmt.executeQuery("SELECT * FROM deposits");
|
||||
while (resultSet.next()) {
|
||||
JSONObject object = new JSONObject();
|
||||
object.put(JsonFields.id_deposit, resultSet.getInt("id"));
|
||||
object.put(JsonFields.name, resultSet.getString("name"));
|
||||
object.put(JsonFields.lat_coord, resultSet.getString("lat_coord"));
|
||||
object.put(JsonFields.long_coord, resultSet.getString("long_coord"));
|
||||
|
||||
listTableDepositJson.put(object);
|
||||
}
|
||||
|
||||
json.put(JsonFields.tableDeposits, listTableDepositJson);
|
||||
}
|
||||
|
||||
private void populateListTableOrderJson(Statement stmt) throws SQLException {
|
||||
ResultSet resultSet = stmt.executeQuery("SELECT * FROM orders");
|
||||
|
||||
while (resultSet.next()) {
|
||||
JSONObject item = new JSONObject();
|
||||
int id_order = resultSet.getInt("id");
|
||||
String fileName = getNameOfFileRoute(Database.getConnection(), id_order, "orders");
|
||||
String path_to_file = "D:\\Server Delivery Planner\\orders\\" + fileName + "_order.txt";
|
||||
|
||||
StringBuilder content = new StringBuilder();
|
||||
|
||||
try {
|
||||
File myObj = new File(path_to_file);
|
||||
Scanner myReader = new Scanner(myObj);
|
||||
while (myReader.hasNextLine()) {
|
||||
content.append(myReader.nextLine());
|
||||
}
|
||||
} catch (IOException e) {
|
||||
System.out.println(e.getMessage());
|
||||
System.out.flush();
|
||||
}
|
||||
|
||||
item.put(JsonFields.id_order, id_order);
|
||||
item.put(JsonFields.order, new JSONArray(content.toString()));
|
||||
listTableOrderJson.put(item);
|
||||
}
|
||||
|
||||
resultSet.close();
|
||||
json.put(JsonFields.tableOrders, listTableOrderJson);
|
||||
}
|
||||
|
||||
private void populateListTableProdInDepoJson(Statement stmt) throws SQLException {
|
||||
ResultSet resultSet = stmt.executeQuery("SELECT * FROM prod_in_depo");
|
||||
while (resultSet.next()) {
|
||||
JSONObject object = new JSONObject();
|
||||
object.put(JsonFields.id_prod_in_depo, resultSet.getInt("id"));
|
||||
object.put(JsonFields.id_product, resultSet.getInt("id_product"));
|
||||
object.put(JsonFields.id_deposit, resultSet.getInt("id_deposit"));
|
||||
object.put(JsonFields.quantity, resultSet.getInt("quantity"));
|
||||
|
||||
listTableProdInDepoJson.put(object);
|
||||
}
|
||||
|
||||
json.put(JsonFields.tableProdInDepo, listTableProdInDepoJson);
|
||||
}
|
||||
|
||||
private void populateListTableProductJson(Statement stmt) throws SQLException {
|
||||
ResultSet resultSet = stmt.executeQuery("SELECT * FROM products");
|
||||
while (resultSet.next()) {
|
||||
JSONObject object = new JSONObject();
|
||||
object.put(JsonFields.id_product, resultSet.getInt("id"));
|
||||
object.put(JsonFields.name, resultSet.getString("name"));
|
||||
|
||||
listTableProductJson.put(object);
|
||||
}
|
||||
|
||||
json.put(JsonFields.tableProducts, listTableProductJson);
|
||||
}
|
||||
|
||||
private void populateListTableRouteJson(Statement stmt) throws SQLException {
|
||||
ResultSet resultSet = stmt.executeQuery("SELECT id FROM routes");
|
||||
while (resultSet.next()) {
|
||||
JSONObject item = new JSONObject();
|
||||
int id_route = resultSet.getInt("id");
|
||||
String fileName = getNameOfFileRoute(Database.getConnection(), id_route, "routes");
|
||||
String path_to_file = "D:\\Server Delivery Planner\\routes\\" + fileName + "_route.txt";
|
||||
StringBuilder content = new StringBuilder();
|
||||
|
||||
try {
|
||||
File myObj = new File(path_to_file);
|
||||
Scanner myReader = new Scanner(myObj);
|
||||
while (myReader.hasNextLine()) {
|
||||
content.append(myReader.nextLine());
|
||||
}
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
|
||||
item.put(JsonFields.id_route, id_route);
|
||||
item.put(JsonFields.route, new JSONObject(content.toString()));
|
||||
listTableRouteJson.put(item);
|
||||
}
|
||||
|
||||
json.put(JsonFields.tableRoutes, listTableRouteJson);
|
||||
}
|
||||
|
||||
private void populateListTableUserJson(Statement stmt) throws SQLException {
|
||||
ResultSet resultSet = stmt.executeQuery("SELECT * FROM users");
|
||||
while (resultSet.next()) {
|
||||
JSONObject object = new JSONObject();
|
||||
object.put(JsonFields.id_user, resultSet.getInt("id"));
|
||||
object.put(JsonFields.name, resultSet.getString("username"));
|
||||
object.put(JsonFields.email, resultSet.getString("email"));
|
||||
object.put(JsonFields.password, resultSet.getString("password"));
|
||||
object.put(JsonFields.lat_coord, resultSet.getString("lat_coord"));
|
||||
object.put(JsonFields.long_coord, resultSet.getString("long_coord"));
|
||||
|
||||
listTableUserJson.put(object);
|
||||
}
|
||||
|
||||
json.put(JsonFields.tableUsers, listTableUserJson);
|
||||
}
|
||||
|
||||
private void populateListTableUserOrderJson(Statement stmt) throws SQLException {
|
||||
ResultSet resultSet = stmt.executeQuery("SELECT * FROM user_orders");
|
||||
while (resultSet.next()) {
|
||||
JSONObject object = new JSONObject();
|
||||
|
||||
object.put(JsonFields.id_user_orders, resultSet.getInt("id"));
|
||||
object.put(JsonFields.id_user, resultSet.getInt("id_user"));
|
||||
object.put(JsonFields.id_order, resultSet.getInt("id_order"));
|
||||
|
||||
listTableUserOrderJson.put(object);
|
||||
}
|
||||
|
||||
json.put(JsonFields.tableUserOrders, listTableUserOrderJson);
|
||||
}
|
||||
|
||||
private static String getNameOfFileRoute(Connection conn, int id, String tableName) throws SQLException {
|
||||
PreparedStatement pstmt = conn.prepareStatement("SELECT path_to_file FROM " + tableName + " WHERE id = ?");
|
||||
pstmt.setInt(1, id);
|
||||
ResultSet resultSet1 = pstmt.executeQuery();
|
||||
resultSet1.next();
|
||||
|
||||
String resultStringToProcess = resultSet1.getString("path_to_file");
|
||||
int left, right = resultStringToProcess.indexOf('_');
|
||||
left = right;
|
||||
|
||||
while (resultStringToProcess.charAt(left) != '\\') {
|
||||
left--;
|
||||
}
|
||||
left++;
|
||||
|
||||
return resultStringToProcess.substring(left, right);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.andreicerbu.items;
|
||||
|
||||
import com.andreicerbu.interfaces.JSONMethods;
|
||||
import com.andreicerbu.json.JsonFields;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class Order extends BaseItem implements JSONMethods {
|
||||
List<ProductForOrder> listOfProducts = new ArrayList<>();
|
||||
JSONArray listOfProductsJSON = new JSONArray();
|
||||
|
||||
public Order(){}
|
||||
|
||||
public Order(Integer id_user){
|
||||
this.id_user = id_user;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void createJSON() {}
|
||||
|
||||
@Override
|
||||
public JSONObject getJSON() {
|
||||
json.put(JsonFields.id_user, id_user);
|
||||
json.put(JsonFields.listOfProducts, listOfProductsJSON);
|
||||
return json;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deserializeJSON(JSONObject json) {
|
||||
id_user = json.getInt(JsonFields.id_user);
|
||||
|
||||
JSONArray listOfProducts = json.getJSONArray(JsonFields.listOfProducts);
|
||||
for(int index = 0; index < listOfProducts.length(); index++){
|
||||
JSONObject product = listOfProducts.getJSONObject(index);
|
||||
|
||||
this.listOfProducts.add(new ProductForOrder(product.getInt(JsonFields.id_product), product.getInt(JsonFields.quantity)));
|
||||
}
|
||||
}
|
||||
|
||||
public List<ProductForOrder> getListOfProducts() {
|
||||
return listOfProducts;
|
||||
}
|
||||
|
||||
public void addProductToOrder(ProductForOrder product){
|
||||
listOfProductsJSON.put(product.getJSON());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.andreicerbu.items;
|
||||
|
||||
import com.andreicerbu.interfaces.JSONMethods;
|
||||
import com.andreicerbu.json.JsonFields;
|
||||
import org.json.JSONObject;
|
||||
|
||||
public class ProductForOrder extends BaseItem implements JSONMethods {
|
||||
public ProductForOrder(Integer id_product, Integer quantity){
|
||||
this.id_product = id_product;
|
||||
this.quantity = quantity;
|
||||
|
||||
createJSON();
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void createJSON() {
|
||||
json.put(JsonFields.id_product, id_product);
|
||||
json.put(JsonFields.quantity, quantity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public JSONObject getJSON() {
|
||||
return json;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deserializeJSON(JSONObject json){
|
||||
this.id_product = json.getInt(JsonFields.id_product);
|
||||
this.quantity = json.getInt(JsonFields.quantity);
|
||||
}
|
||||
|
||||
public String toString(){
|
||||
return id_product + " " + quantity;
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package com.andreicerbu.items.database;
|
||||
|
||||
import com.andreicerbu.items.BaseItem;
|
||||
|
||||
public class TableDeposit extends BaseItem {
|
||||
public TableDeposit(Integer id_deposit, String name, Float lat_coord, Float long_coord){
|
||||
this.id_deposit = id_deposit;
|
||||
this.name = name;
|
||||
this.lat_coord = lat_coord;
|
||||
this.long_coord = long_coord;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.andreicerbu.items.database;
|
||||
|
||||
import com.andreicerbu.items.BaseItem;
|
||||
|
||||
public class TableOrder extends BaseItem {
|
||||
public TableOrder(Integer id_order, String file_name){
|
||||
this.id_order = id_order;
|
||||
this.name = file_name;
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package com.andreicerbu.items.database;
|
||||
|
||||
import com.andreicerbu.items.BaseItem;
|
||||
|
||||
public class TableProdInDepo extends BaseItem {
|
||||
public TableProdInDepo(Integer id_prod_in_depo, Integer id_product, Integer id_deposit, String prod_in_depo_name, Integer quantity){
|
||||
this.id_prod_in_depo = id_prod_in_depo;
|
||||
this.id_product = id_product;
|
||||
this.id_deposit = id_deposit;
|
||||
this.name = prod_in_depo_name;
|
||||
this.quantity = quantity;
|
||||
}
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package com.andreicerbu.items.database;
|
||||
|
||||
import com.andreicerbu.items.BaseItem;
|
||||
|
||||
public class TableProduct extends BaseItem {
|
||||
public TableProduct(Integer id_product, String name){
|
||||
this.id_product = id_product;
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.andreicerbu.items.database;
|
||||
|
||||
import com.andreicerbu.items.BaseItem;
|
||||
|
||||
public class TableRoute extends BaseItem {
|
||||
public TableRoute(Integer id_route, String name, Integer id_order){
|
||||
this.id_route = id_route;
|
||||
this.name = name;
|
||||
this.id_order = id_order;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.andreicerbu.items.database;
|
||||
|
||||
import com.andreicerbu.items.BaseItem;
|
||||
|
||||
public class TableUser extends BaseItem {
|
||||
public TableUser(Integer id_user, String username, String email, String password,
|
||||
Float lat_coord, Float long_coord){
|
||||
this.id_user = id_user;
|
||||
this.name = username;
|
||||
this.email = email;
|
||||
this.password = password;
|
||||
this.lat_coord = lat_coord;
|
||||
this.long_coord = long_coord;
|
||||
}
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
package com.andreicerbu.items.database;
|
||||
|
||||
import com.andreicerbu.items.BaseItem;
|
||||
|
||||
public class TableUserOrder extends BaseItem {
|
||||
public TableUserOrder(Integer id_user_orders, Integer id_user, Integer id_order){
|
||||
this.id_user_orders = id_user_orders;
|
||||
this.id_user = id_user;
|
||||
this.id_order = id_order;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.andreicerbu.json;
|
||||
|
||||
public class JsonFields {
|
||||
public static final String response = "response";
|
||||
public static final String responseSuccess = "success";
|
||||
public static final String responseError = "error";
|
||||
public static final String responseMessage = "message";
|
||||
|
||||
public static final String id_user = "id_user";
|
||||
public static final String id_order = "id_order";
|
||||
public static final String id_deposit = "id_deposit";
|
||||
public static final String id_prod_in_depo = "id_prod_in_depo";
|
||||
public static final String id_product = "id_product";
|
||||
public static final String id_user_orders = "id_user_orders";
|
||||
public static final String id_route = "id_route";
|
||||
|
||||
public static final String quantity = "quantity";
|
||||
public static final String name = "name";
|
||||
public static final String oldName = "oldName";
|
||||
public static final String email = "email";
|
||||
public static final String password = "password";
|
||||
public static final String lat_coord = "lat_coord";
|
||||
public static final String long_coord = "long_coord";
|
||||
public static final String order = "order";
|
||||
public static final String route = "route";
|
||||
public static final String distance = "distance";
|
||||
|
||||
public static final String listOfProducts = "products";
|
||||
public static final String listOfDeposits = "deposits";
|
||||
public static final String listOfValues = "values";
|
||||
|
||||
public static final String destination = "destination";
|
||||
public static final String table = "table";
|
||||
public static final String tableOrders = "orders";
|
||||
public static final String tableDeposits = "deposits";
|
||||
public static final String tableProdInDepo = "prod_in_depo";
|
||||
public static final String tableProducts = "products";
|
||||
public static final String tableRoutes = "routes";
|
||||
public static final String tableUsers = "users";
|
||||
public static final String tableUserOrders = "user_orders";
|
||||
|
||||
public static final String command = "command";
|
||||
public static final String commandGetDatabase = "getDatabase";
|
||||
public static final String commandGetUserDatabase = "userDatabase";
|
||||
public static final String commandInsert = "insert";
|
||||
public static final String commandUpdate = "update";
|
||||
public static final String commandDelete = "delete";
|
||||
public static final String commandRegister = "register";
|
||||
public static final String commandLogin = "login";
|
||||
public static final String commandGetOrders = "getOrders";
|
||||
public static final String commandPlaceOrder = "placeOrder";
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.andreicerbu;
|
||||
|
||||
public class test {
|
||||
public static void main (String[] args){
|
||||
float x1 = 258, y1 = 326; // user
|
||||
|
||||
float x2 = 200, y2 = 320;
|
||||
float x3 = 250, y3 = 280;
|
||||
float x4 = 230, y4 = 310;
|
||||
|
||||
System.out.println(calculateDistance(x1, y1, x2, y2));
|
||||
System.out.println(calculateDistance(x1, y1, x3, y3));
|
||||
System.out.println(calculateDistance(x1, y1, x4, y4));
|
||||
}
|
||||
|
||||
public static float calculateDistance(float x1, float y1, float x2, float y2){
|
||||
return (float) Math.sqrt(
|
||||
Math.pow(x2-x1, 2) + Math.pow(y2-y1, 2)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
<archetype>
|
||||
<id>Server_Delivery_Planner</id>
|
||||
<sources>
|
||||
<source>src/main/java/App.java</source>
|
||||
</sources>
|
||||
<testSources>
|
||||
<source>src/test/java/AppTest.java</source>
|
||||
</testSources>
|
||||
</archetype>
|
||||
@@ -0,0 +1,15 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>$com.andreicerbu.deliveryplanner</groupId>
|
||||
<artifactId>$Server_Delivery_Planner</artifactId>
|
||||
<version>$1.0-SNAPSHOT</version>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>3.8.1</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
@@ -0,0 +1,13 @@
|
||||
package $com.andreicerbu.deliveryplanner;
|
||||
|
||||
/**
|
||||
* Hello world!
|
||||
*
|
||||
*/
|
||||
public class App
|
||||
{
|
||||
public static void main( String[] args )
|
||||
{
|
||||
System.out.println( "Hello World!" );
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package $com.andreicerbu.deliveryplanner;
|
||||
|
||||
import junit.framework.Test;
|
||||
import junit.framework.TestCase;
|
||||
import junit.framework.TestSuite;
|
||||
|
||||
/**
|
||||
* Unit test for simple App.
|
||||
*/
|
||||
public class AppTest
|
||||
extends TestCase
|
||||
{
|
||||
/**
|
||||
* Create the test case
|
||||
*
|
||||
* @param testName name of the test case
|
||||
*/
|
||||
public AppTest( String testName )
|
||||
{
|
||||
super( testName );
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the suite of tests being tested
|
||||
*/
|
||||
public static Test suite()
|
||||
{
|
||||
return new TestSuite( AppTest.class );
|
||||
}
|
||||
|
||||
/**
|
||||
* Rigourous Test :-)
|
||||
*/
|
||||
public void testApp()
|
||||
{
|
||||
assertTrue( true );
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user