#Auth and #valid annotation not working together in java 17 - java

I am trying to use #auth and #valid annotation together in one of the APIs in my resource class and it is not being intialized and gives following error at runtime :
Caused by: org.glassfish.jersey.server.model.ModelValidationException:
Validation of the application resource model has failed during
application initialization. [[FATAL] No injection source found for a
parameter of type public javax.ws.rs.core.Response
this is what my api declaration looks like :
#POST
#ApiOperation(value = "Add feature"
#Path("/add/")
#RolesAllowed({"ADMINISTRATORS"})
public Response addTransactionType(#ApiParam(hidden = true) #Auth User user, #Valid CreateRequest request) throws Exception {
whereas the other api method which doesn't have #auth and #valid annotation together works fine, for example :
#GET
#ApiOperation(value = "get detail")
#Path("/detail/{id}")
#RolesAllowed({"USERS"})
public Response get(#ApiParam(hidden = true) #Auth User user, #PathParam("id") int id) throws Exception {
I am using java 17 with dropwizard 2.
I tried changing the order of parameters being passed and removing #valid annotation but nothing worked. Checked if there are multiple apis sharing same path and that doesn't seem to be the case. also have registered the auth binder as well in the app, so that doesn't seem to be the issue as well.

Related

Getting ConstraintViolationException when trying to use BindingResult in Spring Controller

I have and endpoint, where I validate received json document which contains collections of objects. I would like to only log these objects which don't pass a validation, when others i would like to store in db. Controller should return 200 OK in that situation. I was trying to use BindingResult object for this purpose. Unfortunately i always get a ConstraintViolationException. It seems that it validates it before it enter the method and throw exception. How can I force it to use BindingResult object ?
#RestController
#Validated
#RequestMapping(path = "/test")
class TestController {
#PostMapping(consumes = APPLICATION_JSON_VALUE)
public ResponseEntity<Void> addObjects(#RequestBody #Valid List<Document> objects, BindingResult bindingResult) {
if(bindingResult.hasErrors()){
}
return new ResponseEntity<Void>(HttpStatus.OK);
}
}
I'm using Spring Boot 1.5.9.RELEASE with Java 8
I've managed to solve it finally. Problem is with #Validated annotation on controller class. With this annotation spring do a validation on request and throw ConstraintViolationException. Without that, validation is triggered later and it results are stored in BindingResult object as expected
Could You please add the model classes with its annotations?
Remember that if You have any fields in Document class which are Your custom defined classes and You want it to be validated also then You have to decorate these fields with #Valid annotation too.

how to Add a DefaultEndpoint if No endpoint mapping is found

In my Spring boot app replacing a legacy, i have defined a webservice EndPoint.
soem of the user today comes in with payload that does nothave the namespace URI.
since namespace is not there, Spring throws No Endpoint mapping found error.
Is there a way i can add a default Endpoint so that it will get invoked if no mapping is found.
Thanks
You can try the following to create a fallback method for all request
#RequestMapping(value = "*", method = RequestMethod.GET)
#ResponseBody
public String getFallback() {
return "Fallback for GET Requests";
}
You can get more information here https://www.baeldung.com/spring-requestmapping

Passing arguments to a secured dropwizard resource

I have a resource, which is secured, if I remove the authentication, it appears to work, but then without the security, then what is the point?
Here is my code :
#POST
#Path("/secured")
#Timed
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
#UnitOfWork
#RolesAllowed("mainUser")
public Response aliveSecure(#Auth User user, CustomRequest test)
{
CustomResponse resp = new CustomResponse();
System.out.println(test.getMessage());
return Response.status(Response.Status.ACCEPTED).entity(resp).build();
}
The CustomRequest and CustomResponse types are pretty standard POJOs, they just hold a string called "Message" - they are actually identical, but this is just an exercise I am trying to complete for the sake of learning DropWizard.
Now, if I remove the #Auth stuff here, and the #RolesAllowed, etc - making it a insecure, then the method performs as normal - but as is, this is the error I get when trying to start the application.
org.glassfish.jersey.server.model.ModelValidationException: Validation of the application resource model has failed during application initialization.
! [[FATAL] No injection source found for a parameter of type public CustomRequest at index 0.;
The auth manual reads it clear -
If you want to use #Auth to inject a custom principal type into your
resource.
Hence you shall ensure adding the following to your Service that extends io.dropwizard.Application
#Override
public void run(SomeConfigThatExtendsConfiguration config, Environment environment) throws Exception {
....
environment.jersey().register(new AuthValueFactoryProvider.Binder<>(User.class));
}

Spring bean validation with hibernate annotation warning messages resolution

I have a problem how messages are resolved using hibernate annotations in Spring forms.
I have following method in the controller:
#RequestMapping(value = "/path", method = RequestMethod.POST)
public CustResponse storeForm(HttpServletResponse response, HttpServletRequest request,
#Valid #RequestBody Form form, BindingResult result) {
And when request comes I want to resolve all error messages into CustResponse object. In order to resolve warning message I am using following method from BindingResult result:
result.getCode();
According to documentation it:
Return the default code of this resolvable, that is, * the last
one in the codes array.
And default code are is resolved is very general: NotBlank for this annotation:
import org.hibernate.validator.constraints.NotBlank;
However it also exists other more specific error codes in the BindingResult result. As example:
[NotBlank.form.fieldNAme, NotBlank.fieldNAme, NotBlank.java.lang.String, NotBlank]
And I think it makes more sense to resolve error message using most meaningful error code:
NotBlank.form.fieldNAme
In order to resolve warning message I don't want to iterate through all error codes.
How would you suggest to cope with such kind of issue ?

#RequestMapping does not work on type and method in Spring 2.5

I have been reading on Spring 3.2 lately and I am now trying the following code using Spring 2.5. From what I have read this should mean that it should map profile/tags/me. However it doesn't. It just throws a No mapping found for HTTP request with URI .... What is wrong with the code, or didn't Spring 2.5 work like it does in Spring 3?
Problem when using Spring 2.5
#Controller
#RequestMapping("/profile/tags")
public class ProfileController { ... }
And this is the method inside ProfileController class:
#RequestMapping(value = "/me", method = RequestMethod.GET)
public String show(#RequestParam final long id, final ModelMap model) { ... }
According to Spring documentation, I imagine you're missing the required configuration to receive the request parameter, if you mean to receive this request parameter:
#RequestMapping(value = "/me/{id}", method = RequestMethod.GET)
public String show(#RequestParam("id") final long id, final ModelMap model) { ... }
Or you should remove RequestParam.
Update for Spring 2.5
Additionally, since you're using Spring 2.5, make sure that you've configured your DispatcherServlet in the expected way; Sections 13.11, subsections 1, 2, and 3. In summary:
DispatcherServlet should be told to load annotated RequestMappings.
DispatcherServlet should be told to load Controller annotations.
Not sure but maybe you need to refine the paths you use for the request mappings.
Hope this helps.

Categories

Resources