Merge branch 'fix/checkstyleAndComments' into 'master'

Fix/checkstyle and comments

See merge request cse1105/2018-2019/oopp-group-43/template!44
This commit is contained in:
Merel Steenbergen
2019-03-26 15:06:24 +00:00
29 changed files with 386 additions and 233 deletions

View File

@@ -4,19 +4,21 @@ import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import java.io.IOException;
@SpringBootApplication
public class Application extends javafx.application.Application {
private static ConfigurableApplicationContext springContext;
private static final Logger log = LoggerFactory.getLogger(Application.class);
/**
* This (main) method starts launch.
* @param args the arguments
*/
public static void main(String[] args) {
launch(args);
}
@@ -33,22 +35,34 @@ public class Application extends javafx.application.Application {
return loader.load();
}
/**
* This method initializes the application.
*/
@Override
public void init() throws Exception {
public void init() {
springContext = SpringApplication.run(Application.class);
}
/**
* This method opens the login window.
* @param primaryStage the login window
* @throws Exception in case fxml file is not found
*/
@Override
public void start(Stage primaryStage) throws Exception {
Parent rootNode = load(this.getClass().getClassLoader().getResource("fxml/LoginWindow.fxml"));
Parent rootNode = load(this.getClass().getClassLoader()
.getResource("fxml/LoginWindow.fxml"));
primaryStage.setTitle("Greenify");
Scene scene = new Scene(rootNode);
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* This method stops the application.
*/
@Override
public void stop() {
springContext.stop();
}
}
}

View File

@@ -22,9 +22,9 @@ import org.springframework.stereotype.Controller;
import java.io.IOException;
//Class that controls the dashboard fxml file (the GUI Screen)
/**
* Class that controls the dashboard fxml file (the GUI Screen).
*/
@Controller
public class DashBoardController {
@Autowired
@@ -32,7 +32,6 @@ public class DashBoardController {
private FadeTransition fadeTrans; //transition for switching between the different panels
private int net;
private int count = 0;
@FXML
private AnchorPane dashboardPane;
@@ -43,8 +42,6 @@ public class DashBoardController {
@FXML
private AnchorPane friendsPane;
@FXML
private Label veganMealCounter;
@FXML
private Label totalVeganMealCounter;
@FXML
private Label welcomebacktext;
@@ -65,11 +62,8 @@ public class DashBoardController {
@FXML
private Button calculateFootPrintButton;
/**
* loads the the necessary things before anything else.
* Loads the the necessary things before anything else.
*/
public void initialize() {
//sets the text of the 'welcome back' text to include the username
@@ -90,7 +84,7 @@ public class DashBoardController {
}
/**
* adds a fade transition for switching between the different panes.
* 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) {
@@ -103,7 +97,7 @@ public class DashBoardController {
/**
* displays the dashboard pane.
* Displays the dashboard pane.
* @param event the event (clicking the button)
*/
public void displayDashboard(ActionEvent event) {
@@ -117,7 +111,7 @@ public class DashBoardController {
}
/**
* displays the activities pane.
* Displays the activities pane.
* @param event the event (clicking the button)
*/
public void displayActivities(ActionEvent event) {
@@ -131,7 +125,7 @@ public class DashBoardController {
}
/**
* displays the user profile pane.
* Displays the user profile pane.
* @param event the event (clicking the button)
*/
public void displayUser(ActionEvent event) {
@@ -144,6 +138,10 @@ public class DashBoardController {
}
/**
* Displays the friends pane.
* @param event the event (clicking the button)
*/
public void displayFriends(ActionEvent event) {
addFadeTransition(friendsPane);
System.out.println("display friends");
@@ -151,6 +149,7 @@ public class DashBoardController {
userPane.setVisible(false);
activitiesPane.setVisible(false);
friendsPane.setVisible(true);
}
//sets the slide in transition for startup
@@ -159,11 +158,16 @@ public class DashBoardController {
pathTrans.play();
}
/**
* Opens the calculator.
* @throws IOException if the Application doesn't load.
*/
public void openCalculator() throws IOException {
Parent calc = Application.load(this.getClass().getClassLoader()
.getResource("fxml/calculator.fxml"));
Scene scene = new Scene(calc);
scene.getStylesheets().add(getClass().getClassLoader().getResource("stylesheets/calculatorStyle.css").toExternalForm());
scene.getStylesheets().add(getClass().getClassLoader()
.getResource("stylesheets/calculatorStyle.css").toExternalForm());
Stage calcStage = new Stage();
calcStage.setScene(scene);
@@ -197,4 +201,4 @@ public class DashBoardController {
}
}
}
}

View File

@@ -9,7 +9,6 @@ import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.shape.Line;
import javafx.stage.Stage;
import javafx.stage.Window;
import javafx.util.Duration;
@@ -18,7 +17,9 @@ import org.springframework.stereotype.Controller;
import java.util.concurrent.TimeUnit;
//class that controls the actions for the register window
/**
* Class that controls the actions for the register window.
*/
@Controller
public class RegisterWindowController {
@@ -32,12 +33,17 @@ public class RegisterWindowController {
@FXML
private PasswordField passwordField2;
@FXML
private Button signupButton;
@FXML
private Line uNamePathLine;
private Button signUpButton;
//@FXML
//private Line uNamePathLine;
/**
* Initializes the animation.
* @throws InterruptedException exception when interrupted
*/
public void initialize() throws InterruptedException {
// PathTransition pathTransUName = new PathTransition(Duration.millis(1100), uNamePathLine, userNameText);
// PathTransition pathTransUName = new PathTransition(Duration.millis(1100),
// uNamePathLine, userNameText);
// pathTransUName.play();
addSlideAnimation(1100, userNameText, -300);
addSlideAnimation(1100, passwordField, 300);
@@ -46,7 +52,13 @@ public class RegisterWindowController {
}
public void addSlideAnimation(int duration, Node node, int from) {
/**
* Adds the slide animation.
* @param duration the duration
* @param node the node
* @param from from where
*/
private void addSlideAnimation(int duration, Node node, int from) {
TranslateTransition slideIn = new TranslateTransition(Duration.millis(duration), node);
slideIn.setFromX(from);
slideIn.setToX(0);
@@ -54,13 +66,13 @@ public class RegisterWindowController {
}
/**
* signs the user up.
* Signs up the user.
* @param event the click of the sign up button
*/
@FXML
public void handleSignUpButton(ActionEvent event) {
//set the window to the current window (for displaying the alerts)
Window owner = signupButton.getScene().getWindow();
Window owner = signUpButton.getScene().getWindow();
//check if the username field is empty
if (userNameText.getText().isEmpty()) {
//if so, display an alert

View File

@@ -16,8 +16,11 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import java.io.IOException;
import java.util.Objects;
//class that controls the actions for the login screen
/**
* Class that controls the actions for the login screen.
*/
@Controller
public class UserController {
@Autowired
@@ -33,10 +36,10 @@ public class UserController {
private Button loginButton;
@FXML
private Button signupButton;
private Button 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
* and gives alerts if they aren't filled in.
* @param event the click of the login button
@@ -75,18 +78,18 @@ public class UserController {
}
/**
* opens the dashboard stage.
* Opens the dashboard stage.
* @throws IOException exception if fxml file can't be found
* @author sem
*/
public void openDashboard() throws IOException {
private void openDashboard() throws IOException {
//load the fxml file
Parent dash = Application.load(this.getClass().getClassLoader()
.getResource("fxml/dashboard.fxml"));
Scene scene = new Scene(dash);
//add the stylesheet for the CSS
scene.getStylesheets().add(getClass().getClassLoader()
.getResource("stylesheets/dashboardStyle.css").toExternalForm());
scene.getStylesheets().add(Objects.requireNonNull(getClass().getClassLoader()
.getResource("stylesheets/dashboardStyle.css")).toExternalForm());
Stage appStage = new Stage();
appStage.setScene(scene);
//set the title
@@ -94,8 +97,10 @@ public class UserController {
appStage.show();
}
//class for showing the alerts
public static class AlertHelper {
/**
* Class for showing the alerts.
*/
static class AlertHelper {
/**
* alerts for the login screen.
* @param alertType the type of alert
@@ -103,10 +108,10 @@ public class UserController {
* @param title the title given to the displayed alert
* @param message the message displayed in the alert
*/
public static void showAlert(Alert.AlertType alertType,
Window owner,
String title,
String message) {
static void showAlert(Alert.AlertType alertType,
Window owner,
String title,
String message) {
Alert alert = new Alert(alertType);
alert.setTitle(title);
alert.setHeaderText(null);

View File

@@ -8,25 +8,23 @@ import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
@Service
public class UserService {
public UserDto currentUser;
@Autowired
RestTemplate restTemplate;
public UserDto currentUser;
@Bean
RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
/**
* registers the user.
* Registers the user.
* @param name the username of the user
* @param password the password of the user
* @return a userDTO
@@ -37,7 +35,7 @@ public class UserService {
public UserDto registerUser(String name, String password) {
//headers for http
HttpHeaders headers = new HttpHeaders();
//set the accept header in JSÖN value
//set the accept header in JSON value
headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
//connect to the server with the needed url
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("http://localhost:8080/registerUser")
@@ -47,7 +45,7 @@ public class UserService {
//getting the password from the database
//create a http entity to be sent
HttpEntity<?> entity = new HttpEntity<>(headers);
new HttpEntity<>(headers);
System.out.println(builder.build().encode().toUri());
//the result to be sent is a userDto
@@ -59,7 +57,7 @@ public class UserService {
}
/**
* sign ins the user.
* Signs in the user.
* @param name the username of the user
* @param password the password of the user
* @return a userDTO
@@ -72,7 +70,7 @@ public class UserService {
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("http://localhost:8080/loginUser")
.queryParam("name", name)
.queryParam("password", password);
HttpEntity<?> entity = new HttpEntity<>(headers);
new HttpEntity<>(headers);
System.out.println(builder.build().encode().toUri());
UserDto result = this.restTemplate.getForObject(builder.build()
.encode().toUri(), UserDto.class);
@@ -80,6 +78,13 @@ public class UserService {
return result;
}
/**
* Updates the input of the user.
* @param name name of the user
* @param inputName name of the input
* @param value value of the input
* @return returns the result
*/
@SuppressWarnings("Duplicates")
public String updateInput(String name, String inputName, String value) {
HttpHeaders headers = new HttpHeaders();
@@ -88,13 +93,18 @@ public class UserService {
.queryParam("name", name)
.queryParam("inputName", inputName)
.queryParam("value",value);
HttpEntity<?> entity = new HttpEntity<>(headers);
new HttpEntity<>(headers);
System.out.println(builder.build().encode().toUri());
String result = this.restTemplate.getForObject(builder.build()
return this.restTemplate.getForObject(builder.build()
.encode().toUri(), String.class);
return result;
}
/**
* Adds a friend to the user.
* @param name the username of the current user.
* @param friend the username of the friend you want to add.
* @return a userDTO
*/
@SuppressWarnings("Duplicates")
public String addFriend(String name, String friend) {
HttpHeaders headers = new HttpHeaders();

View File

@@ -17,7 +17,7 @@
</font>
</Text>
<Button fx:id="loginButton" layoutX="419.0" layoutY="274.0" mnemonicParsing="false" onAction="#handleLoginButtonAction" prefHeight="26.0" prefWidth="96.0" text="Login" textAlignment="CENTER" />
<Button fx:id="signupButton" layoutX="42.0" layoutY="52.0" mnemonicParsing="false" onAction="#handleRegisterButtonAction" prefHeight="10.0" prefWidth="96.0" text="Sign up!" />
<Button fx:id="signUpButton" layoutX="42.0" layoutY="52.0" mnemonicParsing="false" onAction="#handleRegisterButtonAction" prefHeight="10.0" prefWidth="96.0" text="Sign up!" />
<PasswordField fx:id="passwordField" layoutX="318.0" layoutY="210.0" prefHeight="42.0" prefWidth="303.0" promptText="Password" />
<Hyperlink alignment="CENTER" layoutX="384.0" layoutY="301.0" prefHeight="42.0" prefWidth="173.0" text="Forgot Password?" textAlignment="CENTER" textFill="#3db25a" textOverrun="LEADING_WORD_ELLIPSIS">
<font>

View File

@@ -24,7 +24,7 @@
<Font size="13.0" />
</font>
</TextField>
<Button fx:id="signupButton" layoutX="115.0" layoutY="229.0" mnemonicParsing="false" onAction="#handleSignUpButton" style="-fx-background-color: #005e07;" 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 name="Corbel Bold" size="14.0" />
</font>

View File

@@ -8,5 +8,5 @@ import org.springframework.test.context.junit4.SpringRunner;
public class ApplicationTest {
@Test
public void contextLoads() throws Exception{ }
public void contextLoads() { }
}

View File

@@ -8,13 +8,13 @@ import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.Spy;
import org.mockito.junit.MockitoJUnitRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
import org.springframework.web.client.RestTemplate;
@RunWith(MockitoJUnitRunner.class)
public class UserServiceTest {
private static Logger logger = LoggerFactory.getLogger(UserServiceTest.class);
// private static Logger logger = LoggerFactory.getLogger(UserServiceTest.class);
@Mock
RestTemplate restTemplate;

View File

@@ -1,6 +1,10 @@
package greenify.common;
public class ApplicationException extends RuntimeException {
/**
* This method sends an application exception message.
* @param message the exception message
*/
public ApplicationException(String message) {
super(message);
}

View File

@@ -1,19 +1,34 @@
package greenify.common;
public class ErrorResponse {
String message;
private String message;
/**
* The method creates a new error response with a message.
* @param message the message you want to response with
*/
public ErrorResponse(String message) {
this.message = message;
}
/**
* This method creates an error response without a message.
*/
public ErrorResponse() { }
/**
* This method gets the message.
* @return the message
*/
public String getMessage() {
return message;
}
/**
* This method sets a message.
* @param message the message you want set
*/
public void setMessage(String message) {
this.message = message;
}
}
}

View File

@@ -1,9 +1,14 @@
/*
DTO stands for Data Transfer Object.
is an object that carries data between processes.
The motivation for its use is that communication between processes
is usually done
resorting to remote interfaces (e.g., web services),
where each call is an expensive operation.
*/
package greenify.common;
// DTO stands for Data Transfer Object.
// is an object that carries data between processes.
// The motivation for its use is that communication between processes is usually done
// resorting to remote interfaces (e.g., web services), where each call is an expensive operation.
public class UserDto {
private Long id;
private String name;
@@ -21,19 +26,35 @@ public class UserDto {
this.name = name;
}
/**
* Method that returns the name of a user.
* @return name
*/
public String getName() {
return name;
}
/**
* Method that sets the name of a user.
* @param name name of a user
*/
public void setName(String name) {
this.name = name;
}
/**
* Method that returns the ID of a user.
* @return id
*/
public Long getId() {
return id;
}
/**
* Method that sets the ID of a user.
* @param id id of a user
*/
public void setId(Long id) {
this.id = id;
}
}
}

View File

@@ -1,17 +1,16 @@
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import greenify.common.ErrorResponse;
import org.junit.Test;
public class ErrorResponseTest {
@Test
public void setAndGetTest() {
ErrorResponse response = new ErrorResponse("New error");
ErrorResponse testResponse = new ErrorResponse();
testResponse.setMessage("New error");
assertTrue(response.getMessage().equals("New error"));
assertEquals("New error", response.getMessage());
}
@Test
@@ -19,6 +18,6 @@ public class ErrorResponseTest {
ErrorResponse first = new ErrorResponse("New error");
ErrorResponse second = new ErrorResponse("New error");
assertEquals(first.getMessage(), second.getMessage());
assertTrue(first.getMessage().equals(second.getMessage()));
}
}
}

View File

@@ -1,17 +1,17 @@
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import greenify.common.UserDto;
import org.junit.Test;
public class UserDtoTest {
@Test
public void setAndGetTest() {
UserDto testUser = new UserDto();
testUser.setId(1L);
testUser.setName("greenify");
UserDto user = new UserDto(1L, "greenify");
assertTrue(user.getId() == 1L);
assertEquals(1L, (long) user.getId());
assertEquals(user.getName(), "greenify");
}
@@ -22,4 +22,5 @@ public class UserDtoTest {
assertEquals(first.getId(), second.getId());
assertEquals(first.getName(), second.getName());
}
}
}

View File

@@ -6,6 +6,10 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
/**
* This method starts the server.
* @param args the arguments
*/
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}

View File

@@ -4,68 +4,69 @@ 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<InputItem> inputItems = Arrays.asList(
new InputItem("input_size", false, "1"),
new InputItem("input_income", false, "40000"),
new InputItem("transportation_num_vehicles", false, "1" ),
new InputItem("transportation_num_vehicles", false, "1"),
new InputItem("transportation_miles1", false, "16100", false),
new InputItem("transportation_fuels1", false, "2" , false),
new InputItem("transportation_mpg1", false, null, false ),
new InputItem("transportation_miles2", false, "13200", false ),
new InputItem("transportation_fuels2", false, "0" , false),
new InputItem("transportation_mpg2", false, "22" ,false),
new InputItem("transportation_publicTrans", false, "436" ),
new InputItem("transportation_air", false, "3900" ),
new InputItem("housing_electricity_kwh_year", false, "12632" ),
new InputItem("housing_cleanPercent", false, "0" ),
new InputItem("housing_naturalGas_therms_year", false, "472" ),
new InputItem("housing_heatingOil_gallons_year", false, "73" ),
new InputItem("housing_square_feet", false, "1850" ),
new InputItem("housing_water_sewage", false, "100" ),
new InputItem("food_meat_fish_eggs", true, "2.4" ),
new InputItem("food_grains", true, "4.1" ),
new InputItem("food_dairy", true, "2.2" ),
new InputItem("food_fruit_vegetables", true, "3.5" ),
new InputItem("food_snacks_drinks", true, "3.4" ),
new InputItem("shopping_goods", false, "1310" ),
new InputItem("shopping_services", false, "2413" )
new InputItem("transportation_fuels1", false, "2", false),
new InputItem("transportation_mpg1", false, null, false),
new InputItem("transportation_miles2", false, "13200", false),
new InputItem("transportation_fuels2", false, "0", false),
new InputItem("transportation_mpg2", false, "22", false),
new InputItem("transportation_publicTrans", false, "436"),
new InputItem("transportation_air", false, "3900"),
new InputItem("housing_electricity_kwh_year", false, "12632"),
new InputItem("housing_cleanPercent", false, "0"),
new InputItem("housing_naturalGas_therms_year", false, "472"),
new InputItem("housing_heatingOil_gallons_year", false, "73"),
new InputItem("housing_square_feet", false, "1850"),
new InputItem("housing_water_sewage", false, "100"),
new InputItem("food_meat_fish_eggs", true, "2.4"),
new InputItem("food_grains", true, "4.1"),
new InputItem("food_dairy", true, "2.2"),
new InputItem("food_fruit_vegetables", true, "3.5"),
new InputItem("food_snacks_drinks", true, "3.4"),
new InputItem("shopping_goods", false, "1310"),
new InputItem("shopping_services", false, "2413")
);
/**
* The method checks that the id is valid or not.
* The method checks whether the id is valid or not.
* @param inputName the name of input
* @return true or false
*/
public static Boolean isValidItem(String inputName) {
return inputItems.stream().filter(i -> i.getName() == inputName).findAny().isPresent();
return inputItems.stream().anyMatch(i -> i.getName().equals(inputName));
}
/**
* The method checks that the item value is valid or not.
* The method checks whether the item value is valid or not.
* @param inputName the name of input
* @param value the value of item
* @return true or false
*/
public static boolean isValidItemValue(String inputName, String value) {
InputItem item = null;
for (int i = 0; i < inputItems.size(); i++) {
if (inputItems.get(i).getName() == inputName) {
item = inputItems.get(i);
for (InputItem inputItem : inputItems) {
if (inputItem.getName().equals(inputName)) {
item = inputItem;
}
}
if (item.getFloat()) {
if (Objects.requireNonNull(item).getFloat()) {
try {
Float number = Float.parseFloat(value);
Float.parseFloat(value);
} catch (NumberFormatException | NullPointerException nfe) {
return false;
}
return true;
} else {
try {
Integer number = Integer.parseInt(value);
Integer.parseInt(value);
} catch (NumberFormatException | NullPointerException nfe) {
return false;
}
@@ -74,13 +75,13 @@ public class InputValidator {
}
/**
* getter for default values.
* This method gets default values.
* @return the map of default values
*/
public static Map<String, String> getDefaultValues() {
Map<String,String> map = new HashMap<String, String>(){};
for (int i = 0; i < inputItems.size(); i++) {
map.put(inputItems.get(i).getName(), inputItems.get(i).getDefaultValue());
Map<String, String> map = new HashMap<String, String>() { };
for (InputItem inputItem : inputItems) {
map.put(inputItem.getName(), inputItem.getDefaultValue());
}
return map;
}

View File

@@ -4,11 +4,11 @@ import greenify.common.ApplicationException;
import greenify.server.InputValidator;
import lombok.Data;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.ArrayList;
import java.util.Collection;
import javax.persistence.*;
@@ -34,7 +34,7 @@ public class User {
private Float footPrint = 0.0f;
@ElementCollection
private Map<String,String> footPrintInputs = new HashMap<>();
private Map<String, String> footPrintInputs = new HashMap<>();
@ManyToMany
@JoinColumn
@@ -43,7 +43,7 @@ public class User {
public User() {}
/**
* makes a user object.
* This method makes a user object.
* @param id the id of the user.
* @param name the supplied username
* @param password the supplied password
@@ -57,53 +57,81 @@ public class User {
}
/**
* gets the id.
* @return the id
* This method gets the ID of the user.
* @return the id of the user
*/
public Long getId() {
return id;
}
public void setId(Long id) {
/**
* This method sets the ID of the user.
* @param id the id of the user
*/
void setId(Long id) {
this.id = id;
}
/**
* gets the name.
* @return the name
* This method gets the name of the user.
* @return the name of the user
*/
public String getName() {
return name;
}
/**
* This method sets the name of the user.
* @param name the name of the user
*/
public void setName(String name) {
this.name = name;
}
/**
* gets the password.
* @return the password
* This method gets the password of the user.
* @return the password of the user
*/
public String getPassword() {
return password;
}
public void setPassword(String password) {
/**
* This method sets the password of the user.
* @param password the password of the user
*/
void setPassword(String password) {
this.password = password;
}
/**
* gets the footPrint of user.
* @return the footPrint
* This method gets the footPrint of user.
* @return the footprint of the user
*/
public Float getFootPrint() {
return footPrint;
}
/**
* This method sets the footprint of a user.
* @param footPrint footprint of a user
*/
public void setFootPrint(Float footPrint) {
this.footPrint = footPrint;
}
/**
* This method gets the footprint inputs of the user.
* @return footprint inputs of the user
*/
public Map<String, String> getFootPrintInputs() {
return footPrintInputs;
}
/**
* This method sets the footprint inputs of the user.
* @param footPrintInputs footprint inputs of the user
*/
public void setFootPrintInputs(Map<String, String> footPrintInputs) {
this.footPrintInputs = footPrintInputs;
}
@@ -126,13 +154,8 @@ public class User {
}
}
public void setFootPrint(Float footPrint) {
this.footPrint = footPrint;
}
/**
* Returns a human readable object. It's in JSON.
* This method gets a human readable (JSON) object.
* @return the JSON form of the object.
*/
@Override
@@ -145,7 +168,7 @@ public class User {
* Returns the name and score of the friends in JSON. Needed for the leaderboard.
* @return a JSON object of the friendlist with only names and scores.
*/
public String friendsToString(){
public String friendsToString() {
String result = "friends=[";
for (User u : friends) {
result += "{name=" + u.getName() + ", footprint=" + u.getFootPrint() + "}, ";
@@ -156,18 +179,24 @@ public class User {
return result + "]";
}
/** This method checks whether two users are equal or not.
* @param other an other user
* @return users are (not) equal
*/
@Override
public boolean equals(Object other) {
if (other instanceof User) {
User that = (User)other;
if (that.id == this.id && that.name.equals(this.name)
&& that.password.equals(this.password)) {
return true;
}
User that = (User) other;
return that.id.equals(this.id) && that.name.equals(this.name)
&& that.password.equals(this.password);
}
return false;
}
/**
* This method gets the hashcode of a user.
* @return hashcode of a user
*/
@Override
public int hashCode() {
return Objects.hash(id, name, password);

View File

@@ -3,10 +3,17 @@ package greenify.server.data.repository;
import greenify.server.data.model.User;
import org.springframework.data.repository.CrudRepository;
//userRepository that saves all the user and talks to the database
/**
* UserRepository that saves all the users and talks to the database.
*/
public interface UserRepository extends CrudRepository<User, Integer> {
User findByName(String name);
/**
* This method saves a user in the database.
* @param user the user you want saved
* @param <T> always a user
* @return the user
*/
<T extends User> T save(T user);
}

View File

@@ -7,12 +7,14 @@ import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
//class that handles exceptions for the rest server
/**
* This class handles exceptions for the REST server.
*/
@RestControllerAdvice
public class RestExceptionHandler {
class RestExceptionHandler {
@ExceptionHandler(ApplicationException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public static ErrorResponse applicationException(ApplicationException ex) {
static ErrorResponse applicationException(ApplicationException ex) {
return new ErrorResponse(ex.getMessage());
}
}

View File

@@ -10,24 +10,43 @@ import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@Autowired
UserService userService;
private
UserService userService;
/**
* This method registers the user.
* @param name name of the user
* @param password password of the user
* @return the userDto of the user
*/
@RequestMapping("/registerUser")
public UserDto registerUser(@RequestParam(value = "name") String name,
@RequestParam(value = "password") String password) {
return userService.registerUser(name, password);
}
/**
* This method logs in the user.
* @param name name of the user
* @param password password of the user
* @return the userDto of the user
*/
@RequestMapping("/loginUser")
public UserDto loginUser(@RequestParam(value = "name") String name,
@RequestParam(value = "password") String password) {
return userService.loginUser(name, password);
}
/**
* This method sets 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("/setInput")
public void setInput(@RequestParam(value = "name") String name,
@RequestParam(value = "inputName") String inputName,
@RequestParam(value = "value") String value) {
userService.setInput(name, inputName, value);
}
}
}

View File

@@ -16,21 +16,27 @@ import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import java.util.Map;
import java.util.Objects;
@Service
public class CalculatorService {
Logger logger = LoggerFactory.getLogger(UserService.class);
class CalculatorService {
@Autowired
RestTemplate restTemplate;
private Logger logger = LoggerFactory.getLogger(UserService.class);
@Bean
RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
protected Float invokeExternalService(Map<String, String> map) {
/**
/**
* This method invokes the external service that calculates a footprint.
* @param map used variables to calculate a footprint
* @return a footprint
*/
Float invokeExternalService(Map<String, String> map) {
/*
* curl -X GET "https://apis.berkeley.edu/coolclimate/footprint-sandbox?input_location_mode=1
* &input_location=48001&input_income=1&input_size=0&input_footprint_transportation_miles1=3
* &input_footprint_transportation_mpg1=5&input_footprint_transportation_fuel1=0"
@@ -52,7 +58,7 @@ public class CalculatorService {
entity, String.class);
logger.info(response.getStatusCode().toString());
logger.info(response.getBody());
String result = response.getBody().substring(response.getBody()
String result = response.getBody().substring(Objects.requireNonNull(response.getBody())
.indexOf("<result_grand_total>")
+ 20, response.getBody().indexOf("</result_grand_total>"));
// to do: in not HTTP 200 or exception case throws exception
@@ -60,7 +66,12 @@ public class CalculatorService {
return Float.parseFloat(result);
}
public Float calculateFootprint(User user) {
/**
* The method calculates a users footprint.
* @param user the user
* @return the footprint of the user
*/
Float calculateFootprint(User user) {
return invokeExternalService(user.getFootPrintInputs());
}
}

View File

@@ -14,19 +14,19 @@ import org.springframework.web.bind.annotation.ResponseBody;
@Service
public class UserService {
Logger logger = LoggerFactory.getLogger(UserService.class);
@Autowired
CalculatorService calculatorService;
@Autowired
UserRepository userRepository;
@Autowired
CalculatorService calculatorService;
private Logger logger = LoggerFactory.getLogger(UserService.class);
/**
* registers the user.
* @param name the username of the user
* @param password the password of the user
* @return a userDTO of the registered user
* This method registers the user.
* @param name name of the user
* @param password password of the user
* @return the userDto of the user
*/
public UserDto registerUser(String name, String password) {
User user = userRepository.findByName(name);
@@ -42,10 +42,10 @@ public class UserService {
}
/**
* logs the user in.
* @param name the username of the user
* @param password the password of the user
* @return a userDTO of the logged in user
* This method logs in the user.
* @param name name of the user
* @param password password of the user
* @return the userDto of the user
*/
public UserDto loginUser(String name, String password) {
User user = userRepository.findByName(name);
@@ -60,6 +60,7 @@ 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.
@@ -85,10 +86,10 @@ public class UserService {
}
/**
* The method sets input value.
* @param name of the user
* @param inputName is the name of the setting input
* @param value of the input
* This method sets 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 setInput(String name, String inputName, String value) {
User user = userRepository.findByName(name);
@@ -106,31 +107,37 @@ public class UserService {
}
/**
* Gets the input value of an input.
* This method gets the input value of an input.
* @param name of the user
* @param inputName name of the input
* @return input value
*/
public String getInput(String name, String inputName) {
String getInput(String name, String inputName) {
User user = userRepository.findByName(name);
if (InputValidator.isValidItem(inputName)) {
String item = user.getFootPrintInputs().get(inputName);
return item;
return user.getFootPrintInputs().get(inputName);
} else {
throw new ApplicationException("Invalid input");
}
}
public Float getFootprint(String name) {
/**
* This method gets the footprint of a user.
* @param name name of the user
* @return footprint of the user
*/
Float getFootprint(String name) {
User user = userRepository.findByName(name);
return calculatorService.calculateFootprint(user);
}
/**
* This method gets a JSON of XML with all users.
* @return JSON/XML of all users
*/
@GetMapping(path = "/all")
@ResponseBody
public Iterable<User> getAllUsers() {
// This returns a JSON or XML with the users
Iterable<User> getAllUsers() {
return userRepository.findAll();
}
}

View File

@@ -8,6 +8,6 @@ import org.springframework.test.context.junit4.SpringRunner;
public class ApplicationTest {
@Test
public void contextLoads() throws Exception{ }
public void contextLoads() { }
}

View File

@@ -1,5 +1,8 @@
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import greenify.server.InputValidator;
import org.junit.Assert;
import org.junit.Test;
import java.util.HashMap;
@@ -9,20 +12,20 @@ public class InputValidatorTest {
@Test
public void validItemIdTest() {
InputValidator inputValidator = new InputValidator();
Assert.assertEquals(inputValidator.isValidItem("transportation_num_vehicles"), true);
Assert.assertEquals(inputValidator.isValidItem("test"), false);
new InputValidator();
assertEquals(InputValidator.isValidItem("transportation_num_vehicles"), true);
assertEquals(InputValidator.isValidItem("test"), false);
}
@Test
public void validItemValueTest() {
Assert.assertEquals(true, InputValidator
assertTrue(InputValidator
.isValidItemValue("transportation_num_vehicles", "4"));
Assert.assertEquals(false, InputValidator
assertFalse(InputValidator
.isValidItemValue("transportation_num_vehicles", "3.5"));
Assert.assertEquals(false, InputValidator.isValidItemValue( "food_grains", "hello"));
Assert.assertEquals(true, InputValidator.isValidItemValue("food_grains", "5"));
Assert.assertEquals(true, InputValidator.isValidItemValue("food_grains", "3.5"));
assertFalse(InputValidator.isValidItemValue("food_grains", "hello"));
assertTrue(InputValidator.isValidItemValue("food_grains", "5"));
assertTrue(InputValidator.isValidItemValue("food_grains", "3.5"));
}
@Test
@@ -54,6 +57,6 @@ public class InputValidatorTest {
put("shopping_services", "2413");
}
};
Assert.assertEquals(InputValidator.getDefaultValues(), map);
assertEquals(InputValidator.getDefaultValues(), map);
}
}

View File

@@ -1,16 +1,17 @@
package greenify.server.data.model;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import greenify.common.ApplicationException;
import org.junit.Test;
import java.util.ArrayList;
public class UserTest {
@Test
public void setAndGetTest() {
User testUser = new User();
@@ -18,7 +19,7 @@ public class UserTest {
testUser.setName("greenify");
testUser.setPassword("password");
User user = new User(1L, "greenify", "password");
assertTrue(user.getId().equals(1L));
assertEquals(1L, (long) user.getId());
assertEquals(user.getName(), "greenify");
assertEquals(user.getPassword(), "password");
assertEquals(user, testUser);
@@ -32,47 +33,47 @@ public class UserTest {
@Test
public void equalsTest() {
User first = new User(1L, "greenify", "password");
User second = new User(1L, "greenify", "password");
User first = new User(2L, "greenify", "12345");
User second = new User(2L, "greenify", "12345");
assertEquals(first.getId(), second.getId());
assertEquals(first.getName(), second.getName());
assertEquals(first.getPassword(), second.getPassword());
assertTrue(first.equals(second));
assertEquals(first, second);
}
@Test
public void equalsDifferentId() {
User first = new User(1L, "greenify", "password");
User second = new User(2L, "greenify", "password");
assertFalse(first.equals(second));
assertNotEquals(first, second);
}
@Test
public void equalsDifferentName() {
User first = new User(1L, "greenify", "password");
User second = new User(1L, "hello", "password");
assertFalse(first.equals(second));
User first = new User(5L, "greenify", "password");
User second = new User(5L, "hello", "password");
assertNotEquals(first, second);
}
@Test
public void equalsDifferentPassword() {
User first = new User(1L, "greenify", "password");
User second = new User(1L, "greenify", "hi");
assertFalse(first.equals(second));
assertNotEquals(first, second);
}
@Test
public void notEqualsTest() {
User first = new User(1L, "greenify", "password");
User second = new User(2L, "greenify", "password");
assertFalse(first.equals(second));
assertNotEquals(first, second);
}
@Test
public void instanceOfTest() {
User first = new User();
Object second = new Object();
assertFalse(first.equals(second));
assertNotEquals(first, second);
}
@Test
@@ -120,4 +121,3 @@ public class UserTest {
assertEquals(first.friendsToString(), "friends=[{name=merel, footprint=0.0}]");
}
}

View File

@@ -3,6 +3,7 @@ package greenify.server.data.repository;
import static org.junit.Assert.assertEquals;
import greenify.server.data.model.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
@@ -16,9 +17,10 @@ public class UserRepositoryTest {
private UserRepository repository;
@Test
public void findByUsernameTest() throws Exception {
public void findByUsernameTest() {
repository.save(new User(296L, "cugurlu", "password"));
User user = this.repository.findByName("cugurlu");
assertEquals(user.getName(), "cugurlu");
}
}

View File

@@ -55,8 +55,8 @@ public class UserControllerTest {
.andExpect(status().isOk()).andExpect(content().json("{'id':1,'name':'ceren'}"));
}
@Test
public void setInputTest() throws Exception {
}
//@Test
//public void setInputTest() {
//
//}
}

View File

@@ -37,8 +37,7 @@ public class CalculatorServiceTest {
@Bean
public CalculatorService calculatorService() {
CalculatorService calculatorService = new CalculatorService();
return calculatorService;
return new CalculatorService();
}
@Bean

View File

@@ -1,7 +1,6 @@
package greenify.server.service;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.when;
@@ -62,9 +61,7 @@ public class UserServiceTest {
@Test
public void loginExceptionTest() {
assertThrows(ApplicationException.class, () -> {
userService.loginUser("alex", "greenify");
});
assertThrows(ApplicationException.class, () -> userService.loginUser("alex", "greenify"));
}
@Test
@@ -76,9 +73,8 @@ public class UserServiceTest {
@Test
public void registerExceptionTest() {
assertThrows(ApplicationException.class, () -> {
userService.registerUser("alex", "password");
});
assertThrows(ApplicationException.class, () ->
userService.registerUser("alex", "password"));
}
@Test
@@ -92,26 +88,20 @@ public class UserServiceTest {
@Test
public void setInputNullTest() {
assertThrows(ApplicationException.class, () -> {
userService.setInput(null, "hello", "5.5");
});
assertThrows(ApplicationException.class, () -> userService.setInput(null, "hello", "5.5"));
}
@Test
public void setInputApplicationTestItem() {
assertThrows(ApplicationException.class, () -> {
userService.setInput("alex", "hello", "3.5");
});
assertThrows(ApplicationException.class, () -> userService.setInput("tom", "hello", "3.5"));
}
@Test
public void setInputApplicationTestValue() {
assertThrows(ApplicationException.class, () -> {
userService.setInput("alex", "transportation_num_vehicles", "5.5");
});
assertThrows(ApplicationException.class, () ->
userService.setInput("tom", "transportation_num_vehicles", "5.5"));
}
@Test
public void setInputFootprintTest() {
User alex = new User(1L, "alex", "password");
@@ -120,7 +110,7 @@ public class UserServiceTest {
when(calculatorService.calculateFootprint(alex))
.thenReturn(15f);
userService.setInput("alex", "food_grains", "6.5");
assertTrue(15f == alex.getFootPrint());
assertEquals(15f, alex.getFootPrint(), 0.0);
}
@Test
@@ -134,9 +124,7 @@ public class UserServiceTest {
@Test
public void getInputExceptionTest() {
assertThrows(ApplicationException.class, () -> {
userService.getInput("alex", "hello");
});
assertThrows(ApplicationException.class, () -> userService.getInput("alex", "hello"));
}
@Test
@@ -147,7 +135,7 @@ public class UserServiceTest {
when(calculatorService.calculateFootprint(alex))
.thenReturn(15f);
userService.setInput("alex", "food_grains", "6.5");
assertTrue(15f == userService.getFootprint("alex"));
assertEquals(15f, userService.getFootprint("alex"), 0.0);
}
@Test
@@ -157,10 +145,7 @@ public class UserServiceTest {
@Test
public void invalidLoginTest() {
User user = null;
assertThrows(ApplicationException.class, () -> {
userService.loginUser(null, null);
});
assertThrows(ApplicationException.class, () -> userService.loginUser(null, null));
}
@Test
@@ -182,5 +167,4 @@ public class UserServiceTest {
assertEquals(userService.getLeaderboard("alex"), "friends=[{name=lola, footprint=0.0}]");
}
}