Gradle test with Quarkus Framework - java

The following code is give: User/UserResources/UserService
I wrote: Schritt3.java
I have to write a test, but I am completely lost. I googled so much and did not come closer to a Solution.
The first try get´s this error: RESTEASY003320: Failed processing arguments of public java.util.List de.hse.swa.jaxquarkus.step3.UserResource.addUser(java.lang.String,java.lang.String,java.lang.String,java.lang.Boolean)
The second one thise on: Expected status code <200> but was <400>.
As you can see I have tried different encoding types and ways to parse data. But googeling the error messages did not help me at all. I don´t know if I am just on the wrong path or if there is something else wrong.
So the question is: How to correctly pass the data.
User.java
import javax.ws.rs.FormParam;
public class User {
private Long id;
#FormParam("username")
private String username;
#FormParam("password")
private String password;
#FormParam("firstName")
private String fullName;
#FormParam("isAdmin")
private boolean isAdmin = false;
public User() {
}
public User(String username, String password, String fullName, boolean isAdmin) {
this.username = username;
this.password = password;
this.fullName = fullName;
this.isAdmin = isAdmin;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
// #JsonIgnore()
public String getPassword() {
return password;
}
// #JsonProperty()
public void setPassword(String password) {
this.password = password;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public boolean isAdmin() {
return isAdmin;
}
public void setAdmin(boolean admin) {
isAdmin = admin;
}
}
UserResource.java
import java.util.List;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import org.jboss.resteasy.annotations.Form;
import io.vertx.core.http.HttpServerRequest;
#RequestScoped
#Path("/step3/users")
public class UserResource {
#Inject
UserService service;
#Context
HttpServerRequest request;
#GET
#Produces("application/json")
public List<User> greeting() {
return service.getUsers();
}
#PUT
#Produces("application/json")
#Consumes("application/json")
public List<User> addUser(
#FormParam("username") String username,
#FormParam("password") String password,
#FormParam("fullName") String fullName,
#FormParam("isAdmin") Boolean isAdmin) {
User user = new User(username, password, fullName, isAdmin);
return service.addUser(user);
}
#POST
#Consumes("application/json")
#Produces("application/json")
public List<User> updateUser(#Form User form) {
User user = new User(form.getUsername(), form.getPassword(),
form.getFullName(), form.isAdmin());
return service.addUser(user);
}
}
User Service.java
import java.util.ArrayList;
import java.util.List;
import javax.enterprise.context.ApplicationScoped;
#ApplicationScoped
public class UserService {
public static List<User> users = new ArrayList<User>();
public static Long id = 1L;
public List<User> getUsers() {
return users;
}
public List<User> addUser(User user) {
user.setId(id++);
users.add(user);
return users;
}
public List<User> updateUser(User user) {
for (int index = 0; index < users.size(); ++index) {
if (users.get(index).getId().equals(user.getId())) {
users.set(index, user);
break;
}
}
return users;
}
public List<User> removeUser(User user) {
for (int index = 0; index < users.size(); ++index) {
if (users.get(index).getId().equals(user.getId())) {
users.remove(index);
break;
}
}
return users;
}
}
Schritt3.java
package de.hse.swa.jaxquarkus;
import de.hse.swa.jaxquarkus.step3.User;
import static org.hamcrest.CoreMatchers.containsString;
import javax.ws.rs.core.MediaType;
import io.quarkus.test.junit.QuarkusTest;
//import io.restassured.RestAssured;
import io.restassured.response.Response;
//import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import static io.restassured.RestAssured.given;
#QuarkusTest
public class Schritt3 {
String username = "test";
String password = "123";
String fullName = "testing";
Boolean isAdmin = false;
private static String requestBody = "{\n" +
" \"username\": \"123\",\n" +
" \"password\": \"456\",\n" +
" \"fullName\": \"789\",\n" +
" \"isAdmin\": \"true\" \n}";
#Test
public void postRequest()
{
/* First Try
Response response = given()
.header("Content-type", "application/json")
.contentType(ContentType.JSON)
//.body(requestBody)
.body(username + password + fullName + isAdmin)
.when()
.put("/step3/users")
.then()
.extract().response();
System.out.println("Respone from Step3 is:");
System.out.println(response.asString());
// Assertions.assertEquals("1234", response.jsonPath().getString("username"));
*/
/* Second Try
*/
RestAssured.baseURI = "http://localhost:8080";
given().urlEncodingEnabled(true)
.param("username", "user#site.com")
.param("password", "Pas54321")
.param("fullName", "MAtze")
.param("isAdmin", "true")
//.header("Accept", ContentType.JSON.getAcceptHeader())
// .header("Content-type", "application/json")
.contentType("application/json")
.put("/step3/users")
.then().statusCode(200);
}
}

Long story short:
The Code I was given works not as intended. To solve the Problem I had to change the Consume to:
#Consumes("application/x-www-form-urlencoded")
Then I could simply send the Request via formParam:
Response response =
given()
.formParam("username", "username")
.formParam("password", "password")
.formParam("fullName", "fullName")
.formParam("isAdmin", true)
.when()
.put("/step3/users")
.then()
.extract().response();
The Test can then be done via Assertions.
Assertions.assertEquals("username", response.jsonPath().getString("username"));
The only problem remaining is, that the returned Json Object starts and ends with []. So if I am checking for the username I have to add the brackets for the test so succeed.

Related

User Update Test in the Junit Doesn't Work

I'm trying make a test to Update User method that first get a User by id and after update the user , work it, but when I try to make a test in the Junit show me that couldn't find the user by Id. Can anyone help me, please?
UserClass
package br.com.projectsmanagement.entities;
import java.util.Date;
import java.util.Objects;
import jakarta.persistence.*;
#Entity
#Table(name = "tb_users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
private String password;
#Temporal(TemporalType.TIMESTAMP)
private Date dataCadastro;
public User() {
}
public User(String name, String email, String password, Date dataCadastro) {
this.name = name;
this.email = email;
this.password = password;
this.dataCadastro = dataCadastro;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Date getDataCadastro() {
return dataCadastro;
}
public void setDataCadastro(Date dataCadastro) {
this.dataCadastro = dataCadastro;
}
#Override
public int hashCode() {
return Objects.hash(id);
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
return Objects.equals(id, other.id);
}
}
UserServiceImpl
#Override
public User updateUser(Long id, User user) {
try {
User userUpdated = userRepository.findById(id).get();
userUpdated.setName(user.getName());
userUpdated.setPassword(user.getPassword());
return userRepository.saveAndFlush(userUpdated);
} catch (NoSuchElementException e) {
throw new InvalidIdException("Usuário não encontrado!");
}
}
And finally my UserServiceImplTest
package br.com.projectsmanagement.services.impl;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.boot.test.context.SpringBootTest;
import br.com.projectsmanagement.entities.User;
import br.com.projectsmanagement.exception.EmailExistException;
import br.com.projectsmanagement.repositories.UserRepository;
#SpringBootTest
class UserServiceImplTest {
#InjectMocks
private UserServiceImpl userServiceImpl;
#Mock
private UserRepository userRepository;
private User user;
private Optional<User> optionalUser;
#BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
startUser();
}
#Test
void whenFindAllThenReturnAnListofUsers() {
when(userRepository.findAll()).thenReturn(List.of(user));
List<User> response = userServiceImpl.listUsers();
assertNotNull(response);
assertEquals(1, response.size());
assertEquals(User.class, response.get(0).getClass());
}
#Test
void whenFindByIdThenReturnAnUserInstance() {
when(userRepository.findById(anyLong())).thenReturn(optionalUser);
Optional<User> response = userServiceImpl.getUserById(1L);
assertThat(response).isPresent();
assertEquals(optionalUser.getClass(), response.getClass());
assertEquals(optionalUser.get().getName(), "Valdir");
}
#Test
void whenRegisterThenReturnSuccess() {
when(userRepository.saveAndFlush(any())).thenReturn(user);
User response = userServiceImpl.registerUser(user);
assertNotNull(response);
assertEquals(User.class, response.getClass());
assertEquals(user.getId(), response.getId());
}
#Test
void whenRegisterThenReturnAnEmailExistException() {
when(userRepository.findByEmail(anyString())).thenReturn(user);
try {
userServiceImpl.registerUser(user);
} catch (ClassCastException e) {
assertEquals(EmailExistException.class, e.getClass());
assertEquals("Esse e-mail já está cadastrado!", e.getMessage());
}
User response = userServiceImpl.registerUser(user);
assertNotNull(response);
assertEquals(User.class, response.getClass());
assertEquals(user.getId(), response.getId());
}
#Test
void whenUpdateThenReturnSuccess() {
when(userRepository.saveAndFlush(any())).thenReturn(user);
User response = userServiceImpl.updateUser(1L, user);
assertNotNull(response);
assertEquals(User.class, response.getClass());
}
#Test
void testDeleteUser() {
fail("Not yet implemented");
}
private void startUser() {
user = new User("Valdir", "valdir#gmail.com", "123456", new Date());
optionalUser = Optional.of(new User("Valdir", "valdir#gmail.com", "123456", new Date()));
}
}
I modified my class many times, but even doesn't work it
I think in your test case whenUpdateThenReturnSuccess(), you forgot to mock the userRepository.findById(id) that you call when updating your user.
If not mocked, it returns null.
#Test
void whenUpdateThenReturnSuccess() {
when(userRepository.findById(anyLong())).thenReturn(optionalUser);
when(userRepository.saveAndFlush(any(User.class))).thenReturn(user);
User response = userServiceImpl.updateUser(1L, user);
assertNotNull(response);
assertEquals(User.class, response.getClass());
}

#Scheduled not updating my JSON values to FALSE

I'm trying to set all the values of a column of my H2 bank to false at 1:00 PM, but I'm having difficulties doing that, the message is being printed on the console, but the votes remain as TRUE.
My table looks like this, I would like every day at 1:00PM the values of the VOTED field to be FALSE
ID
EMAIL
PASSWORD
NAME
VOTED
1
bruno#gmail.com
$2a$10$j1Eic8Okp.IczSVQbU.ru.s.dXoxd1fdzWtK2os9oE9y9ZO8wvMx6
Bruno
TRUE
2
james#gmail.com
$2a$10$F/KLm5ULaNRVEL/K6MMeveZXr770G5cI3S7HZnEw.b7TZDENkCWBC
James
TRUE
3
robert#gmail.com
$2a$10$uHZjSrroGBtRBB/V.norRuOcDVz42MXnm0/2yLPGpE3P5XtPRo7L6
Robert
FALSE
This is the logic I'm using in my UserServices.java
Despite the project running, users remain as TRUE after the time determined in #Scheduled
#Scheduled(cron = "0 00 13* * *")
public void resetVotes() throws InterruptedException {
List<User> userArray = repository.findAll();
for(User user: userArray ) {
user.setVoted(false);
}
}
And this is the message I get on the console when I arrive at the time I determined in #Scheduled
Hibernate:
select
user0_.id as id1_1_,
user0_.email as email2_1_,
user0_.password as password3_1_,
user0_.name as name4_1_,
user0_.voted as voted5_1_
from
db_users user0_
Here are the classes I'm using for the project:
User.java
package com.dbserver.restaurantes.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "db_users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "Name")
private String username;
private String email;
private String password;
private Boolean voted = false;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Boolean getVoted() {
return voted;
}
public void setVoted(Boolean voted) {
this.voted = voted;
}
}
UserDTO.java
package com.dbserver.restaurantes.dto;
import com.dbserver.restaurantes.entities.User;
public class UserDTO {
private Long id;
private String username;
private String email;
private String password;
private Boolean voted = false;
public UserDTO() {
}
public UserDTO(Long id, String username, String email, String password, Boolean voted) {
this.id = id;
this.username = username;
this.email = email;
this.password = password;
this.voted = voted;
}
public UserDTO(User user) {
id = user.getId();
username = user.getUsername();
email = user.getEmail();
password = user.getPassword();
voted = user.getVoted();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Boolean getVoted() {
return voted;
}
public void setVoted(Boolean voted) {
this.voted = voted;
}
}
UserServices.java
package com.dbserver.restaurantes.services;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.dbserver.restaurantes.entities.User;
import com.dbserver.restaurantes.exceptions.HttpClientErrorException;
import com.dbserver.restaurantes.repositories.UserRepository;
#Service
public class UserServices {
#Autowired
private UserRepository repository;
PasswordEncoder passwordEncoder;
public UserServices(UserRepository userRepository) {
this.passwordEncoder = new BCryptPasswordEncoder();
}
#SuppressWarnings("rawtypes")
#Transactional(readOnly = true)
public List<User> findAllUsers(List list) {
List<User> result = repository.findAll();
return result;
}
#Transactional
public User addUser(User newUser) {
if (repository.findByEmail(newUser.getEmail()) != null) {
throw new HttpClientErrorException("O e-mail informado já existe no sistema");
}
String encodedPassword = this.passwordEncoder.encode(newUser.getPassword());
newUser.setPassword(encodedPassword);
return repository.saveAndFlush(newUser);
}
#Scheduled(cron = "0 00 13* * *")
public void resetVotes() throws InterruptedException {
List<User> userArray = repository.findAll();
for(User user: userArray ) {
user.setVoted(false);
}
}
}
UserRepository.java
package com.dbserver.restaurantes.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import com.dbserver.restaurantes.entities.User;
public interface UserRepository extends JpaRepository<User, Long> {
User findByEmail(String email);
}
UserController.java
package com.dbserver.restaurantes.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.dbserver.restaurantes.entities.User;
import com.dbserver.restaurantes.services.UserServices;
#RestController
#RequestMapping(value = "/users")
public class UserController {
#Autowired
private UserServices service;
#PostMapping
public User addUser(#RequestBody User newUser) {
return service.addUser(newUser);
}
}
I think you need to re-update the user list after setVoted(false)
#Scheduled(cron = "0 00 13* * *")
public void resetVotes() throws InterruptedException {
List<User> userArray = repository.findAll();
for(User user: userArray ) {
user.setVoted(false);
}
repository.save(userArray);
}
You dont need to load all user from db.
You can just update data by a custom query.
#Scheduled(cron = "0 00 13* * *")
public void resetVotes() throws InterruptedException {
repository.resetVotes();
}
UserRepository.java
package com.dbserver.restaurantes.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import com.dbserver.restaurantes.entities.User;
public interface UserRepository extends JpaRepository<User, Long> {
User findByEmail(String email);
//update custom query
#Modifying
#Query("update User set voted=false ")
int resetVotes();
}

I am getting null values from registration panel to my database

I am trying save data about registred users/client to database but I am getting null values. I have been looking what causes this but I have no idea what I am doing wrong. I have posted four of my classes.
In IntelljIDEA i have such Hibernate query
Hibernate:
select
nextval ('client_sequence')
Hibernate:
insert
into
client
(email, firstName, lastName, phoneNumber, age, appUserRole, gender, loginName, password, id)
values
(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
RegistrationController
package com.example.demo.registration;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
#Controller
#RequestMapping("/registration")
#AllArgsConstructor
public class RegistrationController {
RegistrationService registrationService;
/* HTTP GET Request for read registartion.html page from server */
#GetMapping
public String showRegistrationPanel() {
return "registration";
}
/* HTTP POST Request for insert data to database on server */
#PostMapping
public String register(#ModelAttribute("client") RegistrationDTO request, Model model) {
registrationService.register(request);
model.addAttribute("client",request);
return "redirect:/registration?success";
}
}
RegistrationService
package com.example.demo.registration;
import com.example.demo.client.AppUserRole;
import com.example.demo.client.Client;
import com.example.demo.client.ClientService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
#Service
#AllArgsConstructor
public class RegistrationService {
/* */
private final ClientService clientService;
/* */
private final EmailValidator emailValidator;
/* Method register new user to system */
public Client register(RegistrationDTO request) {
/* Check if Email is valid */
/* boolean isValidEmail = emailValidator.test(request.getEmail());
if(!isValidEmail) {
throw new IllegalStateException("email not valid");
} */
/* This method uses clientService to register new client */
return clientService.signUpClient(
new Client(
request.getFirstName(),
request.getLastName(),
request.getEmail(),
request.getPhoneNumber(),
request.getLoginName(),
request.getPassword(),
AppUserRole.USER
)
);
}
}
ClientService
package com.example.demo.client;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.List;
#Service("clientService")
#AllArgsConstructor
#Data
public class ClientService implements UserDetailsService {
private final static String USER_NOT_FOUND = "user with email %s not found";
private final ClientRepository clientRepository;
private final BCryptPasswordEncoder bCryptPasswordEncoder;
public List<Client> getClients() {
return clientRepository.findAll();
}
public void saveClient(Client client) {
clientRepository.save(client);
}
public void deleteClient(Client client) {
clientRepository.delete(client);
}
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
return clientRepository.findByEmail(username).
orElseThrow(() ->
new UsernameNotFoundException(String.format(USER_NOT_FOUND)));
}
public Client signUpClient(Client client) {
// String encodedPassword = bCryptPasswordEncoder.encode(client.getPassword());
// client.setPassword(encodedPassword);
return clientRepository.save(client);
}
}
}
Client
package com.example.demo.client;
import lombok.*;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import javax.persistence.*;
import java.util.Collection;
import java.util.Collections;
#Entity
#Table(name="client",uniqueConstraints = #UniqueConstraint(columnNames = "email"))
#AttributeOverrides({
#AttributeOverride(name="Id",column=#Column(name="Id")),
#AttributeOverride(name="firstName",column=#Column(name="firstName")),
#AttributeOverride(name="lastName",column=#Column(name="lastName")),
#AttributeOverride(name="email",column=#Column(name="email")),
#AttributeOverride(name="phoneNumber",column=#Column(name="phoneNumber"))
})
#Getter
#Setter
#ToString
#EqualsAndHashCode
#NoArgsConstructor
public class Client extends Person implements UserDetails {
#Column(name="age")
private int age;
#Column(name="gender")
private String gender;
#Column(name="loginName")
private String loginName;
#Column(name="password")
private String password;
#Enumerated (EnumType.STRING)
private AppUserRole appUserRole;
public Client(String firstName, String lastName, String email,
String phoneNumber, String loginName,String password,AppUserRole appUserRole) {
super(firstName, lastName, email, phoneNumber);
this.loginName = loginName;
this.password = password;
this.appUserRole = appUserRole;
}
public Client(String firstName, String lastName, String email,
String phoneNumber, int age, String gender,
String loginName,String password,AppUserRole appUserRole) {
super(firstName, lastName, email, phoneNumber);
this.age = age;
this.gender = gender;
this.loginName = loginName;
this.password = password;
this.appUserRole = appUserRole;
}
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
SimpleGrantedAuthority authority =
new SimpleGrantedAuthority(appUserRole.name());
return Collections.singletonList(authority);
}
#Override
public String getPassword() {
return password;
}
#Override
public String getUsername() {
return loginName;
}
}

