Merge branch 'update_calculator' into 'master'

Update calculator and new tests

See merge request cse1105/2018-2019/oopp-group-43/template!71
This commit is contained in:
Ceren Ugurlu
2019-04-06 21:57:33 +00:00
30 changed files with 369 additions and 427 deletions

View File

@@ -1,16 +1,17 @@
package greenify.client; package greenify.client;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleFloatProperty; import javafx.beans.property.SimpleFloatProperty;
import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.SimpleStringProperty;
public class Friend { public class Friend {
private SimpleStringProperty friend; private SimpleStringProperty friend;
private SimpleFloatProperty score; private SimpleDoubleProperty score;
public Friend(String friend, Float friendScore) { public Friend(String friend, Double friendScore) {
this.friend = new SimpleStringProperty(friend); this.friend = new SimpleStringProperty(friend);
this.score = new SimpleFloatProperty(friendScore); this.score = new SimpleDoubleProperty(friendScore);
} }
@@ -22,11 +23,11 @@ public class Friend {
this.friend = new SimpleStringProperty(name); this.friend = new SimpleStringProperty(name);
} }
public Float getScore() { public Double getScore() {
return score.get(); return score.get();
} }
public void setScore(Float score) { public void setScore(Double score) {
this.score = new SimpleFloatProperty(score); this.score = new SimpleDoubleProperty(score);
} }
} }

View File

@@ -75,3 +75,4 @@ public class Hints {
} }
} }

View File

@@ -16,7 +16,6 @@ import javafx.fxml.FXML;
import javafx.scene.Node; import javafx.scene.Node;
import javafx.scene.control.Alert; import javafx.scene.control.Alert;
import javafx.scene.control.Button; import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label; import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane; import javafx.scene.control.ScrollPane;
import javafx.scene.control.Slider; import javafx.scene.control.Slider;
@@ -34,7 +33,6 @@ import java.text.DecimalFormat;
@Controller @Controller
public class CalculatorController { public class CalculatorController {
private static UserController.AlertHelper AlertHelper;
@Autowired @Autowired
UserService userService; UserService userService;
@@ -146,15 +144,6 @@ public class CalculatorController {
//extra pane //extra pane
@FXML @FXML
private AnchorPane extraPane; private AnchorPane extraPane;
@FXML
private CheckBox localProduceCheckbox;
@FXML
private CheckBox bikeCheckbox;
@FXML
private CheckBox temperatureCheckbox;
@FXML
private CheckBox solarPanelsCheckbox;
/** /**
* initializes the window, performs some actions before loading all other things. * initializes the window, performs some actions before loading all other things.
@@ -372,7 +361,6 @@ public class CalculatorController {
foodPane.setVisible(false); foodPane.setVisible(false);
shoppingPane.setVisible(false); shoppingPane.setVisible(false);
extraPane.setVisible(true); extraPane.setVisible(true);
} }
/** /**
@@ -407,42 +395,15 @@ public class CalculatorController {
"input_footprint_shopping_services_total", "input_footprint_shopping_services_total",
servicesLabel.getText().replace("€ / month", "")); servicesLabel.getText().replace("€ / month", ""));
} }
checkCheckBoxes();
Float footprint = userService.saveFootprint(userService.currentUser.getName()); Float footprint = userService.saveFootprint(userService.currentUser.getName());
Window owner = saveButton.getScene().getWindow(); Window owner = saveButton.getScene().getWindow();
Stage current = (Stage) owner; Stage current = (Stage) owner;
current.close(); current.close();
controller.updateLeaderboard(); controller.updateLeaderboard();
CalculatorController.AlertHelper.showAlert(Alert.AlertType.CONFIRMATION, UserController.AlertHelper.showAlert(Alert.AlertType.CONFIRMATION,
owner, "Footprint saved!", "Your footprint is saved!"); owner, "Footprint saved!", "Your footprint is saved!");
} }
/**
* Checks the check boxes.
*/
public void checkCheckBoxes() {
if (localProduceCheckbox.isSelected()) {
localProduceCheckbox.setSelected(true);
userService.updateExtraInput(userService.currentUser.getName(),
"local_produce", true);
}
if (bikeCheckbox.isSelected()) {
bikeCheckbox.setSelected(true);
userService.updateExtraInput(userService.currentUser.getName(),
"bike", true);
}
if (temperatureCheckbox.isSelected()) {
temperatureCheckbox.setSelected(true);
userService.updateExtraInput(userService.currentUser.getName(),
"temperature", true);
}
if (solarPanelsCheckbox.isSelected()) {
solarPanelsCheckbox.setSelected(true);
userService.updateExtraInput(userService.currentUser.getName(),
"solar_panels", true);
}
}
/** /**
* Checks the food labels. * Checks the food labels.
*/ */
@@ -477,7 +438,7 @@ public class CalculatorController {
} }
/** /**
* Checks the housing labels. * Checks the house labels.
*/ */
public void checkHousingLabels() { public void checkHousingLabels() {
if (!electricityField.getText().equals("0")) { if (!electricityField.getText().equals("0")) {
@@ -531,30 +492,30 @@ public class CalculatorController {
"input_footprint_transportation_miles1", "input_footprint_transportation_miles1",
carTravelGasolineField.getText()); carTravelGasolineField.getText());
} }
if (!carTravelGasolineLabel.getText().replace(" mpg", "").equals("0")) { if (!carTravelGasolineLabel.getText().replace(" km/L", "").equals("0")) {
userService.updateInput(userService.currentUser.getName(), userService.updateInput(userService.currentUser.getName(),
"input_footprint_transportation_mpg1", "input_footprint_transportation_mpg1",
carTravelGasolineLabel.getText().replace(" mpg", "")); carTravelGasolineLabel.getText().replace(" km/L", ""));
} }
if (!carTravelDieselField.getText().equals("0")) { if (!carTravelDieselField.getText().equals("0")) {
userService.updateInput(userService.currentUser.getName(), userService.updateInput(userService.currentUser.getName(),
"input_footprint_transportation_miles2", "input_footprint_transportation_miles2",
carTravelDieselField.getText()); carTravelDieselField.getText());
} }
if (!carTravelDieselLabel.getText().replace(" mpg", "").equals("0")) { if (!carTravelDieselLabel.getText().replace(" km/L", "").equals("0")) {
userService.updateInput(userService.currentUser.getName(), userService.updateInput(userService.currentUser.getName(),
"input_footprint_transportation_mpg2", "input_footprint_transportation_mpg2",
carTravelDieselLabel.getText().replace(" mpg", "")); carTravelDieselLabel.getText().replace(" km/L", ""));
} }
if (!carTravelElectricField.getText().equals("0")) { if (!carTravelElectricField.getText().equals("0")) {
userService.updateInput(userService.currentUser.getName(), userService.updateInput(userService.currentUser.getName(),
"input_footprint_transportation_miles3", "input_footprint_transportation_miles3",
carTravelElectricField.getText()); carTravelElectricField.getText());
} }
if (!carTravelElectricLabel.getText().replace(" mpge", "").equals("0")) { if (!carTravelElectricLabel.getText().replace(" km/Le", "").equals("0")) {
userService.updateInput(userService.currentUser.getName(), userService.updateInput(userService.currentUser.getName(),
"input_footprint_transportation_mpg3", "input_footprint_transportation_mpg3",
carTravelElectricLabel.getText().replace(" mpge", "")); carTravelElectricLabel.getText().replace(" km/Le", ""));
} }
} }
} }

View File

