From 42d7c8294b8f92eeddd54eeeceb8d9dcbb22768e Mon Sep 17 00:00:00 2001 From: morabba <292.arma@gmail.com> Date: Tue, 14 Jul 2020 18:08:42 +0430 Subject: [PATCH 01/28] Ummm... not good. --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 8826177..2dbb668 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,5 @@ 98110349 Arman Babaei 98101363 M.Taha Jahani-Nezhad 98106072 Ali Mahdavifar + +[Server repo](https://github.com/Arman17Babaei/ProjectServer) From aedf97d5128fb4b97f2d54ba463a7bbf38caf91b Mon Sep 17 00:00:00 2001 From: morabba <292.arma@gmail.com> Date: Sat, 18 Jul 2020 23:20:30 +0430 Subject: [PATCH 02/28] some advances. now the server is updated with client. --- README.md | 2 + .../java/controller/CustomerController.java | 8 +- src/main/java/controller/Database.java | 153 ++++++++++++++---- .../java/controller/ManagerController.java | 4 +- .../java/controller/SellerController.java | 2 +- src/main/java/controller/UserController.java | 10 +- src/main/java/graphics/AddCategoryPage.java | 4 +- src/main/java/graphics/AdditionalInfo.java | 5 +- src/main/java/graphics/ProfilePage.java | 7 +- src/main/java/graphics/PropertyPage.java | 2 +- src/main/java/main/Main.java | 7 +- src/main/java/model/Comment.java | 2 +- src/main/java/model/Discount.java | 2 +- src/main/java/model/Product.java | 4 +- src/main/resources/fxml/MainMenu.fxml | 5 +- 15 files changed, 155 insertions(+), 62 deletions(-) diff --git a/README.md b/README.md index 2dbb668..8d78fec 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,7 @@ 98110349 Arman Babaei + 98101363 M.Taha Jahani-Nezhad + 98106072 Ali Mahdavifar [Server repo](https://github.com/Arman17Babaei/ProjectServer) diff --git a/src/main/java/controller/CustomerController.java b/src/main/java/controller/CustomerController.java index f088c51..e2430c3 100644 --- a/src/main/java/controller/CustomerController.java +++ b/src/main/java/controller/CustomerController.java @@ -16,7 +16,7 @@ public Customer getCustomerLoggedOn() { public CustomerController(Customer user, ProductController productController) { super(user, productController); - this.customerLoggedOn = (Customer) user; + this.customerLoggedOn = user; } public static Customer newDefaultUser() { @@ -30,7 +30,7 @@ private String viewPersonalInfo() { "Phone number: " + customerLoggedOn.getPhoneNumber() + "\n"; } - public void changePersonalInfo(HashMap infoToSet) { + public void changePersonalInfo(HashMap infoToSet) throws Exception { super.changePersonalInfo(infoToSet); } @@ -146,7 +146,7 @@ public long purchase() throws Exception { return totalPrice; } - private void payEachSeller() { + private void payEachSeller() throws Exception { for (Product product : customerLoggedOn.getCart().keySet()) { Seller seller = product.getSellers().get(0); seller.addToCredit(product.getPrice()); @@ -154,7 +154,7 @@ private void payEachSeller() { } } - public void createSellLogForAllProducts() { + public void createSellLogForAllProducts() throws Exception { for (Product product : customerLoggedOn.getCart().keySet()) { SellLog log = product.createSellLog(); log.setCustomer(customerLoggedOn); diff --git a/src/main/java/controller/Database.java b/src/main/java/controller/Database.java index e53539c..48399ee 100644 --- a/src/main/java/controller/Database.java +++ b/src/main/java/controller/Database.java @@ -6,13 +6,15 @@ import com.google.gson.JsonObject; import model.*; -import java.io.File; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; +import java.io.*; +import java.net.HttpURLConnection; +import java.net.URL; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; public class Database { + private static final String USER_AGENT = "Mozilla/5.0"; + private static final String serverUrl = "http://localhost:8888/"; private static final ArrayList allUsers = new ArrayList<>(); private static final ArrayList allProducts = new ArrayList<>(); private static final ArrayList allRequests = new ArrayList<>(); @@ -27,6 +29,8 @@ public class Database { private static final ArrayList allProductAds = new ArrayList<>(); private static final ArrayList allPossibleManagers = new ArrayList<>(); + private static String token = "random-customer"; + public static void loadAllData() { makeDirectories(); loadLists(); @@ -69,7 +73,7 @@ private static void loadLists() { } private static String getPath(String folderName) { - return "Database\\" + folderName + "\\"; + return "Database\\" + folderName + "\\"; } private static String getPath(Object object) { @@ -101,11 +105,89 @@ private static void loadList(ArrayList list, Class cls, Stri } } - static void writeObject(Object object, String id) { + private static JsonObject sendGET(String url, String objectClass, String objectId) throws Exception { + url = serverUrl + url + "?token=" + token + "&className=" + objectClass + "&objectId=" + objectId; + System.out.println(url); + URL obj = new URL(url); + HttpURLConnection con = (HttpURLConnection) obj.openConnection(); + con.setRequestMethod("GET"); + con.setRequestProperty("User-Agent", USER_AGENT); + int responseCode = con.getResponseCode(); + System.out.println("GET Response Code :: " + responseCode); + System.out.println(" Response Body : " + con.getResponseMessage()); + JsonObject convertedObject = getJsonObjectFromReader(con, responseCode); + + token = convertedObject.get("token").getAsString(); + + return convertedObject; + } + + + private static void sendPost(String url, String objectClass, String objectId, Object object) throws Exception { + url = serverUrl + url; + System.out.println(url + objectClass + objectId); + URL obj = new URL(url); + HttpURLConnection con = (HttpURLConnection) obj.openConnection(); + + con.setRequestMethod("POST"); + con.setRequestProperty("Content-Type", "application/json; utf-8"); + con.setRequestProperty("Accept", "application/json"); + con.setRequestProperty("User-Agent", USER_AGENT); + con.setDoOutput(true); + try (OutputStream os = con.getOutputStream()) { + JsonObject jsonObject = new JsonObject(); + jsonObject.addProperty("className", objectClass); + jsonObject.addProperty("objectId", objectId); + jsonObject.addProperty("token", token); + jsonObject.add("object", new Gson().toJsonTree(object).getAsJsonObject()); + String jsonInputString = new Gson().toJson(jsonObject); + byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8); + os.write(input, 0, input.length); + } + int responseCode = con.getResponseCode(); + System.out.println("POST Response Code :: " + responseCode); + System.out.println(" Response Body : " + con.getResponseMessage()); + JsonObject convertedObject = getJsonObjectFromReader(con, responseCode); + + token = convertedObject.get("token").getAsString(); + } + + private static JsonObject getJsonObjectFromReader(HttpURLConnection con, int responseCode) throws Exception { + BufferedReader in; + if (responseCode >= 200 && responseCode < 300) { + in = new BufferedReader(new InputStreamReader(con.getInputStream())); + } else { + in = new BufferedReader(new InputStreamReader(con.getErrorStream())); + String json = getStringFromReader(in); + JsonObject convertedObject = new Gson().fromJson(json, JsonObject.class); + con.disconnect(); + throw new Exception("Network Error: " + convertedObject.get("error").getAsString()); + } + String json = getStringFromReader(in); + con.disconnect(); + return new Gson().fromJson(json, JsonObject.class); + } + + + private static String getStringFromReader(BufferedReader in) throws IOException { + String inputLine; + StringBuilder response = new StringBuilder(); + + while ((inputLine = in.readLine()) != null) { + response.append(inputLine); + } + in.close(); + return response.toString(); + } + + + static void writeObject(Object object, String id) throws Exception { writeObject(object, id, object.getClass().getSimpleName()); } - static void writeObject(Object object, String id, String folderName) { + static void writeObject(Object object, String id, String folderName) throws Exception { + sendPost("resource", folderName, id, object); + String fileName = getPath(folderName) + id + ".json"; FileWriter writer; try { @@ -130,19 +212,19 @@ private static void deleteObject(String id, String folderName) { } } - public static void addPossibleManager(String username) { + public static void addPossibleManager(String username) throws Exception { if (!allPossibleManagers.contains(username)) { allPossibleManagers.add(username); } writeObject(username, username); } - public static void add(User user) { + public static void add(User user) throws Exception { allUsers.add(user); writeObject(user, user.getId()); } - public static void add(Product product) { + public static void add(Product product) throws Exception { for (Product productIn : allProducts) { if (productIn.equals(product.getId())) { allProducts.remove(productIn); @@ -152,42 +234,42 @@ public static void add(Product product) { writeObject(product, product.getId()); } - public static void add(JsonObject request) { + public static void add(JsonObject request) throws Exception { allRequests.add(request); writeObject(request, request.getAsJsonObject().get("id").getAsString()); } - public static void add(Discount discount) { + public static void add(Discount discount) throws Exception { allDiscountCodes.add(discount); writeObject(discount, discount.getId()); } - public static void add(Category category) { + public static void add(Category category) throws Exception { allCategories.add(category); writeObject(category, category.getId()); } - public static void add(Comment comment) { + public static void add(Comment comment) throws Exception { allComments.add(comment); writeObject(comment, comment.getId()); } - public static void add(Property property) { + public static void add(Property property) throws Exception { allProperties.add(property); writeObject(property, property.getId()); } - public static void add(Score score) { + public static void add(Score score) throws Exception { allScores.add(score); writeObject(score, score.getId()); } - public static void add(PurchaseLog log) { + public static void add(PurchaseLog log) throws Exception { allPurchaseLogs.add(log); writeObject(log, log.getId()); } - public static void add (SellLog log) { + public static void add(SellLog log) throws Exception { allSellLogs.add(log); writeObject(log, log.getId()); } @@ -198,7 +280,7 @@ public static void add(Off off) throws Exception { writeObject(off, off.getId()); } - public static void addProductToAds(Product product) { + public static void addProductToAds(Product product) throws Exception { allProductAds.add(product); writeObject(product, product.getId(), "ProductAd"); } @@ -230,19 +312,32 @@ public static void removeProductFromAds(Product product) { } public static Product getProductById(String id) throws Exception { - for (Product product : allProducts) { - if (product.getId().equals(id)) - return product; + try { + System.out.println("get product by id"); + JsonObject jsonObject = sendGET("resource", "Product", id); + return new Gson().fromJson(jsonObject.get("object"), Product.class); + } catch (Exception e) { + e.printStackTrace(); + for (Product product : allProducts) { + if (product.getId().equals(id)) + return product; + } + throw new Exception("product id not found"); } - throw new Exception("product id not found"); } public static User getUserById(String id) { - for (User user : allUsers) { - if (user.getId().equals(id)) - return user; + try { + JsonObject jsonObject = sendGET("resource", "User", id); + return new Gson().fromJson(jsonObject.get("object"), User.class); + } catch (Exception e) { + e.printStackTrace(); + for (User user : allUsers) { + if (user.getId().equals(id)) + return user; + } + return null; } - return null; } public static JsonElement getRequestById(String id) { @@ -310,7 +405,7 @@ public static PurchaseLog getPurchaseLogById(String id) { return null; } - public static SellLog getSellLogById (String id) { + public static SellLog getSellLogById(String id) { for (SellLog log : allSellLogs) { if (log.getId().equals(id)) return log; @@ -402,7 +497,7 @@ public static ArrayList getAllOffs() { return allOffs; } - public static void update(Object object, String id) { + public static void update(Object object, String id) throws Exception { writeObject(object, id); } diff --git a/src/main/java/controller/ManagerController.java b/src/main/java/controller/ManagerController.java index 5405ab8..c3c3129 100644 --- a/src/main/java/controller/ManagerController.java +++ b/src/main/java/controller/ManagerController.java @@ -32,7 +32,7 @@ public void createDiscount(HashMap data) throws Exception { throw new Exception("got a discount code: " + data); } - public void createDiscount(Discount discount) { + public void createDiscount(Discount discount) throws Exception { Database.add(discount); } @@ -176,7 +176,7 @@ public void editCategory(String category, HashMap fields) { // this should change into something functional for adding/removing properties } - public void createCategory(HashMap fields) { + public void createCategory(HashMap fields) throws Exception { // what to do with arguments? Database.add(new Category(fields.get("name"))); } diff --git a/src/main/java/controller/SellerController.java b/src/main/java/controller/SellerController.java index 8f2e72d..a0f7ffd 100644 --- a/src/main/java/controller/SellerController.java +++ b/src/main/java/controller/SellerController.java @@ -84,7 +84,7 @@ public void addProduct(HashMap fields) throws Exception { Database.add(jsonElement.getAsJsonObject()); } - public void addProduct (Product product) { + public void addProduct(Product product) throws Exception { Gson request = new Gson(); JsonElement jsonElement = new JsonObject(); jsonElement.getAsJsonObject().addProperty("requestStatus", "pending"); //pending, accepted, rejected diff --git a/src/main/java/controller/UserController.java b/src/main/java/controller/UserController.java index afd21e9..1b8b182 100644 --- a/src/main/java/controller/UserController.java +++ b/src/main/java/controller/UserController.java @@ -113,19 +113,19 @@ private String getString(String field, User user) { } } - public void changePersonalInfo(String field, String newValue) { + public void changePersonalInfo(String field, String newValue) throws Exception { HashMap hashMap = new HashMap<>(); hashMap.put(field, newValue); changePersonalInfo(hashMap); } - public void changePersonalInfo(String username, String field, String newValue) { + public void changePersonalInfo(String username, String field, String newValue) throws Exception { HashMap hashMap = new HashMap<>(); hashMap.put(field, newValue); changePersonalInfo(username, hashMap); } - public void changePersonalInfo(String username, HashMap infoToSet) { + public void changePersonalInfo(String username, HashMap infoToSet) throws Exception { User user = Database.getUserByUsername(username); for (String info : infoToSet.keySet()) { String value = infoToSet.get(info); @@ -168,7 +168,7 @@ public void changePersonalInfo(String username, HashMap infoToSe Database.writeObject(user, user.getId()); } - public void changePersonalInfo(HashMap infoToSet) { + public void changePersonalInfo(HashMap infoToSet) throws Exception { for (String info : infoToSet.keySet()) { String value = infoToSet.get(info); switch (info) { @@ -210,7 +210,7 @@ public void changePersonalInfo(HashMap infoToSet) { Database.writeObject(userLoggedOn, userLoggedOn.getId()); } - public void addReview(String title, String text) { + public void addReview(String title, String text) throws Exception { Comment thisComment = new Comment(null, this.userLoggedOn, productController.getCurrentProduct(), title, text); diff --git a/src/main/java/graphics/AddCategoryPage.java b/src/main/java/graphics/AddCategoryPage.java index cee5aca..49029f5 100644 --- a/src/main/java/graphics/AddCategoryPage.java +++ b/src/main/java/graphics/AddCategoryPage.java @@ -119,7 +119,7 @@ public void newPropertyPressed(ActionEvent actionEvent) throws IOException { Main.popupStage.show(); } - public void submitPressed(ActionEvent actionEvent) throws IOException { + public void submitPressed(ActionEvent actionEvent) throws Exception { if (category.getName() == null) { category.setName(name.getText()); Database.add(category); @@ -134,7 +134,7 @@ public void submitPressed(ActionEvent actionEvent) throws IOException { Main.setMainStage("Manage Categories", "src/main/resources/fxml/ManageCategories.fxml"); } - public void addProperty(String name, String type) { + public void addProperty(String name, String type) throws Exception { Property property = new Property(); property.setNumber(type.equals("Integer")); property.setName(name); diff --git a/src/main/java/graphics/AdditionalInfo.java b/src/main/java/graphics/AdditionalInfo.java index 9234b28..9b150b2 100644 --- a/src/main/java/graphics/AdditionalInfo.java +++ b/src/main/java/graphics/AdditionalInfo.java @@ -11,7 +11,6 @@ import main.Main; import java.io.File; -import java.net.MalformedURLException; import java.util.HashMap; public class AdditionalInfo { @@ -23,7 +22,7 @@ public class AdditionalInfo { private FileChooser fileChooser = new FileChooser(); - public void submitButtonPressed(ActionEvent actionEvent) { + public void submitButtonPressed(ActionEvent actionEvent) throws Exception { HashMap data = new HashMap<>(); data.put("email", email.getText()); data.put("gender", gender.getValue().toString()); @@ -33,7 +32,7 @@ public void submitButtonPressed(ActionEvent actionEvent) { Main.popupStage.close(); } - public void chooseProfilePicture(ActionEvent actionEvent) throws MalformedURLException { + public void chooseProfilePicture(ActionEvent actionEvent) throws Exception { fileChooser.setTitle("Choose new profile picture..."); fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("Image Files", "*.png", "*.jpg", "*.gif")); File selectedFile = fileChooser.showOpenDialog(Main.popupStage); diff --git a/src/main/java/graphics/ProfilePage.java b/src/main/java/graphics/ProfilePage.java index 3743db2..0aeca46 100644 --- a/src/main/java/graphics/ProfilePage.java +++ b/src/main/java/graphics/ProfilePage.java @@ -3,8 +3,6 @@ import com.jfoenix.controls.JFXButton; import com.jfoenix.controls.JFXComboBox; import com.jfoenix.controls.JFXDatePicker; -import controller.CustomerController; -import controller.SellerController; import javafx.event.ActionEvent; import javafx.scene.control.TextInputControl; import javafx.scene.image.Image; @@ -15,7 +13,6 @@ import java.io.File; import java.io.IOException; -import java.net.MalformedURLException; import java.time.LocalDate; public class ProfilePage { @@ -79,7 +76,7 @@ public void initialize() { } } - public void chooseProfilePicture(ActionEvent actionEvent) throws MalformedURLException { + public void chooseProfilePicture(ActionEvent actionEvent) throws Exception { fileChooser.setTitle("Choose new profile picture..."); fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("Image Files", "*.png", "*.jpg", "*.gif")); File selectedFile = fileChooser.showOpenDialog(Main.popupStage); @@ -92,7 +89,7 @@ public void chooseProfilePicture(ActionEvent actionEvent) throws MalformedURLExc } } - public void propertyChanged(ActionEvent actionEvent) { + public void propertyChanged(ActionEvent actionEvent) throws Exception { switch (actionEvent.getSource().getClass().getName()) { case "com.jfoenix.controls.JFXDatePicker": System.out.println(((JFXDatePicker) actionEvent.getSource()).getValue().toString()); diff --git a/src/main/java/graphics/PropertyPage.java b/src/main/java/graphics/PropertyPage.java index c5b54c8..1c09600 100644 --- a/src/main/java/graphics/PropertyPage.java +++ b/src/main/java/graphics/PropertyPage.java @@ -11,7 +11,7 @@ public class PropertyPage { public AddCategoryPage categoryPage; - public void submitPressed(ActionEvent actionEvent) { + public void submitPressed(ActionEvent actionEvent) throws Exception { categoryPage.addProperty(name.getText(), type.getValue().toString()); Main.popupStage.close(); } diff --git a/src/main/java/main/Main.java b/src/main/java/main/Main.java index 325bb8d..3c7e364 100644 --- a/src/main/java/main/Main.java +++ b/src/main/java/main/Main.java @@ -14,7 +14,6 @@ import javafx.util.Duration; import model.Customer; import model.Discount; -import model.Seller; import view.Menu; import view.userstuff.RegisterLoginMenu; @@ -72,7 +71,11 @@ private static void makeRandomDiscounts() { discount.setRepetitionNumber(1); discount.addUser(Database.getAllUsers().get(userIndex)); System.out.println(Database.getAllUsers().get(userIndex).getUsername()); - Database.add(discount); + try { + Database.add(discount); + } catch (Exception e) { + e.printStackTrace(); + } } }); diff --git a/src/main/java/model/Comment.java b/src/main/java/model/Comment.java index cb615db..5ebb1b6 100644 --- a/src/main/java/model/Comment.java +++ b/src/main/java/model/Comment.java @@ -79,7 +79,7 @@ public LocalDate getDate() { return time; } - public void addChild(Comment comment) { + public void addChild(Comment comment) throws Exception { childern.add(comment.getId()); Database.update(this, getId()); } diff --git a/src/main/java/model/Discount.java b/src/main/java/model/Discount.java index 2b9aa99..19c7be6 100644 --- a/src/main/java/model/Discount.java +++ b/src/main/java/model/Discount.java @@ -135,7 +135,7 @@ public static String generateRandomCode () { return String.valueOf(randomCode); } - public static Discount getGiftDiscount (Customer customer, int percent) { + public static Discount getGiftDiscount(Customer customer, int percent) throws Exception { Discount discount = new Discount(); discount.addUser(customer); discount.setRepetitionNumber(1); diff --git a/src/main/java/model/Product.java b/src/main/java/model/Product.java index 87ed2c4..5b29676 100644 --- a/src/main/java/model/Product.java +++ b/src/main/java/model/Product.java @@ -192,7 +192,7 @@ public ObservableList getAllSpecialProperties() { return result; } - public void setCategory(Category category) { + public void setCategory(Category category) throws Exception { this.category = category.getId(); allSpecialProperties = new ArrayList<>(); for (Property property : category.getSpecialProperties()) { @@ -328,7 +328,7 @@ public boolean hasOff() { return false; } - public SellLog createSellLog() { + public SellLog createSellLog() throws Exception { SellLog log = new SellLog(); log.setSoldProduct(this); log.setDate(LocalDateTime.now()); diff --git a/src/main/resources/fxml/MainMenu.fxml b/src/main/resources/fxml/MainMenu.fxml index 6ca5874..ddf4773 100644 --- a/src/main/resources/fxml/MainMenu.fxml +++ b/src/main/resources/fxml/MainMenu.fxml @@ -1,15 +1,12 @@ - - - @@ -23,7 +20,7 @@ - + From 9f37ea46828b1afb9b93892ceec349f81c60ea14 Mon Sep 17 00:00:00 2001 From: morabba <292.arma@gmail.com> Date: Sun, 19 Jul 2020 21:56:09 +0430 Subject: [PATCH 03/28] login and logout added. --- src/main/java/controller/Database.java | 54 +++++++++++++++++++- src/main/java/controller/UserController.java | 4 +- 2 files changed, 56 insertions(+), 2 deletions(-) diff --git a/src/main/java/controller/Database.java b/src/main/java/controller/Database.java index 48399ee..0918050 100644 --- a/src/main/java/controller/Database.java +++ b/src/main/java/controller/Database.java @@ -329,7 +329,7 @@ public static Product getProductById(String id) throws Exception { public static User getUserById(String id) { try { JsonObject jsonObject = sendGET("resource", "User", id); - return new Gson().fromJson(jsonObject.get("object"), User.class); + return (User) new Gson().fromJson(jsonObject.get("object"), Class.forName("model." + jsonObject.get("className").getAsString())); } catch (Exception e) { e.printStackTrace(); for (User user : allUsers) { @@ -508,4 +508,56 @@ public static void remove(Category category) { allCategories.remove(category); deleteObject(category, category.getId()); } + + public static void login(String username, String password) throws Exception { + String url = serverUrl + "login"; + URL obj = new URL(url); + HttpURLConnection con = (HttpURLConnection) obj.openConnection(); + String urlParameters = "username=" + username + "&password=" + password; + byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8); + int postDataLength = postData.length; + con.setDoOutput(true); + con.setInstanceFollowRedirects(false); + con.setRequestMethod("POST"); + con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); + con.setRequestProperty("charset", "utf-8"); + con.setRequestProperty("Content-Length", Integer.toString(postDataLength)); + con.setUseCaches(false); + try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) { + wr.write(postData); + } + + int responseCode = con.getResponseCode(); + System.out.println("POST Response Code :: " + responseCode); + System.out.println(" Response Body : " + con.getResponseMessage()); + JsonObject convertedObject = getJsonObjectFromReader(con, responseCode); + + token = convertedObject.get("token").getAsString(); + } + + public static void logout() throws Exception { + String url = serverUrl + "logout"; + URL obj = new URL(url); + HttpURLConnection con = (HttpURLConnection) obj.openConnection(); + String urlParameters = "token=" + token; + byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8); + int postDataLength = postData.length; + con.setDoOutput(true); + con.setInstanceFollowRedirects(false); + con.setRequestMethod("DELETE"); + con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); + con.setRequestProperty("charset", "utf-8"); + con.setRequestProperty("Content-Length", Integer.toString(postDataLength)); + con.setUseCaches(false); + try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) { + wr.write(postData); + } + + int responseCode = con.getResponseCode(); + System.out.println("POST Response Code :: " + responseCode); + System.out.println(" Response Body : " + con.getResponseMessage()); + JsonObject convertedObject = getJsonObjectFromReader(con, responseCode); + + token = "random-customer"; + } } diff --git a/src/main/java/controller/UserController.java b/src/main/java/controller/UserController.java index 1b8b182..7c4975c 100644 --- a/src/main/java/controller/UserController.java +++ b/src/main/java/controller/UserController.java @@ -19,6 +19,7 @@ public UserController(User userLoggedOn, ProductController productController) { } public void loginUser(String username, String password) throws Exception { + Database.login(username, password); User thisUser = Database.getUserByUsername(username); if (thisUser == null) throw new UserNotFoundException(); @@ -229,7 +230,8 @@ public boolean canBeManager(String username) { return Database.getAllPossibleManagers().contains(username); } - public void logout() { + public void logout() throws Exception { + Database.logout(); userLoggedOn = CustomerController.newDefaultUser(); } From 258b754bdbe80f48995ecd8d632174c95a1ef283 Mon Sep 17 00:00:00 2001 From: TahaJahani Date: Wed, 22 Jul 2020 07:18:30 +0430 Subject: [PATCH 04/28] primary payment method added --- .../java/controller/CustomerController.java | 69 +++++++++++++++---- src/main/java/controller/Database.java | 10 ++- src/main/java/graphics/PaymentPage.java | 21 +++++- src/main/java/model/Customer.java | 11 ++- src/main/java/model/Manager.java | 2 + src/main/java/model/Seller.java | 4 ++ src/main/java/model/User.java | 30 ++++++++ src/main/resources/fxml/PaymentPage.fxml | 5 ++ 8 files changed, 131 insertions(+), 21 deletions(-) diff --git a/src/main/java/controller/CustomerController.java b/src/main/java/controller/CustomerController.java index e2430c3..72fa831 100644 --- a/src/main/java/controller/CustomerController.java +++ b/src/main/java/controller/CustomerController.java @@ -1,12 +1,17 @@ package controller; +import com.google.gson.JsonObject; import model.*; import model.exception.DefaultUser; +import java.net.HttpURLConnection; +import java.net.URL; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.HashMap; +import static controller.Database.getJsonObjectFromReader; + public class CustomerController extends UserController { private Customer customerLoggedOn; @@ -40,7 +45,7 @@ public void addAddress(HashMap information) { public String getPaymentCheck() { try { - long totalPrice = purchase(); + long totalPrice = purchase("e-wallet"); return "Succesfully purchased\n" + "Total price: " + totalPrice + "\n" + "Your current credit: " + customerLoggedOn.getCredit(); @@ -49,7 +54,7 @@ public String getPaymentCheck() { } } - public String viewCartProducts() throws Exception { + public String viewCartProducts() { StringBuilder stringToReturn = new StringBuilder(); stringToReturn.append("Product ID\tProduct name\tUnit price\tNumber\n"); HashMap customerCart = customerLoggedOn.getCart(); @@ -101,7 +106,7 @@ public void decreaseNumberOfProduct(String productId) { removeFromCart(productId); } - public long getTotalPrice() throws Exception { + public long getTotalPrice() { long totalPrice = 0; for (Product product : customerLoggedOn.getCart().keySet()) { totalPrice += product.getPrice() * customerLoggedOn.getCart().get(product); @@ -111,6 +116,14 @@ public long getTotalPrice() throws Exception { return totalPrice; } + public long getProductPrice (Product product) { + long totalPrice = 0; + totalPrice += product.getPrice() * customerLoggedOn.getCart().get(product); + if (customerLoggedOn.getDiscountUsed() != null) + totalPrice *= (double) (100 - customerLoggedOn.getDiscountUsed().getDiscountPercent()) / 100; + return totalPrice; + } + public boolean validateDiscountCode(String code) { Discount discount = Database.getDiscountByCode(code); if (discount != null) { @@ -131,13 +144,14 @@ public void removeDiscountCode () { customerLoggedOn.undoUseDiscount(); } - public long purchase() throws Exception { + public long purchase(String method) throws Exception { long totalPrice = getTotalPrice(); - customerLoggedOn.payCredit(totalPrice); + payEachSeller(method); + //creating log PurchaseLog newLog = createPurchaseLog(); createSellLogForAllProducts(); - payEachSeller(); customerLoggedOn.deleteDiscount(); + //should be changed? Database.add(newLog); customerLoggedOn.addToPurchaseHistory(newLog); this.addCustomerToProducts(); @@ -146,14 +160,45 @@ public long purchase() throws Exception { return totalPrice; } - private void payEachSeller() throws Exception { + private void payEachSeller(String method) throws Exception { for (Product product : customerLoggedOn.getCart().keySet()) { - Seller seller = product.getSellers().get(0); - seller.addToCredit(product.getPrice()); - Database.update(seller, seller.getId()); + String destId = product.getSellers().get(0).getId(); + String reply; + if (method.equalsIgnoreCase("e-wallet")) + reply = sendCreditPaymentRequest(getProductPrice(product), destId); + else + reply = sendBankPaymentRequest(getProductPrice(product), destId); + System.out.println(product.getName() + ": " + reply); } } + private String sendBankPaymentRequest(long productPrice, String destId) throws Exception { + String url = Database.getServerUrl() + "/paySellerByBankAccount" + "?username=" + userLoggedOn.getUsername() + + "&password=" + userLoggedOn.getPassword() + "&money=" + productPrice + "&sourceId=" + + userLoggedOn.getBankAccountId() + "&destId=" + destId; + return sendRequestToServer(url); + } + + private String sendRequestToServer(String url) throws Exception { + System.out.println(url); + URL obj = new URL(url); + HttpURLConnection con = (HttpURLConnection) obj.openConnection(); + con.setRequestMethod("GET"); + con.setRequestProperty("User-Agent", Database.getUserAgent()); + int responseCode = con.getResponseCode(); + System.out.println("GET Response Code :: " + responseCode); + System.out.println(" Response Body : " + con.getResponseMessage()); + JsonObject convertedObject = getJsonObjectFromReader(con, responseCode); + + return convertedObject.get("reply").getAsString(); + } + + private String sendCreditPaymentRequest(long productPrice, String destId) throws Exception { + String url = Database.getServerUrl() + "/paySellerCredit" + "?sourceId=" + userLoggedOn.getId() + + "&money=" + productPrice + "&destId=" + destId; + return sendRequestToServer(url); + } + public void createSellLogForAllProducts() throws Exception { for (Product product : customerLoggedOn.getCart().keySet()) { SellLog log = product.createSellLog(); @@ -163,13 +208,13 @@ public void createSellLogForAllProducts() throws Exception { } } - public void addCustomerToProducts() throws Exception { + public void addCustomerToProducts() { for (Product product : this.customerLoggedOn.getCart().keySet()) { product.addBuyer(this.customerLoggedOn); } } - private PurchaseLog createPurchaseLog() throws Exception { + private PurchaseLog createPurchaseLog() { PurchaseLog log = new PurchaseLog(); log.setDate(LocalDateTime.now()); log.setAmountPaid(getTotalPrice()); diff --git a/src/main/java/controller/Database.java b/src/main/java/controller/Database.java index 0918050..0cc247f 100644 --- a/src/main/java/controller/Database.java +++ b/src/main/java/controller/Database.java @@ -152,7 +152,7 @@ private static void sendPost(String url, String objectClass, String objectId, Ob token = convertedObject.get("token").getAsString(); } - private static JsonObject getJsonObjectFromReader(HttpURLConnection con, int responseCode) throws Exception { + public static JsonObject getJsonObjectFromReader(HttpURLConnection con, int responseCode) throws Exception { BufferedReader in; if (responseCode >= 200 && responseCode < 300) { in = new BufferedReader(new InputStreamReader(con.getInputStream())); @@ -493,6 +493,14 @@ public static ArrayList getAllSellLogs() { return allSellLogs; } + public static String getServerUrl() { + return serverUrl; + } + + public static String getUserAgent() { + return USER_AGENT; + } + public static ArrayList getAllOffs() { return allOffs; } diff --git a/src/main/java/graphics/PaymentPage.java b/src/main/java/graphics/PaymentPage.java index 3b2c983..77939e6 100644 --- a/src/main/java/graphics/PaymentPage.java +++ b/src/main/java/graphics/PaymentPage.java @@ -1,6 +1,7 @@ package graphics; import com.jfoenix.controls.JFXButton; +import com.jfoenix.controls.JFXRadioButton; import com.jfoenix.controls.JFXTextArea; import com.jfoenix.controls.JFXTextField; import controller.CustomerController; @@ -13,6 +14,8 @@ import javafx.scene.control.Alert; import javafx.scene.control.ButtonType; import javafx.scene.control.Label; +import javafx.scene.control.ToggleGroup; +import javafx.scene.paint.Color; import javafx.stage.Modality; import javafx.stage.Stage; import main.Main; @@ -31,6 +34,10 @@ public class PaymentPage { public Label totalPriceLabel; public JFXButton payButton; private CustomerController controller; + public JFXRadioButton bankButton; + public JFXRadioButton walletButton; + private ToggleGroup radioGroup = new ToggleGroup(); + private String paymentMethod = "e-wallet"; public void show(CustomerController controller) throws Exception { URL url = new File("src/main/resources/fxml/PaymentPage.fxml").toURI().toURL(); @@ -43,6 +50,14 @@ public void show(CustomerController controller) throws Exception { Main.popupStage.show(); ((PaymentPage)fxmlLoader.getController()).refresh(); ((PaymentPage) fxmlLoader.getController()).checkAddress(); + ((PaymentPage) fxmlLoader.getController()).toggleButtons(); + } + + private void toggleButtons() { + walletButton.setToggleGroup(radioGroup); + bankButton.setToggleGroup(radioGroup); + bankButton.setSelectedColor(Color.rgb(177, 66, 255)); + walletButton.setSelectedColor(Color.rgb(177, 66, 255)); } private void checkAddress() throws Exception { @@ -85,7 +100,7 @@ private void refresh() { } public void finishPayment(ActionEvent actionEvent) throws Exception { - long totalPrice = controller.purchase(); + long totalPrice = controller.purchase(paymentMethod); Discount gift; if (totalPrice >= 5100 && totalPrice <= 10000) { gift = Discount.getGiftDiscount(controller.getCustomerLoggedOn(), (int) ((totalPrice - 5000)/100)); @@ -108,4 +123,8 @@ private void showGiftMessage(Discount discount) { "Code: " + discount.getCode()); message.showAndWait(); } + + public void updatePaymentMethod(ActionEvent actionEvent) { + paymentMethod = ((JFXRadioButton)radioGroup.getSelectedToggle()).getText(); + } } diff --git a/src/main/java/model/Customer.java b/src/main/java/model/Customer.java index ce7f5bd..b71dc60 100644 --- a/src/main/java/model/Customer.java +++ b/src/main/java/model/Customer.java @@ -14,6 +14,10 @@ public class Customer extends User { public Customer(String username, String name, String surname, String email, String phoneNumber, String password, long credit) { super(username, name, surname, email, phoneNumber, password, credit); + try { + this.bankAccountId = createBankAccount(); + } catch (Exception ignored) { + } } @Override @@ -117,13 +121,6 @@ public int getProductInCart(String productId) { return 0; } - public void payCredit(long cost) throws Exception { - if (this.credit >= cost) - this.setCredit(this.getCredit() - cost); - else - throw new Exception("Not enough credit"); - } - public ArrayList getPurchaseHistory() { ArrayList purchaseLogs = new ArrayList<>(); for (String log : this.purchaseHistory) { diff --git a/src/main/java/model/Manager.java b/src/main/java/model/Manager.java index ee0f62f..2341c7c 100644 --- a/src/main/java/model/Manager.java +++ b/src/main/java/model/Manager.java @@ -1,5 +1,7 @@ package model; +import controller.Database; + public class Manager extends User { public Manager(String username, String name, String surname, String email, String phoneNumber, String password, long credit) { super(username, name, surname, email, phoneNumber, password, credit); diff --git a/src/main/java/model/Seller.java b/src/main/java/model/Seller.java index 8e976c0..970f74e 100644 --- a/src/main/java/model/Seller.java +++ b/src/main/java/model/Seller.java @@ -15,6 +15,10 @@ public Seller(String username, String name, String surname, String email, String super(username, name, surname, email, phoneNumber, password, credit); this.companyName = companyName; this.companyInfo = companyInfo; + try { + this.bankAccountId = createBankAccount(); + } catch (Exception ignored) { + } } public String getCompanyName() { diff --git a/src/main/java/model/User.java b/src/main/java/model/User.java index c114b98..ea4727e 100644 --- a/src/main/java/model/User.java +++ b/src/main/java/model/User.java @@ -1,8 +1,17 @@ package model; +import com.google.gson.JsonObject; +import controller.Database; + import java.io.File; +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; import java.util.UUID; +import static controller.Database.getJsonObjectFromReader; + public abstract class User { protected String username; protected String name; @@ -11,6 +20,7 @@ public abstract class User { protected String phoneNumber; protected String password; protected long credit; + protected String bankAccountId; protected String id; protected String birthDate = "2007-12-03"; protected String gender = "Prefer not to say"; @@ -61,10 +71,30 @@ public User(String username, String name, String surname, String email, String p this.id = UUID.randomUUID().toString(); } + protected String createBankAccount () throws Exception { + String url = Database.getServerUrl() + "/createBankAccount" + "?firstName=" + this.name + + "&lastName=" + this.surname + "&username=" + this.username + "&password=" + this.password; + System.out.println(url); + URL obj = new URL(url); + HttpURLConnection con = (HttpURLConnection) obj.openConnection(); + con.setRequestMethod("GET"); + con.setRequestProperty("User-Agent", Database.getUserAgent()); + int responseCode = con.getResponseCode(); + System.out.println("GET Response Code :: " + responseCode); + System.out.println(" Response Body : " + con.getResponseMessage()); + JsonObject convertedObject = getJsonObjectFromReader(con, responseCode); + + return convertedObject.get("accountId").getAsString(); + } + public String getId() { return id; } + public String getBankAccountId() { + return bankAccountId; + } + public String getEmail() { return email; } diff --git a/src/main/resources/fxml/PaymentPage.fxml b/src/main/resources/fxml/PaymentPage.fxml index ac051b3..e987fa2 100644 --- a/src/main/resources/fxml/PaymentPage.fxml +++ b/src/main/resources/fxml/PaymentPage.fxml @@ -27,6 +27,11 @@