#StackBounty: #mysql #hibernate #spring-boot #hikaricp #spring-repositories HikariCP not releasing active MySql connections

Bounty: 50

I have recently updated from JDK 8 to JDK 11 and in the process updated the app Hikari dependency to ‘com.zaxxer:HikariCP:3.3.1’ and I am using springBootVersion = ‘2.1.3.RELEASE’. The app has 2 data sources, 1 postgres and 1 MySql. Postgres is fine but MySql is not. As the Pool expires connections and adds new connections the active connections are created and never released, from the hikari perspective. When querying the DB it only shows the 5 idle connections that I expect to see. This continues until I reach the max pool size and then the app starts to sporadically fail to connect.
Has anyone seen anything like this and/or does anyone know something that could help me get to the bottom of this?

The limited logs I could get for this issue:

mysql-17 - After cleanup stats (total=12, active=7, idle=5, waiting=0)
mysql-17 - Before cleanup stats (total=12, active=7, idle=5, waiting=0)
at com.mysql.cj.protocol.a.NativeProtocol.readMessage(NativeProtocol.java:562)
... 89 more
at com.mysql.cj.jdbc.StatementImpl.executeQuery(StatementImpl.java:1186)
at batch.processor.Processor.processRequest(Processor.java:50)
at batch.processor.Processor.checkinStaleAssignedTransaction(Processor.java:76)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:153)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:527)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:275)
SQL Error: 0, SQLState: 08S01
mysql-17 - After cleanup stats (total=11, active=6, idle=5, waiting=0)
mysql-17 - Before cleanup stats (total=11, active=6, idle=5, waiting=0)
at java.base/sun.security.ssl.Alert.createSSLException(Alert.java:117)
at java.base/sun.security.ssl.Alert.createSSLException(Alert.java:133)
javax.net.ssl.SSLException: closing inbound before receiving peer's close_notify
STACKTRACE:
MESSAGE: closing inbound before receiving peer's close_notify
javax.net.ssl.SSLException
** BEGIN NESTED EXCEPTION **
EXCEPTION STACK TRACE:
Thu Jul 25 14:52:55 UTC 2019 WARN: Caught while disconnecting...
mysql-17 - Closing connection com.mysql.cj.jdbc.ConnectionImpl@79447870: (

The MySql Config is:

# MySql Properties
mysql.datasource.type=com.zaxxer.hikari.HikariDataSource
mysql.datasource.jdbcUrl=${DB_URL}
mysql.datasource.username=${SECRET_DB_USERNAME}
mysql.datasource.password=${SECRET_DB_PASSWORD}
mysql.datasource.driver-class-name=com.mysql.jdbc.Driver

mysql.datasource.connection-timeout=7000
mysql.datasource.maximum-pool-size=30
mysql.datasource.minimum-idle=5
mysql.datasource.idle-timeout=300000
mysql.datasource.max-lifetime=600000
mysql.datasource.connection-test-query=SELECT 1
mysql.datasource.leak-detection-threshold=3000
mysql.datasource.pool-name=mysql-${node.id}

mysql.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect

The MySql Spring Java config is:

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "mySqlEntityManagerFactory", transactionManagerRef = "mySqlTransactionManager", basePackages = {"mysql.dao", "models"})
public class MySqlConfiguration {
    @Value("${mysql.jpa.properties.hibernate.dialect}")
    private String dialect;

    @Primary
    @Bean(name = "mySqlTransactionManager")
    public PlatformTransactionManager mySqlTransactionManager() {
        return new JpaTransactionManager(mySqlEntityManagerFactory().getObject());
    }

    @Primary
    @Bean(name = {
        "entityManagerFactory", "mySqlEntityManagerFactory"
    })
    public LocalContainerEntityManagerFactoryBean mySqlEntityManagerFactory() {
        LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        Properties props = new Properties();
        props.put("hibernate.dialect", dialect);

        factoryBean.setPersistenceUnitName("mysql");
        factoryBean.setJpaProperties(props);
        factoryBean.setDataSource(mysqlDataSource());
        factoryBean.setJpaVendorAdapter(vendorAdapter);
        factoryBean.setPackagesToScan("models", "mysql.entity");

        return factoryBean;
    }

