java8 spring 4.2.5 can't convert to java.util.Optional - spring

I have a problem with spring 4.2.5 and java8.
Trying to write simple rest:
#RequestMapping(value = "raw2", method = RequestMethod.GET)
ResponseEntity<String> getTest(#RequestParam Optional<String> p) {
return new ResponseEntity<>(HttpStatus.OK);
}
But keep getting errors:
2016-04-05 20:51:41,436 DEBUG [o.s.web.servlet.DispatcherServlet] DispatcherServlet with name 'dispatcher' processing GET request for [/internal/raw2]
2016-04-05 20:51:41,438 DEBUG [o.s.w.s.m.a.DefaultAnnotationHandlerMapping] Mapping [/internal/raw2] to HandlerExecutionChain with handler [com.test.con] and 1 interceptor
2016-04-05 20:51:41,440 DEBUG [o.s.web.servlet.DispatcherServlet] Last-Modified value for [/internal/raw2] is: -1
2016-04-05 20:51:41,453 DEBUG [org.springframework.beans.BeanUtils] No property editor [java.util.OptionalEditor] found for type java.util.Optional according to 'Editor' suffix convention
2016-04-05 20:51:41,453 DEBUG [o.s.w.s.m.a.AnnotationMethodHandlerExceptionResolver] Resolving exception from handler [com.test.con]: org.springframework.beans.ConversionNotSupportedException: Failed to convert value of type [java.lang.String] to required type [java.util.Optional]; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [java.util.Optional]: no matching editors or conversion strategy found
2016-04-05 20:51:41,454 DEBUG [o.s.w.s.m.a.ResponseStatusExceptionResolver] Resolving exception from handler [com.test.con]: org.springframework.beans.ConversionNotSupportedException: Failed to convert value of type [java.lang.String] to required type [java.util.Optional]; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [java.util.Optional]: no matching editors or conversion strategy found
2016-04-05 20:51:41,454 DEBUG [o.s.w.s.m.s.DefaultHandlerExceptionResolver] Resolving exception from handler [com.test.con]: org.springframework.beans.ConversionNotSupportedException: Failed to convert value of type [java.lang.String] to required type [java.util.Optional]; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [java.util.Optional]: no matching editors or conversion strategy found
2016-04-05 20:51:41,454 WARN [o.s.w.s.m.s.DefaultHandlerExceptionResolver] Failed to convert request element: org.springframework.beans.ConversionNotSupportedException: Failed to convert value of type [java.lang.String] to required type [java.util.Optional]; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [java.util.Optional]: no matching editors or conversion strategy found

Ensure you have added the <mvc:annotation-driven> tag in XML. This will make sure that convertors are available

Related

Expected type 'Upload' to be a GraphQLInputType Was a type only permitted for object types incorrectly used as an input type, or vice-versa

