windows 10 pro office 2019 pro office 365 pro windows 10 home windows 10 enterprise office 2019 home and business office 2016 pro windows 10 education visio 2019 microsoft project 2019 microsoft project 2016 visio professional 2016 windows server 2012 windows server 2016 windows server 2019 Betriebssysteme office software windows server https://softhier.com/ instagram takipçi instagram beğeni instagram görüntüleme instagram otomatik beğeni facebook beğeni facebook sayfa beğenisi facebook takipçi twitter takipçi twitter beğeni twitter retweet youtube izlenme youtube abone instagram

Spring boot Data Rest: 500 error Validation failed

Asked By: Anonymous

I’m developing a Spring boot web application. and I’m working on spring boot to save users , but i’m getting this error everytime i try to add a caregiver

Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is javax.validation.ConstraintViolationException: Validation failed for classes [com.bezkoder.springjwt.models.Caregiver] during persist time for groups [javax.validation.groups.Default, ]
List of constraint violations:[
    ConstraintViolationImpl{interpolatedMessage='must not be blank', propertyPath=password, rootBeanClass=class com.bezkoder.springjwt.models.Caregiver, messageTemplate='{javax.validation.constraints.NotBlank.message}'}
    ConstraintViolationImpl{interpolatedMessage='must not be blank', propertyPath=firstname, rootBeanClass=class com.bezkoder.springjwt.models.Caregiver, messageTemplate='{javax.validation.constraints.NotBlank.message}'}
    ConstraintViolationImpl{interpolatedMessage='must not be blank', propertyPath=username, rootBeanClass=class com.bezkoder.springjwt.models.Caregiver, messageTemplate='{javax.validation.constraints.NotBlank.message}'}
    ConstraintViolationImpl{interpolatedMessage='must not be blank', propertyPath=numcode, rootBeanClass=class com.bezkoder.springjwt.models.Caregiver, messageTemplate='{javax.validation.constraints.NotBlank.message}'}
    ConstraintViolationImpl{interpolatedMessage='must not be blank', propertyPath=email, rootBeanClass=class com.bezkoder.springjwt.models.Caregiver, messageTemplate='{javax.validation.constraints.NotBlank.message}'}
    ConstraintViolationImpl{interpolatedMessage='must not be blank', propertyPath=lastname, rootBeanClass=class com.bezkoder.springjwt.models.Caregiver, messageTemplate='{javax.validation.constraints.NotBlank.message}'}
    ConstraintViolationImpl{interpolatedMessage='must not be blank', propertyPath=gender, rootBeanClass=class com.bezkoder.springjwt.models.Caregiver, messageTemplate='{javax.validation.constraints.NotBlank.message}'}
]] with root cause

and this is the error on postman

"status": 500,
    "error": "Internal Server Error",
    "message": "Validation failed for classes [com.bezkoder.springjwt.models.Caregiver] during persist time for groups [javax.validation.groups.Default, ]nList of constraint violations:[ntConstraintViolationImpl{interpolatedMessage='must not be blank', propertyPath=password, rootBeanClass=class com.bezkoder.springjwt.models.Caregiver, messageTemplate='{javax.validation.constraints.NotBlank.message}'}ntConstraintViolationImpl{interpolatedMessage='must not be blank', propertyPath=firstname, rootBeanClass=class com.bezkoder.springjwt.models.Caregiver, messageTemplate='{javax.validation.constraints.NotBlank.message}'}ntConstraintViolationImpl{interpolatedMessage='must not be blank', propertyPath=username, rootBeanClass=class com.bezkoder.springjwt.models.Caregiver, messageTemplate='{javax.validation.constraints.NotBlank.message}'}ntConstraintViolationImpl{interpolatedMessage='must not be blank', propertyPath=numcode, rootBeanClass=class com.bezkoder.springjwt.models.Caregiver, messageTemplate='{javax.validation.constraints.NotBlank.message}'}ntConstraintViolationImpl{interpolatedMessage='must not be blank', propertyPath=email, rootBeanClass=class com.bezkoder.springjwt.models.Caregiver, messageTemplate='{javax.validation.constraints.NotBlank.message}'}ntConstraintViolationImpl{interpolatedMessage='must not be blank', propertyPath=lastname, rootBeanClass=class com.bezkoder.springjwt.models.Caregiver, messageTemplate='{javax.validation.constraints.NotBlank.message}'}ntConstraintViolationImpl{interpolatedMessage='must not be blank', propertyPath=gender, rootBeanClass=class com.bezkoder.springjwt.models.Caregiver, messageTemplate='{javax.validation.constraints.NotBlank.message}'}n]",
    "path": "/api/auth/signup/c"