    @Primary
    @Bean(name = "mysqlDataSource")
    @ConfigurationProperties(prefix = "mysql.datasource")
    public DataSource mysqlDataSource() {
        return DataSourceBuilder.create().type(HikariDataSource.class).build();
    }
}

**** EDIT ****
Some additional logging that may help:

org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection; nested exception is com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure

The last packet successfully received from the server was 417 milliseconds ago.  The last packet sent successfully to the server was 417 milliseconds ago.
    at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:81)
    at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:324)
    at org.springframework.boot.actuate.jdbc.DataSourceHealthIndicator.getProduct(DataSourceHealthIndicator.java:122)
    at org.springframework.boot.actuate.jdbc.DataSourceHealthIndicator.doDataSourceHealthCheck(DataSourceHealthIndicator.java:109)
    at org.springframework.boot.actuate.jdbc.DataSourceHealthIndicator.doHealthCheck(DataSourceHealthIndicator.java:104)
    at org.springframework.boot.actuate.health.AbstractHealthIndicator.health(AbstractHealthIndicator.java:84)
    at org.springframework.boot.actuate.health.CompositeHealthIndicator.health(CompositeHealthIndicator.java:98)
    at org.springframework.boot.actuate.health.CompositeHealthIndicator.health(CompositeHealthIndicator.java:98)
    at org.springframework.boot.actuate.health.HealthEndpoint.health(HealthEndpoint.java:50)
    at org.springframework.boot.actuate.health.HealthEndpointWebExtension.health(HealthEndpointWebExtension.java:54)
    at jdk.internal.reflect.GeneratedMethodAccessor206.invoke(Unknown Source)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at org.springframework.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:246)
    at org.springframework.boot.actuate.endpoint.invoke.reflect.ReflectiveOperationInvoker.invoke(ReflectiveOperationInvoker.java:76)
    at org.springframework.boot.actuate.endpoint.annotation.AbstractDiscoveredOperation.invoke(AbstractDiscoveredOperation.java:61)
    at org.springframework.boot.actuate.endpoint.web.servlet.AbstractWebMvcEndpointHandlerMapping$ServletWebOperationAdapter.handle(AbstractWebMvcEndpointHandlerMapping.java:294)
    at org.springframework.boot.actuate.endpoint.web.servlet.AbstractWebMvcEndpointHandlerMapping$OperationHandler.handle(AbstractWebMvcEndpointHandlerMapping.java:355)
    at jdk.internal.reflect.GeneratedMethodAccessor205.invoke(Unknown Source)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:189)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:645)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:750)
    at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:867)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1623)
    at org.eclipse.jetty.websocket.server.WebSocketUpgradeFilter.doFilter(WebSocketUpgradeFilter.java:214)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1610)
    at org.springframework.boot.actuate.web.trace.servlet.HttpTraceFilter.doFilterInternal(HttpTraceFilter.java:90)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1610)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:209)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1610)
    at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.filterAndRecordMetrics(WebMvcMetricsFilter.java:117)
    at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:106)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1610)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1610)
    at tracing.shadow.io.opentracing.contrib.web.servlet.filter.TracingFilter.doFilter(TracingFilter.java:140)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1610)
    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:540)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:146)
    at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:548)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:132)
    at org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:257)
    at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:1588)
    at org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:255)
    at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1345)
    at org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:203)
    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:480)
    at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:1557)
    at org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:201)
    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1247)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:144)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:132)
    at org.eclipse.jetty.server.Server.handle(Server.java:502)
    at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:364)
    at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:260)
    at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:305)
    at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:103)
    at org.eclipse.jetty.io.ChannelEndPoint$2.run(ChannelEndPoint.java:118)
    at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.runTask(EatWhatYouKill.java:333)
    at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.doProduce(EatWhatYouKill.java:310)
    at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.tryProduce(EatWhatYouKill.java:168)
    at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.run(EatWhatYouKill.java:126)
    at org.eclipse.jetty.util.thread.ReservedThreadExecutor$ReservedThread.run(ReservedThreadExecutor.java:366)
    at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:765)
    at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:683)
    at java.base/java.lang.Thread.run(Thread.java:835)
Caused by: com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure

The last packet successfully received from the server was 417 milliseconds ago.  The last packet sent successfully to the server was 417 milliseconds ago.
    at com.mysql.cj.jdbc.exceptions.SQLError.createCommunicationsException(SQLError.java:174)
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:64)
    at com.mysql.cj.jdbc.StatementImpl.executeQuery(StatementImpl.java:1218)
    at com.mysql.cj.jdbc.DatabaseMetaData.getUserName(DatabaseMetaData.java:4036)
    at tracing.shadow.io.opentracing.contrib.spring.cloud.jdbc.JdbcAspect.getConnection(JdbcAspect.java:44)
    at jdk.internal.reflect.GeneratedMethodAccessor201.invoke(Unknown Source)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:644)
    at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:633)
    at org.springframework.aop.aspectj.AspectJAroundAdvice.invoke(AspectJAroundAdvice.java:70)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:175)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:93)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688)
    at com.zaxxer.hikari.HikariDataSource$$EnhancerBySpringCGLIB$$8dfc4e21.getConnection(<generated>)
    at org.springframework.jdbc.datasource.DataSourceUtils.fetchConnection(DataSourceUtils.java:157)
    at org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:115)
    at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:78)
    ... 83 common frames omitted
Caused by: com.mysql.cj.exceptions.CJCommunicationsException: Communications link failure

The last packet successfully received from the server was 417 milliseconds ago.  The last packet sent successfully to the server was 417 milliseconds ago.
    at jdk.internal.reflect.GeneratedConstructorAccessor201.newInstance(Unknown Source)
    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500)
    at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:481)
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:61)
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:105)
    at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:151)
    at com.mysql.cj.exceptions.ExceptionFactory.createCommunicationsException(ExceptionFactory.java:167)
    at com.mysql.cj.protocol.a.NativeProtocol.readMessage(NativeProtocol.java:562)
    at com.mysql.cj.protocol.a.NativeProtocol.checkErrorMessage(NativeProtocol.java:732)
    at com.mysql.cj.protocol.a.NativeProtocol.sendCommand(NativeProtocol.java:671)
    at com.mysql.cj.protocol.a.NativeProtocol.sendQueryPacket(NativeProtocol.java:986)
    at com.mysql.cj.protocol.a.NativeProtocol.sendQueryString(NativeProtocol.java:921)
    at com.mysql.cj.NativeSession.execSQL(NativeSession.java:1154)
    at com.mysql.cj.jdbc.StatementImpl.executeQuery(StatementImpl.java:1186)
    ... 99 common frames omitted
Caused by: java.io.EOFException: Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpectedly lost.
    at com.mysql.cj.protocol.FullReadInputStream.readFully(FullReadInputStream.java:67)
    at com.mysql.cj.protocol.a.SimplePacketReader.readHeader(SimplePacketReader.java:63)
    at com.mysql.cj.protocol.a.SimplePacketReader.readHeader(SimplePacketReader.java:45)
    at com.mysql.cj.protocol.a.TimeTrackingPacketReader.readHeader(TimeTrackingPacketReader.java:52)
    at com.mysql.cj.protocol.a.TimeTrackingPacketReader.readHeader(TimeTrackingPacketReader.java:41)
    at com.mysql.cj.protocol.a.MultiPacketReader.readHeader(MultiPacketReader.java:54)
    at com.mysql.cj.protocol.a.MultiPacketReader.readHeader(MultiPacketReader.java:44)
    at com.mysql.cj.protocol.a.NativeProtocol.readMessage(NativeProtocol.java:556)
    ... 105 common frames omitted


Get this bounty!!!

#StackBounty: #spring #spring-boot #docker #oauth-2.0 #keycloak Keycloak and Spring Boot web app in dockerized environment

Bounty: 100

Consider the following environment:

  • one docker container is keycloak
  • another docker container is our web app that uses keycloak for authentication

The web app is a Spring Boot application with “keycloak-spring-boot-starter” applied. In application.properties:

keycloak.auth-server-url = http://localhost:8028/auth

A user accessing our web app will be redirected to keycloak using the URL for the exposed port of the keycloak docker container. Login is done without problems in keycloak and the user (browser) is redirected to our web app again. Now, the authorization code needs to be exchanged for an access token. Hence, our web app (keycloak client) tries to connect to the same host and port configured in keycloak.auth-server-url. But this is a problem because the web app resides in a docker container and not on the host machine, so it should rather access http://keycloak:8080 or something where keycloak is the linked keycloak docker container.