Spring MVC application

Hi all I´m learning how to use Spring, I don´t have experience in MVC.
So I´m making a website who makes registrations, de-registrations and changes in the data of a mysql database.
The login and inserts to DB are ready but I can't make the delete registered user part.
My model:
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotEmpty;
public class StudentDelete {
#NotEmpty
#Size(min=4, max=20)
private String userName;
#NotEmpty
#Size(min=4, max=8)
private String password;
public String getPassword() {
return password;
}
public String getUserName() {
return userName;
}
public void setPassword(String password) {
this.password = password;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
My Controller:
#Controller
#SessionAttributes("student")
public class StudentController {
#Autowired
private StudentService studentService;
#RequestMapping(value="/delete", method=RequestMethod.GET)
public String delete(Model model) {
Student studentDelete = new Student();
model.addAttribute("studentDelete", studentDelete);
return "delete";
}
blablabla
#RequestMapping(value="/delete", method=RequestMethod.POST)
public String delete(#Valid #ModelAttribute("studentDelete") StudentDelete studentDelete, BindingResult result) {
if (result.hasErrors()) {
return "delete";
} else {
boolean found = studentService.findByLogin(studentDelete.getUserName(), studentDelete.getPassword());
if (found) {
studentService.deleteByLogin(studentDelete.getUserName(), studentDelete.getPassword());
return "successD";
} else {
return "failureD";
}
}
}
My Service and the implementation:
package com.github.elizabetht.service;
import com.github.elizabetht.model.Student;
public interface StudentService {
Student save(Student student);
boolean findByLogin(String userName, String password);
boolean findByUserName(String userName);
boolean deleteByLogin(String userName, String password);
}
Implementation:
public boolean deleteByLogin(String userName, String password) {
StudentDelete stud = studentDeleteRepository.deleteByLogin(userName, password);
if(stud != null) {
return true;
}
return false;
}
And finally The StudentDeleteRepository:
package com.github.elizabetht.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.github.elizabetht.model.Student;
import com.github.elizabetht.model.StudentDelete;
#Repository("studentDeleteRepository")
public interface StudentDeleteRepository extends JpaRepository<StudentDelete, Long> {
#Query("delete s from Student s where s.userName = :userName and s.password = :password")
StudentDelete deleteByLogin(#Param("userName") String userName, #Param("password") String password);
}
StudentRepository.java
package com.github.elizabetht.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.github.elizabetht.model.Student;
#Repository("studentRepository")
public interface StudentRepository extends JpaRepository<Student, Long> {
#Query("select s from Student s where s.userName = :userName")
Student findByUserName(#Param("userName") String userName);
}
In my delete.jsp all starts with this:
<form:form id="myForm" method="post"
class="bs-example form-horizontal" commandName="studentDelete">
I'm getting this error:
java.lang.NullPointerException
com.github.elizabetht.service.StudentServiceImpl.deleteByLogin(StudentServiceImpl.java:47)
Which is this part:
StudentDelete stud = studentDeleteRepository.deleteByLogin(userName, password);
Why it doesnt happen with the save method?
Any help is appreciated.
Thanks!
Your issue is that parameter you are passing below:
StudentDelete stud = studentDeleteRepository.deleteByLogin(userName, password);
username or password are empty.
Hence the null pointer exception.
Change your implementation to following formate:
public boolean deleteByLogin(String userName, String password) {
if(userName == null || password == null)
return false; // it failed essentially
StudentDelete stud = studentDeleteRepository.deleteByLogin(userName, password);
if(stud != null) {
return true;
}
return false;
}
I think the error you specified in the comments:
Not a managed type: class com.github.elizabetht.model.StudentDelete
is because you are missing the JPA #Entity annotation on your model class:
import javax.validation.constraints.Size;
import javax.persistence.Entity;
import javax.persistence.Table;
import org.hibernate.validator.constraints.NotEmpty;
#Entity
#Table("student")
public class StudentDelete {
#NotEmpty
#Size(min=4, max=20)
private String userName;
#NotEmpty
#Size(min=4, max=8)
private String password;
public String getPassword() {
return password;
}
public String getUserName() {
return userName;
}
public void setPassword(String password) {
this.password = password;
}
public void setUserName(String userName) {
this.userName = userName;
}
}

Google App Engine User Registration System

I am creating a user registration system in google app engine, and so far I could develop the registration side of the app. But I can't log in and create a HttpSession.
Here what I did, I created login.jsp and two text boxes to input email and password.
And then I created Bean class and DAO class as following.
package com.myfirstguide.beans;
import javax.servlet.http.HttpSession;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
public class UserDAO {
public static UserBean login(UserBean bean){
String email = bean.getEmail();
String password = bean.getPassword();
try{
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Query q = new Query("Account");
q.addFilter("email", Query.FilterOperator.EQUAL, email);
q.addFilter("password", Query.FilterOperator.EQUAL, password);
PreparedQuery pq = datastore.prepare(q);
Entity result = pq.asSingleEntity();
if(result != null){
bean.setValid(true);
}
//return bean;
}catch(Exception e){
}
return bean;
}
}
Here is the Bean class.
package com.myfirstguide.beans;
public class UserBean {
private String username;
private String password;
private String firstName;
private String lastName;
private String email;
public boolean valid;
public String getFirstName() {
return firstName;
}
public void setFirstName(String newFirstName) {
firstName = newFirstName;
}
public void setEmail(String semail){
email = semail;
}
public String getEmail(){
return email;
}
public String getLastName() {
return lastName;
}
public void setLastName(String newLastName) {
lastName = newLastName;
}
public String getPassword() {
return password;
}
public void setPassword(String newPassword) {
password = newPassword;
}
public String getUsername() {
return username;
}
public void setUserName(String newUsername) {
username = newUsername;
}
public boolean isValid() {
return valid;
}
public void setValid(boolean newValid) {
valid = newValid;
}
}
And here is the Servlet.
package com.myfirstguide.users;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.myfirstguide.beans.UserBean;
import com.myfirstguide.beans.UserDAO;
public class SignIn extends HttpServlet{
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String email = req.getParameter("email");
String password = req.getParameter("password");
try{
UserBean ubean = new UserBean();
ubean.setEmail(email);
ubean.setPassword(password);
ubean = UserDAO.login(ubean);
if(ubean.isValid()){
HttpSession session = req.getSession(true);
session.setAttribute("currentSessionUser",ubean);
resp.sendRedirect("index.jsp?session=" + ubean.getFirstName()); //logged-in page
}
}catch(Throwable e){
System.out.println(e);
}
}
}
And I don't know JPA. And if there is better way to do this, please tell me.
Thank you!
Have you enabled sessions?
https://developers.google.com/appengine/docs/java/config/appconfig#Enabling_Sessions

Categories

Resources