this is the code I’m using for the job

package com.bezkoder.springjwt.models;

import javax.persistence.Entity;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import java.util.Date;

@Entity
@Table(name = "caregiver")
@PrimaryKeyJoinColumn(name = "id")
public class Caregiver  extends User {

    private static final long serialVersionUID = 1L;

    public Caregiver() {

    }

    public Caregiver(String username, String email, String encode, String firstname, Boolean active, Date dateEntry, Date dateExit, String lastname, String numcode, String gender) {

    }
}

package com.bezkoder.springjwt.security.services;

import com.bezkoder.springjwt.models.Caregiver;
import com.bezkoder.springjwt.models.User;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

public class CaregiverDetailsImpl  implements UserDetails {
   private static final long serialVersionUID = 1L;

   private Long id;

   private String username;

   private String email;

   @JsonIgnore
   private String password;


   private  String firstname;

   private Boolean isActive;

   private Date dateEntry;

   private Date dateExit ;


   private  String lastname;

   private  String numcode;

   private  String gender;

   private Collection<? extends GrantedAuthority> authorities;

   public CaregiverDetailsImpl(Long id, String username, String email, String password,String firstname,
                          Boolean isActive, Date dateEntry, Date dateExit, String lastname,
                          String numcode, String gender,
                          Collection<? extends GrantedAuthority> authorities) {
       this.id = id;
       this.username = username;
       this.email = email;
       this.password = password;
       this.authorities = authorities;
       this.firstname = firstname;
       this.isActive = isActive;
       this.dateEntry = dateEntry;
       this.dateExit = dateExit;
       this.lastname = lastname;
       this.numcode = numcode;
       this.gender = gender;
   }

   public static CaregiverDetailsImpl build(Caregiver caregiver) {
       List<GrantedAuthority> authorities = caregiver.getRoles().stream()
               .map(role -> new SimpleGrantedAuthority(role.getName().name()))
               .collect(Collectors.toList());

       return new CaregiverDetailsImpl(
               caregiver.getId(),
               caregiver.getUsername(),
               caregiver.getEmail(),
               caregiver.getPassword(),
               caregiver.getFirstname(),
               caregiver.getActive(),
               caregiver.getDateEntry(),
               caregiver.getDateExit(),
               caregiver.getLastname(),
               caregiver.getNumcode(),
               caregiver.getGender(),
               authorities);
   }

   @Override
   public Collection<? extends GrantedAuthority> getAuthorities() {
       return authorities;
   }

   public Long getId() {
       return id;
   }

   public String getEmail() {
       return email;
   }

   public String getFirstname() {
       return firstname;
   }

   public Boolean getActive() {
       return isActive;
   }

   @Override
   public String getPassword() {
       return password;
   }

   @Override
   public String getUsername() {
       return username;
   }

   @Override
   public boolean isAccountNonExpired() {
       return true;
   }

   @Override
   public boolean isAccountNonLocked() {
       return true;
   }

   @Override
   public boolean isCredentialsNonExpired() {
       return true;
   }

   @Override
   public boolean isEnabled() {
       return true;
   }

   @Override
   public boolean equals(Object o) {
       if (this == o)
           return true;
       if (o == null || getClass() != o.getClass())
           return false;
       CaregiverDetailsImpl caregiver = (CaregiverDetailsImpl) o;
       return Objects.equals(id, caregiver.id);
   }
}
package com.bezkoder.springjwt.controllers;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;
import java.util.stream.Collectors;

import javax.validation.Valid;