So the question is: How can I configure the keycloak client to apply different URLs for browser redirection and access token endpoints?


Get this bounty!!!

#StackBounty: #java #spring-boot #jasper-reports #multilingual #export-to-pdf jasper report Multi language- cannot display font while g…

Bounty: 50

I’m generating a multi-language report using JasperReports in Java.

When I generate pdf, few languages do not display properly.

enter image description here

Whereas, When I generate Excel, The report is generated properly with the correct language.

enter image description here

searching on the internet I found pdf font is not supported.

here my code set to font:

 Style rowStyle = new Style();
 Font font = new Font(FONT_SIZE_SMALL, "Noto Sans", false, false, false);
 font.setPdfFontName("Noto Sans");
 font.setPdfFontEncoding(Font.PDF_ENCODING_Identity_H_Unicode_with_horizontal_writing);
 font.setPdfFontEmbedded(false);
 rowStyle.setFont(font);

any idea how to solve?


Get this bounty!!!

#StackBounty: #java #spring #spring-boot #redis #spring-data-redis Redis: Set different time to live for methods annotated with @Cachea…

Bounty: 200

I have a set of cached methods that look somewhat like this:

@Cacheable(value = "myCacheName", keyGenerator = "myKeyGenerator")
public Product getProduct(ProductRequest request) {
    // ...
}

And I need to set different time to live (expiration interval) for objects returned by these methods.

Problem: According to the documentation, the offered way is using @RedisHash(timeToLive=…​) or @TimeToLive annotations on the return type of the methods. However, I don’t want to pollute my domain classes with caching related logic. In addition, some of my methods return strings or objects of classes which I can not modify. I would prefer to implement it in a more configurable way. There is also a configuration property called spring.cache.redis.time-to-live, but it applies the same time-to-live in all places.

Question: Is there a way to specify time to live/expiration interval on the method level? Or generally, how to implement it in a more elegant way?


Get this bounty!!!

#StackBounty: #java #spring #mongodb #spring-boot #tomcat8.5 Spring boot + tomcat 8.5 + mongoDB, AsyncRequestTimeoutException

Bounty: 50

I have created a spring boot web application and deployed war of the same to tomcat container.
The application connects to mongoDB using Async connections. I am using mongodb-driver-async library for that.

At startup everything works fine. But as soon as load increases, It shows following exception in DB connections:

org.springframework.web.context.request.async.AsyncRequestTimeoutException: null
        at org.springframework.web.context.request.async.TimeoutDeferredResultProcessingInterceptor.handleTimeout(TimeoutDeferredResultProcessingInterceptor.java:42)
        at org.springframework.web.context.request.async.DeferredResultInterceptorChain.triggerAfterTimeout(DeferredResultInterceptorChain.java:75)
        at org.springframework.web.context.request.async.WebAsyncManager$5.run(WebAsyncManager.java:392)
        at org.springframework.web.context.request.async.StandardServletAsyncWebRequest.onTimeout(StandardServletAsyncWebRequest.java:143)
        at org.apache.catalina.core.AsyncListenerWrapper.fireOnTimeout(AsyncListenerWrapper.java:44)
        at org.apache.catalina.core.AsyncContextImpl.timeout(AsyncContextImpl.java:131)
        at org.apache.catalina.connector.CoyoteAdapter.asyncDispatch(CoyoteAdapter.java:157)

I am using following versions of software:

  1. Spring boot -> 1.5.4.RELEASE
  2. Tomcat (installed as standalone binary) -> apache-tomcat-8.5.37
  3. Mongo DB version: v3.4.10
  4. mongodb-driver-async: 3.4.2

As soon as I restart the tomcat service, everything starts working fine.

Please help, what could be the root cause of this issue.

P.S.: I am using DeferredResult and CompletableFuture to create Async REST API.

I have also tried using spring.mvc.async.request-timeout in application and configured asynTimeout in tomcat. But still getting same error.


Get this bounty!!!

#StackBounty: #java #spring #spring-boot #spring-security Initialize repositories protected by Spring authentication

Bounty: 50

