Login with SpringBoot - spring-boot

I'm taking the first steps with SpringBoot ... I want to make a service Log in where you put a user and a password and if it is correct it returns the user's data.
At the moment, with what I can do the user's data according to, but I can solve what I want, I would appreciate it.
The problem that I have 2. I do not know how to send 2 parameters "username", "password" for a moment Send 1.
Repository:
import org.springframework.data.repository.CrudRepository;
import prueba.Usuario;
public interface UsuRepository extends CrudRepository<Usuario,String>{
}
usuarioClass:
#Entity
#Table(name="usuario")
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Usuario {
#Id
#Column(name="id")
private int id;
#Column(name="name")
private String name;
#Column(name="email")
private String email;
public Usuario() {
}
public Usuario(int id, String name, String email) {
this.id = id;
this.name = name;
this.email = email;
}
public int getId() {
return id;
}
public void setId(int 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;
}
#Override
public String toString() {
return "User[id=" + id + ", name=" + name + ", email=" + email + "]";
}
Controller
#RestController
#RequestMapping(value={"/usu"})
public class UsuController {
#Autowired
UsuService usuRepository;
#RequestMapping("/")
String home() {
return "Servicio Usuario!";
}
#RequestMapping(method=RequestMethod.GET, path = "/Login/{userName}" , produces = MediaType.APPLICATION_JSON_VALUE)
public Usuario Login(#PathVariable("userName") String userName) {
Usuario tasks = usuRepository.getUsu(userName);
return tasks;
}
Interface:
public interface UsuService {
public List<Usuario> getUsus() ;
public Usuario getUsu(String name);
}
Service:
#Override
public Usuario getUsu(String user) {
Usuario usu;
return usu = usuRepository.findOne(user);
}
run:
http://localhost:8080/usu/Login/edu
Error:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Mon Jul 02 10:31:34 CEST 2018
There was an unexpected error (type=Internal Server Error, status=500).
Provided id of the wrong type for class prueba.Usuario. Expected: class java.lang.Integer, got class java.lang.String; nested exception is java.lang.IllegalArgumentException: Provided id of the wrong type for class prueba.Usuario. Expected: class java.lang.Integer, got class java.lang.String
I already did a test returning all the users and it works.
At the moment I want to have my username, I return my data, and then I will do the Log in with password. Thanks.
I saw others tutorials The Login with SpringBoot, but this tutorials has "Security, encriptyng , etc " but I am new With this, I need service Login easy...

I think you're mixing some concepts here. See you have this:
1) Class Usuario with an id of type int:
public class Usuario {
#Id
#Column(name="id")
private int id;
...
}
2) A request mapping receiving an user name of type String:
#RequestMapping(method=RequestMethod.GET, path = "/Login/{userName}" , produces = MediaType.APPLICATION_JSON_VALUE)
public Usuario Login(#PathVariable("userName") String userName) { ...
3) A repository configured with String as the id type of the Usuario entity:
public interface UsuRepository extends CrudRepository<Usuario,String>
Conclussion:
When you do:
public Usuario getUsu(**String** user) {
...
return usu = usuRepository.findOne(**user**);
}
You're asking the repository to find an Usuario entity with a String ID but Usuario has an int as an ID.
Therefore the error:
Provided id of the wrong type for class prueba.Usuario. **Expected**: class java.lang.Integer, **got** class java.lang.String; nested exception is java.lang.IllegalArgumentException: Provided id of the wrong type for class prueba.Usuario. Expected: class java.lang.Integer, got class java.lang.String
You need something like this:
public interface UsuRepository extends CrudRepository<Usuario,Integer> {
Usuario getByName(String username);
}
Hope I helped. :-)

Related

Retrive a object of parent class into child class in spring boot application