Here i'm trying to receive Upload file in Graphql. My Code as follows
Graphql schema example.graphqls
scalar Upload
type Mutation {
uploadFile(input: CreateFileUploadInput): Boolean
}
input CreateFileUploadInput {
files: Upload
id: String
}
Graphql Scalar upload defined in GraphqlConfig.java
#Configuration
public class GraphqlConfig {
#Bean
public SchemaParserOptions schemaParserOptions(
GraphQlObjectMapperConfigurer customObjectMapperConfigurer) {
return SchemaParserOptions.newOptions().objectMapperConfigurer(customObjectMapperConfigurer)
.build();
}
#Bean
GraphQLScalarType upload() {
return graphql.servlet.ApolloScalars.Upload;
}
}
Graphql Objectmapper configurer GraphQlObjectMapperConfigurer.java
#Component
public class GraphQlObjectMapperConfigurer implements ObjectMapperConfigurer {
#Override
public void configure(ObjectMapper mapper, ObjectMapperConfigurerContext context) {
mapper.registerModule(new JavaTimeModule())
.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)
.setTimeZone(TimeZone.getDefault());
}
}
my Model class CreateFileUploadInput.java
#Data
#NoArgsConstructor
#AllArgsConstructor
public class CreateFileUploadInput {
private Part files;
private String id;
}
I'm using graphql spring boot version in build.gradle is 5.8.1 and gradle gradle-5.6.2-bin
Im getting below Exception while i run my Spring Boot application!
2020-01-17 15:20:24.618 WARN 37316 --- [ main] c.c.graphql.tools.SchemaClassScanner : Cannot find definition for field 'files: Upload' on input type 'CreateFileUploadInput' -> javax.servlet.http.Part. Try adding it manually to the dictionary
2020-01-17 15:20:24.665 WARN 37316 --- [ main] c.c.graphql.tools.SchemaClassScanner : Schema type was defined but can never be accessed, and can be safely deleted: Upload
2020-01-17 15:20:24.665 WARN 37316 --- [ main] c.c.graphql.tools.SchemaClassScanner : Schema type was defined but can never be accessed, and can be safely deleted: PageInfo
2020-01-17 15:20:24.752 ERROR 37316 --- [ main] o.s.b.web.embedded.tomcat.TomcatStarter : Error starting Tomcat context. Exception: org.springframework.beans.factory.UnsatisfiedDependencyException. Message: Error creating bean with name 'graphQLServletRegistrationBean' defined in class path resource [com/oembedler/moon/graphql/boot/GraphQLWebAutoConfiguration.class]: Unsatisfied dependency expressed through method 'graphQLServletRegistrationBean' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'graphQLHttpServlet' defined in class path resource [com/oembedler/moon/graphql/boot/GraphQLWebAutoConfiguration.class]: Unsatisfied dependency expressed through method 'graphQLHttpServlet' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'graphQLServletConfiguration' defined in class path resource [com/oembedler/moon/graphql/boot/GraphQLWebAutoConfiguration.class]: Unsatisfied dependency expressed through method 'graphQLServletConfiguration' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'invocationInputFactory' defined in class path resource [com/oembedler/moon/graphql/boot/GraphQLWebAutoConfiguration.class]: Unsatisfied dependency expressed through method 'invocationInputFactory' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'graphQLSchemaProvider' defined in class path resource [com/oembedler/moon/graphql/boot/GraphQLWebAutoConfiguration.class]: Unsatisfied dependency expressed through method 'graphQLSchemaProvider' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'graphQLSchema' defined in class path resource [com/oembedler/moon/graphql/boot/GraphQLJavaToolsAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [graphql.schema.GraphQLSchema]: Factory method 'graphQLSchema' threw exception; nested exception is com.coxautodev.graphql.tools.SchemaError: Expected type 'Upload' to be a GraphQLInputType, but it wasn't! Was a type only permitted for object types incorrectly used as an input type, or vice-versa?
2020-01-17 15:20:24.789 INFO 37316 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2020-01-17 15:20:24.794 WARN 37316 --- [ main] o.a.c.loader.WebappClassLoaderBase : The web application [ROOT] appears to have started a thread named [HikariPool-1 housekeeper] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
sun.misc.Unsafe.park(Native Method)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [graphql.schema.GraphQLSchema]: Factory method 'graphQLSchema' threw exception; nested exception is com.coxautodev.graphql.tools.SchemaError: Expected type 'Upload' to be a GraphQLInputType, but it wasn't! Was a type only permitted for object types incorrectly used as an input type, or vice-versa?
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:622) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
... 128 common frames omitted
Caused by: com.coxautodev.graphql.tools.SchemaError: Expected type 'Upload' to be a GraphQLInputType, but it wasn't! Was a type only permitted for object types incorrectly used as an input type, or vice-versa?
at com.coxautodev.graphql.tools.SchemaParser.determineType(SchemaParser.kt:350) ~[graphql-java-tools-5.6.0.jar:na]
I have been spending lot of times to investigate this issue, still i could't solve it. Pls help!
I encountered this error when I tried to use a type rather than input as an input, which isn't allowed. This is slightly different from the original question, but you'll see the same error:
So this was NOT working:
scalar Upload
type Mutation {
uploadFile(input: CreateFileUploadInput): Boolean
}
type CreateFileUploadInput {
files: Upload
id: String
}
This fixed it:
input CreateFileUploadInput {
files: Upload
id: String
}
(Just changed it from type to input)
I was having the same problem over here and was able to solve it (be it not in a very nice way) after reading something mentioned on https://github.com/graphql-java-kickstart/graphql-java-tools/issues/77.
It states that by using the type explicitly in the root of a query/mutation, it will also be available on a nested level. In your case this would mean adding an additional method e.g. typLoaderDummy, as shown in the sample below (which will not actually be used) to your definition. Keep in mind that you will need to provide an implementation for this "dummy" method on your Java implementation.
scalar Upload
type Mutation {
uploadFile(input: CreateFileUploadInput): Boolean
typeLoaderDummy(upload: Upload): Boolean
}
For me this workaround solved the problem.

org.springframework.beans.ConversionNotSupportedException:Failed to convert value of type 'java.lang.String' to required type 'java.util.Optional'