I use Spring Boot Data REST to map Hibernate repositories of entities to REST routes. I also use Spring Security’s @PreAuthorize annotation to secure certain methods of those repositories. This works fine during production, but when I want to programmatically initialize the repositories with data (e.g. adding a first user to get started and some other sample data), it complains that “An Authentication object was not found in the SecurityContext”. I realize that this is because there is no authenticated user in the security context at the time I configure the database (with an autowired component saving objects to repositories). However, I’d like to temporarily circumvent this authorization during configuration, so that I can initialize the database.

Is there any way to achieve this? And if not, how can I manually log in in the initialization method? I’ve seen some attempts to the second approach, but they all require access to an AuthenticationManager, which I don’t know how to obtain.


Get this bounty!!!

#StackBounty: #spring-boot #spring-security-oauth2 #spring-oauth2 #spring-security-rest How to validate facebook authorization token an…

Bounty: 50

I am developing an app whose frontend is written using React.js and the backend REST API is written using the Spring framework. I wanted to add social logins to my website, so after days of googling and research, I understood that OAuth2 is the solution. I came to know that the frontend should handle getting the authorization token from the Resource Server(Facebook here) and my backend(java) should validate that token and connect with Facebook to get an access token. Then that access token should be stored in my database along with the user details(e.g email).

Here is my requirement, once the user clicks on the “Continue with Facebook” button, my app should create there account in my own database using details – email and Name(the signup feature). And later whenever they click on this button again, they will be logged in not sign up. The way other websites handle it.

As of now, I have the button working in my app, which brings me the authorization token from Facebook.

Can someone please guide me the path I should follow here.

Also, any special attention to some error handling I should follow.


Get this bounty!!!

#StackBounty: #spring #spring-boot #spring-security #jwt #spring-security-oauth2 OAuth2 + Spring Boot 2 – ResourceServer in ZuulGateway…

Bounty: 50

I am trying OAuth 2 + JWT integration using Spring Boot 2 + Netflix OSS. On requesting access token, I am getting the below error in Zuul Gateway which acts as a Resource Server.

2019-05-04 14:41:29.157 DEBUG 23272 — [nio-8765-exec-2] o.s.s.w.a.ExceptionTranslationFilter : Authentication exception occurred; redirecting to authentication entry point
org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext

Can someone help and tell me what am I missing in the code ?

Zuul Gateway + Resource Server

@Configuration
@EnableResourceServer
@Order(value = 0)
@EnableOAuth2Sso
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
            .antMatchers("/oauth/token/**").permitAll()
            //.antMatchers("/login/**,/oauth/**").permitAll()
            .antMatchers("/trips/**").hasAnyRole("CLIENT", "USER", "ANONYMOUS")
            .and().csrf().disable()
            .anonymous().disable();

    }
}

application.yml

logging:
  level:
    org.springframework: DEBUG

server:
  port: 8765

spring:
  application:
    name: gateway