import com.bezkoder.springjwt.models.Caregiver;
import com.bezkoder.springjwt.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import com.bezkoder.springjwt.models.ERole;
import com.bezkoder.springjwt.models.Role;
import com.bezkoder.springjwt.models.User;
import com.bezkoder.springjwt.payload.request.LoginRequest;
import com.bezkoder.springjwt.payload.request.SignupRequest;
import com.bezkoder.springjwt.payload.response.JwtResponse;
import com.bezkoder.springjwt.payload.response.MessageResponse;
import com.bezkoder.springjwt.repository.RoleRepository;
import com.bezkoder.springjwt.repository.UserRepository;
import com.bezkoder.springjwt.security.jwt.JwtUtils;
import com.bezkoder.springjwt.security.services.UserDetailsImpl;

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/auth")
public class AuthController {


    Logger logger = Logger.getLogger("com.Appel.lib.Controller.UsersController");

    @Autowired
    private UserService userService ;


    @Autowired
    AuthenticationManager authenticationManager;

    @Autowired
    UserRepository userRepository;

    @Autowired
    RoleRepository roleRepository;

    @Autowired
    PasswordEncoder encoder;

    @Autowired
    JwtUtils jwtUtils;

    @PostMapping("/signin")
    public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {

        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));

        SecurityContextHolder.getContext().setAuthentication(authentication);
        String jwt = jwtUtils.generateJwtToken(authentication);
        
        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();      
        List<String> roles = userDetails.getAuthorities().stream()
                .map(item -> item.getAuthority())
                .collect(Collectors.toList());

        return ResponseEntity.ok(new JwtResponse(jwt, 
                                                 userDetails.getId(), 
                                                 userDetails.getUsername(), 
                                                 userDetails.getEmail(), 
                                                 roles));
    }

    @PostMapping("/signup")
    public ResponseEntity<?> registerUser(@Valid @RequestBody SignupRequest signUpRequest) {
        if (userRepository.existsByUsername(signUpRequest.getUsername())) {
            return ResponseEntity
                    .badRequest()
                    .body(new MessageResponse("Error: Username is already taken!"));
        }

        if (userRepository.existsByEmail(signUpRequest.getEmail())) {
            return ResponseEntity
                    .badRequest()
                    .body(new MessageResponse("Error: Email is already in use!"));
        }

        // Create new user's account
        User user = new User(signUpRequest.getUsername(), 
                             signUpRequest.getEmail(),

                             encoder.encode(signUpRequest.getPassword()),

                                     signUpRequest.getFirstname(),
                signUpRequest.getActive(),
                signUpRequest.getDateEntry(),
                signUpRequest.getDateExit(),
                signUpRequest.getLastname(),
                signUpRequest.getNumcode(),
                signUpRequest.getGender()


                            );

        Set<String> strRoles = signUpRequest.getRole();
        Set<Role> roles = new HashSet<>();

        if (strRoles == null) {
            Role userRole = roleRepository.findByName(ERole.ROLE_ADMIN)
                    .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
            roles.add(userRole);
        } else {
            strRoles.forEach(role -> {
                switch (role) {
                case "admin":
                    Role adminRole = roleRepository.findByName(ERole.ROLE_ADMIN)
                            .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
                    roles.add(adminRole);

                    break;
                case "mod":
                    Role modRole = roleRepository.findByName(ERole.ROLE_MODERATOR)
                            .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
                    roles.add(modRole);

                    break;
                default:
                    Role userRole = roleRepository.findByName(ERole.ROLE_USER)
                            .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
                    roles.add(userRole);
                }
            });
        }


    Boolean isActive = signUpRequest.getActive();


        if (isActive == null) {
            isActive = true;

        }

        Date dateEntry = signUpRequest.getDateEntry();
        Date dateExit = signUpRequest.getDateExit();


        if (dateEntry == null) {
            dateEntry = new Date();
            dateExit =  null;

        }


        user.setRoles(roles);
        user.setActive(isActive);
        user.setDateEntry(dateEntry);
        user.setDateExit(dateExit);
        userRepository.save(user);

        return ResponseEntity.ok(new MessageResponse("User registered successfully!"));
    }



    /***************************** Ad Care giver ****************************/

    @PostMapping("/signup/c")
    public ResponseEntity<?> registerCaregiver(@Valid @RequestBody SignupRequest signUpRequest) {
        if (userRepository.existsByUsername(signUpRequest.getUsername())) {
            return ResponseEntity
                    .badRequest()
                    .body(new MessageResponse("Error: Username is already taken!"));
        }

        if (userRepository.existsByEmail(signUpRequest.getEmail())) {
            return ResponseEntity
                    .badRequest()
                    .body(new MessageResponse("Error: Email is already in use!"));
        }

        // Create new user's account
        Caregiver caregiver = new Caregiver(signUpRequest.getUsername(),
                signUpRequest.getEmail(),

                encoder.encode(signUpRequest.getPassword()),

                signUpRequest.getFirstname(),
                signUpRequest.getActive(),
                signUpRequest.getDateEntry(),
                signUpRequest.getDateExit(),
                signUpRequest.getLastname(),
                signUpRequest.getNumcode(),
                signUpRequest.getGender()


        );

        Set<String> strRoles = signUpRequest.getRole();
        Set<Role> roles = new HashSet<>();

        if (strRoles == null) {
            Role userRole = roleRepository.findByName(ERole.ROLE_ADMIN)
                    .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
            roles.add(userRole);
        } else {
            strRoles.forEach(role -> {
                switch (role) {
                    case "admin":
                        Role adminRole = roleRepository.findByName(ERole.ROLE_ADMIN)
                                .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
                        roles.add(adminRole);

                        break;
                    case "mod":
                        Role modRole = roleRepository.findByName(ERole.ROLE_MODERATOR)
                                .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
                        roles.add(modRole);

                        break;
                    default:
                        Role userRole = roleRepository.findByName(ERole.ROLE_USER)
                                .orElseThrow(() -> new RuntimeException("Error: Role is not found."));
                        roles.add(userRole);
                }
            });
        }

        Boolean isActive = signUpRequest.getActive();


        if (isActive == null) {
            isActive = true;

        }

        Date dateEntry = signUpRequest.getDateEntry();
        Date dateExit = signUpRequest.getDateExit();


        if (dateEntry == null) {
            dateEntry = new Date();
            dateExit =  null;

        }


        caregiver.setRoles(roles);
        caregiver.setActive(isActive);
        caregiver.setDateEntry(dateEntry);
        caregiver.setDateExit(dateExit);
        userRepository.save(caregiver);

        return ResponseEntity.ok(new MessageResponse("User registered successfully!"));
    }

    @GetMapping(path = "/getuser")
    public ResponseEntity<List<User>> getAllUsers() {

        logger.info("Getting all Users  from Users table...Call getAllUsers() ");
        return ResponseEntity.ok(userService.getAll());
    }

    @GetMapping(path = "getById/{id}")
    public ResponseEntity<User> getUserById(@PathVariable Long id) {
        logger.info("Getting all Users  by id from User table...Call getUserById() ");
        User  user = userService.get(id);
        return user != null ? ResponseEntity.ok(user) : new ResponseEntity<User>(HttpStatus.NOT_FOUND);
    }

    @PutMapping(path = "Update/{id}")
    public ResponseEntity<User> updateUser(@PathVariable Long id, @RequestBody User user) {

        logger.info("Add new  Users  to  Users table...Call updateUser() ");

        if (id != null && user.getId() != null && user.getId() == id) {
            user.setActive(true);
            User  modifyuser = userService.save(user);
            return modifyuser != null && modifyuser.getId() != null ? ResponseEntity.ok(modifyuser)
                    : new ResponseEntity<User>(HttpStatus.NOT_MODIFIED);
        }
        else {
            return new ResponseEntity<User>(HttpStatus.NOT_MODIFIED);
        }
    }

    @DeleteMapping(path = "Delete/{id}")
    public ResponseEntity<String> deleteUser(@PathVariable Long id, @RequestBody User user) {

        logger.info("Desactive  Users  from  Users table...Call deleteUser() ");

    //  Date dateExit = new Date();


        if (id != null && userService.get(id) != null) {

            user.setActive(false);

            user.setDateExit(new Date());

            userService.save(user);
            //userService.delete(id);
            return ResponseEntity.ok("Deleted");
        }

        return new ResponseEntity<String>(HttpStatus.NOT_FOUND);

    }
}
package com.bezkoder.springjwt.models;

