Getting ModelValidation Exception when using MultipartFormData [duplicate] - jersey

This question already has answers here:
MULTIPART_FORM_DATA: No injection source found for a parameter of type public javax.ws.rs.core.Response
(11 answers)
Closed 5 years ago.
The service Code looks like below. I have defined #PATH in main class.
#POST
#Timed
#Produces(MediaType.MULTIPART_FORM_DATA)
#ResponseStatusOverride(httpStatus = 202)
public MetaLinks CreateEdmUpload(#ApiParam(hidden = true) #Auth User user,
#FormDataParam("importInput") FormDataBodyPart jsonPart,
#FormDataParam("file") InputStream mdfStream,
#FormDataParam("file") FormDataContentDisposition cdh)
throws ApiException {
jsonPart.setMediaType(MediaType.APPLICATION_JSON_TYPE);
ImportInput importInput = jsonPart.getValueAs(ImportInput.class);
I have the following dependency in POM
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-multipart</artifactId>
<version>2.23.1</version>
</dependency>
AND I am registering the class as well in my client request but when i start the JAVA application to try to POST i get the following error
alidation of the application resource model has failed during application initialization.
[[FATAL] No injection source found for a parameter of type public com.rm
What could be wrong.. Can someone please suggest

Yes registering multipartFeature solved the problem.

Related

pjp.getArgs() is only capturing 1 argument

I am using ProceedingJoinPoint in my springboot application to capture arguments passed to log.info. I am using aspectjweaver-1.9.7. I have added the following dependencies in my maven pom.xml
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.9.7</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.7</version>
</dependency>
I have created a library which is basically a wrapper around slf4j logger. So whenever log.info or log.debug is called, I have written an #Aspect class called LoggerAspect , in which I have a #Around Method which will do the required work.
Here is the #Around Method
#Around("call(* org.slf4j.Logger.info(..))")
public void injectLogConfigInfo(ProceedingJoinPoint pjp) throws Throwable {
System.out.println(pjp.getArgs().length);
Object[] args = logMod(pjp.getArgs());
pjp.proceed(args);
MDC.clear();
}
Now, when i am implementing the logger in my application , i am facing the following issue:
Example: log.info("This is test of info", SomeObject);
when i am passing this, pjp is only picking up the first String but it is ignoring the object. I had read that it returns all the arguments as an object[] array. The method logmod(pjp.getArgs()) does some processing on the object array which pjp returns. I am not that proficient in posting questions so do forgive me for missing out on details.
Due to restrictions at my org, i cannot post the whole code but i have included the required bits. Now I know that when debugging, it is beneficial to view the whole picture but I do not have that priviledge. So even if you do not have the exact answer, if you can share your experience whether you have faced this issue and what you did to resolve it?
Thanks

Quarkus Tika Native Image generation failed Error

I am trying to create native image from Quarkus Tika. I use below dependencies with this code snippet.
#Inject
TikaParser parser;
#POST
#Path("/text")
#Produces(MediaType.TEXT_PLAIN)
public String extractText(InputStream stream) {
Instant start = Instant.now();
String text = null;
try {
text = parser.getText(stream);
} catch (Exception e) {
log.info("error" + e);
}
<dependency>
<groupId>io.quarkiverse.tika</groupId>
<artifactId>quarkus-tika</artifactId>
<version>1.0.3</version>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-resteasy-reactive</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-awt</artifactId>
</dependency>
quarkus-quickstarts/tika-quickstart$ mvn clean install -Dnative
I used sample project from https://quarkiverse.github.io/quarkiverse-docs/quarkus-tika/dev/index.html
Even though i used "initialize-at-run-time" parameter for related classes, i got same error.
<quarkus.native.additional-build-args>--initialize-at-run-time=org.apache.sis.internal.system.DelayedExecutor\,org.apache.sis.internal.system.ReferenceQueueConsumer\,ucar.nc2.grib.grib2.Grib2JpegDecoder\,ucar.nc2.grib.grib2.Grib2DataReader2</quarkus.native.additional-build-args>
Here are my config files:
application.properties
quarkus.tika.tika-config-path=tika-config.xml
tika-config.xml
<?xml version="1.0" encoding="UTF-8"?> <properties> <parsers>
<parser class="org.apache.tika.parser.pdf.PDFParser">
<mime>application/pdf</mime>
</parser>
<parser class="org.apache.tika.parser.txt.TXTParser">
<mime>text/plain</mime>
</parser> </parsers> </properties>
Error:
Fatal error: org.graalvm.compiler.debug.GraalError: com.oracle.graal.pointsto.constraints.UnsupportedFeatureException: Detected a started Thread in the image heap. Threads running in the image generator are no longer running at image runtime. To see how this object got instantiated use --trace-object-instantiation=org.apache.sis.internal.system.DelayedExecutor. The object was probably created by a class initializer and is reachable from a static field. You can request class initialization at image runtime by using the option --initialize-at-run-time=<class-name>. Or you can write your own initialization methods and call them explicitly from your main entry point.
at com.oracle.graal.pointsto.util.AnalysisFuture.setException(AnalysisFuture.java:49)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:269)
at com.oracle.graal.pointsto.util.AnalysisFuture.ensureDone(AnalysisFuture.java:63)
at com.oracle.graal.pointsto.heap.ImageHeapScanner.lambda$postTask$9(ImageHeapScanner.java:611)
at com.oracle.graal.pointsto.util.CompletionExecutor.executeCommand(CompletionExecutor.java:193)
at com.oracle.graal.pointsto.util.CompletionExecutor.lambda$executeService$0(CompletionExecutor.java:177)
at java.base/java.util.concurrent.ForkJoinTask$RunnableExecuteAction.exec(ForkJoinTask.java:1426)
at java.base/java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:290)
at java.base/java.util.concurrent.ForkJoinPool$WorkQueue.topLevelExec(ForkJoinPool.java:1020)
at java.base/java.util.concurrent.ForkJoinPool.scan(ForkJoinPool.java:1656)
at java.base/java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1594)
at java.base/java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:183)
Caused by: com.oracle.graal.pointsto.constraints.UnsupportedFeatureException: Detected a started Thread in the image heap. Threads running in the image generator are no longer running at image runtime. To see how this object got instantiated use --trace-object-instantiation=org.apache.sis.internal.system.DelayedExecutor. The object was probably created by a class initializer and is reachable from a static field. You can request class initialization at image runtime by using the option --initialize-at-run-time=<class-name>. Or you can write your own initialization methods and call them explicitly from your main entry point.
at com.oracle.svm.hosted.image.DisallowedImageHeapObjectFeature.error(DisallowedImageHeapObjectFeature.java:173)
at com.oracle.svm.core.image.DisallowedImageHeapObjects.check(DisallowedImageHeapObjects.java:74)
at com.oracle.svm.hosted.image.DisallowedImageHeapObjectFeature.replacer(DisallowedImageHeapObjectFeature.java:149)
at com.oracle.graal.pointsto.meta.AnalysisUniverse.replaceObject(AnalysisUniverse.java:582)
at com.oracle.svm.hosted.ameta.AnalysisConstantReflectionProvider.replaceObject(AnalysisConstantReflectionProvider.java:257)
at com.oracle.svm.hosted.ameta.AnalysisConstantReflectionProvider.interceptValue(AnalysisConstantReflectionProvider.java:228)
at com.oracle.svm.hosted.heap.SVMImageHeapScanner.transformFieldValue(SVMImageHeapScanner.java:126)
at com.oracle.graal.pointsto.heap.ImageHeapScanner.onFieldValueReachable(ImageHeapScanner.java:331)
at com.oracle.graal.pointsto.heap.ImageHeapScanner.lambda$createImageHeapObject$3(ImageHeapScanner.java:272)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
... 10 more