# Map path to auth service
zuul:
  routes:
    trips:
      path: /trips/**
      url: http://localhost:1000/api/trips
    rides:
      path: /rides/**
      url: http://localhost:1000/api/rides
    mauth:
      path: /oauth/**
      url: http://localhost:1000/oauth



#OAuth Configurations
security:
  oauth2:
    client:
      #access-token-uri: https://auth/login
      #user-authorization-uri: /auth/oauth/authorize
      accessTokenUri: http://localhost:1000/oauth/authorize
      userAuthorizationUri: http://localhost:1000/oauth/token
      client-id: sapepool
      client-secret: sapepool
    resource:
      jwt:
        key-uri: http://localhost:1000/oauth/token_key
        #key-value:

Authorization Server

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

        @Autowired
        @Qualifier("authenticationManagerBean")
        private AuthenticationManager authenticationManager;

        @Autowired
        @Qualifier("customUserDetailsService")
        private UserDetailsService userDetailsService;

        /**
         * Token store.
         *
         * @return the token store
         */
        /*@Bean
        public DatastoreTokenStore tokenStore() {
            return new DatastoreTokenStore(datastoreDataSource);
        }*/
        @Bean
        public TokenStore tokenStore() {
            return new JwtTokenStore(jwtAccessTokenConverter());
        }

        @Bean
        public JwtAccessTokenConverter jwtAccessTokenConverter() {
            JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
            converter.setKeyPair(new KeyStoreKeyFactory(new ClassPathResource("jwt.jks"), "password".toCharArray()).getKeyPair("jwt"));
            converter.setSigningKey("123");
            converter.setVerifierKey("123");
            return converter;
        }

        /**
         * 
         */
        @Override
        public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {

            endpoints.authenticationManager(authenticationManager).userDetailsService(userDetailsService)
                    .tokenStore(tokenStore())//.tokenServices(tokenServices())
                    .tokenEnhancer(jwtAccessTokenConverter())
                    .accessTokenConverter(jwtAccessTokenConverter())
                    .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);
        }

         /**
         * Authorization server security Configuration.
         *
         * @param oauthServer
         *            the oauth server
         * @throws Exception
         *             the exception
         */
        @Override
        public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
            oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");
        }

        @Override
        public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
            clients.inMemory()
                .withClient("sapepool")
                .secret("{noop}sapepool")
                //.secret("sapepool")
                .authorizedGrantTypes("client_credentials", "password","refresh_token")
                .authorities("ROLE_CLIENT", "ROLE_ANDROID_CLIENT", "ROLE_ANONYMOUS")
                .scopes("read", "write", "trust")
                .accessTokenValiditySeconds(5000)
                .refreshTokenValiditySeconds(50000);
                //.resourceIds("oauth2-resource") - isAutoApprove()
        }
    }

Authorization Server – Web Security Config

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    private static Logger log = LoggerFactory.getLogger(WebSecurityConfig.class);


    @Autowired
    private UserDetailsService userDetailsService;


    @Override
    @Bean
    public UserDetailsService userDetailsServiceBean() throws Exception {
        return super.userDetailsServiceBean();
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
            .antMatchers("/oauth/token/**").permitAll()
            .anyRequest().permitAll()
            //.antMatchers("*/oauth/**").permitAll()
            //.antMatchers("/**").permitAll()
            .and().csrf().disable();
            //.anonymous().disable();

        /*
         * http.csrf().disable().exceptionHandling() //.authenticationEntryPoint( //
         * (request, response, authException) ->
         * response.sendError(HttpServletResponse.SC_UNAUTHORIZED))
         * .and().authorizeRequests().antMatchers("/**").authenticated().and().httpBasic
         * ();
         */
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }
}


Get this bounty!!!

#StackBounty: #java #spring-boot #heroku #oauth-2.0 How do I stop Heroku from changing the location header and causing 401 with my Spri…

Bounty: 150

I have a spring boot oauth2 service working locally. But when I deploy this to Heroku it fails with a 401.

So on my local system I go to the UI and I have no valid JWT so it does a redirect to:

localhost:8080/api/auth/oauth/authorize?response_type=token&client_id=clienteagleeye&redirect_uri=http%3A%2F%2Flocalhost%3A4200&scope=webClient

The spring gateway routes to my auth service, localhost:8066/auth/login. I login with valid username/password and it routes to localhost:8066/auth/validate, which gives this response header:

Location: localhost:8066/auth/oauth/authorize?response_type=token&client_id=clienteagleeye&redirect_uri=http%3A%2F%2Flocalhost%3A4200&scope=webClient

It redirects to:

localhost:8066/auth/oauth/authorize?response_type=token&client_id=clienteagleeye&redirect_uri=http%3A%2F%2Flocalhost%3A4200&scope=webClient

…and the response header location on that call is: localhost:4200#access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.etc...

It routes back to the UI and I have the access token. Everything works as expected.

I do this in Heroku I get to this auth/validate step abc-authserver.herokuapp.com/auth/validate, and the response header location is Location: abc-authserver.herokuapp.com/auth/.

I am expecting it to be:

abc-authserver.herokuapp.com/auth/oauth/authorize?response_type=token&client_id=clienteagleeye&redirect_uri=https%3A%2F%dummyui&scope=webClient

but its not so it routes to abc-authserver.herokuapp.com/auth/ and I get a 401.

Why is Heroku dropping my response_type, client_id, scope and redirect_uri information? Why is it changing the Location in the response header when I am validating? The logs show that my username and password are correct and I have the information. It just has no idea where to go.