I am building REST API using spring boot application. I have connected application to Mongodb database. I have created a database named "Employee" and collection as "Employee" itself. Now i want to create a document. I have three class. Class A, Class B and class C.
Class A is the parent Class having property (id,name,password). Class B is child class and extends Class A with property(address,phoneNumber) and class C is child class which also extends class A with property (fatherName,MotherName).
Now i want to add the data to database as object of B or object of C and also want to retrive the data from database as object of B or Object of C.
here is code of Class A:
package com.example.webproject;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Document(collection="Employee")
public class A {
#Id
private String id;
private String passwd;
private String username;
public String getId() {
return id;
}
public void setIp(String string) {
this.ip = string;
}
public String getPasswd() {
return passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
class B:
package com.example.webproject;
public class B extends A {
private String address;
private String phoneNumber;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber= phoneNumber;
}
}
Class C :
package com.example.webproject;
public class C extends A {
private String fatherName;
private String motherName;
public String getFatherName() {
return fatherName;
}
public void setFatherName(String fatherName) {
this.fatherName = fatherName;
}
public String getMotherName() {
return motherName;
}
public void setMotherName(String motherName) {
this.motherName = motherName;
}
}
EmployeeRepository.java
package com.example.webproject;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface EmployeeRepository extends MongoRepository<A,String> {}
EmployeeController.java
#RestController
public class EmployeeController {
#Autowired
private EmployeeRepository repo;
#PostMapping("/addByB")
public String addDataByB(#RequestBody B res) {
repo.save(res);
return "added";
}
#PostMapping("/addByC")
public String addDataByC(#RequestBody C res) {
repo.save(res);
return "added";
}
#GetMapping("/getByB")
public List<B> getDataByB(){
List<B> b= repo.findAll(); #Here it throws error because repo.findAll return object of A.
return b;
}
When i try to add data as B object or C object using swagger , the data is getting stored in database. Now i want to retrieve the data as B object or C object, how to achieve this?
Because you just create Repository of class A and call it, you nedd to creat two another repo of class B and C then call them like you call " EmployeeRepository " so you can use them and get the data.

QuerySyntaxException with enum

I have a UserAssignmentRole class like this :
#Data
#Entity
public class UserAssignmentRole {
...
#Enumerated(EnumType.STRING)
public Role role;
}
And the Role is enum, it looks like this:
public enum Role{
admin,
member,
pending
}
Now when in my repository I try to query to select all with role of admin, it gives me error:
#Query("select uar from UserAssignmentRole uar where uar.role=Role.admin")
public List<UserAssignmentRole> listAdmin(Long userID, Long assignmentID);
How this can be solved?
Error : org.hibernate.hql.internal.ast.QuerySyntaxException: Invalid path: 'Role.admin'
Full error : https://pastebin.com/tk9r3wDg
It is a strange but intended behaviour of Hibernate since 5.2.x
An enum value is a constant and you're using a non-conventional naming (lowercase)
Take a look at this issue and Vlad Mihalcea's long explanation of the performance penalty.
If you’re using non-conventional Java constants, then you’ll have to set the hibernate.query.conventional_java_constants configuration property to false. This way, Hibernate will fall back to the previous behavior, treating any expression as a possible candidate for a Java constant.
You can try not to write this sql by yourself but with repository create code like this:
#Repository
public interface UserAssignmentRolelRepository extends JpaRepository<UserModel, Long>{
public List<UserAssignmentRole> findByRole(Role role);
}
And then:
#Autowired
UserAssignmentRolelRepository repository ;
public void someMethod(){
List<UserAssignmentRole> userAssignmentRoles = repository.findByRole(Role.admin);
}
UPDATE 1
As it was point out in this answer: non-conventional naming. You can change labels in your enum to uppercase.
public enum Role{
Admin,
Member,
Pending
}
and then:
#Query("select uar from UserAssignmentRole uar where uar.role=com.example.package.Role.Admin")
public List<UserAssignmentRole> listAdmin(Long userID, Long assignmentID);
UPDATE 2
But if you really want to have lowercase in DB.
It requires more code to change. Enum change to:
public enum Role{
Admin("admin"),
Member("member"),
Pending("pending");
private String name;
Role(String name) {
this.name = name;
}
public String getName() { return name; }
public static Role parse(String id) {
Role role = null; // Default
for (Role item : Role.values()) {
if (item.name.equals(id)) {
role = item;
break;
}
}
return role;
}
}
In UserAssignmentRole
// #Enumerated(EnumType.STRING)
#Convert(converter = RoleConverter.class)
private Role role;
And additional class:
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
#Converter(autoApply = true)
public class RoleConverter implements AttributeConverter<Role, String> {
#Override
public String convertToDatabaseColumn(Role role) {
return role.getName();
}
#Override
public Role convertToEntityAttribute(String dbData) {
return Role.parse(dbData);
}
}

MapStruct does not detect setters in builder

I am building a simple REST service using spring. I separated my entities from DTOs and I made the DTOs immutable using Immutables. I needed mapping between DTOs and DAOs, so I chose MapStruct. The Mapper is not able to detect the setters I have defined in my DAOs.
The problem is exactly similar to this question. This question does not have an accepted answer and I have tried all of the suggestions in that question and they don't work. I don't want to try this answer because I feel it defeats the purpose for which I am using Immutables. #marc-von-renteln summarizes this reason nicely in the comment here
I tried the answer provided by #tobias-schulte. But that caused a different problem. In the Mapper class in the answer, trying to return Immutable*.Builder from the mapping method throws an error saying the Immutable type cannot be found.
I have exhaustively searched issues logged against MapStruct and Immutables and I haven't been able to find a solution. Unfortunately there are hardly few examples or people using a combination of MapStruct and Immutables. The mapstruct-examples repository also doesn't have an example for working with Immutables.
I even tried defining separate Mapper interfaces for each of the DtTOs (like UserStatusMapper). I was only making it more complicated with more errors.
I have created a sample spring project to demonstrate the problem.
GitHub Repo Link. This demo app is almost same as the REST service I am creating. All database (spring-data-jpa , hibernate) stuff is removed and I am using mock data.
If you checkout the project and run the demo-app you can make two API calls.
GetUser:
Request:
http://localhost:8080/user/api/v1/users/1
Response:
{
"id": 0,
"username": "TestUser",
"email": "TestUser#demo.com",
"userStatus": {
"id": 1,
"status": 1,
"statusName": "Active"
}
Createuser: PROBLEM HERE
http://localhost:8080/user/api/v1/users/create
Sample Input:
{
"username": "TestUser",
"email": "TestUser#demo.com",
"userStatus": {
"id": 1,
"status": 1,
"statusName": "Active"
}
}
Response:
{
"timestamp": "2019-04-28T09:29:24.933+0000",
"status": 500,
"error": "Internal Server Error",
"message": "Type definition error: [simple type, class com.immutablesmapstruct.demo.dto.model.ImmutableUserDto$Builder]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `com.immutablesmapstruct.demo.dto.model.ImmutableUserDto$Builder`, problem: Cannot build UserDto, some of required attributes are not set [username, email, userStatus]\n at [Source: (PushbackInputStream); line: 9, column: 1]",
"path": "/user/api/v1/users/create"
}
Below are important pieces of code related to problem:
Daos:
1. UserDao
public class User {
// Primary Key. Something that is annotated with #Id
private int id;
private String username;
private String email;
private UserStatus userStatus;
private User(Builder builder) {
id = builder.id;
username = builder.username;
email = builder.email;
userStatus = builder.userStatus;
}
public static Builder builder() {
return new Builder();
}
public int getId() {
return id;
}
public String getUsername() {
return username;
}
public String getEmail() {
return email;
}
public UserStatus getUserStatus() {
return userStatus;
}
public static final class Builder {
private int id;
private String username;
private String email;
private UserStatus userStatus;
private Builder() {
}
public Builder setId(int id) {
this.id = id;
return this;
}
public Builder setUsername(String username) {
this.username = username;
return this;
}
public Builder setEmail(String email) {
this.email = email;
return this;
}
public Builder setUserStatus(UserStatus userStatus) {
this.userStatus = userStatus;
return this;
}
public User build() {
return new User(this);
}
2. UserStatusDao:
package com.immutablesmapstruct.demo.dao.model;
/**
* Status of user.
* Example: Active or Inactive
*/
public class UserStatus {
// Primary Key. Something that is annotated with #Id
private int id;
// A value of 1 or 0
private int status;
// Active , InActive
private String statusName;
private UserStatus(Builder builder) {
id = builder.id;
status = builder.status;
statusName = builder.statusName;
}
public static Builder builder() {
return new Builder();
}
public int getId() {
return id;
}
public int getStatus() {
return status;
}
public String getStatusName() {
return statusName;
}
public static final class Builder {
private int id;
private int status;
private String statusName;
private Builder() {
}
public Builder setId(int id) {
this.id = id;
return this;
}
public Builder setStatus(int status) {
this.status = status;
return this;
}
public Builder setStatusName(String statusName) {
this.statusName = statusName;
return this;
}
public UserStatus build() {
return new UserStatus(this);
}
}
}
DTOs
1. UserDto:
package com.immutablesmapstruct.demo.dto.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.immutables.value.Value;
#Value.Immutable
#Value.Style(defaults = #Value.Immutable(copy = false), init = "set*")
#JsonSerialize(as = ImmutableUserDto.class)
#JsonDeserialize(builder = ImmutableUserDto.Builder.class)
public abstract class UserDto {
#Value.Default
#JsonProperty
public int id() {
return 0;
}
#JsonProperty
public abstract String username();
#JsonProperty
public abstract String email();
#JsonProperty
public abstract UserStatusDto userStatus();
2. UserStatusDto:
package com.immutablesmapstruct.demo.dto.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.immutables.value.Value;
#Value.Immutable
#Value.Style(defaults = #Value.Immutable(copy = false), init = "set*")
#JsonSerialize(as = ImmutableUserStatusDto.class)
#JsonDeserialize(builder = ImmutableUserStatusDto.Builder.class)
public abstract class UserStatusDto {
#JsonProperty
public abstract int id();
#JsonProperty
public abstract int status();
#JsonProperty
public abstract String statusName();
}
MapStruct UserMapper:
package com.immutablesmapstruct.demo.dto.mapper;
import com.immutablesmapstruct.demo.dao.model.User;
import com.immutablesmapstruct.demo.dao.model.UserStatus;
import com.immutablesmapstruct.demo.dto.model.UserDto;
import com.immutablesmapstruct.demo.dto.model.UserStatusDto;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
#Mapper(componentModel = "spring")
public interface UserMapper {
UserMapper USER_MAPPER_INSTANCE = Mappers.getMapper(UserMapper.class);
UserDto userDaoToDto(User user);
//Problem here.
User userDtoToDao(UserDto userDto);
UserStatusDto userStatusDaoToDto(UserStatus userStatusDao);
UserStatus userStatusDtoToDao(UserStatusDto userStatusDto);
}
If I look at the concrete method generated by MapStruct for userDtoToDao I can clearly see that the setters are not being recognized.
package com.immutablesmapstruct.demo.dto.mapper;
#Generated(
value = "org.mapstruct.ap.MappingProcessor",
date = "2019-04-28T02:29:03-0700",
comments = "version: 1.3.0.Final, compiler: javac, environment: Java 1.8.0_191 (Oracle Corporation)"
)
#Component
public class UserMapperImpl implements UserMapper {
...
...
#Override
public User userDtoToDao(UserDto userDto) {
if ( userDto == null ) {
return null;
}
com.immutablesmapstruct.demo.dao.model.User.Builder user = User.builder();
return user.build();
}
....
....
}
Mapstruct doesn't recognize your getters in UserDto and UserStatusDto.
When you change the existing methods (like public abstract String username()) in these abstract classes to classic getters like
#JsonProperty("username")
public abstract String getUsername();
the MapperImpl will contain the required calls. Note, that the #JsonProperty needs to have the attributes name itself afterwards (because of the changed method name).
Here are the complete classes UserDto and UserStatusDto with said changes:
package com.immutablesmapstruct.demo.dto.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.immutables.value.Value;
#Value.Immutable
#Value.Style(defaults = #Value.Immutable(copy = false), init = "set*")
#JsonSerialize(as = ImmutableUserDto.class)
#JsonDeserialize(builder = ImmutableUserDto.Builder.class)
public abstract class UserDto {
#Value.Default
#JsonProperty("id")
public int getId() {
return 0;
}
#JsonProperty("username")
public abstract String getUsername();
#JsonProperty("email")
public abstract String getEmail();
#JsonProperty("userStatus")
public abstract UserStatusDto getUserStatus();
}
package com.immutablesmapstruct.demo.dto.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.immutables.value.Value;
#Value.Immutable
#Value.Style(defaults = #Value.Immutable(copy = false), init = "set*")
#JsonSerialize(as = ImmutableUserStatusDto.class)
#JsonDeserialize(builder = ImmutableUserStatusDto.Builder.class)
public abstract class UserStatusDto {
#JsonProperty("id")
public abstract int getId();
#JsonProperty("status")
public abstract int getStatus();
#JsonProperty("statusName")
public abstract String getStatusName();
}

DuplicateKeyException in mongodb and spring boot

I am using Spring Boot and MongoDB and I am able to store a document in MongoDB successfully. When I was trying to insert a second document, it is showing duplicatekeyexception. The total message of exception is as follows:
com.mongodb.DuplicateKeyException: Write failed with error code 11000
and error message 'E11000 duplicate key error collection:
Football_Admin.SignUp index: id dup key: { : 0 }'
The code is as follows:
SignUpRepository.java
package com.admin.Repository;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import com.admin.Model.SignUp;
#Repository
public interface SignUpRepository extends MongoRepository<SignUp,String>{
}
Controller
#Controller
#RequestMapping("/SignIn_Up")
public class HomeController {
#Autowired
SignUpRepository repository;
#RequestMapping(value = "/addadmin", method = RequestMethod.POST)
public String addAdmin(#ModelAttribute("SignUp") SignUp sign) throws NoSuchAlgorithmException,InvalidKeySpecException {
String originalPassword = sign.getPassword();
String generatedSecuredPasswordHash = generateStorngPasswordHash(originalPassword);
String email = sign.getEmail();
String fullname = sign.getFullName();
try {
sign.setEmail(email);
sign.setFullName(fullname);
sign.setPassword(generatedSecuredPasswordHash);
repository.save(sign);
}
catch (DuplicateKeyException e) {
e.printStackTrace();
}
System.out.println(generatedSecuredPasswordHash);
System.out.println("Email name is:"+sign.getEmail());
System.out.println("Full Name is:"+sign.getFullName());
System.out.println("Password is:"+sign.getPassword());
return "welcome";
}
Entity
package com.admin.Model;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Document(collection="SignUp")
public class SignUp {
#Id
private int id;
private String fullName;
private String email;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String toString() {
return id+""+fullName+""+password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
MongoDb driver don't know how to create a unique Id of type int when inserting so you received unique index exception
So either you manually create and maintain your index (quite hard) or change your id field type to ObjectId

No composite key property found for type error in Spring JPA2

I have an error in spring JPA
org.springframework.data.mapping.PropertyReferenceException: No property CompanyId found for type CompanyUserDetail!
#Embeddable
public class CompanyUserKey implements Serializable {
public CompanyUserKey() {
}
#Column(name = "company_id")
private UUID companyId;
#Column(name = "user_name")
private String userName;
public UUID getCompanyId() {
return companyId;
}
public void setCompanyId(UUID companyId) {
this.companyId = companyId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
#Entity
#Table(name = "company_user_detail")
public class CompanyUserDetail {
#EmbeddedId
CompanyUserKey companyUserkey;
public CompanyUserKey getCompanyUserkey() {
return companyUserkey;
}
public void setCompanyUserkey(CompanyUserKey companyUserkey) {
this.companyUserkey = companyUserkey;
}
}
I am trying to access below method Service layer
#Component
public interface CompanyUserRepository extends JpaRepository<CompanyUserDetail, CompanyUserKey> {
public List<CompanyUserDetail> findByCompanyId(UUID companyId);
}
How can I achieve this ?
Thanks
Since in java model your CompanyUserKey is a property in the CompanyUserDetail class, I believe you should use full path (companyUserkey.companyId) to reach companyId:
public List<CompanyUserDetail> findByCompanyUserkeyCompanyId(UUID companyId);
Also note that you have a naming inconsistency: field in CompanyUserDetail is named companyUserkey instead of companyUserKey.
Assuming you are not using spring-data-jpa's auto generated implementations, your method contents might look something like the following:
FROM CompanyUserDetail c WHERE c.companyUserKey.companyId = :companyId
Now simply provide that query to the EntityManager
entityManager.createQuery( queryString, CompanyUserDetail.class )
.setParameter( "companyId", companyId )
.getResultList();
The key points are:
Query uses a named bind parameter called :companyId (not the leading :).
Parameter values are bound in a secondary step using setParameter method variants.
createQuery uses a second argument to influence type safety so that the return value from getResultList is a List<CompanyUserDetail> just like you requested.
Looking at spring-data-jpa's implementation however, I suspect it could look like this:
public interface CustomerUserRepository
extends JpaRepository<CompanyUserDetail, CompanyUserKey> {
#Query("select c FROM CompanyUserDetail c WHERE c.companyUserKey.companyId = :companyId")
List<CompanyUserDetail> findByCompanyId(#Param("companyId") UUID companyId);
}

Resources