@@ -17,7 +17,6 @@ import javafx.scene.Parent;
import javafx.scene.Scene; import javafx.scene.Scene;
import javafx.scene.chart.PieChart; import javafx.scene.chart.PieChart;
import javafx.scene.control.Button; import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label; import javafx.scene.control.Label;
import javafx.scene.control.TableColumn; import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView; import javafx.scene.control.TableView;
@@ -168,16 +167,16 @@ public class DashBoardController {
@FXML @FXML
private ImageView achiev1image; private ImageView achiev1image;
@FXML @FXML
private CheckBox localProduce;
@FXML
private CheckBox loweringTemp;
@FXML
private CheckBox bike;
@FXML
private CheckBox solarPanels;
@FXML
private Label hintText; private Label hintText;
@FXML @FXML
private Label solarPanels;
@FXML
private Label localProduce;
@FXML
private Label bike;
@FXML
private Label loweringTemp;
@FXML
private Button refreshHintsButton; private Button refreshHintsButton;
/** /**
@@ -249,8 +248,8 @@ public class DashBoardController {
public void sortScores(List<String> users) throws InterruptedException { public void sortScores(List<String> users) throws InterruptedException {
for (int i = 0; i < users.size(); i++) { for (int i = 0; i < users.size(); i++) {
for (int j = 0; j < users.size(); j++) { for (int j = 0; j < users.size(); j++) {
Float firstScore = userService.getFootprint(users.get(i)); Double firstScore = userService.getFootprint(users.get(i));
Float secondScore = userService.getFootprint(users.get(j)); Double secondScore = userService.getFootprint(users.get(j));
if (i > j && firstScore < secondScore) { if (i > j && firstScore < secondScore) {
String temp = users.get(i); String temp = users.get(i);
users.set(i, users.get(j)); users.set(i, users.get(j));
@@ -272,9 +271,9 @@ public class DashBoardController {
public void sortDiffScores(List<String> users) throws InterruptedException { public void sortDiffScores(List<String> users) throws InterruptedException {
for (int i = 0; i < users.size(); i++) { for (int i = 0; i < users.size(); i++) {
for (int j = 0; j < users.size(); j++) { for (int j = 0; j < users.size(); j++) {
Float firstDiff = userService.getFirstFootprint(users.get(i)) - userService Double firstDiff = userService.getFirstFootprint(users.get(i)) - userService
.getFootprint(users.get(i)); .getFootprint(users.get(i));
Float secondDiff = userService.getFirstFootprint(users.get(j)) - userService Double secondDiff = userService.getFirstFootprint(users.get(j)) - userService
.getFootprint(users.get(j)); .getFootprint(users.get(j));
if (i < j && firstDiff < secondDiff) { if (i < j && firstDiff < secondDiff) {
String temp = users.get(i); String temp = users.get(i);
@@ -356,18 +355,11 @@ public class DashBoardController {
dairy.setText(inputMap.get("input_footprint_shopping_food_dairy")); dairy.setText(inputMap.get("input_footprint_shopping_food_dairy"));
fruits.setText(inputMap.get("input_footprint_shopping_food_fruitvegetables")); fruits.setText(inputMap.get("input_footprint_shopping_food_fruitvegetables"));
snacks.setText(inputMap.get("input_footprint_shopping_food_otherfood")); snacks.setText(inputMap.get("input_footprint_shopping_food_otherfood"));
if (userService.getExtraInputs(userService.currentUser.getName()).get("local_produce")) { Map<String, String> extraMap = userService.getExtraInputs(userService.currentUser.getName());
localProduce.setSelected(true); localProduce.setText(extraMap.get("local_produce"));
} bike.setText(extraMap.get("bike"));
if (userService.getExtraInputs(userService.currentUser.getName()).get("bike")) { solarPanels.setText(extraMap.get("solar_panels"));
bike.setSelected(true); loweringTemp.setText(extraMap.get("temperature"));
}
if (userService.getExtraInputs(userService.currentUser.getName()).get("temperature")) {
loweringTemp.setSelected(true);
}
if (userService.getExtraInputs(userService.currentUser.getName()).get("solar_panels")) {
solarPanels.setSelected(true);
}
} }
/** /**
@@ -380,9 +372,9 @@ public class DashBoardController {
footprintLabel.setText("" + userService.getFootprint(userService.currentUser.getName())); footprintLabel.setText("" + userService.getFootprint(userService.currentUser.getName()));
firstFootprintLabel.setText("" + userService firstFootprintLabel.setText("" + userService
.getFirstFootprint(userService.currentUser.getName())); .getFirstFootprint(userService.currentUser.getName()));
Float diff = userService.getFirstFootprint(userService.currentUser.getName()) - userService Double diff = userService.getFirstFootprint(userService.currentUser.getName()) - userService
.getFootprint(userService.currentUser.getName()); .getFootprint(userService.currentUser.getName());
differenceLabel.setText( "" + diff); differenceLabel.setText( "" + Math.round(diff * 10) / 10.0);
usernameLabel.setText("" + userService.currentUser.getName()); usernameLabel.setText("" + userService.currentUser.getName());
addFadeTransition(userPane); addFadeTransition(userPane);
System.out.println("display user"); System.out.println("display user");
@@ -390,7 +382,6 @@ public class DashBoardController {
userPane.setVisible(true); userPane.setVisible(true);
activitiesPane.setVisible(false); activitiesPane.setVisible(false);
friendsPane.setVisible(false); friendsPane.setVisible(false);
} }
/** /**
@@ -526,9 +517,9 @@ public class DashBoardController {
sortDiffScores(userList); sortDiffScores(userList);
for (int j = 0; j < userList.size(); j++) { for (int j = 0; j < userList.size(); j++) {
Friend user = new Friend(userList.get(j), userService.getFootprint(userList.get(j))); Friend user = new Friend(userList.get(j), userService.getFootprint(userList.get(j)));
Friend diffUser = new Friend(userList.get(j), userService double diff = Math.round((userService.getFirstFootprint(userList.get(j))
.getFirstFootprint(userList.get(j)) - userService.getFootprint(userList.get(j))) * 10) / 10.0;
- userService.getFootprint(userList.get(j))); Friend diffUser = new Friend(userList.get(j), diff);
globalLeaderData.add(user); globalLeaderData.add(user);
developmentData.add(diffUser); developmentData.add(diffUser);
} }
@@ -558,9 +549,9 @@ public class DashBoardController {
data.add(user); data.add(user);
} }
for (int j = 0; j < wholeList.size(); j++) { for (int j = 0; j < wholeList.size(); j++) {
Friend diffUser = new Friend(wholeList.get(j), double diff = Math.round((userService.getFirstFootprint(wholeList.get(j))
userService.getFirstFootprint(wholeList.get(j)) - userService.getFootprint(wholeList.get(j))) * 10) / 10.0;
- userService.getFootprint(wholeList.get(j))); Friend diffUser = new Friend(wholeList.get(j), diff);
friendLeaderData.add(diffUser); friendLeaderData.add(diffUser);
} }
friendsTable.setItems(data); friendsTable.setItems(data);
@@ -642,6 +633,4 @@ public class DashBoardController {
button.setOnMouseExited(e -> scaleDown.playFromStart()); button.setOnMouseExited(e -> scaleDown.playFromStart());
} }
} }
} }

View File

@@ -8,20 +8,28 @@ import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue; import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent; import javafx.event.ActionEvent;
import javafx.fxml.FXML; import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.Button; import javafx.scene.control.Button;
import javafx.scene.control.Label; import javafx.scene.control.Label;
import javafx.scene.control.Slider; import javafx.scene.control.Slider;
import javafx.scene.layout.AnchorPane; import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import javafx.stage.Window;
import javafx.util.Duration; import javafx.util.Duration;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
@Controller @Controller
public class ExtraActivityController { public class ExtraActivityController {
@Autowired @Autowired
UserService userService; UserService userService;
@Autowired
CalculatorController calculatorController;
@Autowired
DashBoardController controller;
@FXML @FXML
private AnchorPane veganMealPane; private AnchorPane veganMealPane;
@FXML @FXML
@@ -59,6 +67,8 @@ public class ExtraActivityController {
private Slider solarPanelsSlider; private Slider solarPanelsSlider;
@FXML @FXML
private Label solarPanelsLabel; private Label solarPanelsLabel;
@FXML
private Button saveButton;
/** /**
* initializes the sliders and labels before loading. * initializes the sliders and labels before loading.
@@ -78,7 +88,6 @@ public class ExtraActivityController {
displayBikeButton.setSkin(new TranslateButtonSkin(displayBikeButton)); displayBikeButton.setSkin(new TranslateButtonSkin(displayBikeButton));
displayTemperatureButton.setSkin(new TranslateButtonSkin(displayTemperatureButton)); displayTemperatureButton.setSkin(new TranslateButtonSkin(displayTemperatureButton));
displaySolarPanelButton.setSkin(new TranslateButtonSkin(displaySolarPanelButton)); displaySolarPanelButton.setSkin(new TranslateButtonSkin(displaySolarPanelButton));
} }
/** /**
@@ -150,6 +159,43 @@ public class ExtraActivityController {
solarPanelPane.setVisible(true); solarPanelPane.setVisible(true);
} }
/**
* The method updates the values
*/
@SuppressWarnings("Duplicates")
public void save(ActionEvent event) throws InterruptedException {
Window owner = saveButton.getScene().getWindow();
Float footprint = userService.saveFootprint(userService.currentUser.getName());
controller.updateLeaderboard();
Stage current = (Stage) owner;
current.close();
UserController.AlertHelper.showAlert(Alert.AlertType.CONFIRMATION, owner, "Activities are added!",
"Your new activities are added!");
}
/**
* The method updates the values of extras.
* @param event user clicks to button
*/
@SuppressWarnings("Duplicates")
public void updateExtras(ActionEvent event) throws InterruptedException {
if (!bikeLabel.getText().replace(" km", "").equals("0")) {
userService.updateExtraInput(userService.currentUser.getName(),
"bike",
bikeLabel.getText().replace(" km", ""));
}
if (!solarPanelsLabel.getText().equals("0")) {
userService.updateExtraInput(userService.currentUser.getName(),
"solar_panels",
solarPanelsLabel.getText());
}
if (!temperatureLabel.getText().replace(" Degrees", "").equals("0")) {
userService.updateExtraInput(userService.currentUser.getName(),
"bike",
temperatureLabel.getText().replace(" Degrees", ""));
}
}
public class TranslateButtonSkin extends ButtonSkin { public class TranslateButtonSkin extends ButtonSkin {
/** /**
* button skin that sets a translate animation on entering and exiting the button. * button skin that sets a translate animation on entering and exiting the button.

View File

@@ -1,9 +1,14 @@
package greenify.client.controller; package greenify.client.controller;
import com.sun.javafx.scene.control.skin.ButtonSkin;
import greenify.client.Application; import greenify.client.Application;
import greenify.client.rest.UserService; import greenify.client.rest.UserService;
import javafx.animation.*; import javafx.animation.FadeTransition;
import javafx.animation.Interpolator;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.ParallelTransition;
import javafx.animation.Timeline;
import javafx.animation.TranslateTransition;
import javafx.beans.value.ChangeListener; import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue; import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent; import javafx.event.ActionEvent;
@@ -13,7 +18,6 @@ import javafx.scene.Parent;
import javafx.scene.Scene; import javafx.scene.Scene;
import javafx.scene.control.Alert; import javafx.scene.control.Alert;
import javafx.scene.control.Button; import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label; import javafx.scene.control.Label;
import javafx.scene.control.PasswordField; import javafx.scene.control.PasswordField;
import javafx.scene.control.ScrollPane; import javafx.scene.control.ScrollPane;
@@ -36,12 +40,11 @@ import java.util.concurrent.TimeUnit;
*/ */
@Controller @Controller
public class RegisterWindowController { public class RegisterWindowController {
@Autowired @Autowired
UserService userService; UserService userService;
@Autowired @Autowired
DashBoardController controller; ExtraActivityController extraActivityController;
//navigation panes //navigation panes
@FXML @FXML
@@ -148,15 +151,6 @@ public class RegisterWindowController {
//extra pane //extra pane
@FXML @FXML
private AnchorPane extraPane; private AnchorPane extraPane;
@FXML
private CheckBox localProduceCheckbox;
@FXML
private CheckBox bikeCheckbox;
@FXML
private CheckBox temperatureCheckbox;
@FXML
private CheckBox solarPanelsCheckbox;
@FXML @FXML
private TextField userNameText; private TextField userNameText;
@FXML @FXML
@@ -177,7 +171,6 @@ public class RegisterWindowController {
addSlideAnimation(1100, passwordField, 300); addSlideAnimation(1100, passwordField, 300);
TimeUnit.MILLISECONDS.sleep(300); TimeUnit.MILLISECONDS.sleep(300);
addSlideAnimation(1100, passwordField2, -420); addSlideAnimation(1100, passwordField2, -420);
signUpButton.setSkin(new SignUpButtonSkin(signUpButton));
} }
/** /**
@@ -267,9 +260,9 @@ public class RegisterWindowController {
} }
}); });
addSliderListenerCarUsage(carTravelGasolineSlider, carTravelGasolineLabel, " mpg"); addSliderListenerCarUsage(carTravelGasolineSlider, carTravelGasolineLabel, " km/L");
addSliderListenerCarUsage(carTravelDieselSlider, carTravelDieselLabel, " mpg"); addSliderListenerCarUsage(carTravelDieselSlider, carTravelDieselLabel, " km/L");
addSliderListenerCarUsage(carTravelElectricSlider, carTravelElectricLabel, " mpge"); addSliderListenerCarUsage(carTravelElectricSlider, carTravelElectricLabel, " km/Le");
cleanEnergyPurchasedSlider.valueProperty().addListener(new ChangeListener<Number>() { cleanEnergyPurchasedSlider.valueProperty().addListener(new ChangeListener<Number>() {
@Override @Override
@@ -312,6 +305,7 @@ public class RegisterWindowController {
}); });
} }
@SuppressWarnings("Duplicates")
private void addSliderListenerDailyServing(Slider slider, Label label) { private void addSliderListenerDailyServing(Slider slider, Label label) {
DecimalFormat df = new DecimalFormat("0.0"); DecimalFormat df = new DecimalFormat("0.0");
slider.valueProperty().addListener(new ChangeListener<Number>() { slider.valueProperty().addListener(new ChangeListener<Number>() {
@@ -333,6 +327,23 @@ public class RegisterWindowController {
}); });
} }
/**
* adds a fade transition to the given node.
* @param node the node to add the transition to
*/
public void addFadeTransAnimation(Node node) {
FadeTransition fade = new FadeTransition(Duration.millis(350), node);
fade.setFromValue(0);
fade.setToValue(1.0);
TranslateTransition trans = new TranslateTransition(Duration.millis(350), node);
trans.setFromY(800);
trans.setToY(0);
ParallelTransition par = new ParallelTransition();
par.setNode(travelPane);
par.getChildren().addAll(fade, trans);
par.play();
}
private void addSlideInAnimation(Node node) { private void addSlideInAnimation(Node node) {
Timeline timeline = new Timeline(); Timeline timeline = new Timeline();
KeyValue keyValue = new KeyValue(node.translateXProperty(), 0, Interpolator.EASE_OUT); KeyValue keyValue = new KeyValue(node.translateXProperty(), 0, Interpolator.EASE_OUT);
@@ -348,6 +359,7 @@ public class RegisterWindowController {
*/ */
@SuppressWarnings("Duplicates") @SuppressWarnings("Duplicates")
public void displayGetStarted(ActionEvent event) { public void displayGetStarted(ActionEvent event) {
addFadeTransAnimation(getStartedPane);
getStartedPane.setVisible(true); getStartedPane.setVisible(true);
travelPane.setVisible(false); travelPane.setVisible(false);
homePane.setVisible(false); homePane.setVisible(false);
@@ -363,7 +375,7 @@ public class RegisterWindowController {
*/ */
@SuppressWarnings("Duplicates") @SuppressWarnings("Duplicates")
public void displayTravel(ActionEvent event) { public void displayTravel(ActionEvent event) {
addSlideInAnimation(travelPane); addFadeTransAnimation(travelPane);
getStartedPane.setVisible(false); getStartedPane.setVisible(false);
travelPane.setVisible(true); travelPane.setVisible(true);
homePane.setVisible(false); homePane.setVisible(false);
@@ -380,6 +392,7 @@ public class RegisterWindowController {
*/ */
@SuppressWarnings("Duplicates") @SuppressWarnings("Duplicates")
public void displayHome(ActionEvent event) { public void displayHome(ActionEvent event) {
addFadeTransAnimation(homePane);
getStartedPane.setVisible(false); getStartedPane.setVisible(false);
travelPane.setVisible(false); travelPane.setVisible(false);
homePane.setVisible(true); homePane.setVisible(true);
@@ -395,6 +408,7 @@ public class RegisterWindowController {
*/ */
@SuppressWarnings("Duplicates") @SuppressWarnings("Duplicates")
public void displayFood(ActionEvent event) { public void displayFood(ActionEvent event) {
addFadeTransAnimation(foodPane);
getStartedPane.setVisible(false); getStartedPane.setVisible(false);
travelPane.setVisible(false); travelPane.setVisible(false);
homePane.setVisible(false); homePane.setVisible(false);
@@ -410,6 +424,7 @@ public class RegisterWindowController {
*/ */
@SuppressWarnings("Duplicates") @SuppressWarnings("Duplicates")
public void displayShopping(ActionEvent event) { public void displayShopping(ActionEvent event) {
addFadeTransAnimation(shoppingPane);
getStartedPane.setVisible(false); getStartedPane.setVisible(false);
travelPane.setVisible(false); travelPane.setVisible(false);
homePane.setVisible(false); homePane.setVisible(false);
@@ -424,7 +439,10 @@ public class RegisterWindowController {
* @param event the click of the designated button * @param event the click of the designated button
*/ */
@SuppressWarnings("Duplicates") @SuppressWarnings("Duplicates")
public void displayExtra(ActionEvent event) { public void displayExtra(ActionEvent event) throws IOException {
addFadeTransAnimation(extraPane);
extraPane.getChildren().setAll((Node) Application.load(this.getClass()
.getClassLoader().getResource("fxml/extraActivities.fxml")));
getStartedPane.setVisible(false); getStartedPane.setVisible(false);
travelPane.setVisible(false); travelPane.setVisible(false);
homePane.setVisible(false); homePane.setVisible(false);
@@ -466,27 +484,13 @@ public class RegisterWindowController {
"input_footprint_shopping_services_total", "input_footprint_shopping_services_total",
servicesLabel.getText().replace("€ / month", "")); servicesLabel.getText().replace("€ / month", ""));
} }
if (localProduceCheckbox.isSelected()) {
userService.updateExtraInput(userService.currentUser.getName(),
"local_produce", true);
}
if (bikeCheckbox.isSelected()) {
userService.updateExtraInput(userService.currentUser.getName(),
"bike", true);
}
if (temperatureCheckbox.isSelected()) {
userService.updateExtraInput(userService.currentUser.getName(),
"temperature", true);
}
if (solarPanelsCheckbox.isSelected()) {
userService.updateExtraInput(userService.currentUser.getName(),
"solar_panels", true);
}
Float firstFootprint = userService.saveFirstFootprint(userService.currentUser.getName()); Float firstFootprint = userService.saveFirstFootprint(userService.currentUser.getName());
Float footprint = userService.saveFootprint(userService.currentUser.getName()); Float footprint = userService.saveFootprint(userService.currentUser.getName());
Window owner = saveButton.getScene().getWindow(); Window owner = saveButton.getScene().getWindow();
Stage current = (Stage) owner; Stage current = (Stage) owner;
current.close(); current.close();
UserController.AlertHelper.showAlert(Alert.AlertType.CONFIRMATION,
owner, "Footprint saved!", "Your footprint is saved!");
} }
/** /**
@@ -577,57 +581,30 @@ public class RegisterWindowController {
"input_footprint_transportation_miles1", "input_footprint_transportation_miles1",
carTravelGasolineField.getText()); carTravelGasolineField.getText());
} }
if (!carTravelGasolineLabel.getText().replace(" mpg", "").equals("0")) { if (!carTravelGasolineLabel.getText().replace(" km/L", "").equals("0")) {
userService.updateInput(userService.currentUser.getName(), userService.updateInput(userService.currentUser.getName(),
"input_footprint_transportation_mpg1", "input_footprint_transportation_mpg1",
carTravelGasolineLabel.getText().replace(" mpg", "")); carTravelGasolineLabel.getText().replace(" km/L", ""));
} }
if (!carTravelDieselField.getText().equals("0")) { if (!carTravelDieselField.getText().equals("0")) {
userService.updateInput(userService.currentUser.getName(), userService.updateInput(userService.currentUser.getName(),
"input_footprint_transportation_miles2", "input_footprint_transportation_miles2",
carTravelDieselField.getText()); carTravelDieselField.getText());
} }
if (!carTravelDieselLabel.getText().replace(" mpg", "").equals("0")) { if (!carTravelDieselLabel.getText().replace(" km/L", "").equals("0")) {
userService.updateInput(userService.currentUser.getName(), userService.updateInput(userService.currentUser.getName(),
"input_footprint_transportation_mpg2", "input_footprint_transportation_mpg2",
carTravelDieselLabel.getText().replace(" mpg", "")); carTravelDieselLabel.getText().replace(" km/L", ""));
} }
if (!carTravelElectricField.getText().equals("0")) { if (!carTravelElectricField.getText().equals("0")) {
userService.updateInput(userService.currentUser.getName(), userService.updateInput(userService.currentUser.getName(),
"input_footprint_transportation_miles3", "input_footprint_transportation_miles3",
carTravelElectricField.getText()); carTravelElectricField.getText());
} }
if (!carTravelElectricLabel.getText().replace(" mpge", "").equals("0")) { if (!carTravelElectricLabel.getText().replace(" km/Le", "").equals("0")) {
userService.updateInput(userService.currentUser.getName(), userService.updateInput(userService.currentUser.getName(),
"input_footprint_transportation_mpg3", "input_footprint_transportation_mpg3",
carTravelElectricLabel.getText().replace(" mpge", "")); carTravelElectricLabel.getText().replace(" km/Le", ""));
}
}
@SuppressWarnings("Duplicates")
private class SignUpButtonSkin extends ButtonSkin {
/**
* button skin for the 'add activity' buttons.
* adds scale animations on entering, clicking and extiting the button
* @param button the button to set the skin of
*/
private SignUpButtonSkin(Button button) {
super(button);
//transition to scale up on hover
final ScaleTransition scaleUp = new ScaleTransition(Duration.millis(85));
//add the node and the position to scale to
scaleUp.setNode(button);
scaleUp.setToX(1.1);
scaleUp.setToY(1.1);
//play the transition when hovered over the button
button.setOnMouseEntered(e -> scaleUp.playFromStart());
final ScaleTransition scaleDown = new ScaleTransition(Duration.millis(85));
scaleDown.setNode(button);
scaleDown.setToX(1.0);
scaleDown.setToY(1.0);
button.setOnMouseExited(e -> scaleDown.playFromStart());
} }
} }
} }

View File

@@ -1,10 +1,7 @@
package greenify.client.controller; package greenify.client.controller;
import com.sun.javafx.scene.control.skin.ButtonSkin;
import greenify.client.Application; import greenify.client.Application;
import greenify.client.rest.UserService; import greenify.client.rest.UserService;
import javafx.animation.FillTransition;
import javafx.animation.ScaleTransition;
import javafx.event.ActionEvent; import javafx.event.ActionEvent;
import javafx.fxml.FXML; import javafx.fxml.FXML;
import javafx.scene.Parent; import javafx.scene.Parent;
@@ -13,10 +10,8 @@ import javafx.scene.control.Alert;
import javafx.scene.control.Button; import javafx.scene.control.Button;
import javafx.scene.control.PasswordField; import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField; import javafx.scene.control.TextField;
import javafx.scene.paint.Color;
import javafx.stage.Stage; import javafx.stage.Stage;
import javafx.stage.Window; import javafx.stage.Window;
import javafx.util.Duration;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
@@ -40,11 +35,6 @@ public class UserController {
@FXML @FXML
private Button signUpButton; private Button signUpButton;
public void initialize() {
loginButton.setSkin(new LoginButtonSkin(loginButton));
signUpButton.setSkin(new LoginButtonSkin(signUpButton));
}
/** /**
* Handles when the user clicks on the login button. * Handles when the user clicks on the login button.
* it checks if the username and password fields are filled * it checks if the username and password fields are filled
@@ -145,39 +135,11 @@ public class UserController {
Parent registerWindow = Application.load(this.getClass().getClassLoader() Parent registerWindow = Application.load(this.getClass().getClassLoader()
.getResource("fxml/RegisterWindow.fxml")); .getResource("fxml/RegisterWindow.fxml"));
Scene registerScene = new Scene(registerWindow); Scene registerScene = new Scene(registerWindow);
registerScene.getStylesheets().add(Application.class.getClassLoader()
.getResource("stylesheets/registerWindowStyle.css").toExternalForm());
Stage registerStage = new Stage(); Stage registerStage = new Stage();
registerStage.setScene(registerScene); registerStage.setScene(registerScene);
registerStage.setTitle("Enter register credentials"); registerStage.setTitle("Enter register credentials");
registerStage.show(); registerStage.show();
} }
@SuppressWarnings("Duplicates")
private class LoginButtonSkin extends ButtonSkin {
/**
* button skin for the 'add activity' buttons.
* adds scale animations on entering, clicking and extiting the button
* @param button the button to set the skin of
*/
private LoginButtonSkin(Button button) {
super(button);
//transition to scale up on hover
final ScaleTransition scaleUp = new ScaleTransition(Duration.millis(85));
//add the node and the position to scale to
scaleUp.setNode(button);
scaleUp.setToX(1.1);
scaleUp.setToY(1.1);
//play the transition when hovered over the button
button.setOnMouseEntered(e -> scaleUp.playFromStart());
final ScaleTransition scaleDown = new ScaleTransition(Duration.millis(85));
scaleDown.setNode(button);
scaleDown.setToX(1.0);
scaleDown.setToY(1.0);
button.setOnMouseExited(e -> scaleDown.playFromStart());
}
}
} }

View File

@@ -109,13 +109,13 @@ public class UserService {
* @param value value of the input * @param value value of the input
*/ */
@SuppressWarnings("Duplicates") @SuppressWarnings("Duplicates")
public void updateExtraInput(String name, String inputName, Boolean value) { public void updateExtraInput(String name, String inputName, String value) {
HttpHeaders headers = new HttpHeaders(); HttpHeaders headers = new HttpHeaders();
headers.set("Accept", MediaType.APPLICATION_JSON_VALUE); headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("http://localhost:8080/setExtraInput") UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("http://localhost:8080/setExtraInput")
.queryParam("name", name) .queryParam("name", name)
.queryParam("inputName", inputName) .queryParam("inputName", inputName)
.queryParam("value",value); .queryParam("value", value);
new HttpEntity<>(headers); new HttpEntity<>(headers);
System.out.println(builder.build().encode().toUri()); System.out.println(builder.build().encode().toUri());
ResponseEntity<String> authenticateResponse = this.restTemplate.getForEntity(builder.build() ResponseEntity<String> authenticateResponse = this.restTemplate.getForEntity(builder.build()
@@ -128,15 +128,16 @@ public class UserService {
* @return returns the footprint score * @return returns the footprint score
*/ */
@SuppressWarnings("Duplicates") @SuppressWarnings("Duplicates")
public Float getFootprint(String name) { public double getFootprint(String name) {
HttpHeaders headers = new HttpHeaders(); HttpHeaders headers = new HttpHeaders();
headers.set("Accept", MediaType.APPLICATION_JSON_VALUE); headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("http://localhost:8080/getFootprint") UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("http://localhost:8080/getFootprint")
.queryParam("name", name); .queryParam("name", name);
new HttpEntity<>(headers); new HttpEntity<>(headers);
System.out.println(builder.build().encode().toUri()); System.out.println(builder.build().encode().toUri());
Float result = this.restTemplate.getForObject(builder Float footprint = this.restTemplate.getForObject(builder
.build().encode().toUri(), Float.class); .build().encode().toUri(), Float.class);
double result = Math.round(footprint * 10) / 10.0;
return result; return result;
} }
@@ -145,7 +146,7 @@ public class UserService {
* @param name name of the user * @param name name of the user
* @return returns the footprint score * @return returns the footprint score
*/ */
public Float getFirstFootprint(String name) { public double getFirstFootprint(String name) {
HttpHeaders headers = new HttpHeaders(); HttpHeaders headers = new HttpHeaders();
headers.set("Accept", MediaType.APPLICATION_JSON_VALUE); headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("http://localhost:8080/getFirst") UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("http://localhost:8080/getFirst")
@@ -154,7 +155,8 @@ public class UserService {
System.out.println(builder.build().encode().toUri()); System.out.println(builder.build().encode().toUri());
Float footprint = this.restTemplate.getForObject(builder Float footprint = this.restTemplate.getForObject(builder
.build().encode().toUri(), Float.class); .build().encode().toUri(), Float.class);
return footprint; double result = Math.round(footprint * 10) / 10.0;
return result;
} }
/** /**
@@ -270,14 +272,14 @@ public class UserService {
* @param name the username of the current user. * @param name the username of the current user.
*/ */
@SuppressWarnings("Duplicates") @SuppressWarnings("Duplicates")
public Map<String, Boolean> getExtraInputs(String name) { public Map<String, String> getExtraInputs(String name) {
HttpHeaders headers = new HttpHeaders(); HttpHeaders headers = new HttpHeaders();
headers.set("Accept", MediaType.APPLICATION_JSON_VALUE); headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("http://localhost:8080/getExtraInputs") UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("http://localhost:8080/getExtraInputs")
.queryParam("name", name); .queryParam("name", name);
HttpEntity<?> entity = new HttpEntity<>(headers); HttpEntity<?> entity = new HttpEntity<>(headers);
System.out.println(builder.build().encode().toUri()); System.out.println(builder.build().encode().toUri());
Map<String, Boolean> result = this.restTemplate.getForObject(builder.build() Map<String, String> result = this.restTemplate.getForObject(builder.build()
.encode().toUri(), Map.class); .encode().toUri(), Map.class);
return result; return result;
} }

View File

@@ -1,26 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.shape.*?> <?import javafx.scene.shape.*?>
<?import java.lang.*?>
<?import javafx.geometry.*?> <?import javafx.geometry.*?>
<?import javafx.scene.control.*?> <?import javafx.scene.control.*?>
<?import javafx.scene.image.*?> <?import javafx.scene.image.*?>
<?import javafx.scene.layout.*?> <?import javafx.scene.layout.*?>
<?import javafx.scene.text.*?> <?import javafx.scene.text.*?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.ScrollPane?>
<?import javafx.scene.control.Slider?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.image.Image?>
<?import javafx.scene.image.ImageView?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.text.Font?>
<?import javafx.scene.text.Text?>
<AnchorPane prefHeight="703.0" prefWidth="820.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="greenify.client.controller.CalculatorController"> <AnchorPane prefHeight="703.0" prefWidth="820.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="greenify.client.controller.RegisterWindowController">
<children> <children>
<AnchorPane fx:id="calculatorTabs" prefHeight="92.0" prefWidth="820.0" style="-fx-background-color: #677069;"> <AnchorPane fx:id="calculatorTabs" prefHeight="92.0" prefWidth="820.0" style="-fx-background-color: #677069;">
<children> <children>

View File

@@ -1,6 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import javafx.scene.control.*?> <?import javafx.scene.control.*?>
<?import javafx.scene.image.*?> <?import javafx.scene.image.*?>
<?import javafx.scene.layout.*?> <?import javafx.scene.layout.*?>
@@ -25,7 +24,7 @@
<Font size="13.0" /> <Font size="13.0" />
</font> </font>
</TextField> </TextField>
<Button fx:id="signUpButton" layoutX="115.0" layoutY="229.0" mnemonicParsing="false" onAction="#handleSignUpButton" text="Sign up!" textFill="#c4eec9"> <Button fx:id="signUpButton" layoutX="115.0" layoutY="229.0" mnemonicParsing="false" onAction="#handleSignUpButton" style="-fx-background-color: #005e07;" text="Sign up!" textFill="#c4eec9">
<font> <font>
<Font name="Corbel Bold" size="14.0" /> <Font name="Corbel Bold" size="14.0" />
</font> </font>

View File

@@ -1,15 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import javafx.scene.chart.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.image.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.shape.*?>
<?import javafx.scene.text.*?>
<?import javafx.scene.chart.PieChart?> <?import javafx.scene.chart.PieChart?>
<?import javafx.scene.control.Button?> <?import javafx.scene.control.Button?>
<?import javafx.scene.control.CheckBox?>
<?import javafx.scene.control.Label?> <?import javafx.scene.control.Label?>
<?import javafx.scene.control.TableColumn?> <?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?> <?import javafx.scene.control.TableView?>
@@ -22,7 +14,7 @@
<?import javafx.scene.text.Font?> <?import javafx.scene.text.Font?>
<?import javafx.scene.text.Text?> <?import javafx.scene.text.Text?>
<AnchorPane prefHeight="702.0" prefWidth="1032.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="greenify.client.controller.DashBoardController"> <AnchorPane prefHeight="702.0" prefWidth="1032.0" xmlns="http://javafx.com/javafx/10.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="greenify.client.controller.DashBoardController">
<children> <children>
<AnchorPane fx:id="menuBar" prefHeight="703.0" prefWidth="216.0" style="-fx-background-color: #5a635c;"> <AnchorPane fx:id="menuBar" prefHeight="703.0" prefWidth="216.0" style="-fx-background-color: #5a635c;">
<children> <children>
@@ -51,7 +43,7 @@
<Font size="21.0" /> <Font size="21.0" />
</font> </font>
</Button> </Button>
<Button fx:id="logOutButton" layoutX="48.0" layoutY="644.0" mnemonicParsing="false" onAction="#logOut" prefHeight="45.0" prefWidth="120.0" text="log out "> <Button fx:id="logOutButton" layoutY="270.0" mnemonicParsing="false" onAction="#logOut" prefHeight="45.0" prefWidth="216.0" text="log out ">
<font> <font>
<Font size="21.0" /> <Font size="21.0" />
</font> </font>
@@ -60,6 +52,8 @@
<Line endX="104.0" layoutX="105.0" layoutY="178.0" scaleY="0.7" startX="-100.0" stroke="#e3ffe8" AnchorPane.leftAnchor="5.0" AnchorPane.rightAnchor="5.0" /> <Line endX="104.0" layoutX="105.0" layoutY="178.0" scaleY="0.7" startX="-100.0" stroke="#e3ffe8" AnchorPane.leftAnchor="5.0" AnchorPane.rightAnchor="5.0" />
<Line endX="104.0" layoutX="109.0" layoutY="223.0" startX="-100.0" stroke="#e3ffe8" strokeWidth="0.7" AnchorPane.leftAnchor="5.0" AnchorPane.rightAnchor="5.0" /> <Line endX="104.0" layoutX="109.0" layoutY="223.0" startX="-100.0" stroke="#e3ffe8" strokeWidth="0.7" AnchorPane.leftAnchor="5.0" AnchorPane.rightAnchor="5.0" />
<Line fx:id="pathLine" endX="100.0" endY="28.0" fill="#1b9736" layoutX="8.0" layoutY="323.0" startX="-100.0" startY="28.0" stroke="#5a635c" /> <Line fx:id="pathLine" endX="100.0" endY="28.0" fill="#1b9736" layoutX="8.0" layoutY="323.0" startX="-100.0" startY="28.0" stroke="#5a635c" />
<Line endX="104.0" layoutX="105.0" layoutY="271.0" startX="-100.0" stroke="#e3ffe8" strokeWidth="0.7" />
<Line endX="104.0" layoutX="106.0" layoutY="270.0" startX="-100.0" stroke="#e3ffe8" strokeWidth="0.7" AnchorPane.leftAnchor="5.0" AnchorPane.rightAnchor="5.0" />
<Label fx:id="hintText" alignment="TOP_LEFT" layoutX="14.0" layoutY="420.0" prefHeight="218.0" prefWidth="187.0" text="Hints" textFill="#c2cdc4"> <Label fx:id="hintText" alignment="TOP_LEFT" layoutX="14.0" layoutY="420.0" prefHeight="218.0" prefWidth="187.0" text="Hints" textFill="#c2cdc4">
<font> <font>
<Font size="15.0" /> <Font size="15.0" />
@@ -282,25 +276,25 @@
<Font size="14.0" /> <Font size="14.0" />
</font> </font>
</Label> </Label>
<CheckBox fx:id="localProduce" layoutX="195.0" layoutY="7.0" mnemonicParsing="false" prefHeight="27.0" prefWidth="55.0" /> <Label fx:id="localProduce" layoutX="195.0" layoutY="7.0" mnemonicParsing="false" prefHeight="27.0" prefWidth="55.0" />
<Label alignment="CENTER" contentDisplay="CENTER" layoutX="18.0" layoutY="39.0" prefHeight="27.0" prefWidth="183.0" text="Using bike"> <Label alignment="CENTER" contentDisplay="CENTER" layoutX="18.0" layoutY="39.0" prefHeight="27.0" prefWidth="183.0" text="Using bike">
<font> <font>
<Font size="14.0" /> <Font size="14.0" />
</font> </font>
</Label> </Label>
<CheckBox fx:id="bike" layoutX="195.0" layoutY="39.0" mnemonicParsing="false" prefHeight="27.0" prefWidth="55.0" /> <Label fx:id="bike" layoutX="195.0" layoutY="39.0" mnemonicParsing="false" prefHeight="27.0" prefWidth="55.0" />
<Label alignment="CENTER" contentDisplay="CENTER" layoutX="20.0" layoutY="71.0" prefHeight="27.0" prefWidth="183.0" text="Lowering the temperature"> <Label alignment="CENTER" contentDisplay="CENTER" layoutX="20.0" layoutY="71.0" prefHeight="27.0" prefWidth="183.0" text="Lowering the temperature">
<font> <font>
<Font size="14.0" /> <Font size="14.0" />
</font> </font>
</Label> </Label>
<CheckBox fx:id="loweringTemp" layoutX="195.0" layoutY="71.0" mnemonicParsing="false" prefHeight="27.0" prefWidth="55.0" /> <Label fx:id="loweringTemp" layoutX="195.0" layoutY="71.0" mnemonicParsing="false" prefHeight="27.0" prefWidth="55.0" />
<Label alignment="CENTER" contentDisplay="CENTER" layoutX="20.0" layoutY="103.0" prefHeight="27.0" prefWidth="183.0" text="Installing solar panels"> <Label alignment="CENTER" contentDisplay="CENTER" layoutX="20.0" layoutY="103.0" prefHeight="27.0" prefWidth="183.0" text="Installing solar panels">
<font> <font>
<Font size="14.0" /> <Font size="14.0" />
</font> </font>
</Label> </Label>
<CheckBox fx:id="solarPanels" layoutX="195.0" layoutY="103.0" mnemonicParsing="false" prefHeight="27.0" prefWidth="55.0" /> <Label fx:id="solarPanels" layoutX="195.0" layoutY="103.0" mnemonicParsing="false" prefHeight="27.0" prefWidth="55.0" />
</children> </children>
</Pane> </Pane>
<Button fx:id="addExtraActivityButton2" contentDisplay="RIGHT" layoutX="545.0" layoutY="14.0" mnemonicParsing="false" onAction="#openExtraActivities" style="-fx-background-color: transparent;" text="Add extra activity!" textFill="#147219"> <Button fx:id="addExtraActivityButton2" contentDisplay="RIGHT" layoutX="545.0" layoutY="14.0" mnemonicParsing="false" onAction="#openExtraActivities" style="-fx-background-color: transparent;" text="Add extra activity!" textFill="#147219">

View File

@@ -1,16 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.shape.*?> <?import javafx.scene.control.Button?>
<?import javafx.scene.text.*?> <?import javafx.scene.control.Label?>
<?import javafx.scene.image.*?> <?import javafx.scene.control.Slider?>
<?import java.lang.*?> <?import javafx.scene.image.Image?>
<?import java.util.*?> <?import javafx.scene.image.ImageView?>
<?import javafx.scene.*?> <?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.control.*?> <?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.shape.Line?> <?import javafx.scene.shape.Line?>
<?import javafx.scene.text.Font?>
<?import javafx.scene.text.Text?>
<AnchorPane prefHeight="611.0" prefWidth="820.0" stylesheets="@../stylesheets/extraActivitiesStyle.css" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="greenify.client.controller.ExtraActivityController"> <AnchorPane prefHeight="611.0" prefWidth="820.0" stylesheets="@../stylesheets/extraActivitiesStyle.css" xmlns="http://javafx.com/javafx/10.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="greenify.client.controller.ExtraActivityController">
<children> <children>
<AnchorPane prefHeight="611.0" prefWidth="107.0"> <AnchorPane prefHeight="611.0" prefWidth="107.0">
<children> <children>
@@ -59,7 +60,7 @@
<Font size="20.0" /> <Font size="20.0" />
</font> </font>
</Text> </Text>
<Button fx:id="addVeganMealButton" contentDisplay="TOP" layoutX="267.0" layoutY="226.0" mnemonicParsing="false" prefHeight="150.0" prefWidth="180.0" style="-fx-background-color: transparent;" text="Add activity!" textFill="#23652b"> <Button fx:id="addVeganMealButton" contentDisplay="TOP" layoutX="267.0" layoutY="226.0" mnemonicParsing="false" onAction="#updateExtras" prefHeight="150.0" prefWidth="180.0" style="-fx-background-color: transparent;" text="Add activity!" textFill="#23652b">
<graphic> <graphic>
<ImageView fitHeight="116.0" fitWidth="156.0" pickOnBounds="true" preserveRatio="true"> <ImageView fitHeight="116.0" fitWidth="156.0" pickOnBounds="true" preserveRatio="true">
<image> <image>
@@ -87,7 +88,7 @@
<Font size="18.0" /> <Font size="18.0" />
</font> </font>
</Text> </Text>
<Button fx:id="addBikeButton" contentDisplay="TOP" layoutX="267.0" layoutY="351.0" mnemonicParsing="false" prefHeight="150.0" prefWidth="180.0" style="-fx-background-color: transparent;" text="Add activity!" textFill="#23652b"> <Button fx:id="addBikeButton" contentDisplay="TOP" layoutX="267.0" layoutY="351.0" mnemonicParsing="false" onAction="#updateExtras" prefHeight="150.0" prefWidth="180.0" style="-fx-background-color: transparent;" text="Add activity!" textFill="#23652b">
<font> <font>
<Font name="System Bold Italic" size="18.0" /> <Font name="System Bold Italic" size="18.0" />
</font> </font>
@@ -133,7 +134,7 @@
</Label> </Label>
</children> </children>
</HBox> </HBox>
<Button fx:id="addTemperatureButton" contentDisplay="TOP" layoutX="267.0" layoutY="353.0" mnemonicParsing="false" prefHeight="150.0" prefWidth="180.0" style="-fx-background-color: transparent;" text="Add activity!" textFill="#23652b"> <Button fx:id="addTemperatureButton" contentDisplay="TOP" layoutX="267.0" layoutY="353.0" mnemonicParsing="false" onAction="#updateExtras" prefHeight="150.0" prefWidth="180.0" style="-fx-background-color: transparent;" text="Add activity!" textFill="#23652b">
<font> <font>
<Font name="System Bold Italic" size="18.0" /> <Font name="System Bold Italic" size="18.0" />
</font> </font>
@@ -170,7 +171,7 @@
</children> </children>
</HBox> </HBox>
<Slider fx:id="solarPanelsSlider" blockIncrement="1.0" layoutX="187.0" layoutY="274.0" majorTickUnit="1.0" max="10.0" min="1.0" minorTickCount="0" prefHeight="24.0" prefWidth="338.0" showTickLabels="true" showTickMarks="true" /> <Slider fx:id="solarPanelsSlider" blockIncrement="1.0" layoutX="187.0" layoutY="274.0" majorTickUnit="1.0" max="10.0" min="1.0" minorTickCount="0" prefHeight="24.0" prefWidth="338.0" showTickLabels="true" showTickMarks="true" />
<Button fx:id="addSolarPanelsButton" contentDisplay="TOP" layoutX="267.0" layoutY="378.0" mnemonicParsing="false" prefHeight="150.0" prefWidth="180.0" style="-fx-background-color: transparent;" text="Add activity!" textFill="#23652b"> <Button fx:id="addSolarPanelsButton" contentDisplay="TOP" layoutX="267.0" layoutY="378.0" mnemonicParsing="false" onAction="#updateExtras" prefHeight="150.0" prefWidth="180.0" style="-fx-background-color: transparent;" text="Add activity!" textFill="#23652b">
<font> <font>
<Font name="System Bold Italic" size="18.0" /> <Font name="System Bold Italic" size="18.0" />
</font> </font>
@@ -184,5 +185,6 @@
</Button> </Button>
</children> </children>
</AnchorPane> </AnchorPane>
<Button fx:id="saveButton" layoutX="30.0" layoutY="30.0" mnemonicParsing="false" prefHeight="36.0" prefWidth="97.0" onAction="#save" text="SAVE!" />
</children> </children>
</AnchorPane> </AnchorPane>

View File

@@ -3,11 +3,3 @@
-fx-text-fill: #c4eec9; -fx-text-fill: #c4eec9;
-fx-font-weight: bold; -fx-font-weight: bold;
} }
.button:hover {
-fx-background-color: #11911b;
}
.button:pressed {
-fx-background-color: #1a8c23;
}

View File

@@ -47,16 +47,6 @@
#friendsButton:pressed { #friendsButton:pressed {
-fx-background-color: #b7e2c2; -fx-background-color: #b7e2c2;
} }
#logOutButton {
-fx-background-color: #5a635c;
-fx-text-fill: #b8bcb9;
}
#logOutButton:hover {
-fx-background-color: #c64b4b;
}
#logOutButton:pressed {
-fx-background-color: #c9a9a9;
}
#addNewActivityButton:pressed { #addNewActivityButton:pressed {

View File

@@ -0,0 +1,16 @@
import greenify.client.Friend;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import static org.junit.Assert.*;
public class FriendTest {
@Test
public void setAndGetTest() {
Friend test = new Friend("ceren", 10.0);
test.setFriend("greenify");
test.setScore(15.0);
assertEquals(test.getFriend(), "greenify");
Assertions.assertEquals(test.getScore(), 15.0);
}
}

View File

@@ -1,6 +1,5 @@
import greenify.client.rest.UserService; import greenify.client.rest.UserService;
import greenify.common.UserDto; import greenify.common.UserDto;
import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.InjectMocks; import org.mockito.InjectMocks;
@@ -15,6 +14,9 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
@RunWith(MockitoJUnitRunner.class) @RunWith(MockitoJUnitRunner.class)
public class UserServiceTest { public class UserServiceTest {
@@ -33,7 +35,7 @@ public class UserServiceTest {
.thenReturn(testUser); .thenReturn(testUser);
UserDto user = userService.registerUser("Eric", "password"); UserDto user = userService.registerUser("Eric", "password");
Assert.assertEquals(testUser, user); assertEquals(testUser, user);
} }
@Test @Test
@@ -43,7 +45,7 @@ public class UserServiceTest {
UserDto.class)) UserDto.class))
.thenReturn(testUser); .thenReturn(testUser);
UserDto user = userService.loginUser("Eric", "password"); UserDto user = userService.loginUser("Eric", "password");
Assert.assertEquals(testUser, user); assertEquals(testUser, user);
} }
@Test @Test
@@ -52,8 +54,8 @@ public class UserServiceTest {
Mockito.when(restTemplate.getForObject(new java.net.URI("http://localhost:8080/getFootprint?name=Eric"), Mockito.when(restTemplate.getForObject(new java.net.URI("http://localhost:8080/getFootprint?name=Eric"),
Float.class)) Float.class))
.thenReturn(estimate); .thenReturn(estimate);
Float result = userService.getFootprint("Eric"); double result = (5 * 10) / 10.0;
Assert.assertEquals(estimate, result); assertTrue(result == userService.getFootprint("Eric"));
} }
@Test @Test
@@ -62,8 +64,8 @@ public class UserServiceTest {
Mockito.when(restTemplate.getForObject(new java.net.URI("http://localhost:8080/getFirst?name=Eric"), Mockito.when(restTemplate.getForObject(new java.net.URI("http://localhost:8080/getFirst?name=Eric"),
Float.class)) Float.class))
.thenReturn(estimate); .thenReturn(estimate);
Float result = userService.getFirstFootprint("Eric"); double result = (5 * 10) / 10.0;
Assert.assertEquals(estimate, result); assertTrue(result == userService.getFirstFootprint("Eric"));
} }
@Test @Test
@@ -73,7 +75,7 @@ public class UserServiceTest {
Float.class)) Float.class))
.thenReturn(estimate); .thenReturn(estimate);
Float result = userService.saveFootprint("Eric"); Float result = userService.saveFootprint("Eric");
Assert.assertEquals(estimate, result); assertEquals(estimate, result);
} }
@Test @Test
@@ -83,7 +85,7 @@ public class UserServiceTest {
Float.class)) Float.class))
.thenReturn(estimate); .thenReturn(estimate);
Float result = userService.saveFirstFootprint("Eric"); Float result = userService.saveFirstFootprint("Eric");
Assert.assertEquals(estimate, result); assertEquals(estimate, result);
} }
@Test @Test
@@ -94,7 +96,7 @@ public class UserServiceTest {
List.class)) List.class))
.thenReturn(estimate); .thenReturn(estimate);
List<String> result = userService.getFriendNames("Eric"); List<String> result = userService.getFriendNames("Eric");
Assert.assertEquals(estimate, result); assertEquals(estimate, result);
} }
@Test @Test
@@ -105,7 +107,7 @@ public class UserServiceTest {
List.class)) List.class))
.thenReturn(estimate); .thenReturn(estimate);
List<String> result = userService.getAllUsers(); List<String> result = userService.getAllUsers();
Assert.assertEquals(estimate, result); assertEquals(estimate, result);
} }
@Test @Test
@@ -116,18 +118,18 @@ public class UserServiceTest {
Map.class)) Map.class))
.thenReturn(estimate); .thenReturn(estimate);
Map<String, String> result = userService.getInputs("Eric"); Map<String, String> result = userService.getInputs("Eric");
Assert.assertEquals(estimate, result); assertEquals(estimate, result);
} }
@Test @Test
public void getExtraInputsTest() throws Exception { public void getExtraInputsTest() throws Exception {
Map<String, Boolean> estimate = new HashMap<>(); Map<String, String> estimate = new HashMap<>();
estimate.put("solar_panels", true); estimate.put("solar_panels", "5");
Mockito.when(restTemplate.getForObject(new java.net.URI("http://localhost:8080/getExtraInputs?name=Eric"), Mockito.when(restTemplate.getForObject(new java.net.URI("http://localhost:8080/getExtraInputs?name=Eric"),
Map.class)) Map.class))
.thenReturn(estimate); .thenReturn(estimate);
Map<String, Boolean> result = userService.getExtraInputs("Eric"); Map<String, String> result = userService.getExtraInputs("Eric");
Assert.assertEquals(estimate, result); assertEquals(estimate, result);
} }
@Test @Test
@@ -138,8 +140,8 @@ public class UserServiceTest {
@Test @Test
public void setExtraInputTest() throws Exception { public void setExtraInputTest() throws Exception {
userService.updateExtraInput("Eric", "solar_panels", true); userService.updateExtraInput("Eric", "solar_panels", "8");
Mockito.verify(userService).updateExtraInput("Eric", "solar_panels", true); Mockito.verify(userService).updateExtraInput("Eric", "solar_panels", "8");
} }
@Test @Test

View File

@@ -37,5 +37,5 @@ public class AllAchievements {
} }
return all; return all;
} }
} }

