Spring Data Rest PATCH requests do not fill transient properties not backed by a field - spring

I want to implement a PATCH-Requese on an entity 'User' for changing the password with an additional transient property 'oldpassword' to compare it in the EventHandler.
The POST- and the PUT-request fill the property.
The PATCH-request doesn't: 'oldpassword' is null.
I'm using
spring-boot-starter-parent
spring-boot-starter-data-rest (2.1.6)
spring-boot-starter-web (2.1.6)
spring-boot-starter-data-jpa (2.1.6)
spring-data-jpa 2.1.9
spring-data-rest 3.1.9
spring-security 5.1.5 (presumably irrelevant)
I tried
the annotation #JsonProperty("oldpassword") (even though POST and PUT work).
the annotation #JsonDeserialize (JSON: #Transient field not seralizing)
to configure Jackson to disable the check for #Transient annotations (JPA Transient Annotation and JSON)
#JsonAutoDetect(fieldVisibility = Visibility.ANY) as class decorator
The simplified code is:
The entity 'User'
#Entity
public class User implements UserDetails, Serializable {
[...]
#NotNull
String password;
#Transient
String newpassword;
#Transient
String oldpassword;
public void setPassword(String password) {
this.newpassword = password;
}
public void setOldpassword(String oldpassword) {
this.oldpassword = oldpassword;
}
[...]
}
The Repository
#RepositoryRestResource(exported = true)
public interface UserRepository extends JpaRepository<User, Long> {
}
PATCH-Request (
HTTP Method = PATCH
Request URI = /api/users/2
Parameters = {}
Headers = [Content-Type:"application/json;charset=UTF-8", Authorization:"Basic aXJ0Z2VuZGFhczpFaW4gcGFzc3dvcmQ="]
Body = {
"username": "myusername",
"password": "mynewpassword",
"oldpassword": "theoldone"
}
The EventHandler
#Component
#RepositoryEventHandler(User.class)
public class UserEventHandler {
#HandleBeforeSave
public void printdata(User p) {
/* returns the new password*/
System.out.println("newpassword" + p.newpassword);
/* returns null (if it's a PATCH-request) */
System.out.println("oldpassword" + p.oldpassword);
/* returns the old persisted password */
System.out.println("password" + p.password);
}
}
The transient property 'newpassword' works, since I use the setter of the persisted property 'password'.

It seems you want to create a change-password feature. It won't work this way. Create a unique controller method for it.
It's not a standard REST request anyway.

Related

How to make Set using spring-data-aerospike

Environment:
spring-boot v2.0.4 RELEASE
spring-data-aerospike v2.0.1.RELEASE
java - 8
Here are my application code and properties.
// application.properties
aerospike.hosts=xxx:3000
aerospike.namespace=test
// aerospike configuration class
#Configuration
#RequiredArgsConstructor
#EnableConfigurationProperties(AerospikeConfiguration.AerospikeConfigurationProperties.class)
#EnableAerospikeRepositories(basePackageClassses = TestAeroRepository.class)
public class AerospikeConfiguration extends AbstractAerospikeDataConfiguration {
private final AerospikeConfigurationProperties aerospikeConfigurationProperties;
#Override
protected Collection<Host> getHosts() {
return Host.parseServiceHosts(aerospikeConfigurationProperties.getHosts());
}
#Override
protected String nameSpace() {
return aerospikeConfigurationProperties.getNamespace();
}
#Data
#Validate
#ConfigurationProperties("aerospike")
public static class AerospikeConfigurationProperties {
#NotEmpty
String hsots;
#NotEmpty
String namespace;
}
}
# Entity class
#Value
#Document
#Builder(toBuilder = true)
#AllArgsConstructor
public class testEntity() {
#Id
int id;
#Field
String name;
#Field
String timestamp;
}
#Repository
public interface TestAeroRepository extends AerospikeRepository<TestEntity, Integer> {
}
public interface TestAeroService {
void save();
}
#Service
#RequiredArgsConstructor
public class TestAeroServiceImpl implements TestAeroService {
private final TestAeroRepository testAeroRepository;
#Override
public void save(TestEntity entity) {
testAeroRepository.save(entity);
}
}
I checked Aerospike client connection has no problem.
But error is occurred when save() method is executed.
org.springframework.cglib.core.ReflectUtils.defineClass(Ljava/lang/String;[BLjava/lang/ClassLoader;Ljava/security/ProtectionDomain;Ljava/lang/Class;)Ljava/lang/Class;
Have to make sets before execute the application? I didn't make sets.
Any problem with my code?
You’re using an old version of spring-data-aerospike (2.0.1.RELEASE was released on April 2019) is there any chance you can upgrade to the latest version? 2.4.2.RELEASE
You can see how to setup a simple spring data aerospike application here: https://medium.com/aerospike-developer-blog/simple-web-application-using-java-spring-boot-aerospike-database-and-docker-ad13795e0089
Please share the entire project’s code and the entire exception.
I would look into:
The configuration class (The Aerospike Beans creation).
The content of the testEntity class - are you using #Id annotation on the primary key field?
Extending the repository class with specifying the testEntity object (… extends AerospikeRepository<testEntity, Object> {) you can see an example in the link I added.
The set is automatically created and takes the name of your object class, which is testEntity in your case. For example, based on your code, if you do not specify a collection in the #Document annotation a set named "testEntity" will automatically be created. I added the #Document(collection = "testEntitys") annotation and all I did was create two set. Once you insert your first record, run the "SHOW SETS" aql command and it will be there. So that's one way to do it.

Spring Boot : How to do REST validation based on input group?

I have a form in which :
firstname and lastname are mandatory fields for registered user.
ssn for new user.
contract number for owner.
So, on clicking the submit button, REST API (connect API) is called with values
from either of the above groups.
My bean class has members :
FN
LN
SSN
contractNum
How do I validate using bean/hibernate validator and identify which group has been passed ?
From the Hibernate Documentation, you can read for detail
https://hibernate.org/validator/
Hibernate Validator allows to express and validate application
constraints. The default metadata source are annotations, with the
ability to override and extend through the use of XML. It is not tied
to a specific application tier or programming model and is available
for both server and client application programming. But a simple
example says more than 1000 words:
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class User {
#NotNull
private String firstName;
#NotNull
private String lastName;
#NotNull
private String ssn;
}
Bean Validation is best used for simple validation logic. If your validation requires more complexity, use Spring's Validator interface instead.
I don't know the context domain, so I'll just call your bean "Form" with all String fields for the example:
public class Form {
private String firstName;
private String lastName;
private String ssn;
private String contractNumber;
// getters and setters
}
Then create a validator for this class:
public class FormValidator implements Validator {
public boolean supports(Class clazz) {
return Form.class.isAssignableFrom(clazz);
}
public void validate(Object target, Errors errors) {
Form form = (Form) target;
// validation logic
}
}
Then you can simply use it like this:
Form form = ...;
Validator validator = new FormValidator();
Errors errors = new Errors();
validator.validate(form, errors);
if (errors.hasErrors() {
// not valid
} else {
// is valid
}

Custom form validation in Spring boot

I am working on a spring boot application and I have a password reset form. I am using a class like this to validate the inputs.
public class PasswordResetForm {
#NotEmpty
#Size(min=6, message="must be at least 6 characters")
private String password;
private String passwordConfirm;
//Getter and Setters
}
So, I now want to validate if the fields passwordConfirm and password are equals, I searched all over but could not find how to add a custom validation in this case. So, how do I add custom validation for other fields?
My controller's action looks like this
#RequestMapping(value = "/password-change/{id}-{tokenNumber}", method = RequestMethod.POST)
public String changePassword(#PathVariable String id, #PathVariable String tokenNumber, #Valid PasswordResetForm form, BindingResult formBinding, Model model) {
if (formBinding.hasErrors())
return "change-password";
//Other stuff
}
or if you wanna validate simply only this (passwordConfirm and password are equals) case.
you can use #AssertTrue.
#AssertTrue
public boolean isDifferentPass() {
return !password.equals(passwordConfirm);
}
if these two fileds are same , then your controller's BindingResult has error
For your needs, you could consider creating a custom #Constraint. You would first create the constraint annotation:
#Target({ElementType.METHOD, ElementType.FIELD})
#Retention(RetentionPolicy.RUNTIME)
#Constraint(validatedBy=MyConstraintValidator.class)
public #interface MyConstraint {
}
And then the constraint validator:
import javax.validation.ConstraintValidator;
public class MyConstraintValidator implements ConstraintValidator {
#Autowired;
private Foo aDependency;
...
}
You can find additional reference for this here:
Dependency Injection in JSR-303 Constraint Validator with Spring fails
And on the Spring Docs:
http://docs.spring.io/autorepo/docs/spring/3.2.x/spring-framework-reference/html/validation.html
You can use #Validated annotation for forcing validation of #RequestParam and #PathVariable. #Valid is for forcing validation of #RequestBody

Externalize mongo json query using spring boot

I have just started using spring data MongoDb with Spring-Boot.
I have some mongo based json queries added in the interface using #query annotation when using spring data repository.
I want to know if it is possible to externalize or separate out the JSON query outside the codebase so that it can be optimized separately and
also not having it mixed with code.
Thanks for your suggestions.
This is the code which i have added in my interface and annotated with #query annotation.
#Query("{ 'firstname' : ?0 ,'lastname': ?1}")
List findByCriteria(String firstname,String lastname);
The above is a simple example. I have complex conditions involving $and and $or operators too .
What i basically want to achieve is externalize the above native mongo json query to a config file and refer that in the above annotation.
Spring data supports something similar when using jpa with hibernate. But not sure if we can do the same using spring data mongodb with spring boot.
Do like this (I am explaining only for the API)
Suppose you have an Entity user
At the Top there will be User domain
public class User extends CoreDomain {
private static final long serialVersionUID = -4292195532570879677L;
#Length(min = 2)
private String name;
#Length(min = 2)
#UniqueUserName(message = "User name already registered,Please choose something Different")
private String userName;
#Length(min = 6)
private String password;
}
User Controller
User Service (Interface)
User ServiceImpl(Service Implementation)
Mongo Repository(Since, I have MongoDb)
Now in userController you will take all the queries , Param(Parameters) , Pagerequest like this
public class UserController extends CoreController {
#Autowired
private UserService userService;
/*
* This controller is for getting the UserDetails on passing the UserId in
* the #param Annotation
*/
#GET
#Path("{id}")
public User getUser(#PathParam("id") String UserId) {
User user = new User();
user = userService.findUserId(UserId);
if (user == null)
throw new NotFoundException();
log.info("The userId you searched is having the details as :" + user);
return user;
}}
For serviceInterface you will have :
public interface UserService {
// Boolean authenticateUser(User user);
User findUserId(String UserId);
}
For serviceImpl :
public class UserServiceImpl implements UserService {
#Setter
#Autowired
private UserRepository userRepository;
/*
* This method will find user on the basis of their userIds passed in the
* parameter.
*/
#Override
public User findUserId(String UserId) {
User userIdResult = userRepository.findOne(UserId);
log.info("The userDetail is" + userIdResult);
return userIdResult;
}
In mongoRepository for user we will have:
A default query findById(String userId);
Hopefully this will help you.

Got two instances of struts2 action which is unexcepted

I am new to spring and struts2. I found there were two instances of my action, one with the spring injection and the other not.
Here are my simple WelcomeUserAction.java
public class WelcomeUserAction extends ActionSupport {
private String username;
private String password;
private String name;
private UserDaoImpl userDao;
#Action(value="Welcome", results = {
#Result(name ="success",location="pages/welcome_user.jsp"),
#Result(name ="input", location="pages/signup.jsp")
})
public String execute(){
User user = new User();
user.setPassword(password);
user.setUsername(username);
user.setName(name);
if (getUserDao() == null){
System.out.println("getUserDao is null");
}
getUserDao().saveUser(user);
return SUCCESS;
}
/* getter and setters... */
}
When I debug this application, I found even before the index page loaded, the spring was doing the injection. As the pic shows
And when the WelcomeUserAction starts working, there is another WelcomeUserAction instance, and the spring managing part,that is userDao became null.
I don't know why this happens. Should I provide more information such as applicationContext.xml and web.xml ?
I found what I am missing. I forgot to add struts2-spring-plugin.jar to my buildpath.

Resources