import java.io.Serializable;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.*;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;

@Entity

@Table( name = "users", 
        uniqueConstraints = { 
            @UniqueConstraint(columnNames = "username"),
            @UniqueConstraint(columnNames = "email") 
        })

@Inheritance(strategy = InheritanceType.JOINED)

public class User   implements  Serializable{

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotBlank
    @Size(max = 20)
    private String username;

    @NotBlank
    @Size(max = 50)
    @Email
    private String email;

    @NotBlank
    @Size(max = 120)
    private String password;

    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable( name = "user_roles", 
                joinColumns = @JoinColumn(name = "user_id"), 
                inverseJoinColumns = @JoinColumn(name = "role_id"))
    private Set<Role> roles = new HashSet<>();


    @NotBlank
    private String firstname;


   private Boolean isActive  ;

    @Column( nullable = false, unique = true, updatable = false)
   private Date dateEntry ;

    @Column(  unique = true)
    private Date dateExit ;

    @NotBlank
    private  String lastname;

    @NotBlank
    private  String numcode;

    @NotBlank
    private  String gender;






    public User(String username, String email, String password, String firstname, Boolean active,
                Date dateEntry, Date dateExit , String lastname, String numcode, String gender) {
        this.username = username;
        this.email = email;
        this.password = password;
        this.roles = roles;
        this.firstname = firstname;
        this.isActive = active;
        this.dateEntry = dateEntry;
        this.dateExit = dateExit;
        this.lastname = lastname;
        this.numcode = numcode;
        this.gender = gender;

    }


