diff --git a/src/Client/src/main/java/greenify/client/Friend.java b/src/Client/src/main/java/greenify/client/Friend.java new file mode 100644 index 0000000..5612f79 --- /dev/null +++ b/src/Client/src/main/java/greenify/client/Friend.java @@ -0,0 +1,32 @@ +package greenify.client; + +import javafx.beans.property.SimpleFloatProperty; +import javafx.beans.property.SimpleStringProperty; + +public class Friend { + + private SimpleStringProperty friend; + private SimpleFloatProperty score; + + public Friend(String friend, Float friendScore) { + this.friend = new SimpleStringProperty(friend); + this.score = new SimpleFloatProperty(friendScore); + } + + + public String getFriend() { + return friend.get(); + } + + public void setFriend(String name) { + this.friend = new SimpleStringProperty(name); + } + + public Float getScore() { + return score.get(); + } + + public void setScore(Float score) { + this.score = new SimpleFloatProperty(score); + } +} diff --git a/src/Client/src/main/java/greenify/client/Hints.java b/src/Client/src/main/java/greenify/client/Hints.java new file mode 100644 index 0000000..5130954 --- /dev/null +++ b/src/Client/src/main/java/greenify/client/Hints.java @@ -0,0 +1,68 @@ +package greenify.client; + +import java.util.ArrayList; +import java.util.Random; + +public class Hints { + public ArrayList hints; + + public Hints() { + this.hints = new ArrayList(); + initHints(); + } + + /** + * This method adds all the Strings to the arraylist. + */ + private void initHints() { + hints.add("Buying local produce will not only decrease your carbon " + + "footprint, but also help your local economy: A win-win!"); + hints.add("Did you know that a gas oven only uses 6% of its energy " + + "to cook? And an electric oven is not much better at 12%."); + hints.add("70% of the deforestation of the Amazon is to provide land for cattle ranches."); + hints.add("Research shows that reducing meat consumption can increase" + + " your life span by 3.6 years"); + hints.add("Vegetarians have a lower risk of getting heart disease, high blood pressure, " + + "diabetes and cancer than meat eaters."); + hints.add("Did you know? The carbon footprint of a vegetarian diet is about half " + + "that of a meat-lover’s diet!"); + hints.add("Cycling is good for the environment AND for your body, " + + "so why not grab your bike instead of your car?"); + hints.add("If we could capture all of the sun’s energy shining on the Earth for just one " + + "hour, we could power the entire world for one year!"); + hints.add("27,000 trees are cut down each day so we can have toilet paper."); + hints.add("A glass bottle made in our time will take more than 4,000 years to decompose."); + hints.add("Don't forget to turn off the lights and heating in rooms" + + " you're not using at the moment!"); + hints.add("Did you know that about 4.5% of the Dutch population does not eat meat"); + hints.add("Reuse your bags when you go grocery shopping. You will save plastic bags."); + hints.add("An estimated 250 million trees can be save each year " + + "if every published newspaper is recycled."); + hints.add("About 88,000 jobs were created in 2015 through the wind power sector."); + hints.add("You can use LED lights in your home to safe energy!"); + hints.add("If you isolate your home well, it will be warmer " + + "and you'll save energy as well!"); + hints.add("Do you have leftovers? Donate them to food kitchens. This way you won't waste " + + "food and help people at the same time."); + hints.add("A lot of coffee places give you a discount if you bring your own cup. " + + "Get rid of those disposable cups!"); + hints.add("When shopping, look for products with minimal to no packaging, " + + "or at least packaging made from recycled items. "); + hints.add("If you order food, you can ask the restaurant to not include " + + "utensils and napkins, it saves plastic and paper."); + hints.add("It takes about 66 days to form a new habit, keep going!"); + hints.add("Get yourself a nice reusable water bottle! It's cheaper and better for " + + "the environment to refill than to buy a new one every time it's empty."); + } + + /** + * This method gets a random hint from the list of hints. + * @return the random hint. + */ + public String randomHint() { + Random rand = new Random(); + int index = rand.nextInt(hints.size()); + return hints.get(index); + } + +} diff --git a/src/Client/src/main/java/greenify/client/controller/DashBoardController.java b/src/Client/src/main/java/greenify/client/controller/DashBoardController.java index 6355b03..471e8d4 100644 --- a/src/Client/src/main/java/greenify/client/controller/DashBoardController.java +++ b/src/Client/src/main/java/greenify/client/controller/DashBoardController.java @@ -2,17 +2,25 @@ package greenify.client.controller; import com.sun.javafx.scene.control.skin.ButtonSkin; import greenify.client.Application; +import greenify.client.Friend; import greenify.client.rest.UserService; import javafx.animation.FadeTransition; import javafx.animation.PathTransition; import javafx.animation.ScaleTransition; +import javafx.collections.FXCollections; +import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; +import javafx.scene.chart.PieChart; import javafx.scene.control.Button; +import javafx.scene.control.CheckBox; import javafx.scene.control.Label; +import javafx.scene.control.TableColumn; +import javafx.scene.control.TableView; +import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.image.ImageView; import javafx.scene.layout.AnchorPane; import javafx.scene.shape.Line; @@ -22,6 +30,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import java.io.IOException; +import java.util.List; import java.util.Map; /** @@ -29,6 +38,11 @@ import java.util.Map; */ @Controller public class DashBoardController { + public static ObservableList data = FXCollections.observableArrayList(); + public ObservableList friendLeaderData = FXCollections.observableArrayList(); + public ObservableList globalLeaderData = FXCollections.observableArrayList(); + public ObservableList developmentData = FXCollections.observableArrayList(); + @Autowired UserService userService; @@ -57,18 +71,110 @@ public class DashBoardController { @FXML private AnchorPane menuBar; @FXML - private Button addNewActivityButton; - @FXML private Button calculateFootPrintButton; @FXML private Label footprintLabel; @FXML + private Label firstFootprintLabel; + @FXML + private Label differenceLabel; + @FXML + private Button addFriendButton; + @FXML + private TableView friendsTable; + @FXML + private TableColumn friendsColumn; + @FXML + private TableColumn scoreColumn; + @FXML + private TableView globalLeaderboard; + @FXML + private TableColumn globalUser; + @FXML + private TableColumn globalScore; + @FXML + private TableView developmentLeaderboard; + @FXML + private TableColumn developmentUser; + @FXML + private TableColumn developmentScore; + @FXML + private TableView friendLeaderboard; + @FXML + private TableColumn friendUser; + @FXML + private TableColumn friendScore; + @FXML + private PieChart pieChart; + @FXML + private Label usernameLabel; + @FXML + private Label peopleNumber; + @FXML + private Label income; + @FXML + private Label electricityUsage; + @FXML + private Label cleanEnergy; + @FXML + private Label naturalGasUsage; + @FXML + private Label heatingOilUsage; + @FXML + private Label waterUsage; + @FXML + private Label livingSpace; + @FXML + private Label gasolineMiles; + @FXML + private Label gasolineMpg; + @FXML + private Label dieselMiles; + @FXML + private Label dieselMpg; + @FXML + private Label electricMiles; + @FXML + private Label electricMpg; + @FXML + private Label publicTransportation; + @FXML + private Label airPlane; + @FXML + private Label goodShopping; + @FXML + private Label serviceShopping; + @FXML + private Label meat; + @FXML + private Label grains; + @FXML + private Label dairy; + @FXML + private Label fruits; + @FXML + private Label snacks; + @FXML private ImageView achiev1image; + @FXML + private CheckBox localProduce; + @FXML + private CheckBox loweringTemp; + @FXML + private CheckBox bike; + @FXML + private CheckBox solarPanels; /** * Loads the the necessary things before anything else. + * @throws InterruptedException exception if interrupted */ - public void initialize() { + public void initialize() throws InterruptedException { + //set the dashboardPane to visible + dashboardPane.setVisible(true); + userPane.setVisible(false); + activitiesPane.setVisible(false); + friendsPane.setVisible(false); //sets the text of the 'welcome back' text to include the username welcomebacktext.setText("Welcome back, " + userService.currentUser.getName() + "!"); //adds the slide transition to the menu bar @@ -78,15 +184,92 @@ public class DashBoardController { activitiesButton.setSkin(new MyButtonSkin(activitiesButton)); userButton.setSkin(new MyButtonSkin(userButton)); friendsButton.setSkin(new MyButtonSkin(friendsButton)); + friendsColumn.setCellValueFactory(new PropertyValueFactory<>("Friend")); + scoreColumn.setCellValueFactory(new PropertyValueFactory<>("Score")); + globalUser.setCellValueFactory(new PropertyValueFactory<>("Friend")); + globalScore.setCellValueFactory(new PropertyValueFactory<>("Score")); + developmentUser.setCellValueFactory(new PropertyValueFactory<>("Friend")); + developmentScore.setCellValueFactory(new PropertyValueFactory<>("Score")); + friendUser.setCellValueFactory(new PropertyValueFactory<>("Friend")); + friendScore.setCellValueFactory(new PropertyValueFactory<>("Score")); + if (pieChart != null) { + ObservableList pieChartData = + FXCollections.observableArrayList( + new PieChart.Data("Vegan Meal", 100), + new PieChart.Data("Public Transport", 200), + new PieChart.Data("Home Temperature", 50), + new PieChart.Data("Bike", 75), + new PieChart.Data("Local Product", 110), + new PieChart.Data("Solar Panel", 300) + ); + pieChart.setTitle("FOOTPRINT DISTRIBUTION"); + pieChart.setMaxSize(1000, 1000); + pieChart.setData(pieChartData); + } + List friendList = userService.getFriendNames(userService.currentUser.getName()); + for (int i = 0; i < friendList.size(); i++) { + Friend friend = new Friend(friendList.get(i), + userService.getFootprint(friendList.get(i))); + data.add(friend); + } + friendsTable.setItems(data); + updateLeaderboard(); updateAchievements(); } + /** + * Sorts the scores of users. + * @param users the list of users + */ + public void sortScores(List users) throws InterruptedException { + for (int i = 0; i < users.size(); i++) { + for (int j = 0; j < users.size(); j++) { + Float firstScore = userService.getFootprint(users.get(i)); + Float secondScore = userService.getFootprint(users.get(j)); + if (i > j && firstScore < secondScore) { + String temp = users.get(i); + users.set(i, users.get(j)); + users.set(j, temp); + } + if (i < j && firstScore > secondScore) { + String temp = users.get(i); + users.set(i, users.get(j)); + users.set(j, temp); + } + } + } + } + + /** + * Sorts the scores of users. + * @param users the list of users + */ + public void sortDiffScores(List users) throws InterruptedException { + for (int i = 0; i < users.size(); i++) { + for (int j = 0; j < users.size(); j++) { + Float firstDiff = userService.getFirstFootprint(users.get(i)) - userService + .getFootprint(users.get(i)); + Float secondDiff = userService.getFirstFootprint(users.get(j)) - userService + .getFootprint(users.get(j)); + if (i < j && firstDiff < secondDiff) { + String temp = users.get(i); + users.set(i, users.get(j)); + users.set(j, temp); + } + if (i > j && firstDiff > secondDiff) { + String temp = users.get(i); + users.set(i, users.get(j)); + users.set(j, temp); + } + } + } + } + /** * Adds a fade transition for switching between the different panes. * @param node the node on which the transition needs to act */ public void addFadeTransition(Node node) { - fadeTrans = new FadeTransition(Duration.millis(400), node); fadeTrans.setFromValue(0); fadeTrans.setToValue(1.0); @@ -98,13 +281,14 @@ public class DashBoardController { * Displays the dashboard pane. * @param event the event (clicking the button) */ - public void displayDashboard(ActionEvent event) { + public void displayDashboard(ActionEvent event) throws InterruptedException { addFadeTransition(dashboardPane); System.out.println("display dashboard"); dashboardPane.setVisible(true); userPane.setVisible(false); activitiesPane.setVisible(false); friendsPane.setVisible(false); + updateLeaderboard(); updateAchievements(); } @@ -119,6 +303,46 @@ public class DashBoardController { userPane.setVisible(false); activitiesPane.setVisible(true); friendsPane.setVisible(false); + Map inputMap = userService.getInputs(userService.currentUser.getName()); + peopleNumber.setText(inputMap.get("input_size")); + income.setText(inputMap.get("input_income") + " €/yr"); + electricityUsage.setText(inputMap.get("input_footprint_housing_electricity_dollars") + + " €/yr"); + cleanEnergy.setText(inputMap.get("input_footprint_housing_gco2_per_kwh")); + naturalGasUsage.setText(inputMap.get("input_footprint_housing_naturalgas_dollars") + + " €/yr"); + heatingOilUsage.setText(inputMap.get("input_footprint_housing_heatingoil_dollars") + + " €/yr"); + waterUsage.setText(inputMap.get("input_footprint_housing_watersewage") + " €/yr"); + livingSpace.setText(inputMap.get("input_footprint_housing_squarefeet") + " m²"); + gasolineMiles.setText(inputMap.get("input_footprint_transportation_miles1")); + gasolineMpg.setText(inputMap.get("input_footprint_transportation_mpg1")); + dieselMiles.setText(inputMap.get("input_footprint_transportation_miles2")); + dieselMpg.setText(inputMap.get("input_footprint_transportation_mpg2")); + electricMiles.setText(inputMap.get("input_footprint_transportation_miles3")); + electricMpg.setText(inputMap.get("input_footprint_transportation_mpg3")); + publicTransportation.setText(inputMap.get("input_footprint_transportation_publictrans") + + " km/yr"); + airPlane.setText(inputMap.get("input_footprint_transportation_airtotal") + " km/yr"); + goodShopping.setText(inputMap.get("input_footprint_shopping_goods_total") + " €/mo"); + serviceShopping.setText(inputMap.get("input_footprint_shopping_services_total") + " €/mo"); + meat.setText(inputMap.get("input_footprint_shopping_food_meatfisheggs")); + grains.setText(inputMap.get("input_footprint_shopping_food_cereals")); + dairy.setText(inputMap.get("input_footprint_shopping_food_dairy")); + fruits.setText(inputMap.get("input_footprint_shopping_food_fruitvegetables")); + snacks.setText(inputMap.get("input_footprint_shopping_food_otherfood")); + if (userService.getExtraInputs(userService.currentUser.getName()).get("local_produce")) { + localProduce.setSelected(true); + } + if (userService.getExtraInputs(userService.currentUser.getName()).get("bike")) { + bike.setSelected(true); + } + if (userService.getExtraInputs(userService.currentUser.getName()).get("temperature")) { + loweringTemp.setSelected(true); + } + if (userService.getExtraInputs(userService.currentUser.getName()).get("solar_panels")) { + solarPanels.setSelected(true); + } } /** @@ -129,6 +353,12 @@ public class DashBoardController { System.out.println(userService.currentUser.getName()); System.out.println(userService.getFootprint(userService.currentUser.getName())); footprintLabel.setText("" + userService.getFootprint(userService.currentUser.getName())); + firstFootprintLabel.setText("" + userService + .getFirstFootprint(userService.currentUser.getName())); + Float diff = userService.getFirstFootprint(userService.currentUser.getName()) - userService + .getFootprint(userService.currentUser.getName()); + differenceLabel.setText( "" + diff); + usernameLabel.setText("" + userService.currentUser.getName()); addFadeTransition(userPane); System.out.println("display user"); dashboardPane.setVisible(false); @@ -142,14 +372,14 @@ public class DashBoardController { * Displays the friends pane. * @param event the event (clicking the button) */ - public void displayFriends(ActionEvent event) { + public void displayFriends(ActionEvent event) throws InterruptedException { addFadeTransition(friendsPane); System.out.println("display friends"); dashboardPane.setVisible(false); userPane.setVisible(false); activitiesPane.setVisible(false); friendsPane.setVisible(true); - + updateFriends(); } //sets the slide in transition for startup @@ -162,7 +392,7 @@ public class DashBoardController { * Opens the calculator. * @throws IOException if the Application doesn't load. */ - public void openCalculator() throws IOException { + public void openCalculator() throws IOException, InterruptedException { Parent calc = Application.load(this.getClass().getClassLoader() .getResource("fxml/calculator.fxml")); Scene scene = new Scene(calc); @@ -175,6 +405,92 @@ public class DashBoardController { calcStage.show(); } + /** + * Opens extra activities. + * @param event the event (clicking the button) + * @throws IOException if the Application doesn't load. + */ + public void openExtraActivities(ActionEvent event) throws IOException { + Parent extra = Application.load(this.getClass().getClassLoader() + .getResource("fxml/extraActivities.fxml")); + Scene scene = new Scene(extra); + Stage extraStage = new Stage(); + extraStage.setScene(scene); + extraStage.setTitle("Add extra activity - " + userService.currentUser.getName()); + extraStage.show(); + } + + /** + * method opens addFriend scene. + * @throws IOException when file is not found + */ + public void openAddFriend() throws IOException { + Parent calc = Application.load(this.getClass().getClassLoader() + .getResource("fxml/AddFriend.fxml")); + Scene scene = new Scene(calc); + Stage calcStage = new Stage(); + calcStage.setScene(scene); + calcStage.setTitle("Add a new friend - " + userService.currentUser.getName()); + calcStage.show(); + } + + /** + * Leaderboard is updating. + * @throws InterruptedException throws exception + */ + public void updateLeaderboard() throws InterruptedException { + List userList = userService.getAllUsers(); + //global leaderboard + globalLeaderboard.getItems().clear(); + globalLeaderData.removeAll(); + sortScores(userList); + //development leaderboard + developmentLeaderboard.getItems().clear(); + developmentData.removeAll(); + sortDiffScores(userList); + for (int j = 0; j < userList.size(); j++) { + Friend user = new Friend(userList.get(j), userService.getFootprint(userList.get(j))); + Friend diffUser = new Friend(userList.get(j), userService + .getFirstFootprint(userList.get(j)) + - userService.getFootprint(userList.get(j))); + globalLeaderData.add(user); + developmentData.add(diffUser); + } + globalLeaderboard.setItems(globalLeaderData); + developmentLeaderboard.setItems(developmentData); + } + + /** + * Friends tables are updating. + * @throws InterruptedException throws exception + */ + public void updateFriends() throws InterruptedException { + List wholeList = userService.getFriendNames(userService.currentUser.getName()); + wholeList.add(userService.currentUser.getName()); + //friend list + friendsTable.getItems().clear(); + data.removeAll(); + List friendList = userService.getFriendNames(userService.currentUser.getName()); + sortScores(friendList); + //friends leaderboard + friendLeaderboard.getItems().clear(); + friendLeaderData.removeAll(); + sortDiffScores(wholeList); + for (int i = 0; i < friendList.size(); i++) { + Friend user = new Friend(friendList.get(i), userService + .getFootprint(friendList.get(i))); + data.add(user); + } + for (int j = 0; j < wholeList.size(); j++) { + Friend diffUser = new Friend(wholeList.get(j), + userService.getFirstFootprint(wholeList.get(j)) + - userService.getFootprint(wholeList.get(j))); + friendLeaderData.add(diffUser); + } + friendsTable.setItems(data); + friendLeaderboard.setItems(friendLeaderData); + } + /** * Updates the achievements. */ @@ -209,6 +525,5 @@ public class DashBoardController { scaleDown.setToX(1.0); button.setOnMouseExited(e -> scaleDown.playFromStart()); } - } } diff --git a/src/Client/src/main/java/greenify/client/rest/UserService.java b/src/Client/src/main/java/greenify/client/rest/UserService.java index 6ea6f8f..bb19bf5 100644 --- a/src/Client/src/main/java/greenify/client/rest/UserService.java +++ b/src/Client/src/main/java/greenify/client/rest/UserService.java @@ -12,6 +12,7 @@ import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponentsBuilder; +import java.util.List; import java.util.Map; @Service @@ -101,6 +102,26 @@ public class UserService { .encode().toUri(), String.class); } + /** + * Updates the extra input of the user. + * @param name name of the user + * @param inputName name of the input + * @param value value of the input + */ + @SuppressWarnings("Duplicates") + public void updateExtraInput(String name, String inputName, Boolean value) { + HttpHeaders headers = new HttpHeaders(); + headers.set("Accept", MediaType.APPLICATION_JSON_VALUE); + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("http://localhost:8080/setExtraInput") + .queryParam("name", name) + .queryParam("inputName", inputName) + .queryParam("value",value); + new HttpEntity<>(headers); + System.out.println(builder.build().encode().toUri()); + ResponseEntity authenticateResponse = this.restTemplate.getForEntity(builder.build() + .encode().toUri(), String.class); + } + /** * Gets the footprint of the user. * @param name name of the user @@ -119,6 +140,78 @@ public class UserService { return result; } + /** + * Gets the first footprint of the user. + * @param name name of the user + * @return returns the footprint score + */ + public Float getFirstFootprint(String name) { + HttpHeaders headers = new HttpHeaders(); + headers.set("Accept", MediaType.APPLICATION_JSON_VALUE); + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("http://localhost:8080/getFirst") + .queryParam("name", name); + new HttpEntity<>(headers); + System.out.println(builder.build().encode().toUri()); + Float footprint = this.restTemplate.getForObject(builder + .build().encode().toUri(), Float.class); + return footprint; + } + + /** + * Saves the footprint of the user. + * @param name name of the user + * @return returns the footprint score + */ + @SuppressWarnings("Duplicates") + public Float saveFootprint(String name) { + HttpHeaders headers = new HttpHeaders(); + headers.set("Accept", MediaType.APPLICATION_JSON_VALUE); + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("http://localhost:8080/saveFootprint") + .queryParam("name", name); + new HttpEntity<>(headers); + System.out.println(builder.build().encode().toUri()); + Float result = this.restTemplate.getForObject(builder + .build().encode().toUri(), Float.class); + return result; + } + + + /** + * Saves the first footprint of the user. + * @param name name of the user + * @return returns the footprint score + */ + @SuppressWarnings("Duplicates") + public Float saveFirstFootprint(String name) { + HttpHeaders headers = new HttpHeaders(); + headers.set("Accept", MediaType.APPLICATION_JSON_VALUE); + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("http://localhost:8080/saveFirstFootprint") + .queryParam("name", name); + new HttpEntity<>(headers); + System.out.println(builder.build().encode().toUri()); + Float result = this.restTemplate.getForObject(builder + .build().encode().toUri(), Float.class); + return result; + } + + /** + * Gets the friend list of the user. + * @param name name of the user + * @return returns the friend list + */ + @SuppressWarnings("Duplicates") + public List getFriendNames(String name) { + HttpHeaders headers = new HttpHeaders(); + headers.set("Accept", MediaType.APPLICATION_JSON_VALUE); + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("http://localhost:8080/getFriends") + .queryParam("name", name); + new HttpEntity<>(headers); + System.out.println(builder.build().encode().toUri()); + List result = this.restTemplate.getForObject(builder + .build().encode().toUri(), List.class); + return result; + } + /** * Adds a friend to the user. * @param name the username of the current user. @@ -137,6 +230,58 @@ public class UserService { .encode().toUri(), String.class); } + /** + * Removes a friend from the friendslist of the user. + * @param name the username of the current user. + * @param friend the username of the friend you want to remove. + */ + @SuppressWarnings("Duplicates") + public void removeFriend(String name, String friend) { + HttpHeaders headers = new HttpHeaders(); + headers.set("Accept", MediaType.APPLICATION_JSON_VALUE); + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("http://localhost:8080/removeFriend") + .queryParam("name", name) + .queryParam("friend",friend); + HttpEntity entity = new HttpEntity<>(headers); + System.out.println(builder.build().encode().toUri()); + ResponseEntity authenticateResponse = this.restTemplate.getForEntity(builder.build() + .encode().toUri(), String.class); + } + + /** + * Gets the footprint inputs of the user. + * @param name the username of the current user. + */ + @SuppressWarnings("Duplicates") + public Map getInputs(String name) { + HttpHeaders headers = new HttpHeaders(); + headers.set("Accept", MediaType.APPLICATION_JSON_VALUE); + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("http://localhost:8080/getInputs") + .queryParam("name", name); + HttpEntity entity = new HttpEntity<>(headers); + System.out.println(builder.build().encode().toUri()); + Map result = this.restTemplate.getForObject(builder.build() + .encode().toUri(), Map.class); + return result; + } + + /** + * Gets the footprint inputs of the user. + * @param name the username of the current user. + */ + @SuppressWarnings("Duplicates") + public Map getExtraInputs(String name) { + HttpHeaders headers = new HttpHeaders(); + headers.set("Accept", MediaType.APPLICATION_JSON_VALUE); + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("http://localhost:8080/getExtraInputs") + .queryParam("name", name); + HttpEntity entity = new HttpEntity<>(headers); + System.out.println(builder.build().encode().toUri()); + Map result = this.restTemplate.getForObject(builder.build() + .encode().toUri(), Map.class); + return result; + } + /** * Gets the achievements of a user. * @param name name of the user @@ -154,4 +299,18 @@ public class UserService { .encode().toUri(), Map.class); } + /** + * Gets the list of all users. + */ + @SuppressWarnings("Duplicates") + public List getAllUsers() { + HttpHeaders headers = new HttpHeaders(); + headers.set("Accept", MediaType.APPLICATION_JSON_VALUE); + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("http://localhost:8080/getAllUsers"); + HttpEntity entity = new HttpEntity<>(headers); + System.out.println(builder.build().encode().toUri()); + List result = this.restTemplate.getForObject(builder + .build().encode().toUri(), List.class); + return result; + } } diff --git a/src/Client/src/main/resources/achiev1pic.jpg b/src/Client/src/main/resources/achiev1pic.jpg new file mode 100644 index 0000000..e0e9318 Binary files /dev/null and b/src/Client/src/main/resources/achiev1pic.jpg differ diff --git a/src/Client/src/main/resources/fxml/dashboard.fxml b/src/Client/src/main/resources/fxml/dashboard.fxml index 5f3fe77..26ab6c3 100644 --- a/src/Client/src/main/resources/fxml/dashboard.fxml +++ b/src/Client/src/main/resources/fxml/dashboard.fxml @@ -1,13 +1,14 @@ + + - @@ -47,127 +48,242 @@ - - + - + - + + - - - - - - + + - + + - - - - - - - + + - + - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -176,28 +292,77 @@ - + - + - - + - + - + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - + + + + + + + + + + + + + + + + + @@ -261,11 +459,33 @@ - + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Client/src/main/resources/icons/butterfly.png b/src/Client/src/main/resources/icons/butterfly.png new file mode 100644 index 0000000..dfefa65 Binary files /dev/null and b/src/Client/src/main/resources/icons/butterfly.png differ diff --git a/src/Client/src/main/resources/icons/friend2.png b/src/Client/src/main/resources/icons/friend2.png new file mode 100644 index 0000000..3934a3e Binary files /dev/null and b/src/Client/src/main/resources/icons/friend2.png differ diff --git a/src/Client/src/test/java/UserServiceTest.java b/src/Client/src/test/java/UserServiceTest.java index cbcf1a8..3878cf2 100644 --- a/src/Client/src/test/java/UserServiceTest.java +++ b/src/Client/src/test/java/UserServiceTest.java @@ -10,6 +10,11 @@ import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.web.client.RestTemplate; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + @RunWith(MockitoJUnitRunner.class) public class UserServiceTest { @@ -51,18 +56,106 @@ public class UserServiceTest { Assert.assertEquals(estimate, result); } + @Test + public void getFirstFootprint() throws Exception { + Float estimate = new Float(5); + Mockito.when(restTemplate.getForObject(new java.net.URI("http://localhost:8080/getFirst?name=Eric"), + Float.class)) + .thenReturn(estimate); + Float result = userService.getFirstFootprint("Eric"); + Assert.assertEquals(estimate, result); + } + + @Test + public void saveFootprint() throws Exception { + Float estimate = new Float(5); + Mockito.when(restTemplate.getForObject(new java.net.URI("http://localhost:8080/saveFootprint?name=Eric"), + Float.class)) + .thenReturn(estimate); + Float result = userService.saveFootprint("Eric"); + Assert.assertEquals(estimate, result); + } + + @Test + public void saveFirstFootprint() throws Exception { + Float estimate = new Float(5); + Mockito.when(restTemplate.getForObject(new java.net.URI("http://localhost:8080/saveFirstFootprint?name=Eric"), + Float.class)) + .thenReturn(estimate); + Float result = userService.saveFirstFootprint("Eric"); + Assert.assertEquals(estimate, result); + } + + @Test + public void getFriendNamesTest() throws Exception { + List estimate = new ArrayList(); + estimate.add("alex"); + Mockito.when(restTemplate.getForObject(new java.net.URI("http://localhost:8080/getFriends?name=Eric"), + List.class)) + .thenReturn(estimate); + List result = userService.getFriendNames("Eric"); + Assert.assertEquals(estimate, result); + } + + @Test + public void getAllUsers() throws Exception { + List estimate = new ArrayList(); + estimate.add("alex"); + Mockito.when(restTemplate.getForObject(new java.net.URI("http://localhost:8080/getAllUsers"), + List.class)) + .thenReturn(estimate); + List result = userService.getAllUsers(); + Assert.assertEquals(estimate, result); + } + + @Test + public void getInputsTest() throws Exception { + Map estimate = new HashMap<>(); + estimate.put("Eric", "3"); + Mockito.when(restTemplate.getForObject(new java.net.URI("http://localhost:8080/getInputs?name=Eric"), + Map.class)) + .thenReturn(estimate); + Map result = userService.getInputs("Eric"); + Assert.assertEquals(estimate, result); + } + + @Test + public void getExtraInputsTest() throws Exception { + Map estimate = new HashMap<>(); + estimate.put("solar_panels", true); + Mockito.when(restTemplate.getForObject(new java.net.URI("http://localhost:8080/getExtraInputs?name=Eric"), + Map.class)) + .thenReturn(estimate); + Map result = userService.getExtraInputs("Eric"); + Assert.assertEquals(estimate, result); + } + @Test public void setInputTest() throws Exception { userService.updateInput("Eric", "input_size", "5"); Mockito.verify(userService).updateInput("Eric", "input_size", "5"); } + @Test + public void setExtraInputTest() throws Exception { + userService.updateExtraInput("Eric", "solar_panels", true); + Mockito.verify(userService).updateExtraInput("Eric", "solar_panels", true); + } + @Test public void addFriendTest() throws Exception { userService.addFriend("Eric", "Ceren"); Mockito.verify(userService).addFriend("Eric", "Ceren"); } + @Test + public void removeFriendTest() throws Exception { + userService.addFriend("Eric", "Ceren"); + Mockito.verify(userService).addFriend("Eric", "Ceren"); + userService.removeFriend("Eric", "Ceren"); + Mockito.verify(userService).removeFriend("Eric", "Ceren"); + } + @Test public void getAchievementsTest() throws Exception { userService.getAchievements("mika"); diff --git a/src/Server/src/main/java/greenify/server/InputValidator.java b/src/Server/src/main/java/greenify/server/InputValidator.java index b7dc6a1..eeb5dc6 100644 --- a/src/Server/src/main/java/greenify/server/InputValidator.java +++ b/src/Server/src/main/java/greenify/server/InputValidator.java @@ -4,127 +4,130 @@ import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Objects; public class InputValidator { private static final List inputItems = Arrays.asList( - new InputItem("input_location", false, "Chicago"), - new InputItem("input_location_mode", false, "1"), - new InputItem("input_size", false, "3"), - new InputItem("input_income", false, "3000"), - new InputItem("input_population", false, "1"), - new InputItem("input_changed", false, "0"), - new InputItem("input_footprint_household_adults", false, "0"), - new InputItem("input_footprint_household_children", false, "0"), - new InputItem("input_footprint_transportation_num_vehicles", false, "1"), - new InputItem("input_footprint_transportation_miles1", false, "16100", false), - new InputItem("input_footprint_transportation_mpg1", false, "22", false), - new InputItem("input_footprint_transportation_fuel1", false, "0", false), - new InputItem("input_footprint_transportation_miles2", false, "0", false), - new InputItem("input_footprint_transportation_fuel2", false, "0", false), - new InputItem("input_footprint_transportation_mpg2", false, "0", false), - new InputItem("input_footprint_transportation_miles3", false, "0", false), - new InputItem("input_footprint_transportation_fuel3", false, "0", false), - new InputItem("input_footprint_transportation_mpg3", false, "0", false), - new InputItem("input_footprint_transportation_miles4", false, "0", false), - new InputItem("input_footprint_transportation_fuel4", false, "0", false), - new InputItem("input_footprint_transportation_mpg4", false, "0", false), - new InputItem("input_footprint_transportation_miles5", false, "0", false), - new InputItem("input_footprint_transportation_fuel5", false, "0", false), - new InputItem("input_footprint_transportation_mpg5", false, "0", false), - new InputItem("input_footprint_transportation_miles6", false, "0", false), - new InputItem("input_footprint_transportation_fuel6", false, "0", false), - new InputItem("input_footprint_transportation_mpg6", false, "0", false), - new InputItem("input_footprint_transportation_miles7", false, "0", false), - new InputItem("input_footprint_transportation_fuel7", false, "0", false), - new InputItem("input_footprint_transportation_mpg7", false, "0", false), - new InputItem("input_footprint_transportation_miles8", false, "0", false), - new InputItem("input_footprint_transportation_fuel8", false, "0", false), - new InputItem("input_footprint_transportation_mpg8", false, "0", false), - new InputItem("input_footprint_transportation_miles9", false, "0", false), - new InputItem("input_footprint_transportation_fuel9", false, "0", false), - new InputItem("input_footprint_transportation_mpg9", false, "0", false), - new InputItem("input_footprint_transportation_miles10", false, "0", false), - new InputItem("input_footprint_transportation_fuel10", false, "0", false), - new InputItem("input_footprint_transportation_mpg10", false, "0", false), - new InputItem("input_footprint_transportation_groundtype", false, "0"), - new InputItem("input_footprint_transportation_publictrans", false, "436"), - new InputItem("input_footprint_transportation_bus", false, "174"), - new InputItem("input_footprint_transportation_transit", false, "131"), - new InputItem("input_footprint_transportation_commuter", false, "87"), - new InputItem("input_footprint_transportation_intercity", false, "44"), - new InputItem("input_footprint_transportation_airtype", false, "0"), - new InputItem("input_footprint_transportation_airtotal", false, "6"), - new InputItem("input_footprint_transportation_airshort", false, "3"), - new InputItem("input_footprint_transportation_airmedium", false, "3"), - new InputItem("input_footprint_transportation_airlong", false, "0"), - new InputItem("input_footprint_transportation_airextended", false, "0"), - new InputItem("input_footprint_housing_cdd", false, "40000"), - new InputItem("input_footprint_housing_hdd", false, "40000"), - new InputItem("input_footprint_housing_electricity_type", false, "0"), - new InputItem("input_footprint_housing_electricity_dollars", false, "1200"), - new InputItem("input_footprint_housing_electricity_kwh", false, "12632"), - new InputItem("input_footprint_housing_cleanpercent", false, "0"), - new InputItem("input_footprint_housing_naturalgas_type", false, "0"), - new InputItem("input_footprint_housing_naturalgas_dollars", false, "600"), - new InputItem("input_footprint_housing_naturalgas_therms", false, "472"), - new InputItem("input_footprint_housing_naturalgas_cuft", false, "472444"), - new InputItem("input_footprint_housing_heatingoil_type", false, "0"), - new InputItem("input_footprint_housing_heatingoil_dollars", false, "220"), - new InputItem("input_footprint_housing_heatingoil_gallons", false, "73"), - new InputItem("input_footprint_housing_heatingoil_dollars_per_gallon", false, "40000"), - new InputItem("input_footprint_housing_squarefeet", false, "1850"), - new InputItem("input_footprint_housing_watersewage", false, "100"), - new InputItem("input_footprint_housing_gco2_per_kwh", false, "0"), - new InputItem("input_footprint_shopping_food_meatfisheggs_default", true, "2.4"), - new InputItem("input_footprint_shopping_food_meat_beefpork_default", true, "1.1"), - new InputItem("input_footprint_shopping_food_meat_poultry_default", true, "0.7"), - new InputItem("input_footprint_shopping_food_meat_fish_default", true, "0.3"), - new InputItem("input_footprint_shopping_food_meat_other_default", true, "0.3"), - new InputItem("input_footprint_shopping_food_fruitvegetables_default", true, "3.5"), - new InputItem("input_footprint_shopping_food_dairy_default", true, "2.2"), - new InputItem("input_footprint_shopping_food_cereals_default", true, "4.1"), - new InputItem("input_footprint_shopping_food_otherfood_default", true, "3.4"), - new InputItem("input_footprint_shopping_food_meattype", true, "0"), - new InputItem("input_footprint_shopping_food_meatfisheggs", true, "2.4"), - new InputItem("input_footprint_shopping_food_meat_beefpork", true, "2.4"), - new InputItem("input_footprint_shopping_food_meat_poultry", true, "2.4"), - new InputItem("input_footprint_shopping_food_meat_fish", true, "2.4"), - new InputItem("input_footprint_shopping_food_meat_other", true, "2.4"), - new InputItem("input_footprint_shopping_food_cereals", true, "4.1"), - new InputItem("input_footprint_shopping_food_dairy", true, "2.2"), - new InputItem("input_footprint_shopping_food_fruitvegetables", true, "3.5"), - new InputItem("input_footprint_shopping_food_otherfood", true, "3.4"), - new InputItem("input_footprint_shopping_goods_default_furnitureappliances", false, "1310"), - new InputItem("input_footprint_shopping_goods_default_clothing", false, "1310"), - new InputItem("input_footprint_shopping_goods_default_other_entertainment", false, "1310"), - new InputItem("input_footprint_shopping_goods_default_other_office", false, "1310"), - new InputItem("input_footprint_shopping_goods_default_other_personalcare", false, "1310"), - new InputItem("input_footprint_shopping_goods_default_other_autoparts", false, "1310"), - new InputItem("input_footprint_shopping_goods_default_other_medical", false, "1310"), - new InputItem("input_footprint_shopping_goods_type", false, "1310"), - new InputItem("input_footprint_shopping_goods_total", false, "1310"), - new InputItem("input_footprint_shopping_goods_furnitureappliances", false, "362"), - new InputItem("input_footprint_shopping_goods_clothing", false, "391"), - new InputItem("input_footprint_shopping_goods_other_type", false, "0"), - new InputItem("input_footprint_shopping_goods_other_total", false, "1311"), - new InputItem("input_footprint_shopping_goods_other_entertainment", false, "200"), - new InputItem("input_footprint_shopping_goods_other_office", false, "38"), - new InputItem("input_footprint_shopping_goods_other_personalcare", false, "103"), - new InputItem("input_footprint_shopping_goods_other_autoparts", false, "45"), - new InputItem("input_footprint_shopping_goods_other_medical", false, "172"), - new InputItem("input_footprint_shopping_services_type", false, "0"), - new InputItem("input_footprint_shopping_services_total", false, "2413"), - new InputItem("input_footprint_shopping_services_healthcare", false, "841"), - new InputItem("input_footprint_shopping_services_education", false, "122"), - new InputItem("input_footprint_shopping_services_communications", false, "163"), - new InputItem("input_footprint_shopping_services_vehicleservices", false, "180"), - new InputItem("input_footprint_shopping_services_finance", false, "566"), - new InputItem("input_footprint_shopping_services_household", false, "28"), - new InputItem("input_footprint_shopping_services_charity", false, "146"), - new InputItem("input_footprint_shopping_services_miscservices", false, "114"), - new InputItem("internal_state_abbreviation", false, "US") + new InputItem("input_location", false, "Chicago"), + new InputItem("input_location_mode", false, "1"), + new InputItem("input_size", false, "3"), + new InputItem("input_income", false, "3000"), + new InputItem("input_population", false, "1"), + new InputItem("input_changed", false, "0"), + new InputItem("input_footprint_household_adults", false, "0"), + new InputItem("input_footprint_household_children", false, "0"), + new InputItem("input_footprint_transportation_num_vehicles", false, "10"), + new InputItem("input_footprint_transportation_miles1", false, "16100", false), + new InputItem("input_footprint_transportation_mpg1", false, "22", false), + new InputItem("input_footprint_transportation_fuel1", false, "0", false), + new InputItem("input_footprint_transportation_miles2", false, "0", false), + new InputItem("input_footprint_transportation_fuel2", false, "0", false), + new InputItem("input_footprint_transportation_mpg2", false, "0", false), + new InputItem("input_footprint_transportation_miles3", false, "0", false), + new InputItem("input_footprint_transportation_fuel3", false, "0", false), + new InputItem("input_footprint_transportation_mpg3", false, "0", false), + new InputItem("input_footprint_transportation_miles4", false, "0", false), + new InputItem("input_footprint_transportation_fuel4", false, "0", false), + new InputItem("input_footprint_transportation_mpg4", false, "0", false), + new InputItem("input_footprint_transportation_miles5", false, "0", false), + new InputItem("input_footprint_transportation_fuel5", false, "0", false), + new InputItem("input_footprint_transportation_mpg5", false, "0", false), + new InputItem("input_footprint_transportation_miles6", false, "0", false), + new InputItem("input_footprint_transportation_fuel6", false, "0", false), + new InputItem("input_footprint_transportation_mpg6", false, "0", false), + new InputItem("input_footprint_transportation_miles7", false, "0", false), + new InputItem("input_footprint_transportation_fuel7", false, "0", false), + new InputItem("input_footprint_transportation_mpg7", false, "0", false), + new InputItem("input_footprint_transportation_miles8", false, "0", false), + new InputItem("input_footprint_transportation_fuel8", false, "0", false), + new InputItem("input_footprint_transportation_mpg8", false, "0", false), + new InputItem("input_footprint_transportation_miles9", false, "0", false), + new InputItem("input_footprint_transportation_fuel9", false, "0", false), + new InputItem("input_footprint_transportation_mpg9", false, "0", false), + new InputItem("input_footprint_transportation_miles10", false, "0", false), + new InputItem("input_footprint_transportation_fuel10", false, "0", false), + new InputItem("input_footprint_transportation_mpg10", false, "0", false), + new InputItem("input_footprint_transportation_groundtype", false, "0"), + new InputItem("input_footprint_transportation_publictrans", false, "436"), + new InputItem("input_footprint_transportation_bus", false, "174"), + new InputItem("input_footprint_transportation_transit", false, "131"), + new InputItem("input_footprint_transportation_commuter", false, "87"), + new InputItem("input_footprint_transportation_intercity", false, "44"), + new InputItem("input_footprint_transportation_airtype", false, "0"), + new InputItem("input_footprint_transportation_airtotal", false, "6"), + new InputItem("input_footprint_transportation_airshort", false, "3"), + new InputItem("input_footprint_transportation_airmedium", false, "3"), + new InputItem("input_footprint_transportation_airlong", false, "0"), + new InputItem("input_footprint_transportation_airextended", false, "0"), + new InputItem("input_footprint_housing_cdd", false, "40000"), + new InputItem("input_footprint_housing_hdd", false, "40000"), + new InputItem("input_footprint_housing_electricity_type", false, "0"), + new InputItem("input_footprint_housing_electricity_dollars", false, "1200"), + new InputItem("input_footprint_housing_electricity_kwh", false, "12632"), + new InputItem("input_footprint_housing_cleanpercent", false, "0"), + new InputItem("input_footprint_housing_naturalgas_type", false, "0"), + new InputItem("input_footprint_housing_naturalgas_dollars", false, "600"), + new InputItem("input_footprint_housing_naturalgas_therms", false, "472"), + new InputItem("input_footprint_housing_naturalgas_cuft", false, "472444"), + new InputItem("input_footprint_housing_heatingoil_type", false, "0"), + new InputItem("input_footprint_housing_heatingoil_dollars", false, "220"), + new InputItem("input_footprint_housing_heatingoil_gallons", false, "73"), + new InputItem("input_footprint_housing_heatingoil_dollars_per_gallon", false, "40000"), + new InputItem("input_footprint_housing_squarefeet", false, "1850"), + new InputItem("input_footprint_housing_watersewage", false, "100"), + new InputItem("input_footprint_housing_gco2_per_kwh", false, "0"), + new InputItem("input_footprint_shopping_food_meatfisheggs_default", true, "2.4"), + new InputItem("input_footprint_shopping_food_meat_beefpork_default", true, "1.1"), + new InputItem("input_footprint_shopping_food_meat_poultry_default", true, "0.7"), + new InputItem("input_footprint_shopping_food_meat_fish_default", true, "0.3"), + new InputItem("input_footprint_shopping_food_meat_other_default", true, "0.3"), + new InputItem("input_footprint_shopping_food_fruitvegetables_default", true, "3.5"), + new InputItem("input_footprint_shopping_food_dairy_default", true, "2.2"), + new InputItem("input_footprint_shopping_food_cereals_default", true, "4.1"), + new InputItem("input_footprint_shopping_food_otherfood_default", true, "3.4"), + new InputItem("input_footprint_shopping_food_meattype", true, "0"), + new InputItem("input_footprint_shopping_food_meatfisheggs", true, "2.4"), + new InputItem("input_footprint_shopping_food_meat_beefpork", true, "2.4"), + new InputItem("input_footprint_shopping_food_meat_poultry", true, "2.4"), + new InputItem("input_footprint_shopping_food_meat_fish", true, "2.4"), + new InputItem("input_footprint_shopping_food_meat_other", true, "2.4"), + new InputItem("input_footprint_shopping_food_cereals", true, "4.1"), + new InputItem("input_footprint_shopping_food_dairy", true, "2.2"), + new InputItem("input_footprint_shopping_food_fruitvegetables", true, "3.5"), + new InputItem("input_footprint_shopping_food_otherfood", true, "3.4"), + new InputItem("input_footprint_shopping_goods_default_furnitureappliances", + false, "1310"), + new InputItem("input_footprint_shopping_goods_default_clothing", false, "1310"), + new InputItem("input_footprint_shopping_goods_default_other_entertainment", + false, "1310"), + new InputItem("input_footprint_shopping_goods_default_other_office", false, "1310"), + new InputItem( + "input_footprint_shopping_goods_default_other_personalcare", false, "1310"), + new InputItem("input_footprint_shopping_goods_default_other_autoparts", + false, "1310"), + new InputItem("input_footprint_shopping_goods_default_other_medical", false, "1310"), + new InputItem("input_footprint_shopping_goods_type", false, "1310"), + new InputItem("input_footprint_shopping_goods_total", false, "1310"), + new InputItem("input_footprint_shopping_goods_furnitureappliances", false, "362"), + new InputItem("input_footprint_shopping_goods_clothing", false, "391"), + new InputItem("input_footprint_shopping_goods_other_type", false, "0"), + new InputItem("input_footprint_shopping_goods_other_total", false, "1311"), + new InputItem("input_footprint_shopping_goods_other_entertainment", false, "200"), + new InputItem("input_footprint_shopping_goods_other_office", false, "38"), + new InputItem("input_footprint_shopping_goods_other_personalcare", false, "103"), + new InputItem("input_footprint_shopping_goods_other_autoparts", false, "45"), + new InputItem("input_footprint_shopping_goods_other_medical", false, "172"), + new InputItem("input_footprint_shopping_services_type", false, "0"), + new InputItem("input_footprint_shopping_services_total", false, "2413"), + new InputItem("input_footprint_shopping_services_healthcare", false, "841"), + new InputItem("input_footprint_shopping_services_education", false, "122"), + new InputItem("input_footprint_shopping_services_communications", false, "163"), + new InputItem("input_footprint_shopping_services_vehicleservices", false, "180"), + new InputItem("input_footprint_shopping_services_finance", false, "566"), + new InputItem("input_footprint_shopping_services_household", false, "28"), + new InputItem("input_footprint_shopping_services_charity", false, "146"), + new InputItem("input_footprint_shopping_services_miscservices", false, "114"), + new InputItem("internal_state_abbreviation", false, "US") ); /** @@ -149,7 +152,7 @@ public class InputValidator { item = inputItem; } } - if (Objects.requireNonNull(item).getFloat()) { + if (item.getFloat()) { try { Float.parseFloat(value); } catch (NumberFormatException | NullPointerException nfe) { @@ -177,4 +180,17 @@ public class InputValidator { } return map; } -} + + /** + * This method gets extra values. + * @return the map of default values + */ + public static Map getExtraValues() { + Map map = new HashMap() { }; + map.put("local_produce", false); + map.put("bike", false); + map.put("temperature", false); + map.put("solar_panels", false); + return map; + } +} \ No newline at end of file diff --git a/src/Server/src/main/java/greenify/server/data/model/User.java b/src/Server/src/main/java/greenify/server/data/model/User.java index e31bb11..1c5a2ea 100644 --- a/src/Server/src/main/java/greenify/server/data/model/User.java +++ b/src/Server/src/main/java/greenify/server/data/model/User.java @@ -6,8 +6,8 @@ import greenify.server.InputValidator; import lombok.Data; import java.util.ArrayList; -import java.util.Collection; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.Objects; @@ -16,7 +16,6 @@ import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; -import javax.persistence.JoinColumn; import javax.persistence.ManyToMany; import javax.persistence.Table; import javax.validation.constraints.NotNull; @@ -28,7 +27,7 @@ public class User { @Id @NotNull - @GeneratedValue(strategy = GenerationType.AUTO) + @GeneratedValue(strategy = GenerationType.TABLE) private Long id; @NotNull @@ -40,12 +39,17 @@ public class User { @NotNull private Float footPrint = 0.0f; + @NotNull + private Float firstFootprint = 0.0f; + @ElementCollection private Map footPrintInputs = new HashMap<>(); + @ElementCollection + private Map extraInputs = new HashMap<>(); + @ManyToMany - @JoinColumn - private Collection friends; + private List friends; @ElementCollection private Map achievements; @@ -63,7 +67,8 @@ public class User { this.name = name; this.password = password; this.setFootPrintInputs(InputValidator.getDefaultValues()); - this.friends = new ArrayList<>(); + this.setExtraInputs(InputValidator.getExtraValues()); + this.friends = new ArrayList(); this.setAchievements(AllAchievements.getDefaults()); } @@ -131,6 +136,22 @@ public class User { this.footPrint = footPrint; } + /** + * This method gets the first footPrint of user. + * @return the footprint of the user + */ + public Float getFirstFootprint() { + return firstFootprint; + } + + /** + * This method sets the footprint of a user. + * @param firstFootprint footprint of a user + */ + public void setFirstFootprint(Float firstFootprint) { + this.firstFootprint = firstFootprint; + } + /** * This method gets the footprint inputs of the user. * @return footprint inputs of the user @@ -147,28 +168,44 @@ public class User { this.footPrintInputs = footPrintInputs; } + /** + * This method gets the extra inputs of the user. + * @return extra inputs of the user + */ + public Map getExtraInputs() { + return extraInputs; + } + + /** + * This method sets the extra inputs of the user. + * @param extraInputs footprint inputs of the user + */ + public void setExtraInputs(Map extraInputs) { + this.extraInputs = extraInputs; + } + /** * This method gets the friends of the user. * @return friends list of the user */ - public ArrayList getFriends() { - return (ArrayList)this.friends; + public List getFriends() { + return this.friends; } /** * This method sets the friend list of the user. * @param friends friend list of the user */ - public void setFriends(Collection friends) { + public void setFriends(List friends) { this.friends = friends; } /** - * Adds a friend to the friends list of the user. + * Adds a friend to the friendslist of the user. * @param user the friend you want to add. */ public void addFriend(User user) { - if (user.equals(this)) { + if (user.equals(this) || friends.contains(user)) { throw new ApplicationException("Cannot add yourself as a friend"); } else { friends.add(user); @@ -176,6 +213,19 @@ public class User { } } + /** + * Removes a friend from the friendslist of the user. + * @param user the friend you want to remove. + */ + public void removeFriend(User user) { + if (!friends.contains(user)) { + throw new ApplicationException("This user is not your friend!"); + } else { + friends.remove(user); + System.out.print("Friend removed"); + } + } + /** * This method sets the achievements of the user. * @param achievements achievements of the user @@ -202,21 +252,6 @@ public class User { + this.password + ")"; } - /** - * Returns the name and score of the friends in JSON. Needed for the leader board. - * @return a JSON object of the friend list with only names and scores. - */ - public String friendsToString() { - String result = "friends=["; - for (User u : friends) { - result += "{name=" + u.getName() + ", footprint=" + u.getFootPrint() + "}, "; - } - if (result.endsWith(", ")) { - return result.substring(0, result.lastIndexOf(",")) + "]"; - } - return result + "]"; - } - /** This method checks whether two users are equal or not. * * @param other an other user * @return users are (not) equal diff --git a/src/Server/src/main/java/greenify/server/rest/UserController.java b/src/Server/src/main/java/greenify/server/rest/UserController.java index 7a0af13..d60f933 100644 --- a/src/Server/src/main/java/greenify/server/rest/UserController.java +++ b/src/Server/src/main/java/greenify/server/rest/UserController.java @@ -7,6 +7,7 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; +import java.util.List; import java.util.Map; @RestController @@ -52,6 +53,20 @@ public class UserController { userService.setInput(name, inputName, value); } + + /** + * This method sets extra input for a user. + * @param name name of the user + * @param inputName name of the input of the user + * @param value value of the input + */ + @RequestMapping("/setExtraInput") + public void setExtraInput(@RequestParam(value = "name") String name, + @RequestParam(value = "inputName") String inputName, + @RequestParam(value = "value") Boolean value) { + userService.setExtraInput(name, inputName, value); + } + /** * This method gets input for a user. * @param name name of the user @@ -74,16 +89,93 @@ public class UserController { } /** - * This method adds friend for a user. + * This method saves footprint for a user. * @param name name of the user - * + */ + @RequestMapping("/saveFootprint") + public Float saveFootprint(@RequestParam(value = "name") String name) { + Float footprint = userService.saveFootprint(name); + return footprint; + } + + /** + * This method saves first footprint for a user. + * @param name name of the user + */ + @RequestMapping("/saveFirstFootprint") + public Float saveFirstFootprint(@RequestParam(value = "name") String name) { + Float footprint = userService.saveFirstFootprint(name); + return footprint; + } + + /** + * This method gets first footprint for a user. + * @param name name of the user + */ + @RequestMapping("/getFirst") + public Float getFirstFootprint(@RequestParam(value = "name") String name) { + System.out.println("hello"); + Float footprint = userService.getFirstFootprint(name); + return footprint; + } + + /** + * This method gets friend list for a user. + * @param name name of the user + */ + @RequestMapping("/getFriends") + public List getFriendNames(@RequestParam(value = "name") String name) { + List friends = userService.getFriends(name); + return friends; + } + + /** + * This method gets the list of all users. + */ + @RequestMapping("/getAllUsers") + public List getAllUsers() { + List users = userService.getAllUsers(); + return users; + } + + /** + * This method gets the input map of the user. + */ + @RequestMapping("/getInputs") + public Map getInputs(@RequestParam(value = "name") String name) { + return userService.getInputMap(name); + } + + /** + * This method gets the extra inputs map of the user. + */ + @RequestMapping("/getExtraInputs") + public Map getExtraInputs(@RequestParam(value = "name") String name) { + return userService.getExtraInputMap(name); + } + + /** + * This method adds a friend to a user. + * @param name name of the user + * @param friend the name of the user you want to add as a friend. */ @RequestMapping("/addFriend") public void addFriend(@RequestParam(value = "name") String name, - @RequestParam(value = "friend") String friend) { + @RequestParam(value = "friend") String friend) { userService.addFriend(name, friend); } + /** + * This method removes a friend from a user. + * @param name name of the user + * @param friend name of the friend you want to remove + */ + @RequestMapping("/removeFriend") + public void removeFriend(@RequestParam(value = "name") String name, + @RequestParam(value = "friend") String friend) { + userService.removeFriend(name, friend); + } + /** * This method gets all achievements of a user. * @param name name of the user diff --git a/src/Server/src/main/java/greenify/server/service/UserService.java b/src/Server/src/main/java/greenify/server/service/UserService.java index 7669597..5f41849 100644 --- a/src/Server/src/main/java/greenify/server/service/UserService.java +++ b/src/Server/src/main/java/greenify/server/service/UserService.java @@ -10,9 +10,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.ResponseBody; +import java.util.ArrayList; +import java.util.List; import java.util.Map; @Service @@ -69,28 +69,35 @@ public class UserService { } /** -<<<<<<< HEAD * Adds a friend to the friendlist of the user. * @param name the username of the user * @param friend the name of the friend you want to add. + * @throws ApplicationException if the user is not in the database. */ public void addFriend(String name, String friend) { User user = userRepository.findByName(name); User add = userRepository.findByName(friend); - if (add == null) { + if (add == null ) { throw new ApplicationException("User does not exist"); } user.addFriend(add); + userRepository.save(user); } /** - * Returns the friendlist of the user in JSON. + * Removes a friend from the friendlist of the user. * @param name the username of the user - * @return a userDTO of the logged in user + * @param friend the name of the friend you want to remove. + * @throws ApplicationException if the user is not in the database. */ - public String getLeaderboard(String name) { + public void removeFriend(String name, String friend) { User user = userRepository.findByName(name); - return user.friendsToString(); + User remove = userRepository.findByName(friend); + if (remove == null ) { + throw new ApplicationException("User does not exist"); + } + user.removeFriend(remove); + userRepository.save(user); } /** @@ -108,15 +115,29 @@ public class UserService { && InputValidator.isValidItemValue(inputName, value)) { user.getFootPrintInputs().put(inputName, value); userRepository.save(user); - user.setFootPrint(calculatorService.calculateFootprint(user)); achievementService.updateAchievements(user); - userRepository.save(user); } else { throw new ApplicationException("Invalid input"); } } } + /** + * This method sets extra input for a user. + * @param name name of the user + * @param inputName name of the input of the user + * @param value value of the input + */ + public void setExtraInput(String name, String inputName, Boolean value) { + User user = userRepository.findByName(name); + if (user == null) { + throw new ApplicationException("User does not exist"); + } else { + user.getExtraInputs().put(inputName, value); + userRepository.save(user); + } + } + /** * This method gets the input value of an input. * @param name of the user @@ -132,6 +153,50 @@ public class UserService { } } + /** + * This method gets the map of the inputs. + * @param name of the user + * @return input map + */ + public Map getInputMap(String name) { + User user = userRepository.findByName(name); + return user.getFootPrintInputs(); + } + + /** + * This method gets the map of extra inputs. + * @param name of the user + * @return extra input map + */ + public Map getExtraInputMap(String name) { + User user = userRepository.findByName(name); + return user.getExtraInputs(); + } + + /** + * This method saves the footprint of a user. + * @param name name of the user + * @return footprint of the user + */ + public Float saveFootprint(String name) { + User user = userRepository.findByName(name); + user.setFootPrint(calculatorService.calculateFootprint(user)); + userRepository.save(user); + return user.getFootPrint(); + } + + /** + * This method saves the first footprint of a user. + * @param name name of the user + * @return footprint of the user + */ + public Float saveFirstFootprint(String name) { + User user = userRepository.findByName(name); + user.setFirstFootprint(calculatorService.calculateFootprint(user)); + userRepository.save(user); + return user.getFootPrint(); + } + /** * This method gets the footprint of a user. * @param name name of the user @@ -139,11 +204,34 @@ public class UserService { */ public Float getFootprint(String name) { User user = userRepository.findByName(name); - user.setFootPrint(calculatorService.calculateFootprint(user)); - userRepository.save(user); return user.getFootPrint(); } + /** + * This method gets the first footprint of a user. + * @param name name of the user + * @return first footprint of the user + */ + public Float getFirstFootprint(String name) { + User user = userRepository.findByName(name); + return user.getFirstFootprint(); + } + + /** + * This method gets the friends of a user. + * @param name name of the user + * @return list of the friends + */ + public List getFriends(String name) { + List result = new ArrayList<>(); + User user = userRepository.findByName(name); + List friends = user.getFriends(); + for (User person : friends) { + result.add(person.getName()); + } + return result; + } + /** * This methods sets a achievement. * @param name name of the user @@ -189,14 +277,16 @@ public class UserService { return user.getAchievements(); } - /** - * This method gets a JSON of XML with all users. - * @return JSON/XML of all users + * This method gets the list of all users. + * @return list of all users */ - @GetMapping(path = "/all") - @ResponseBody - public Iterable getAllUsers() { - return userRepository.findAll(); + public List getAllUsers() { + List result = new ArrayList<>(); + Iterable allUsers = userRepository.findAll(); + for (User person : allUsers) { + result.add(person.getName()); + } + return result; } } diff --git a/src/Server/src/test/java/InputValidatorTest.java b/src/Server/src/test/java/InputValidatorTest.java index 6b56ece..8f1239f 100644 --- a/src/Server/src/test/java/InputValidatorTest.java +++ b/src/Server/src/test/java/InputValidatorTest.java @@ -151,7 +151,7 @@ public class InputValidatorTest { put("input_footprint_shopping_services_charity", "146"); put("input_footprint_shopping_services_miscservices", "114"); put("internal_state_abbreviation", "US"); - } + } }; assertTrue(map.size() == InputValidator.getDefaultValues().size()); } diff --git a/src/Server/src/test/java/greenify/server/data/model/UserTest.java b/src/Server/src/test/java/greenify/server/data/model/UserTest.java index ad47984..146d6d8 100644 --- a/src/Server/src/test/java/greenify/server/data/model/UserTest.java +++ b/src/Server/src/test/java/greenify/server/data/model/UserTest.java @@ -6,12 +6,12 @@ import static org.junit.Assert.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import greenify.common.ApplicationException; - import greenify.server.AllAchievements; + import org.junit.Test; import java.util.ArrayList; -import java.util.Collection; +import java.util.List; public class UserTest { @@ -101,7 +101,7 @@ public class UserTest { User second = new User(1L, "merel", "password"); assertEquals(first.getFriends(), second.getFriends()); first.addFriend(second); - ArrayList test = new ArrayList<>(); + ArrayList test = new ArrayList(); test.add(second); assertEquals(first.getFriends(), test); } @@ -110,21 +110,47 @@ public class UserTest { public void addYourselfTest() { User test = new User(1L, "greenify", "password"); assertEquals(test.getFriends(), new ArrayList()); - assertThrows(ApplicationException.class, () -> test.addFriend(test)); + assertThrows(ApplicationException.class, () -> { + test.addFriend(test); + }); } + @Test + public void addTwiceTest() { + User test = new User(1L, "greenify", "password"); + List friendList = new ArrayList<>(); + friendList.add(test); + User user = new User(1L, "green", "pass"); + user.setFriends(friendList); + assertThrows(ApplicationException.class, () -> { + user.addFriend(test); + }); + } @Test - public void friendsToStringTest() { - User first = new User(1L, "greenify", "password"); - User second = new User(1L, "merel", "password"); - first.addFriend(second); - assertEquals(first.friendsToString(), "friends=[{name=merel, footprint=0.0}]"); + public void removeFriendValidTest() { + User test = new User(1L, "greenify", "password"); + List friendList = new ArrayList<>(); + friendList.add(test); + User user = new User(1L, "green", "pass"); + user.setFriends(friendList); + assertEquals(user.getFriends(), friendList); + user.removeFriend(test); + assertEquals(user.getFriends(), new ArrayList()); + } + + @Test + public void removeFriendInvalidTest() { + User user = new User(1L, "greenify", "password"); + User test = new User(2L, "user", "pass"); + assertThrows(ApplicationException.class, () -> { + user.removeFriend(test); + }); } @Test public void setFriendTest() { - Collection friends = new ArrayList<>(); + List friends = new ArrayList(); User first = new User(1L, "greenify", "password"); User second = new User(1L, "merel", "password"); friends.add(second); diff --git a/src/Server/src/test/java/greenify/server/rest/UserControllerTest.java b/src/Server/src/test/java/greenify/server/rest/UserControllerTest.java index 012f4a5..0f868ae 100644 --- a/src/Server/src/test/java/greenify/server/rest/UserControllerTest.java +++ b/src/Server/src/test/java/greenify/server/rest/UserControllerTest.java @@ -78,6 +78,25 @@ public class UserControllerTest { assertEquals("7", arg3Captor.getValue()); } + @Test + public void setExtraInputTest() throws Exception { + ArgumentCaptor arg1Captor = ArgumentCaptor.forClass(String.class); + ArgumentCaptor arg2Captor = ArgumentCaptor.forClass(String.class); + ArgumentCaptor arg3Captor = ArgumentCaptor.forClass(Boolean.class); + mvc.perform(get("/setExtraInput") + .param("name", "ceren") + .param("inputName", "input_size") + .param("value", "true") + .accept(MediaType.APPLICATION_JSON)) + .andDo(print()) + .andExpect(status().isOk()); + verify(userService, times(1)) + .setExtraInput(arg1Captor.capture(), arg2Captor.capture(), arg3Captor.capture()); + assertEquals("ceren", arg1Captor.getValue()); + assertEquals("input_size", arg2Captor.getValue()); + assertEquals(true, arg3Captor.getValue()); + } + @Test public void addFriendTest() throws Exception { ArgumentCaptor arg1Captor = ArgumentCaptor.forClass(String.class); @@ -94,6 +113,68 @@ public class UserControllerTest { assertEquals("merel", arg2Captor.getValue()); } + @Test + public void removeFriendTest() throws Exception { + ArgumentCaptor arg1Captor = ArgumentCaptor.forClass(String.class); + ArgumentCaptor arg2Captor = ArgumentCaptor.forClass(String.class); + mvc.perform(get("/removeFriend") + .param("name", "ceren") + .param("friend", "merel") + .accept(MediaType.APPLICATION_JSON)) + .andDo(print()) + .andExpect(status().isOk()); + verify(userService, times(1)) + .removeFriend(arg1Captor.capture(), arg2Captor.capture()); + assertEquals("ceren", arg1Captor.getValue()); + assertEquals("merel", arg2Captor.getValue()); + } + + @Test + public void getInputMapTest() throws Exception { + ArgumentCaptor arg1Captor = ArgumentCaptor.forClass(String.class); + mvc.perform(get("/getInputs") + .param("name", "ceren") + .accept(MediaType.APPLICATION_JSON)) + .andDo(print()) + .andExpect(status().isOk()); + verify(userService, times(1)) + .getInputMap(arg1Captor.capture()); + assertEquals("ceren", arg1Captor.getValue()); + } + + @Test + public void getExtraInputMapTest() throws Exception { + ArgumentCaptor arg1Captor = ArgumentCaptor.forClass(String.class); + mvc.perform(get("/getExtraInputs") + .param("name", "ceren") + .accept(MediaType.APPLICATION_JSON)) + .andDo(print()) + .andExpect(status().isOk()); + verify(userService, times(1)) + .getExtraInputMap(arg1Captor.capture()); + assertEquals("ceren", arg1Captor.getValue()); + } + + @Test + public void getAllUsersTest() throws Exception { + mvc.perform(get("/getAllUsers") + .accept(MediaType.APPLICATION_JSON)) + .andDo(print()) + .andExpect(status().isOk()); + } + + @Test + public void getFriendNamesTest() throws Exception { + ArgumentCaptor arg1Captor = ArgumentCaptor.forClass(String.class); + mvc.perform(get("/getFriends") + .param("name", "ceren") + .accept(MediaType.APPLICATION_JSON)) + .andDo(print()) + .andExpect(status().isOk()); + verify(userService, times(1)).getFriends(arg1Captor.capture()); + assertEquals("ceren", arg1Captor.getValue()); + } + @Test public void getInputTest() throws Exception { ArgumentCaptor arg1Captor = ArgumentCaptor.forClass(String.class); @@ -121,6 +202,42 @@ public class UserControllerTest { assertEquals("ceren", arg1Captor.getValue()); } + @Test + public void getFirstFootprintTest() throws Exception { + ArgumentCaptor arg1Captor = ArgumentCaptor.forClass(String.class); + mvc.perform(get("/getFirst") + .param("name", "ceren") + .accept(MediaType.APPLICATION_JSON)) + .andDo(print()) + .andExpect(status().isOk()); + verify(userService, times(1)).getFirstFootprint(arg1Captor.capture()); + assertEquals("ceren", arg1Captor.getValue()); + } + + @Test + public void saveFootprintTest() throws Exception { + ArgumentCaptor arg1Captor = ArgumentCaptor.forClass(String.class); + mvc.perform(get("/saveFootprint") + .param("name", "ceren") + .accept(MediaType.APPLICATION_JSON)) + .andDo(print()) + .andExpect(status().isOk()); + verify(userService, times(1)).saveFootprint(arg1Captor.capture()); + assertEquals("ceren", arg1Captor.getValue()); + } + + @Test + public void saveFirstFootprintTest() throws Exception { + ArgumentCaptor arg1Captor = ArgumentCaptor.forClass(String.class); + mvc.perform(get("/saveFirstFootprint") + .param("name", "ceren") + .accept(MediaType.APPLICATION_JSON)) + .andDo(print()) + .andExpect(status().isOk()); + verify(userService, times(1)).saveFirstFootprint(arg1Captor.capture()); + assertEquals("ceren", arg1Captor.getValue()); + } + @Test public void getAchievementsTest() throws Exception { ArgumentCaptor arg1Captor = ArgumentCaptor.forClass(String.class); @@ -132,4 +249,5 @@ public class UserControllerTest { verify(userService, times(1)).getAchievements(arg1Captor.capture()); assertEquals("mika", arg1Captor.getValue()); } + } diff --git a/src/Server/src/test/java/greenify/server/service/UserServiceTest.java b/src/Server/src/test/java/greenify/server/service/UserServiceTest.java index 5cc0950..69f6a08 100644 --- a/src/Server/src/test/java/greenify/server/service/UserServiceTest.java +++ b/src/Server/src/test/java/greenify/server/service/UserServiceTest.java @@ -9,8 +9,10 @@ import greenify.common.UserDto; import greenify.server.AllAchievements; import greenify.server.data.model.User; import greenify.server.data.repository.UserRepository; +import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.TestConfiguration; @@ -19,6 +21,9 @@ import org.springframework.context.annotation.Bean; import org.springframework.test.context.junit4.SpringRunner; import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; @RunWith(SpringRunner.class) public class UserServiceTest { @@ -91,11 +96,27 @@ public class UserServiceTest { .get("input_footprint_shopping_food_dairy_default")); } + @Test + public void setExtraInputTest() { + User alex = new User(1L, "alex", "password"); + when(userRepository.findByName(alex.getName())) + .thenReturn(alex); + userService.setExtraInput("alex", "solar_panels", true); + assertEquals(true, alex.getExtraInputs() + .get("solar_panels")); + } + @Test public void setInputNullTest() { assertThrows(ApplicationException.class, () -> userService.setInput(null, "hello", "5.5")); } + @Test + public void setExtraInputNullTest() { + assertThrows(ApplicationException.class, () -> userService + .setExtraInput(null, "hello", true)); + } + @Test public void setInputApplicationTestItem() { assertThrows(ApplicationException.class, () -> userService @@ -122,7 +143,8 @@ public class UserServiceTest { when(calculatorService.calculateFootprint(alex)) .thenReturn(15f); userService.setInput("alex", "input_footprint_shopping_food_dairy_default", "6.5"); - assertEquals(15f, alex.getFootPrint(), 0.0); + Assert.assertTrue(alex.getFootPrintInputs() + .get("input_footprint_shopping_food_dairy_default").equals("6.5")); } @Test @@ -136,6 +158,28 @@ public class UserServiceTest { .getInput("alex", "input_footprint_shopping_food_dairy_default")); } + @Test + public void getInputMapTest() { + Map map = new HashMap<>(); + User alex = new User(1L, "alex", "password"); + when(userRepository.findByName(alex.getName())) + .thenReturn(alex); + alex.setFootPrintInputs(map); + assertEquals(map, userService + .getInputMap("alex")); + } + + @Test + public void getExtraInputMapTest() { + Map map = new HashMap<>(); + User alex = new User(1L, "alex", "password"); + when(userRepository.findByName(alex.getName())) + .thenReturn(alex); + alex.setExtraInputs(map); + assertEquals(map, userService + .getExtraInputMap("alex")); + } + @Test public void getInputExceptionTest() { assertThrows(ApplicationException.class, () -> userService.getInput("alex", "hello")); @@ -143,18 +187,71 @@ public class UserServiceTest { @Test public void getFootprintTest() { + User alex = new User(1L, "alex", "password"); + alex.setFootPrint(15F); + when(userRepository.findByName(alex.getName())) + .thenReturn(alex); + Assertions.assertEquals(15F, userService.getFootprint("alex")); + } + + @Test + public void getFirstFootprintTest() { + User alex = new User(1L, "alex", "password"); + alex.setFirstFootprint(15F); + when(userRepository.findByName(alex.getName())) + .thenReturn(alex); + Assertions.assertEquals(15F, userService.getFirstFootprint("alex")); + } + + @Test + public void saveFootprintTest() { User alex = new User(1L, "alex", "password"); when(userRepository.findByName(alex.getName())) .thenReturn(alex); when(calculatorService.calculateFootprint(alex)) .thenReturn(15f); - userService.setInput("alex", "input_footprint_shopping_food_dairy_default", "6.5"); - assertEquals(15f, userService.getFootprint("alex"), 0.0); + userService.saveFootprint("alex"); + Assertions.assertEquals(15f, userService.saveFootprint("alex")); + } + + @Test + public void saveFirstFootprintTest() { + User lola = new User(1L, "lola", "password"); + when(userRepository.findByName(lola.getName())) + .thenReturn(lola); + when(calculatorService.calculateFootprint(lola)) + .thenReturn(0f); + userService.saveFirstFootprint("lola"); + Assertions.assertEquals(0f, userService.saveFirstFootprint("lola")); + } + + @Test + public void getFriendsTest() { + User alex = new User(1L, "alex", "password"); + User lola = new User(2L, "lola", "pass"); + when(userRepository.findByName(alex.getName())) + .thenReturn(alex); + when(userRepository.findByName(lola.getName())) + .thenReturn(lola); + alex.addFriend(lola); + List friendList = new ArrayList<>(); + friendList.add("lola"); + assertEquals(friendList, userService.getFriends("alex")); } @Test public void getAllUserTest() { - assertEquals(userRepository.findAll(), userService.getAllUsers()); + User alex = new User(1L, "alex", "password"); + User lola = new User(2L, "lola", "pass"); + Iterable users = new ArrayList<>(); + ((ArrayList) users).add(alex); + ((ArrayList) users).add(lola); + when(userRepository.findAll()) + .thenReturn(users); + List userList = new ArrayList<>(); + userList.add("alex"); + userList.add("lola"); + assertEquals(userList, userService.getAllUsers()); } @Test @@ -174,16 +271,26 @@ public class UserServiceTest { } @Test - public void addFriendsExceptionTest() { - assertThrows(ApplicationException.class, () -> userService.addFriend("greenify", null)); + public void removeFriendTest() { + User alex = userRepository.findByName("alex"); + User lola = userRepository.findByName("lola"); + assertEquals(lola.getFriends(), alex.getFriends()); + userService.addFriend("alex", "lola"); + ArrayList test = new ArrayList(); + test.add(lola); + assertEquals(alex.getFriends(), test); + userService.removeFriend("alex", "lola"); + assertEquals(lola.getFriends(), alex.getFriends()); } @Test - public void leaderboardTest() { - User alex = userRepository.findByName("alex"); - User lola = userRepository.findByName("lola"); - userService.addFriend("alex", "lola"); - assertEquals(userService.getLeaderboard("alex"), "friends=[{name=lola, footprint=0.0}]"); + public void removeFriendNullTest() { + assertThrows(ApplicationException.class, () -> userService.removeFriend("alex", null)); + } + + @Test + public void addFriendNullFriendTest() { + assertThrows(ApplicationException.class, () -> userService.addFriend("alex", null)); } @Test