java.lang.Exception: HV000041: Call to TraversableResolver.isReachable() threw an exception - validation

We are getting the below mentioned error on websphere 8.5
2020-01-07 15:19:37 [] DEBUG InvocableHandlerMethod.java.getMethodArgumentValues:174:
Could not resolve parameter [1] in public org.springframework.http.ResponseEntity
com.mycorp.uap.controller.WorkFlowController.updateTask(int,com.mycorp.uap.rest.vo.TaskVO)
throws java.lang.Exception: HV000041: Call to TraversableResolver.isReachable() threw an exception.
Method is defined as
public ResponseEntity<TaskVO> updateTask(#PathVariable("id") int taskId, #Valid #RequestBody(required=true) TaskVO task) throws Exception{
WEB-INF/lib contains the below jars related to hibernate, validation and spring
hibernate-commons-annotations-5.1.0.Final.jar
hibernate-core-5.4.4.Final.jar
hibernate-ehcache-5.4.4.Final.jar
hibernate-jpa-2.1-api-1.0.2.jar
hibernate-validator-6.0.15.Final.jar
validation-api-2.0.1.Final.jar
spring-aop-5.1.9.RELEASE.jar
spring-beans-5.1.9.RELEASE.jar
spring-context-5.1.9.RELEASE.jar
spring-context-support-5.1.9.RELEASE.jar
spring-core-5.1.9.RELEASE.jar
spring-data-commons-2.1.9.RELEASE.jar
spring-data-jpa-2.1.9.RELEASE.jar
spring-expression-5.1.9.RELEASE.jar
springfox-core-2.1.2.jar
springfox-schema-2.1.2.jar
springfox-spi-2.1.2.jar
springfox-spring-web-2.1.2.jar
springfox-swagger2-2.1.2.jar
springfox-swagger-common-2.1.2.jar
springfox-swagger-ui-2.1.2.jar
spring-hateoas-0.17.0.RELEASE.jar
spring-jcl-5.1.9.RELEASE.jar
spring-jdbc-5.1.9.RELEASE.jar
spring-ldap-core-2.3.2.RELEASE.jar
spring-messaging-5.1.9.RELEASE.jar
spring-orm-5.1.9.RELEASE.jar
spring-plugin-core-1.2.0.RELEASE.jar
spring-plugin-metadata-1.2.0.RELEASE.jar
spring-security-acl-5.1.6.RELEASE.jar
spring-security-cas-client.jar
spring-security-config-5.1.6.RELEASE.jar
spring-security-core-5.1.6.RELEASE.jar
spring-security-ldap-5.1.6.RELEASE.jar
spring-security-oauth2-2.3.6.RELEASE.jar
spring-security-openid-5.1.6.RELEASE.jar
spring-security-taglibs-5.1.6.RELEASE.jar
spring-security-web-5.1.6.RELEASE.jar
spring-test-5.1.9.RELEASE.jar
spring-tx-5.1.9.RELEASE.jar
spring-web-5.1.9.RELEASE.jar
spring-webmvc-5.1.9.RELEASE.jar
spring-websocket-5.1.9.RELEASE.jar
ParentLast setting is present in WebSphere configuration for our application so that WebSphere should give preference to the jars present in the WEB-INF/lib of our application
There is a similar method where #Valid is not present which works properly.
I looked into similar question on the stack overflow however could not quite get the correct solution.
What should be the correct solution?
Should we remove any jars from our WEB-INF/lib?

To fix this problem, you need to add the HibernatePersistenceProviderResolver class to your project:
HibernatePersistenceProviderResolver.java
and register it in the Application class in the onStartup method
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
HibernatePersistenceProviderResolver.register();
...
}
Reference

Related

Spring Boot #RequestScope and Hibernate schema based multi-tenancy