    public User() {

    }


    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 Set<Role> getRoles() {
        return roles;
    }

    public void setRoles(Set<Role> roles) {
        this.roles = roles;
    }


    /* ################ Ad attribut ################### */

    public String getFirstname() {
        return firstname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public Boolean getActive() {
        return isActive;
    }

    public void setActive(Boolean active) {
        isActive = active;
    }

    public Date getDateEntry() {
        return dateEntry;
    }

    public void setDateEntry(Date dateEntry) {
        this.dateEntry = dateEntry;
    }

    public Date getDateExit() {
        return dateExit;
    }

    public void setDateExit(Date dateExit) {
        this.dateExit = dateExit;
    }

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    public String getNumcode() {
        return numcode;
    }

    public void setNumcode(String numcode) {
        this.numcode = numcode;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }
}

postman request

{
"username":"konf",
"email":"[email protected]",
"password":"fvnnnd",
"firstname":"hhhh",
"lastname":"hdjdh",
"numcode":"dhdhdh",
"gender":"hhfhf"

}

i searched stackoverflow for any solution , but i didn’t find any, by the way i’m using the same code to add a user and its working fine , but when using the same code to add a caregiver i get the error


Solution

Answered By: Anonymous

Your Caregiver constructor is incorrect:

public Caregiver(String username, String email, String encode, String firstname, Boolean active, Date dateEntry, Date dateExit, String lastname, String numcode, String gender) {

}

It should be:

public Caregiver(String username, String email, String encode, String firstname, Boolean active, Date dateEntry, Date dateExit, String lastname, String numcode, String gender) {
    super(username, email, encode, firstname, active, dateEntry, dateExit, lastname, numcode, gender);
}

techinplanet staff

Porno Gratuit Porno Français Adulte XXX Brazzers Porn College Girls Film érotique Hard Porn Inceste Famille Porno Japonais Asiatique Jeunes Filles Porno Latin Brown Femmes Porn Mobile Porn Russe Porn Stars Porno Arabe Turc Porno caché Porno de qualité HD Porno Gratuit Porno Mature de Milf Porno Noir Regarder Porn Relations Lesbiennes Secrétaire de Bureau Porn Sexe en Groupe Sexe Gay Sexe Oral Vidéo Amateur Vidéo Anal

Windows 10 Kaufen Windows 10 Pro Office 2019 Kaufen Office 365 Lizenz Windows 10 Home Lizenz Office 2019 Home Business Kaufen windows office 365 satın al follower kaufen instagram follower kaufen porno