For the first time i am using Optional in Rest Web Service to make a Path Parameter as optional.
#RequestMapping(value = {"/hosts","/hosts/{name}"}, method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<Object> getHosts(#PathVariable Optional<String> name) {
if(name.isPresent()) {
return service.getHosts(name.get());
} else {
return service.getHosts(null);
}
}
When i use the API without the parameter, it works fine.
But when i give the parameter, it throws the following exception:
org.springframework.beans.ConversionNotSupportedException: Failed to convert value of type 'java.lang.String' to required type 'java.util.Optional'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [java.util.Optional]: no matching editors or conversion strategy found
at org.springframework.beans.TypeConverterSupport.doConvert(TypeConverterSupport.java:74)
at org.springframework.beans.TypeConverterSupport.convertIfNecessary(TypeConverterSupport.java:47)
at org.springframework.validation.DataBinder.convertIfNecessary(DataBinder.java:603)
at org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:104)
at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:77)
at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:162)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:129)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
I have spent quite a time debugging this but could't get past this error. Any help is appreciated.
Thanks,
Just add "mvc:annotation-driven/> to your xml file to make it work.

#Value annotation for reading Map from property file

My Java has this
#Value("#{${validators}}")
private Map<String,String> validators;
property file has this
validators={AlphabetValidator:'AlphabetValidator',NumberValidator:'NumberValidator'AlphaNumericValidator:'AlphaNumericValidator',DateValidator:'DateValidator', FixedLengthValidator:'FixedLengthValidator',MinimumLengthValidator:'MinimumLengthValidator',MaximumLengthValidator:'MaximumLengthValidator',CustomValidator:'CustomValidator' MandatoryFieldValidator: 'MandatoryFieldValidator',TimeValidator:'TimeValidator'}
when I run the app.. I am getting this error
Exception in thread "main"
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'validatorProperties': Unsatisfied
dependency expressed through field 'validators'; nested exception is
org.springframework.beans.factory.BeanExpressionException: Expression
parsing failed; nested exception is
org.springframework.expression.spel.SpelParseException: EL1041E:(pos
1): After parsing a valid expression, there is still more data in the
expression: 'lcurly({)'
Check out for comma ',' in property file.
Properties file:
validators={AlphabetValidator:'AlphabetValidator',NumberValidator:'NumberValidator',AlphaNumericValidator:'AlphaNumericValidator',DateValidator:'DateValidator',FixedLengthValidator:'FixedLengthValidator',MinimumLengthValidator:'MinimumLengthValidator',MaximumLengthValidator:'MaximumLengthValidator',CustomValidator:'CustomValidator',MandatoryFieldValidator:'MandatoryFieldValidator',TimeValidator:'TimeValidator'}
Java code:
#Value("#{${validators}}")
private Map<String,String> validators;
You have missed to specify some commas inside your properties. Try with following:
validators={AlphabetValidator:'AlphabetValidator',NumberValidator:'NumberValidator',AlphaNumericValidator:'AlphaNumericValidator',DateValidator:'DateValidator',FixedLengthValidator:'FixedLengthValidator',MinimumLengthValidator:'MinimumLengthValidator',MaximumLengthValidator:'MaximumLengthValidator',CustomValidator:'CustomValidator',MandatoryFieldValidator:'MandatoryFieldValidator',TimeValidator:'TimeValidator'}

ConverterNotFoundException: -Dserver.port=80-noverify No converter found ... String to Integer