I'm working on a schema based multi-tenant app, in which I want to resolve the Tenant Identifier using a #RequestScope bean. My understanding is that #RequestScope uses/injects proxies for the request scoped beans, wherever they are referred (e.g. in other singleton beans). However, this is not working in the #Component that implements CurrentTenantIdentifierResolver and I get the following error when I start my service,
Caused by: org.springframework.beans.factory.support.ScopeNotActiveException: Error creating bean with name 'scopedTarget.userContext': Scope 'request' is not active for the current thread;
Caused by: java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
Following are the relevant pieces of code.
#Component
public class CurrentTenant implements CurrentTenantIdentifierResolver {
#Autowired
private UserContext userContext;
#Override
public String resolveCurrentTenantIdentifier() {
return Optional.of(userContext)
.map(u -> u.getDomain())
.get();
}
#Component
#RequestScope
public class UserContext {
private UUID id;
private String domain;
My questions,
Isn't the proxy for the #RequestScope injected (by default)? Do I need to do anything more?
Is Hibernate/Spring trying to establish a connection to the DB at startup (even when there is no tenant available)?
Hibernate properties:
HashMap<String, Object> properties = new HashMap<>();
properties.put("hibernate.dialect", env.getProperty("hibernate.dialect"));
properties.remove(AvailableSettings.DEFAULT_SCHEMA);
properties.put(AvailableSettings.MULTI_TENANT, MultiTenancyStrategy.SCHEMA);
properties.put(AvailableSettings.MULTI_TENANT_IDENTIFIER_RESOLVER, tenantResolver);
properties.put(AvailableSettings.MULTI_TENANT_CONNECTION_PROVIDER, connectionProvider);
For the time being, I'm preventing the NullPointerException by checking if we are in the RequestContext. However, a connection still gets established to the master database (although I've explicitly specified the dialect and am not specifying hbm2ddl.auto). Since this connection is not associated with any schema, I'd like to avoid making it, so that it does not look for any tables that it won't find anyways.
What seems to be happenning is that when a HTTP request is received, hibernate is trying to resolve the current tenant identifier, even before my #RequestScope bean is created (and even before my #RestController method is called.) If a provide the default connection to the databse, I then get the following error. If I don't provide a connection, it throws an exception and aborts.
2021-09-26 11:55:44.882 WARN 19759 --- [nio-8082-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: 42P01
2021-09-26 11:55:44.882 ERROR 19759 --- [nio-8082-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : ERROR: relation "employees" does not exist
Position: 301
2021-09-26 11:55:44.884 ERROR 19759 --- [nio-8082-exec-2] o.t.n.controller.EmployeeController : Exception: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet

Spring Security OAuth2 v5 : NoSuchBeanDefinitionException: 'org.springframework.security.oauth2.jwt.JwtDecoder'

I have a SpringBoot application that I am trying to update from the older Spring Security OAuth 2.x library to the newer Spring Security 5.5.x. Initially my configuration class was using the #EnableResourceServer annotation, but this was replaced with the Spring Security oauth2ResourceServer DSL method, as per the migration guide.
I have added in a custom JWT authentication converter, but am now getting the following warning on startup:
09:30:51.591 [, , ] [main] WARN %->5level org.springframework.web.context.support.AnnotationConfigWebApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.security.oauth2.jwt.JwtDecoder' available
I can't see where this JwtDecoder is used in the filter chain yet, but it's stopping my application from starting up.
#Configuration
#Order(OAuthTokenApiSecurityConfig.ORDER)
public class OAuthTokenApiSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
public void configure(final HttpSecurity http) throws Exception { // NOPMD
// #formatter:off
http
.requestMatcher(new OAuth2RequestMatcher())
...
...
.oauth2ResourceServer()
.jwt()
.jwtAuthenticationConverter(customTokenAuthenticationConverter());
// #formatter:on
}
#Bean
public CustomTokenAuthenticationConverter customTokenAuthenticationConverter() {
return new CustomTokenAuthenticationConverter();
}
#Bean
public JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter() {
return new JwtGrantedAuthoritiesConverter();
}
}
dependecies {
api("org.springframework.security:spring-security-oauth2-resource-server")
api("org.springframework.security:spring-security-oauth2-core")
api("org.springframework.security:spring-security-oauth2-jose")
api("com.nimbusds:nimbus-jose-jwt")
}
springBootVersion=2.5.3
springSecurity=5.5.1
Is there some dependency that I am missing, or is there some config or something else?
The JwtDecoder is used within the Jwt Configuration to decode, and validate the incoming token against the public keys.
There's multiple ways of building the bean provided via some factory methods in the JwtDecoders class.
Specifically,
JwtDecoders.fromIssuerUri(...) and JwtDecoders.fromOidcIssuerUri(...) and I believe theres now a third method for pointing directly at a key.
The decoder it self can be explicitly set on the decoder method on the jwt configuration if you want/need to build one manually e.g. want to more add validations to the JwtDecoder.
If you read the javadoc of the OAuth2ResourceServerConfigurer there's also the option to set the Jwk Set URI via the jwkSetUri method which would also build a decoder.
The exact point the JwtDecoder is used is within the JwtAuthenticationProvider which will eventually be called from the BearerTokenAuthenticationFilter

Embedded Tomcat with Spring throws IllegalAccessError: <proxy> cannot access its superinterface <class>

I have an application that works just fine as war in tomcat. Now I would like to start it from Embedded Tomcat using such code:
public static void main(String[] args) throws Exception {
Tomcat tomcat = new Tomcat();
tomcat.enableNaming();
StandardContext ctx =
(StandardContext) tomcat.addWebapp("/myapp", new File("src/main/webapp/").getAbsolutePath());
StandardJarScanner jarScanner = (StandardJarScanner) ctx.getJarScanner();
jarScanner.setScanClassPath(false);
jarScanner.setScanAllDirectories(false);
jarScanner.setScanBootstrapClassPath(false);
tomcat.start();
tomcat.getServer().await();
}
Application seams to be starting but after loading of few Spring Services it gets such Exception
Caused by: java.lang.IllegalAccessError: class de.abc.service.intern.$Proxy213 cannot access its superinterface de.abc.service.intern.PageMetadataStorage
at java.lang.reflect.Proxy.defineClass0(Native Method)
at java.lang.reflect.Proxy.access$300(Proxy.java:228)
at java.lang.reflect.Proxy$ProxyClassFactory.apply(Proxy.java:642)
at java.lang.reflect.Proxy$ProxyClassFactory.apply(Proxy.java:557)
at java.lang.reflect.WeakCache$Factory.get(WeakCache.java:230)
at java.lang.reflect.WeakCache.get(WeakCache.java:127)
at java.lang.reflect.Proxy.getProxyClass0(Proxy.java:419)
at java.lang.reflect.Proxy.newProxyInstance(Proxy.java:719)
at org.springframework.aop.framework.JdkDynamicAopProxy.getProxy(JdkDynamicAopProxy.java:122)
at org.springframework.aop.framework.ProxyFactory.getProxy(ProxyFactory.java:109)
Looks like $Proxy213 got loaded by bootstrap class loader and cannot access class from web app. And problematic interface is package protected.
Could some one explain what is happening here? Could I solve it somehow?

Spring Java config exception

I am trying to switch from xml config to java config and getting the following exception when starting the application.
Caused by: java.lang.ClassCastException: $Proxy188 cannot be cast to org.springframework.format.support.FormattingConversionService
This exception is thrown on the first line of the following method:
#Override
public RequestMappingHandlerAdapter requestMappingHandlerAdapter() {
RequestMappingHandlerAdapter adapter = super.requestMappingHandlerAdapter();
adapter.setIgnoreDefaultModelOnRedirect(true);
return adapter;
}
Any idea why this is failing?

Loading Resources with the Context Loader fails with a NullPointerException

I'm just wondering why I cannot load a resource with the Thread context loader in Felix OSGi? Am I not supposed to touch the context loader, am I doing something wrong or is it a bug?
I've a super simple bundle with a simple Activator:
public class Activator implements BundleActivator {
public void start(BundleContext context) throws Exception {
System.out.println("Hello World!!");
String resourcePath = "META-INF/mySuperDuperResource.txt";
// works
System.out.println(Activator.class.getClassLoader().getResource(resourcePath));
// null-pointer exception
System.out.println(Thread.currentThread().getContextClassLoader().getResource(resourcePath));
}
public void stop(BundleContext context) throws Exception {
System.out.println("Goodbye World!!");
}
}
Now loading the resource with with the class loader with the Activator.class.getClassLoader works. But not with the Thread.currentThread().getContextClassLoader(). There I get:
ERROR: Bundle info.gamlor.osgi [26] Unable to get module class path. (java.lang.NullPointerException)
java.lang.NullPointerException
at org.apache.felix.framework.BundleRevisionImpl.calculateContentPath(BundleRevisionImpl.java:410)
at org.apache.felix.framework.BundleRevisionImpl.initializeContentPath(BundleRevisionImpl.java:347)
at org.apache.felix.framework.BundleRevisionImpl.getContentPath(BundleRevisionImpl.java:333)
at org.apache.felix.framework.BundleRevisionImpl.getResourceLocal(BundleRevisionImpl.java:472)
at org.apache.felix.framework.BundleWiringImpl.findClassOrResourceByDelegation(BundleWiringImpl.java:1432)
at org.apache.felix.framework.BundleWiringImpl.getResourceByDelegation(BundleWiringImpl.java:1360)
at org.apache.felix.framework.BundleWiringImpl$BundleClassLoader.getResource(BundleWiringImpl.java:2256)
at info.gamlor.osgi.Activator.start(Activator.java:23)
at org.apache.felix.framework.util.SecureAction.startActivator(SecureAction.java:641)
at org.apache.felix.framework.Felix.activateBundle(Felix.java:1977)
at org.apache.felix.framework.Felix.startBundle(Felix.java:1895)
at org.apache.felix.framework.BundleImpl.start(BundleImpl.java:944)
...
org.osgi.framework.BundleException: Activator start error in bundle info.gamlor.osgi [29].
at org.apache.felix.framework.Felix.activateBundle(Felix.java:2027)
at org.apache.felix.framework.Felix.startBundle(Felix.java:1895)
at org.apache.felix.framework.BundleImpl.start(BundleImpl.java:944)
at org.apache.felix.gogo.command.Basic.start(Basic.java:729)
...
Caused by: java.lang.NullPointerException
at org.apache.felix.framework.BundleRevisionImpl.getResourceLocal(BundleRevisionImpl.java:474)
at org.apache.felix.framework.BundleWiringImpl.findClassOrResourceByDelegation(BundleWiringImpl.java:1432)
at org.apache.felix.framework.BundleWiringImpl.getResourceByDelegation(BundleWiringImpl.java:1360)
at org.apache.felix.framework.BundleWiringImpl$BundleClassLoader.getResource(BundleWiringImpl.java:2256)
at info.gamlor.osgi.Activator.start(Activator.java:23)
at org.apache.felix.framework.util.SecureAction.startActivator(SecureAction.java:641)
at org.apache.felix.framework.Felix.activateBundle(Felix.java:1977)
... 32 more
Now when just set the thread context class loader it works just fine:
Thread.currentThread().setContextClassLoader(Activator.class.getClassLoader());
But that has a hacky feeling to it. Feels like that will bite me later.
I'm not sure why your surprised this happens. A thread's context classloader is, by default, set to the classloader of it's parent, which in the beginning is set to the system classloader. So, assuming you don't do anything special, the context classloader is the system classloader, which is not the same as your bundle's classloader, hence it can't find your resource.
I agree that setting the context classloader has a hacky feel to it, but some libraries require this. I would do something like,
ClassLoader previous = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
badlyBehavedLibraryCall();
Thread.currentThread().setContextClassLoader(previous);

Resources