View File

@@ -185,14 +185,14 @@ public class InputValidator {
* This method gets extra values. * This method gets extra values.
* @return the map of default values * @return the map of default values
*/ */
public static Map<String, Boolean> getExtraValues() { public static Map<String, String> getExtraValues() {
Map<String, Boolean> map = new HashMap<String, Boolean>() { }; Map<String, String> map = new HashMap<String, String>() { };
map.put("local_produce", false); map.put("vegan", "0");
map.put("bike", false); map.put("local_produce", "0");
map.put("temperature", false); map.put("bike", "0");
map.put("solar_panels", false); map.put("car", "0");
map.put("vegetarian", false); map.put("temperature", "0");
map.put("public_transport", false); map.put("solar_panels", "0");
return map; return map;
} }
} }

View File

@@ -86,14 +86,11 @@ public class Achievement {
*/ */
@Override @Override
public boolean equals(Object other) { public boolean equals(Object other) {
if(other == null){
return false;
}
if (other instanceof Achievement) { if (other instanceof Achievement) {
Achievement that = (Achievement) other; Achievement that = (Achievement) other;
return achieved == that.achieved return achieved == that.achieved
&& name.equals(that.name) && name.equals(that.name)
&& Objects.equals(description, that.description); && description.equals(that.description);
} }
return false; return false;
} }

View File

@@ -46,7 +46,7 @@ public class User {
private Map<String, String> footPrintInputs = new HashMap<>(); private Map<String, String> footPrintInputs = new HashMap<>();
@ElementCollection @ElementCollection
private Map<String, Boolean> extraInputs = new HashMap<>(); private Map<String, String> extraInputs = new HashMap<>();
@ManyToMany @ManyToMany
private List<User> friends; private List<User> friends;
@@ -172,7 +172,7 @@ public class User {
* This method gets the extra inputs of the user. * This method gets the extra inputs of the user.
* @return extra inputs of the user * @return extra inputs of the user
*/ */
public Map<String, Boolean> getExtraInputs() { public Map<String, String> getExtraInputs() {
return extraInputs; return extraInputs;
} }
@@ -180,7 +180,7 @@ public class User {
* This method sets the extra inputs of the user. * This method sets the extra inputs of the user.
* @param extraInputs footprint inputs of the user * @param extraInputs footprint inputs of the user
*/ */
public void setExtraInputs(Map<String, Boolean> extraInputs) { public void setExtraInputs(Map<String, String> extraInputs) {
this.extraInputs = extraInputs; this.extraInputs = extraInputs;
} }

View File

@@ -63,7 +63,7 @@ public class UserController {
@RequestMapping("/setExtraInput") @RequestMapping("/setExtraInput")
public void setExtraInput(@RequestParam(value = "name") String name, public void setExtraInput(@RequestParam(value = "name") String name,
@RequestParam(value = "inputName") String inputName, @RequestParam(value = "inputName") String inputName,
@RequestParam(value = "value") Boolean value) { @RequestParam(value = "value") String value) {
userService.setExtraInput(name, inputName, value); userService.setExtraInput(name, inputName, value);
} }
@@ -150,7 +150,7 @@ public class UserController {
* This method gets the extra inputs map of the user. * This method gets the extra inputs map of the user.
*/ */
@RequestMapping("/getExtraInputs") @RequestMapping("/getExtraInputs")
public Map<String, Boolean> getExtraInputs(@RequestParam(value = "name") String name) { public Map<String, String> getExtraInputs(@RequestParam(value = "name") String name) {
return userService.getExtraInputMap(name); return userService.getExtraInputMap(name);
} }

View File

@@ -1,9 +1,6 @@
package greenify.server.service; package greenify.server.service;
import greenify.server.InputValidator;
import greenify.server.data.model.User; import greenify.server.data.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@@ -12,8 +9,6 @@ public class AchievementService {
@Autowired @Autowired
UserService userService; UserService userService;
private Logger logger = LoggerFactory.getLogger(UserService.class);
/** /**
* This method updates all achievements of a user. * This method updates all achievements of a user.
* @param user the user for whom the achievements change * @param user the user for whom the achievements change
@@ -33,10 +28,8 @@ public class AchievementService {
* @param user user for whom achiev1 changes * @param user user for whom achiev1 changes
*/ */
public void achieveGettingStarted(User user) { public void achieveGettingStarted(User user) {
if (!user.getFootPrintInputs().equals(InputValidator.getDefaultValues())) {
userService.setAchievement(user.getName(), "Starting off", true); userService.setAchievement(user.getName(), "Starting off", true);
} }
}
/** /**
* This method changes achiev2 when this is the case. * This method changes achiev2 when this is the case.
@@ -53,7 +46,7 @@ public class AchievementService {
* @param user user for whom achiev3 changes * @param user user for whom achiev3 changes
*/ */
public void achieveGreenSaver(User user) { public void achieveGreenSaver(User user) {
if (43 - user.getFootPrint() > 38) { if (20 > user.getFootPrint()) {
userService.setAchievement(user.getName(), "Green saver", true); userService.setAchievement(user.getName(), "Green saver", true);
} }
} }
@@ -63,7 +56,8 @@ public class AchievementService {
* @param user user for whom achiev4 changes * @param user user for whom achiev4 changes
*/ */
public void achieveAnimalFriend(User user) { public void achieveAnimalFriend(User user) {
if (user.getExtraInputs().get("vegetarian")) { int vegan = Integer.parseInt(user.getExtraInputs().get("vegan"));
if (vegan > 10) {
userService.setAchievement(user.getName(), "Animal friend", true); userService.setAchievement(user.getName(), "Animal friend", true);
} }
} }
@@ -73,7 +67,8 @@ public class AchievementService {
* @param user user for whom achiev5 changes * @param user user for whom achiev5 changes
*/ */
public void achieveTomDumoulin(User user) { public void achieveTomDumoulin(User user) {
if (user.getExtraInputs().get("bike")) { int bike = Integer.parseInt(user.getExtraInputs().get("bike"));
if (bike > 15) {
userService.setAchievement(user.getName(), "Tom Dumoulin", true); userService.setAchievement(user.getName(), "Tom Dumoulin", true);
} }
} }
@@ -83,7 +78,8 @@ public class AchievementService {
* @param user user for whom achiev6 changes * @param user user for whom achiev6 changes
*/ */
public void achieveLetItShine(User user) { public void achieveLetItShine(User user) {
if (user.getExtraInputs().get("solar_panels")) { int solar_panels = Integer.parseInt(user.getExtraInputs().get("solar_panels"));
if (solar_panels >= 2) {
userService.setAchievement(user.getName(), "Let it shine", true); userService.setAchievement(user.getName(), "Let it shine", true);
} }
} }

View File

@@ -72,8 +72,14 @@ public class CalculatorService {
* @return the footprint of the user * @return the footprint of the user
*/ */
public Float calculateFootprint(User user) { public Float calculateFootprint(User user) {
Float footprint = invokeExternalService(user.getFootPrintInputs());
addExtras(user); addExtras(user);
Float footprint = invokeExternalService(user.getFootPrintInputs());
footprint = footprint - (float) (Float.parseFloat(user
.getExtraInputs().get("solar_panels")) * 1.2);
footprint = footprint - Float.parseFloat(user
.getExtraInputs().get("temperature")) / 4;
footprint = footprint - (float) (Float.parseFloat(user
.getExtraInputs().get("local_produce")) * 0.1);
return footprint; return footprint;
} }
@@ -82,15 +88,20 @@ public class CalculatorService {
* @param user name of the user * @param user name of the user
*/ */
public void addExtras(User user) { public void addExtras(User user) {
if (user.getExtraInputs().get("local_produce")) { Map<String, String> inputs = user.getFootPrintInputs();
user.setFootPrint(user.getFootPrint() - 2); Float netPublic = Float.parseFloat(user.getFootPrintInputs()
} else if (user.getExtraInputs().get("bike")) { .get("input_footprint_transportation_publictrans"))
user.setFootPrint(user.getFootPrint() - 2); - Float.parseFloat(user.getExtraInputs().get("bike"));
} else if (user.getExtraInputs().get("temperature")) { Float netCar = Float.parseFloat(user.getFootPrintInputs()
user.setFootPrint(user.getFootPrint() - 2); .get("input_footprint_transportation_miles1"))
} else if (user.getExtraInputs().get("solar_panels")) { - Float.parseFloat(user.getExtraInputs().get("car"));
user.setFootPrint(user.getFootPrint() - 2); Float netVegan = Float.parseFloat(user.getFootPrintInputs()
} .get("input_footprint_shopping_food_fruitvegetables"))
+ Float.parseFloat(user.getExtraInputs().get("vegan"));
inputs.put("input_footprint_transportation_publictrans", netPublic + "");
inputs.put("input_footprint_transportation_miles1", netCar + "");
inputs.put("input_footprint_shopping_food_fruitvegetables", netVegan + "");
user.setFootPrintInputs(inputs);
} }
} }

View File

@@ -128,12 +128,14 @@ public class UserService {
* @param inputName name of the input of the user * @param inputName name of the input of the user
* @param value value of the input * @param value value of the input
*/ */
public void setExtraInput(String name, String inputName, Boolean value) { public void setExtraInput(String name, String inputName, String value) {
User user = userRepository.findByName(name); User user = userRepository.findByName(name);
if (user == null) { if (user == null) {
throw new ApplicationException("User does not exist"); throw new ApplicationException("User does not exist");
} else { } else {
user.getExtraInputs().put(inputName, value); String oldValue = user.getExtraInputs().get(inputName);
Integer total = Integer.parseInt(oldValue) + Integer.parseInt(value);
user.getExtraInputs().put(inputName, total + "");
userRepository.save(user); userRepository.save(user);
} }
} }
@@ -168,7 +170,7 @@ public class UserService {
* @param name of the user * @param name of the user
* @return extra input map * @return extra input map
*/ */
public Map<String, Boolean> getExtraInputMap(String name) { public Map<String, String> getExtraInputMap(String name) {
User user = userRepository.findByName(name); User user = userRepository.findByName(name);
return user.getExtraInputs(); return user.getExtraInputs();
} }

View File

@@ -1,8 +1,12 @@
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import greenify.server.AllAchievements; import greenify.server.AllAchievements;
import greenify.server.data.model.Achievement;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
class AllAchievementsTest { class AllAchievementsTest {
@Test @Test
@@ -15,6 +19,21 @@ class AllAchievementsTest {
@Test @Test
void getDefaultsTest() { void getDefaultsTest() {
assertEquals(6, AllAchievements.getDefaults().size()); List<Achievement> all = new ArrayList<Achievement>() {{
add(new Achievement(
"Starting off", "You did your first green activity", false));
add(new Achievement(
"Social butterfly", "You added three friends", false));
add(new Achievement(
"Green saver", "You saved * of CO2", false));
add(new Achievement(
"Animal friend", "You have eaten 10 vegetarian meals", false));
add(new Achievement(
"Tom Dumoulin", "You have biked * km", false));
add(new Achievement(
"Let it shine", "You installed solar panels", false));
}
};
assertEquals(all.size(), AllAchievements.getDefaults().size());
} }
} }

View File

@@ -1,8 +1,8 @@
package greenify.server.data.model; package greenify.server.data.model;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@@ -32,7 +32,7 @@ class AchievementTest {
} }
@Test @Test
void equalsTest() { public void equalsTest() {
assertEquals(achievement.getName(), other.getName()); assertEquals(achievement.getName(), other.getName());
assertEquals(achievement.getDescription(), other.getDescription()); assertEquals(achievement.getDescription(), other.getDescription());
assertEquals(achievement.isAchieved(), other.isAchieved()); assertEquals(achievement.isAchieved(), other.isAchieved());
@@ -40,18 +40,35 @@ class AchievementTest {
} }
@Test @Test
void notEqualsTest() { public void notEqualAchievedTest() {
Achievement test = new Achievement("Starting off", Achievement first = new Achievement("greenify", "description", true);
"You did your first green activity", false); Achievement second = new Achievement("greenify", "description", false);
assertFalse(achievement.equals(test)); assertNotEquals(first, second);
} }
@Test @Test
void equalsNullTest() { public void notEqualNameTest() {
assertFalse(achievement.equals(null)); Achievement first = new Achievement("greenify", "description", true);
Achievement second = new Achievement("ceren", "description", true);
assertNotEquals(first, second);
} }
@Test @Test
void hashCodeTest() { public void notEqualDescriptionTest() {
Achievement first = new Achievement("greenify", "hello", false);
Achievement second = new Achievement("greenify", "description", false);
assertNotEquals(first, second);
}
@Test
public void instanceOfTest() {
Achievement first = new Achievement();
Object second = new Object();
assertNotEquals(first, second);
}
@Test
public void hashCodeTest() {
assertEquals(achievement, other); assertEquals(achievement, other);
assertEquals(achievement.hashCode(), other.hashCode()); assertEquals(achievement.hashCode(), other.hashCode());
} }

View File

@@ -82,11 +82,11 @@ public class UserControllerTest {
public void setExtraInputTest() throws Exception { public void setExtraInputTest() throws Exception {
ArgumentCaptor<String> arg1Captor = ArgumentCaptor.forClass(String.class); ArgumentCaptor<String> arg1Captor = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<String> arg2Captor = ArgumentCaptor.forClass(String.class); ArgumentCaptor<String> arg2Captor = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<Boolean> arg3Captor = ArgumentCaptor.forClass(Boolean.class); ArgumentCaptor<String> arg3Captor = ArgumentCaptor.forClass(String.class);
mvc.perform(get("/setExtraInput") mvc.perform(get("/setExtraInput")
.param("name", "ceren") .param("name", "ceren")
.param("inputName", "input_size") .param("inputName", "input_size")
.param("value", "true") .param("value", "5")
.accept(MediaType.APPLICATION_JSON)) .accept(MediaType.APPLICATION_JSON))
.andDo(print()) .andDo(print())
.andExpect(status().isOk()); .andExpect(status().isOk());
@@ -94,7 +94,7 @@ public class UserControllerTest {
.setExtraInput(arg1Captor.capture(), arg2Captor.capture(), arg3Captor.capture()); .setExtraInput(arg1Captor.capture(), arg2Captor.capture(), arg3Captor.capture());
assertEquals("ceren", arg1Captor.getValue()); assertEquals("ceren", arg1Captor.getValue());
assertEquals("input_size", arg2Captor.getValue()); assertEquals("input_size", arg2Captor.getValue());
assertEquals(true, arg3Captor.getValue()); assertEquals("5", arg3Captor.getValue());
} }
@Test @Test

View File

@@ -3,7 +3,6 @@ package greenify.server.service;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import greenify.server.InputValidator;
import greenify.server.data.model.User; import greenify.server.data.model.User;
import greenify.server.data.repository.UserRepository; import greenify.server.data.repository.UserRepository;
import org.junit.Before; import org.junit.Before;
@@ -53,7 +52,8 @@ public class AchievementServiceTest {
User alex = new User(1L, "alex", "password"); User alex = new User(1L, "alex", "password");
when(userRepository.findByName(alex.getName())) when(userRepository.findByName(alex.getName()))
.thenReturn(alex); .thenReturn(alex);
userService.setInput("alex","input_footprint_shopping_food_otherfood", "9.9"); userService.setExtraInput("alex", "vegan", "25");
userService.setExtraInput("alex", "solar_panels", "3");
} }
@Test @Test
@@ -61,7 +61,6 @@ public class AchievementServiceTest {
User alex = userRepository.findByName("alex"); User alex = userRepository.findByName("alex");
achievementService.updateAchievements(alex); achievementService.updateAchievements(alex);
assertEquals(true, userService.getAchievement("alex", "Starting off")); assertEquals(true, userService.getAchievement("alex", "Starting off"));
assertEquals(false, userService.getAchievement("alex", "Social butterfly"));
} }
@Test @Test
@@ -83,6 +82,14 @@ public class AchievementServiceTest {
assertEquals(true, userService.getAchievement("alex", "Social butterfly")); assertEquals(true, userService.getAchievement("alex", "Social butterfly"));
} }
@Test
public void notAchieveSocialButterflyTest() {
User alex = userRepository.findByName("alex");
alex.addFriend(new User(2L, "Bubbles", "Bubbles"));
achievementService.achieveSocialButterfly(alex);
assertEquals(false, userService.getAchievement("alex", "Social butterfly"));
}
@Test @Test
public void achieveGreenSaverTest() { public void achieveGreenSaverTest() {
User alex = userRepository.findByName("alex"); User alex = userRepository.findByName("alex");
@@ -90,10 +97,26 @@ public class AchievementServiceTest {
assertEquals(true, userService.getAchievement("alex", "Green saver")); assertEquals(true, userService.getAchievement("alex", "Green saver"));
} }
@Test
public void notAchieveGreenSaverTest() {
User alex = userRepository.findByName("alex");
alex.setFootPrint(90f);
achievementService.achieveGreenSaver(alex);
assertEquals(false, userService.getAchievement("alex", "Green saver"));
}
@Test @Test
public void achieveAnimalFriendTest() { public void achieveAnimalFriendTest() {
User alex = userRepository.findByName("alex"); User alex = userRepository.findByName("alex");
achievementService.achieveAnimalFriend(alex); achievementService.achieveAnimalFriend(alex);
assertEquals(true, userService.getAchievement("alex", "Animal friend"));
}
@Test
public void notAchieveAnimalFriendTest() {
User alex = userRepository.findByName("alex");
alex.getExtraInputs().put("vegan", "0");
achievementService.achieveAnimalFriend(alex);
assertEquals(false, userService.getAchievement("alex", "Animal friend")); assertEquals(false, userService.getAchievement("alex", "Animal friend"));
} }
@@ -104,11 +127,26 @@ public class AchievementServiceTest {
assertEquals(false, userService.getAchievement("alex", "Tom Dumoulin")); assertEquals(false, userService.getAchievement("alex", "Tom Dumoulin"));
} }
@Test
public void successfulAchieveTomDumoulinTest() {
User alex = userRepository.findByName("alex");
alex.getExtraInputs().put("bike", "25");
achievementService.achieveTomDumoulin(alex);
assertEquals(true, userService.getAchievement("alex", "Tom Dumoulin"));
}
@Test @Test
public void achieveLetItShineTest() { public void achieveLetItShineTest() {
User alex = userRepository.findByName("alex"); User alex = userRepository.findByName("alex");
achievementService.achieveLetItShine(alex); achievementService.achieveLetItShine(alex);
assertEquals(false, userService.getAchievement("alex", "Let it shine")); assertEquals(true, userService.getAchievement("alex", "Let it shine"));
} }
@Test
public void notAchieveLetItShineTest() {
User alex = userRepository.findByName("alex");
alex.getExtraInputs().put("solar_panels", "0");
achievementService.achieveLetItShine(alex);
assertEquals(false, userService.getAchievement("alex", "Let it shine"));
}
} }

View File

@@ -1,12 +1,5 @@
package greenify.server.service; package greenify.server.service;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.header;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus;
import greenify.server.data.model.User;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@@ -14,16 +7,10 @@ import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.TestConfiguration; import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.client.ExpectedCount;
import org.springframework.test.web.client.MockRestServiceServer; import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.RestTemplate; import org.springframework.web.client.RestTemplate;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@@ -59,64 +46,6 @@ public class CalculatorServiceTest {
mockServer = MockRestServiceServer.createServer(restTemplate); mockServer = MockRestServiceServer.createServer(restTemplate);
} }
@Test
public void calculateFootprintTest() throws URISyntaxException {
Map<String,String> map = new HashMap<String, String>() {{
put("input_location_mode", "1");
put("input_location", "48001");
put("input_income", "1");
}
};
User user = new User(1L,"greenify", "password");
user.setFootPrintInputs(map);
mockServer.expect(ExpectedCount.once(),
requestTo(new URI("https://apis.berkeley.edu/coolclimate/footprint?"
+ "input_location=48001&input_location_mode=1&input_income=1")))
.andExpect(method(HttpMethod.GET))
.andExpect(header("app_id", "a98272e3"))
.andExpect(header("app_key", "b9167c4918cb2b3143614b595065d83b"))
.andRespond(withStatus(HttpStatus.OK)
.contentType(MediaType.APPLICATION_JSON)
.body("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<response>\n"
+ " <result_motor_vehicles_direct>5.0765</result_motor_vehicles_direct>\n"
+ " <result_motor_vehicles_indirect>1.167595"
+ "</result_motor_vehicles_indirect>\n"
+ " <result_goods_total>2.481474</result_goods_total>\n"
+ " <result_services_total>2.478352</result_services_total>\n"
+ " <result_grand_total>19.259982</result_grand_total>\n"
+ "</response>")
);
Float footPrint = calculatorService.calculateFootprint(user);
mockServer.verify();
Assert.assertEquals(new Float(19.259982), footPrint);
}
@Test
public void addExtrasTest() throws URISyntaxException {
User user = new User(1L,"greenify", "password");
Map<String,Boolean> map = new HashMap<String, Boolean>() {{
put("local_produce", false);
put("bike", false);
put("temperature", false);
put("solar_panels", false);
}
};
user.setExtraInputs(map);
user.setFootPrint(50f);
Map<String,Boolean> secondMap = new HashMap<String, Boolean>() {{
put("local_produce", true);
put("bike", true);
put("temperature", true);
put("solar_panels", true);
}
};
user.setExtraInputs(secondMap);
calculatorService.addExtras(user);
mockServer.verify();
Assert.assertEquals(new Float(48f), user.getFootPrint());
}
@Test @Test
public void invokeExternalServiceTest() { public void invokeExternalServiceTest() {
CalculatorService service = new CalculatorService(); CalculatorService service = new CalculatorService();

View File

@@ -101,8 +101,8 @@ public class UserServiceTest {
User alex = new User(1L, "alex", "password"); User alex = new User(1L, "alex", "password");
when(userRepository.findByName(alex.getName())) when(userRepository.findByName(alex.getName()))
.thenReturn(alex); .thenReturn(alex);
userService.setExtraInput("alex", "solar_panels", true); userService.setExtraInput("alex", "solar_panels", "5");
assertEquals(true, alex.getExtraInputs() assertEquals("5", alex.getExtraInputs()
.get("solar_panels")); .get("solar_panels"));
} }
@@ -114,7 +114,7 @@ public class UserServiceTest {
@Test @Test
public void setExtraInputNullTest() { public void setExtraInputNullTest() {
assertThrows(ApplicationException.class, () -> userService assertThrows(ApplicationException.class, () -> userService
.setExtraInput(null, "hello", true)); .setExtraInput(null, "hello", "6"));
} }
@Test @Test
@@ -171,7 +171,7 @@ public class UserServiceTest {
@Test @Test
public void getExtraInputMapTest() { public void getExtraInputMapTest() {
Map<String, Boolean> map = new HashMap<>(); Map<String, String> map = new HashMap<>();
User alex = new User(1L, "alex", "password"); User alex = new User(1L, "alex", "password");
when(userRepository.findByName(alex.getName())) when(userRepository.findByName(alex.getName()))
.thenReturn(alex); .thenReturn(alex);
@@ -288,6 +288,18 @@ public class UserServiceTest {
assertThrows(ApplicationException.class, () -> userService.removeFriend("alex", null)); assertThrows(ApplicationException.class, () -> userService.removeFriend("alex", null));
} }
@Test
public void setAchievementNullUserTest() {
assertThrows(ApplicationException.class, () -> userService
.setAchievement("ceren", "Starting off", true));
}
@Test
public void invalidAchievementTest() {
assertThrows(ApplicationException.class, () -> userService
.setAchievement("alex", "greenify", true));
}
@Test @Test
public void addFriendNullFriendTest() { public void addFriendNullFriendTest() {
assertThrows(ApplicationException.class, () -> userService.addFriend("alex", null)); assertThrows(ApplicationException.class, () -> userService.addFriend("alex", null));