This is my resourceConfig in the authservice…

@Configuration
@EnableConfigurationProperties
public class ResourceConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .cors().and()
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.NEVER).and()
            .authorizeRequests()
            .antMatchers("/api/**", "/auth/**", "/oauth/**", "/login", "/validate").permitAll()
            .and().formLogin()
            .loginPage("/login").loginProcessingUrl("/validate")
            .and()
            .logout().and().httpBasic().and().authorizeRequests().anyRequest().authenticated();
    }
}

I need to figure out how to not lose the redirect information. I can provide any additional information needed. I am wasting tons of time trying to figure this out. I would appreciate any input. Thanks.


Get this bounty!!!

#StackBounty: #hibernate #spring-boot #jpa #kotlin #jpql JPQL and list of tuples as parameter for SELECT IN statements

Bounty: 50

Given the following table layout:

CREATE TABLE things (
    id      BIGINT PRIMARY KEY NOT NULL,
    foo     BIGINT NOT NULL,
    bar     BIGINT NOT NULL
);

An entity class (Kotlin):

@Entity
@Table(name = "things")
class Thing(
        val foo: Long,
        val bar: Long
) : AbstractPersistable<Long>()

And a repository:

interface ThingRepository : JpaRepository<Thing, Long> {
@Query("SELECT t FROM Thing t WHERE t.foo IN ?1")
fun selectByFoos(foos: Iterable<Long>): Iterable<Thing>

@Query("SELECT t FROM Thing t WHERE (t.foo, t.bar) IN ((1, 2), (3, 4))")
fun selectByFoosAndBarsFixed(): Iterable<Thing>

@Query("SELECT t FROM Thing t WHERE (t.foo, t.bar) IN ?1")
fun selectByFoosAndBars(foosAndBars: Iterable<Pair<Long, Long>>): Iterable<Thing>

The following two calls work fine:

repo.selectByFoos(listOf(1L, 3L))
repo.selectByFoosAndBarsFixed()

However the this one does not:

repo.selectByFoosAndBars(listOf(Pair(1L, 2L), Pair(3L, 4L)))

It throws:

org.springframework.dao.DataIntegrityViolationException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.DataException: could not extract ResultSet

Caused by: org.h2.jdbc.JdbcSQLException: Data conversion error converting "aced00057372000b6b6f746c696e2e50616972fa1b06813de78f780200024c000566697273747400124c6a6176612f6c616e672f4f626a6563743b4c00067365636f6e6471007e000178707372000e6a6176612e6c616e672e4c6f6e673b8be490cc8f23df0200014a000576616c7565787200106a6176612e6c616e672e4e756d62657286ac951d0b94e08b020000787000000000000000017371007e00030000000000000002"; SQL statement:
/* SELECT t FROM Thing t WHERE (t.foo, t.bar) IN ?1 */ select thing0_.id as id1_0_, thing0_.bar as bar2_0_, thing0_.foo as foo3_0_ from things thing0_ where (thing0_.foo , thing0_.bar) in (? , ?) [22018-197]

Caused by: java.lang.NumberFormatException: For input string: "aced00057372000b6b6f746c696e2e50616972fa1b06813de78f780200024c000566697273747400124c6a6176612f6c616e672f4f626a6563743b4c00067365636f6e6471007e000178707372000e6a6176612e6c616e672e4c6f6e673b8be490cc8f23df0200014a000576616c7565787200106a6176612e6c616e672e4e756d62657286ac951d0b94e08b020000787000000000000000017371007e00030000000000000002"

I guess the elements of the list passed as parameter are not inserted correctly into the query. How can I correct this?

Sure, I could manually build the query, like so:

@Repository
class SecondThingRepository(private val entityManager: EntityManager) {
    fun selectByFoosAndBars(foosAndBars: Iterable<Pair<Long, Long>>): Iterable<Thing> {
        val pairsRepr = foosAndBars.joinToString(prefix = "(", postfix = ")") { "(${it.first}, '${it.second}')" }
        val query: TypedQuery<Thing> = entityManager.createQuery("SELECT t FROM Thing t WHERE (t.foo, t.bar) IN $pairsRepr", Thing::class.java)
        return query.resultList
    }
}

But this seems note very good.


Get this bounty!!!