Spring project with aws cognito

I'm trying to use aws Cognito`s user authentication with my spring project. I configured Cognito and got a jwt token from it. When I pass the token to my api endpoint I'm getting error 401 (unauthorized).
I'm working on a ms that working in my localhost.
I saw a few examples and I feel like my application.properties is missing something but I'm not sure what.
My application properties :
spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://cognito-idp.eu-west-2.amazonaws.com/eu-west-2_somecode
spring.security.oauth2.client.registration.app1.client-id=my_app_id_in_cognito
My pom has the following security dependencies :
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-resource-server</artifactId>
<version>5.3.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-jose</artifactId>
<version>5.3.3.RELEASE</version>
</dependency>
My configuration class :
#Configuration
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests()
.anyRequest().authenticated().and()
.oauth2ResourceServer().jwt();
}
Tried also to change the application properties according to some spring examples :
spring.security.oauth2.client.registration.cognito.client-id=my_app_id_in_cognito
spring.security.oauth2.client.registration.cognito.client-name=app1
spring.security.oauth2.client.provider.cognito.issuer-uri=https://cognito-idp.eu-west-2.amazonaws.com/eu-west-1_somecode
but then I got the following exception because I was missing the spring.security.oauth2.resourceserver.jwt.jwk-set-uri settings in application.properties :
Method springSecurityFilterChain in org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration required a bean of type 'org.springframework.security.oauth2.jwt.JwtDecoder' that could not be found.
The following candidates were found but could not be injected:
- Bean method 'jwtDecoderByIssuerUri' in 'OAuth2ResourceServerJwtConfiguration.JwtDecoderConfiguration' not loaded because OpenID Connect Issuer URI Condition did not find issuer-uri property
- Bean method 'jwtDecoderByJwkKeySetUri' in 'OAuth2ResourceServerJwtConfiguration.JwtDecoderConfiguration' not loaded because #ConditionalOnProperty (spring.security.oauth2.resourceserver.jwt.jwk-set-uri) did not find property 'spring.security.oauth2.resourceserver.jwt.jwk-set-uri'
- Bean method 'jwtDecoderByPublicKeyValue' in 'OAuth2ResourceServerJwtConfiguration.JwtDecoderConfiguration' not loaded because Public Key Value Condition did not find public-key-location property
Action:
Consider revisiting the entries above or defining a bean of type 'org.springframework.security.oauth2.jwt.JwtDecoder' in your configuration.
What am I missing ?
I found this article and tried to use the same setting in the application.properties :
spring.security.oauth2.resourceserver.jwt.issuer-uri=https://cognito-idp.{REGION}.amazonaws.com/{POOL_ID}