I'm starting my Spring Boot application from Eclipse with this VM parameter
-Dserver.port=80
application.yml
server:
port: 8080
but I get the following exception "No converter found capable of converting from type [java.lang.String] to type [java.lang.Integer]".
Running with Spring Boot v1.5.4.RELEASE, Spring v4.3.9.RELEASE
...
2017-07-19 11:26:55.299 ERROR 5968 --- [ main] o.s.b.b.PropertiesConfigurationFactory : Properties configuration failed validation
2017-07-19 11:26:55.299 ERROR 5968 --- [ main] o.s.b.b.PropertiesConfigurationFactory : Field error in object 'server' on field 'port': rejected value [80-noverify]; codes [typeMismatch.server.port,typeMismatch.port,typeMismatch.java.lang.Integer,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [server.port,port]; arguments []; default message [port]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.lang.Integer' for property 'port'; nested exception is org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.lang.String] to type [java.lang.Integer]]
Field error in object 'server' on field 'port': rejected value [80-noverify]; codes [typeMismatch.server.port,typeMismatch.port,typeMismatch.java.lang.Integer,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [server.port,port]; arguments []; default message [port]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.lang.Integer' for property 'port'; nested exception is org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.lang.String] to type [java.lang.Integer]]
...
***************************
APPLICATION FAILED TO START
***************************
Description:
Binding to target org.springframework.boot.autoconfigure.web.ServerProperties#caaddaea failed:
Property: server.port
Value: 80-noverify
Reason: Failed to convert property value of type 'java.lang.String' to required type 'java.lang.Integer' for property 'port'; nested exception is org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.lang.String] to type [java.lang.Integer]
Action:
Update your application's configuration
If I use the property server.port in my application.yml it works, no problem.
What am I doing wrong? Thanks for any help.
The issue is caused by the spring boot run configuration: In the run configuration, just disable "Fast startup" and the problem will go away. This option causes -noverify to be added as a VM argument, but, unfortunately, with no spaces.

Spring Batch - "job" scoped beans can not be injected into "job" or "step" scoped beans

I am using spring batch version 3.0.2.RELEASE and spring framework version 3.2.12.RELEASE. And I am trying to inject a job scoped bean to another job scoped bean.
My configuration looks like this
<bean id="beanA" class="com.trial.BeanA" scope="job" >
<property name="beanB" ref="beanB" />
</bean>
<bean id="beanB" class="com.trial.BeanB" scope="job"/>
It throws an exception with details:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.beanA' defined in class path resource [trial-context.xml]: Initialization of bean failed; nested exception is org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'com.sun.proxy.$Proxy1 implementing com.trial.BeanB,org.springframework.beans.factory.InitializingBean,org.springframework.aop.scope.ScopedObject,java.io.Serializable,org.springframework.aop.framework.AopInfrastructureBean,org.springframework.aop.SpringProxy,org.springframework.aop.framework.Advised' to required type 'com.trial.BeanB' for property 'beanB'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [com.sun.proxy.$Proxy1 implementing com.trial.BeanB,org.springframework.beans.factory.InitializingBean,org.springframework.aop.scope.ScopedObject,java.io.Serializable,org.springframework.aop.framework.AopInfrastructureBean,org.springframework.aop.SpringProxy,org.springframework.aop.framework.Advised] to required type [com.trial.BeanB] for property 'beanB': no matching editors or conversion strategy found
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:529)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at org.springframework.beans.factory.support.AbstractBeanFactory$2.getObject(AbstractBeanFactory.java:331)
at org.springframework.batch.core.scope.JobScope.get(JobScope.java:103)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:327)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:191)
at org.springframework.aop.target.SimpleBeanTargetSource.getTarget(SimpleBeanTargetSource.java:34)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:184)
at com.sun.proxy.$Proxy13.getValue(Unknown Source)
at org.springframework.batch.core.listener.CompositeJobExecutionListener.beforeJob(CompositeJobExecutionListener.java:73)
at org.springframework.batch.core.job.AbstractJob.execute(AbstractJob.java:301)
at org.springframework.batch.core.launch.support.SimpleJobLauncher$1.run(SimpleJobLauncher.java:135)
at org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:49)
at org.springframework.batch.core.launch.support.SimpleJobLauncher.run(SimpleJobLauncher.java:128)
Caused by: org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'com.sun.proxy.$Proxy1 implementing com.trial.BeanB,org.springframework.beans.factory.InitializingBean,org.springframework.aop.scope.ScopedObject,java.io.Serializable,org.springframework.aop.framework.AopInfrastructureBean,org.springframework.aop.SpringProxy,org.springframework.aop.framework.Advised' to required type 'com.trial.BeanB' for property 'beanB'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [com.sun.proxy.$Proxy1 implementing com.trial.BeanB,org.springframework.beans.factory.InitializingBean,org.springframework.aop.scope.ScopedObject,java.io.Serializable,org.springframework.aop.framework.AopInfrastructureBean,org.springframework.aop.SpringProxy,org.springframework.aop.framework.Advised] to required type [com.trial.BeanB] for property 'beanB': no matching editors or conversion strategy found
at org.springframework.beans.BeanWrapperImpl.convertIfNecessary(BeanWrapperImpl.java:464)
at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:495)
at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:489)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.convertForProperty(AbstractAutowireCapableBeanFactory.java:1465)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1424)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1160)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
... 18 more
Caused by: java.lang.IllegalStateException: Cannot convert value of type [com.sun.proxy.$Proxy1 implementing com.trial.BeanB,org.springframework.beans.factory.InitializingBean,org.springframework.aop.scope.ScopedObject,java.io.Serializable,org.springframework.aop.framework.AopInfrastructureBean,org.springframework.aop.SpringProxy,org.springframework.aop.framework.Advised] to required type [com.trial.BeanB] for property 'beanB': no matching editors or conversion strategy found
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:267)
at org.springframework.beans.BeanWrapperImpl.convertIfNecessary(BeanWrapperImpl.java:449)
... 24 more
Even I try to inject a "job" scoped bean to a "step" scoped bean, it fails and throws a similar exception.
How can I solve the issue?
You are using java proxying which requires interfaces, yet your BeanB doesn't implement an interface that BeanA is coded against. You need to either switch to dynamic subclassing or have BeanB implement an interface and have BeanA expect that interface.

Resources