Spring Boot WebClient XML

My spring boot application wants to use Webclient to make an http request (XML request body) and receives XML response. Hence I created another spring boot application with jackson-dataformat-xml and created an endpoint to receive and return XML as below.
spring-boot-version=2.2.5
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
#PostMapping(value = "/api",
consumes = MediaType.APPLICATION_XML_VALUE,
produces = MediaType.APPLICATION_XML_VALUE)
public ResponseEntity<MyXmlResponse> trip(#RequestBody MyXmlRequest request) throws Exception {
MyXmlResponse response = new MyXmlResponse();
response.setStatus("SUCCESS");
response.setTripID(request.getTripID());
return ResponseEntity.ok().body(response);
}
It works perfect and obviously no JaxB annotations are required as I use jackson-dataformat-xml. Also the request XML can be case-insensitive.
Now, in my first application I want to consume this API via webclient. I read that Spring webflux do not support Jackson-dataformat-xml yet. Hence I have to annotate my classes with Jaxb annotations.
spring-boot-version=2.2.5
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
webClient.post()
.uri(URI.create("url-to-api-endpoint"))
.body(Mono.just(myXmlRequest), MyXmlRequest.class)
.exchange()
.doOnSuccess(response -> {
HttpStatus statusCode = response.statusCode();
log.info("Status code of external system request {}", statusCode);
})
.doOnError(onError -> {
log.error("Error on connecting to external system {}", onError.getMessage());
})
.flatMap(response -> response.bodyToMono(MyXmlResponse.class))
.subscribe(this::handleResponse);
Above code throws an exception as follows
org.springframework.webreactive.function.UnsupportedMediaTypeException: Content type 'application/xml' not supported for bodyType=com.example.MyXmlRequest
at org.springframework.web.reactive.function.BodyInserters.unsupportedError(BodyInserters.java:391)
I fixed this problem by annotating with XmlRootElement as follows
#Getter #Setter #NoArgsConstructor #ToString
#XmlRootElement()
public class MyXmlRequest {
private String attribute1;
}
On the next attempt I got another error as follows
reactor.core.Exceptions$ErrorCallbackNotImplemented: org.springframework.web.reactive.function.UnsupportedMediaTypeException: Content type 'application/xml' not supported for bodyType=com.example.MyXmlResponse
Caused by: org.springframework.web.reactive.function.UnsupportedMediaTypeException: Content type 'application/xml' not supported for bodyType=com.example.MyXmlResponse
This could be solved by annotating MyXmlResponse with XmlRootElement as follows
#Getter #Setter #NoArgsConstructor #ToString
#XmlRootElement()
public class MyXmlResponse {
private String attr1;
private String attr2;
}
This time I get unmarshallexception as follows
reactor.core.Exceptions$ErrorCallbackNotImplemented: org.springframework.core.codec.DecodingException: Could not unmarshal XML to class com.example.MyXmlResponse; nested exception is javax.xml.bind.UnmarshalException
- with linked exception:
[com.sun.istack.internal.SAXParseException2; lineNumber: 1; columnNumber: 15; unexpected element (uri:"", local:"MyXmlResponse"). Expected elements are <{}myXmlResponse>]
Caused by: org.springframework.core.codec.DecodingException: Could not unmarshal XML to class com.example.MyXmlResponse; nested exception is javax.xml.bind.UnmarshalException
- with linked exception:
I fixed it with additional attributes passed to annotation as follows.
#XmlRootElement(name = "MyXmlResponse", namespace = "")
public class MyXmlResponse {
In future, my XML structures going to be tremendously complex. I want to know if I am doing it the right way.

Spring Data Rest Boot app fails to start with Java config class

I'm trying to run simple Spring Data Rest Boot app (v1.2.3.RELEASE) with only one small modification from working Spring reference example app (http://spring.io/guides/gs/accessing-mongodb-data-rest/) and it failed to start.
To be more specific when I use:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
and just following simple code configuration:
public class Application {
public static void main(String[] args){
SpringApplication.run(Config.class, args);
}
}
#SpringBootApplication
public class Config {
}
without anything else I'm getting following error on startup:
2015-04-20 12:07:32.250 ERROR 5693 --- [ main]
o.s.boot.SpringApplication : Application startup failed
org.springframework.context.ApplicationContextException: Unable to
start embedded container; nested exception is
org.springframework.boot.context.embedded.EmbeddedServletContainerException:
Unable to start embedded Tomcat ...
Caused by:
java.lang.ClassCastException:
jug.ua.json.test.Config$$EnhancerBySpringCGLIB$$79797226 cannot be
cast to
org.springframework.data.rest.core.config.RepositoryRestConfiguration
at
org.springframework.boot.autoconfigure.data.rest.SpringBootRepositoryRestMvcConfiguration$$EnhancerBySpringCGLIB$$3a999d99.config()
...
However following code configuration is working fine:
#SpringBootApplication
public class Application {
public static void main(String[] args){
SpringApplication.run(Application.class, args);
}
}
Also if instead I use:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
separate Java config class approach is working fine as well...
What I'm doing wrong, cause I can't believe I spotted such an obvious bug?
Thank you,
Oleg
The problem appears to be due to a name clash between the config bean method on SpringBootRepositoryRestMvcConfiguration (inherited from Spring Data REST's RepositoryRestMvcConfiguration) and your configuration class named Config. Renaming it to something other than Config should get things working again.

Resources