So I'm trying to switch my database from MySQL to PostgreSQL. I have built an API using Spring Boot that can do a basic CRUD operation perfectly on MySQL. The problem is that when I test my API in Postman with the new PostgreSQL, only GET and DELETE request that work perfectly. POST and PUT request return this bad sql grammar error
Here's the error:
"timestamp": "2023-02-08T02:49:51.307+00:00",
"status": 500,
"error": "Internal Server Error",
"trace": "org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [UPDATE md_jurnal_int SET id_dd_wilayah_kerja=?, kode_file=?, file_id=?, tanggal=?, debet_kredit=?, kode_coa=?, nominal=?, flag=?, id_akmt_subledger=?, id_referensi=?, no_bukti=?, created_date=? WHERE id_md_jurnal_int=?]\r\n\tat org.springframework.jdbc.support.SQLStateSQLExceptionTranslator.doTranslate(SQLStateSQLExceptionTranslator.java:99)\r\n\tat org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:70)\r\n\tat org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:79)\r\n\tat org.springframework.jdbc.core.JdbcTemplate.translateException(JdbcTemplate.java:1538)\r\n\tat org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:667)\r\n\tat org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:960)\r\n\tat org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:1015)\r\n\tat org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:1025)\r\n\tat com.akuntansi.akuntansi.repo.jdbcRepo.putData(jdbcRepo.java:52)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)\r\n\tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)\r\n\tat java.base/java.lang.reflect.Method.invoke(Unknown Source)\r\n\tat org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:343)\r\n\tat org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:196)\r\n\tat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)\r\n\tat org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:752)\r\n\tat org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:137)\r\n\tat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:184)\r\n\tat org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:752)\r\n\tat org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:703)\r\n\tat com.akuntansi.akuntansi.repo.jdbcRepo$$SpringCGLIB$$0.putData(<generated>)\r\n\tat com.akuntansi.akuntansi.controller.DataIntegrasiAkuntansi.update(DataIntegrasiAkuntansi.java:174)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)\r\n\tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)\r\n\tat java.base/java.lang.reflect.Method.invoke(Unknown Source)\r\n\tat org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:207)\r\n\tat org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:152)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:884)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797)\r\n\tat org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)\r\n\tat org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1080)\r\n\tat org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:973)\r\n\tat org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1011)\r\n\tat org.springframework.web.servlet.FrameworkServlet.doPut(FrameworkServlet.java:925)\r\n\tat jakarta.servlet.http.HttpServlet.service(HttpServlet.java:734)\r\n\tat org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:885)\r\n\tat jakarta.servlet.http.HttpServlet.service(HttpServlet.java:814)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:223)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)\r\n\tat org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)\r\n\tat org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)\r\n\tat org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)\r\n\tat org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)\r\n\tat org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:177)\r\n\tat org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)\r\n\tat org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)\r\n\tat org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:119)\r\n\tat org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)\r\n\tat org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)\r\n\tat org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)\r\n\tat org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:400)\r\n\tat org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)\r\n\tat org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:859)\r\n\tat org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1734)\r\n\tat org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52)\r\n\tat org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)\r\n\tat org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)\r\n\tat org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)\r\n\tat java.base/java.lang.Thread.run(Unknown Source)\r\nCaused by: org.postgresql.util.PSQLException: ERROR: column \"tanggal\" is of type date but expression is of type character varying\n Hint: You will need to rewrite or cast the expression.\n Position: 84\r\n\tat org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2676)\r\n\tat org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2366)\r\n\tat org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:356)\r\n\tat org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:496)\r\n\tat org.postgresql.jdbc.PgStatement.execute(PgStatement.java:413)\r\n\tat org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:190)\r\n\tat org.postgresql.jdbc.PgPreparedStatement.executeUpdate(PgPreparedStatement.java:152)\r\n\tat com.zaxxer.hikari.pool.ProxyPreparedStatement.executeUpdate(ProxyPreparedStatement.java:61)\r\n\tat com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeUpdate(HikariProxyPreparedStatement.java)\r\n\tat org.springframework.jdbc.core.JdbcTemplate.lambda$update$2(JdbcTemplate.java:965)\r\n\tat org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:651)\r\n\t... 68 more\r\n",
"message": "PreparedStatementCallback; bad SQL grammar [UPDATE md_jurnal_int SET id_dd_wilayah_kerja=?, kode_file=?, file_id=?, tanggal=?, debet_kredit=?, kode_coa=?, nominal=?, flag=?, id_akmt_subledger=?, id_referensi=?, no_bukti=?, created_date=? WHERE id_md_jurnal_int=?]",
"path": "/AkuntansiAPI/db/1"
Here's the error on the terminal:
2023-02-08T11:32:50.721+07:00 INFO 13440 --- [ restartedMain] c.a.akuntansi.AkuntansiApplication : No active profile set, falling back to 1 default profile: "default"
2023-02-08T11:32:50.809+07:00 INFO 13440 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2023-02-08T11:32:50.809+07:00 INFO 13440 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2023-02-08T11:32:52.522+07:00 INFO 13440 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2023-02-08T11:32:52.539+07:00 INFO 13440 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2023-02-08T11:32:52.539+07:00 INFO 13440 --- [ restartedMain] o.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/10.1.5]
2023-02-08T11:32:52.628+07:00 INFO 13440 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2023-02-08T11:32:52.633+07:00 INFO 13440 --- [ restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1807 ms
2023-02-08T11:32:53.651+07:00 INFO 13440 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2023-02-08T11:32:53.725+07:00 INFO 13440 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2023-02-08T11:32:53.741+07:00 INFO 13440 --- [ restartedMain] c.a.akuntansi.AkuntansiApplication : Started AkuntansiApplication in 3.589 seconds (process running for 4.318)
2023-02-08T11:32:58.498+07:00 INFO 13440 --- [nio-8080-exec-2] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2023-02-08T11:32:58.498+07:00 INFO 13440 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2023-02-08T11:32:58.506+07:00 INFO 13440 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Completed initialization in 8 ms
2023-02-08T11:32:58.699+07:00 INFO 13440 --- [nio-8080-exec-2] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2023-02-08T11:32:58.908+07:00 INFO 13440 --- [nio-8080-exec-2] com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Added connection org.postgresql.jdbc.PgConnection#6caa10fc
2023-02-08T11:32:58.916+07:00 INFO 13440 --- [nio-8080-exec-2] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2023-02-08T11:32:58.981+07:00 ERROR 13440 --- [nio-8080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [UPDATE md_jurnal_int SET id_dd_wilayah_kerja=?, kode_file=?, file_id=?, tanggal=?, debet_kredit=?, kode_coa=?, nominal=?, flag=?, id_akmt_subledger=?, id_referensi=?, no_bukti=?, created_date=? WHERE id_md_jurnal_int=?]] with root cause
org.postgresql.util.PSQLException: ERROR: column "tanggal" is of type date but expression is of type character varying
Hint: You will need to rewrite or cast the expression.
Position: 84
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2676) ~[postgresql-42.5.1.jar:42.5.1]
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2366) ~[postgresql-42.5.1.jar:42.5.1]
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:356) ~[postgresql-42.5.1.jar:42.5.1]
at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:496) ~[postgresql-42.5.1.jar:42.5.1]
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:413) ~[postgresql-42.5.1.jar:42.5.1]
at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:190) ~[postgresql-42.5.1.jar:42.5.1]
at org.postgresql.jdbc.PgPreparedStatement.executeUpdate(PgPreparedStatement.java:152) ~[postgresql-42.5.1.jar:42.5.1]
at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeUpdate(ProxyPreparedStatement.java:61) ~[HikariCP-5.0.1.jar:na]
at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeUpdate(HikariProxyPreparedStatement.java) ~[HikariCP-5.0.1.jar:na]
at org.springframework.jdbc.core.JdbcTemplate.lambda$update$2(JdbcTemplate.java:965) ~[spring-jdbc-6.0.4.jar:6.0.4]
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:651) ~[spring-jdbc-6.0.4.jar:6.0.4]
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:960) ~[spring-jdbc-6.0.4.jar:6.0.4]
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:1015) ~[spring-jdbc-6.0.4.jar:6.0.4]
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:1025) ~[spring-jdbc-6.0.4.jar:6.0.4]
at com.akuntansi.akuntansi.repo.jdbcRepo.putData(jdbcRepo.java:52) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Unknown Source) ~[na:na]
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:343) ~[spring-aop-6.0.4.jar:6.0.4]
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:196) ~[spring-aop-6.0.4.jar:6.0.4]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) ~[spring-aop-6.0.4.jar:6.0.4]
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:752) ~[spring-aop-6.0.4.jar:6.0.4]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:137) ~[spring-tx-6.0.4.jar:6.0.4]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:184) ~[spring-aop-6.0.4.jar:6.0.4]
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:752) ~[spring-aop-6.0.4.jar:6.0.4]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:703) ~[spring-aop-6.0.4.jar:6.0.4]
at com.akuntansi.akuntansi.repo.jdbcRepo$$SpringCGLIB$$0.putData(<generated>) ~[classes/:na]
at com.akuntansi.akuntansi.controller.DataIntegrasiAkuntansi.update(DataIntegrasiAkuntansi.java:174) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Unknown Source) ~[na:na]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:207) ~[spring-web-6.0.4.jar:6.0.4]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:152) ~[spring-web-6.0.4.jar:6.0.4]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117) ~[spring-webmvc-6.0.4.jar:6.0.4]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:884) ~[spring-webmvc-6.0.4.jar:6.0.4]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797) ~[spring-webmvc-6.0.4.jar:6.0.4]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-6.0.4.jar:6.0.4]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1080) ~[spring-webmvc-6.0.4.jar:6.0.4]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:973) ~[spring-webmvc-6.0.4.jar:6.0.4]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1011) ~[spring-webmvc-6.0.4.jar:6.0.4]
at org.springframework.web.servlet.FrameworkServlet.doPut(FrameworkServlet.java:925) ~[spring-webmvc-6.0.4.jar:6.0.4]
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:734) ~[tomcat-embed-core-10.1.5.jar:6.0]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:885) ~[spring-webmvc-6.0.4.jar:6.0.4]
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:814) ~[tomcat-embed-core-10.1.5.jar:6.0]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:223) ~[tomcat-embed-core-10.1.5.jar:10.1.5]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158) ~[tomcat-embed-core-10.1.5.jar:10.1.5]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-10.1.5.jar:10.1.5]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185) ~[tomcat-embed-core-10.1.5.jar:10.1.5]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158) ~[tomcat-embed-core-10.1.5.jar:10.1.5]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-6.0.4.jar:6.0.4]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) ~[spring-web-6.0.4.jar:6.0.4]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185) ~[tomcat-embed-core-10.1.5.jar:10.1.5]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158) ~[tomcat-embed-core-10.1.5.jar:10.1.5]
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-6.0.4.jar:6.0.4]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) ~[spring-web-6.0.4.jar:6.0.4]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185) ~[tomcat-embed-core-10.1.5.jar:10.1.5]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158) ~[tomcat-embed-core-10.1.5.jar:10.1.5]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-6.0.4.jar:6.0.4]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) ~[spring-web-6.0.4.jar:6.0.4]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185) ~[tomcat-embed-core-10.1.5.jar:10.1.5]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158) ~[tomcat-embed-core-10.1.5.jar:10.1.5]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:177) ~[tomcat-embed-core-10.1.5.jar:10.1.5]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) ~[tomcat-embed-core-10.1.5.jar:10.1.5]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542) ~[tomcat-embed-core-10.1.5.jar:10.1.5]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:119) ~[tomcat-embed-core-10.1.5.jar:10.1.5]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-10.1.5.jar:10.1.5]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) ~[tomcat-embed-core-10.1.5.jar:10.1.5]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357) ~[tomcat-embed-core-10.1.5.jar:10.1.5]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:400) ~[tomcat-embed-core-10.1.5.jar:10.1.5]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-10.1.5.jar:10.1.5]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:859) ~[tomcat-embed-core-10.1.5.jar:10.1.5]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1734) ~[tomcat-embed-core-10.1.5.jar:10.1.5]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52) ~[tomcat-embed-core-10.1.5.jar:10.1.5]
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191) ~[tomcat-embed-core-10.1.5.jar:10.1.5]
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659) ~[tomcat-embed-core-10.1.5.jar:10.1.5]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-10.1.5.jar:10.1.5]
at java.base/java.lang.Thread.run(Unknown Source) ~[na:na]
Here's the repo code that do the query:
package com.akuntansi.akuntansi.repo;
import com.akuntansi.akuntansi.model.mAkuntansi;
import java.text.SimpleDateFormat;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
#Repository
public class jdbcRepo implements AkuntansiRepo{
private final String dateFormat1 = "yyyy/mm/dd";
//private final String dateFormat2 = "YYYY-MM-DD";
#Autowired
private JdbcTemplate dbQuery;
#Override
public int postData(mAkuntansi dataAkuntansi){
return dbQuery.update(
//Query
"INSERT INTO md_jurnal_int (" +
//Fields
"id_md_jurnal_int, id_dd_wilayah_kerja , kode_file, file_id, tanggal, debet_kredit, kode_coa, " +
"nominal, flag, id_akmt_subledger, id_referensi, no_bukti, created_date" +
") " +
//Value
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
new Object[]{
dataAkuntansi.getid_md_jurnal_int(),
dataAkuntansi.getid_dd_wilayah_kerja(),
dataAkuntansi.getkode_file(),
dataAkuntansi.getfile_id(),
dataAkuntansi.gettanggal(),
dataAkuntansi.getdebet_kredit(),
dataAkuntansi.getkode_coa(),
dataAkuntansi.getnominal(),
dataAkuntansi.getflag(),
dataAkuntansi.getid_akmt_subledger(),
dataAkuntansi.getid_referensi(),
dataAkuntansi.getno_bukti(),
dataAkuntansi.getcreated_date()
});
}
#Override
public int putData(mAkuntansi dataAkuntansi){
return dbQuery.update(
//Query
"UPDATE md_jurnal_int SET " +
//Fields
"id_dd_wilayah_kerja=?, kode_file=?, file_id=?, tanggal=?, debet_kredit=?, kode_coa=?, " +
"nominal=?, flag=?, id_akmt_subledger=?, id_referensi=?, no_bukti=?, created_date=? " +
//Condition
"WHERE " +
"id_md_jurnal_int=?",
new Object[]{
dataAkuntansi.getid_dd_wilayah_kerja(),
dataAkuntansi.getkode_file(),
dataAkuntansi.getfile_id(),
dataAkuntansi.gettanggal(),
dataAkuntansi.getdebet_kredit(),
dataAkuntansi.getkode_coa(),
dataAkuntansi.getnominal(),
dataAkuntansi.getflag(),
dataAkuntansi.getid_akmt_subledger(),
dataAkuntansi.getid_referensi(),
dataAkuntansi.getno_bukti(),
dataAkuntansi.getcreated_date(),
dataAkuntansi.getid_md_jurnal_int()
});
}
#Override
public mAkuntansi getDataByID(int jurnal_id){
try{
mAkuntansi dataAkuntansi = dbQuery.queryForObject(
//Query
"SELECT * FROM md_jurnal_int WHERE id_md_jurnal_int=?",
BeanPropertyRowMapper.newInstance(mAkuntansi.class),
jurnal_id);
return dataAkuntansi;
}
catch(IncorrectResultSizeDataAccessException e){
System.out.println("No ID match!");
return null;
}
}
#Override
public int deleteDataByID(int jurnal_id){
return dbQuery.update("DELETE FROM md_jurnal_int WHERE id_md_jurnal_int=?", jurnal_id);
}
#Override
public List<mAkuntansi> getDataAll(){
return dbQuery.query("SELECT * FROM md_jurnal_int", BeanPropertyRowMapper.newInstance(mAkuntansi.class));
}
#Override
public int deleteDataAll(){
return dbQuery.update("DELETE FROM md_jurnal_int");
}
#Override
public boolean isValidFormat(String date){
SimpleDateFormat date_format1 = new SimpleDateFormat(dateFormat1);
//SimpleDateFormat date_format2 = new SimpleDateFormat(dateFormat2);
date_format1.setLenient(false);
//date_format2.setLenient(false);
try {
date_format1.parse(date);
//date_format2.parse(date);
return true;
} catch (Exception e) {
return false;
}
}
}
I'm not familiar with PostgreSQL since this is the first time using it. All request when I use MySQL works perfectly, hence why I was so confused when it's not working on PostgreSQL
The tanggal date field is causing the problem. It requires passing the java.sql.Date instead of 'Object' type.
In your object array replace
dataAkuntansi.gettanggal()
with
java.sql.Date.valueOf(dataAkuntansi.gettanggal())
Related
I am trying to access a DynamoDB table from a Java application where the key is a long integer. Reading this guide, https://docs.amazonaws.cn/en_us/amazondynamodb/latest/developerguide/DynamoDBMapper.DataTypes.html, it seems that I can cast my N (number in table) as Long or BigInteger. When I try to retrieve data in both cases, I get this exception:
2023-01-21T17:28:49.970+01:00 ERROR 15940 --- [nio-5000-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMappingException: SensorData[sample_time]; could not unconvert attribute] with root cause
java.lang.NullPointerException: Cannot invoke "java.lang.reflect.Method.invoke(Object, Object[])" because "this.setter" is null
at com.amazonaws.services.dynamodbv2.datamodeling.StandardBeanProperties$MethodReflect.set(StandardBeanProperties.java:133) ~[aws-java-sdk-dynamodb-1.12.388.jar:na]
at com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperFieldModel.set(DynamoDBMapperFieldModel.java:111) ~[aws-java-sdk-dynamodb-1.12.388.jar:na]
at com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperFieldModel.unconvertAndSet(DynamoDBMapperFieldModel.java:164) ~[aws-java-sdk-dynamodb-1.12.388.jar:na]
at com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperTableModel.unconvert(DynamoDBMapperTableModel.java:267) ~[aws-java-sdk-dynamodb-1.12.388.jar:na]
at com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper.privateMarshallIntoObject(DynamoDBMapper.java:472) ~[aws-java-sdk-dynamodb-1.12.388.jar:na]
at com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper.marshallIntoObjects(DynamoDBMapper.java:500) ~[aws-java-sdk-dynamodb-1.12.388.jar:na]
at com.amazonaws.services.dynamodbv2.datamodeling.PaginatedScanList.<init>(PaginatedScanList.java:64) ~[aws-java-sdk-dynamodb-1.12.388.jar:na]
at com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper.scan(DynamoDBMapper.java:1571) ~[aws-java-sdk-dynamodb-1.12.388.jar:na]
at com.amazonaws.services.dynamodbv2.datamodeling.AbstractDynamoDBMapper.scan(AbstractDynamoDBMapper.java:236) ~[aws-java-sdk-dynamodb-1.12.388.jar:na]
at com.steeve.test.SensorDataRepository.getAll(SensorDataRepository.java:19) ~[classes/:na]
at com.steeve.test.TestApplication.health(TestApplication.java:25) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:207) ~[spring-web-6.0.3.jar:6.0.3]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:152) ~[spring-web-6.0.3.jar:6.0.3]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117) ~[spring-webmvc-6.0.3.jar:6.0.3]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:884) ~[spring-webmvc-6.0.3.jar:6.0.3]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797) ~[spring-webmvc-6.0.3.jar:6.0.3]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-6.0.3.jar:6.0.3]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1080) ~[spring-webmvc-6.0.3.jar:6.0.3]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:973) ~[spring-webmvc-6.0.3.jar:6.0.3]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1010) ~[spring-webmvc-6.0.3.jar:6.0.3]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:902) ~[spring-webmvc-6.0.3.jar:6.0.3]
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:705) ~[tomcat-embed-core-10.1.4.jar:6.0]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:884) ~[spring-webmvc-6.0.3.jar:6.0.3]
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:814) ~[tomcat-embed-core-10.1.4.jar:6.0]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:223) ~[tomcat-embed-core-10.1.4.jar:10.1.4]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158) ~[tomcat-embed-core-10.1.4.jar:10.1.4]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-10.1.4.jar:10.1.4]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185) ~[tomcat-embed-core-10.1.4.jar:10.1.4]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158) ~[tomcat-embed-core-10.1.4.jar:10.1.4]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-6.0.3.jar:6.0.3]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) ~[spring-web-6.0.3.jar:6.0.3]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185) ~[tomcat-embed-core-10.1.4.jar:10.1.4]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158) ~[tomcat-embed-core-10.1.4.jar:10.1.4]
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-6.0.3.jar:6.0.3]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) ~[spring-web-6.0.3.jar:6.0.3]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185) ~[tomcat-embed-core-10.1.4.jar:10.1.4]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158) ~[tomcat-embed-core-10.1.4.jar:10.1.4]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-6.0.3.jar:6.0.3]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) ~[spring-web-6.0.3.jar:6.0.3]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185) ~[tomcat-embed-core-10.1.4.jar:10.1.4]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158) ~[tomcat-embed-core-10.1.4.jar:10.1.4]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:177) ~[tomcat-embed-core-10.1.4.jar:10.1.4]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) ~[tomcat-embed-core-10.1.4.jar:10.1.4]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542) ~[tomcat-embed-core-10.1.4.jar:10.1.4]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:119) ~[tomcat-embed-core-10.1.4.jar:10.1.4]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-10.1.4.jar:10.1.4]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) ~[tomcat-embed-core-10.1.4.jar:10.1.4]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357) ~[tomcat-embed-core-10.1.4.jar:10.1.4]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:400) ~[tomcat-embed-core-10.1.4.jar:10.1.4]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-10.1.4.jar:10.1.4]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:859) ~[tomcat-embed-core-10.1.4.jar:10.1.4]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1734) ~[tomcat-embed-core-10.1.4.jar:10.1.4]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52) ~[tomcat-embed-core-10.1.4.jar:10.1.4]
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191) ~[tomcat-embed-core-10.1.4.jar:10.1.4]
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659) ~[tomcat-embed-core-10.1.4.jar:10.1.4]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-10.1.4.jar:10.1.4]
at java.base/java.lang.Thread.run(Thread.java:833) ~[na:na]
The exception is the same for Long and BigInteger. If I map the value as Integer the exception is different, it fails when it tries to do Integer.parseInt() with a too long number:
2023-01-21T17:35:08.136+01:00 ERROR 5064 --- [nio-5000-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMappingException: SensorData[sample_time]; could not unconvert attribute] with root cause
java.lang.NumberFormatException: For input string: "1674256283832"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67) ~[na:na]
at java.base/java.lang.Integer.parseInt(Integer.java:668) ~[na:na]
at java.base/java.lang.Integer.valueOf(Integer.java:999) ~[na:na]
at com.amazonaws.services.dynamodbv2.datamodeling.StandardTypeConverters$ToInteger$2.convert(StandardTypeConverters.java:773) ~[aws-java-sdk-dynamodb-1.12.388.jar:na]
at com.amazonaws.services.dynamodbv2.datamodeling.StandardTypeConverters$ToInteger$2.convert(StandardTypeConverters.java:770) ~[aws-java-sdk-dynamodb-1.12.388.jar:na]
at com.amazonaws.services.dynamodbv2.datamodeling.StandardTypeConverters$1.unconvert(StandardTypeConverters.java:75) ~[aws-java-sdk-dynamodb-1.12.388.jar:na]
at com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTypeConverter$DelegateConverter.unconvert(DynamoDBTypeConverter.java:109) ~[aws-java-sdk-dynamodb-1.12.388.jar:na]
at com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTypeConverter$NullSafeConverter.unconvert(DynamoDBTypeConverter.java:128) ~[aws-java-sdk-dynamodb-1.12.388.jar:na]
at com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTypeConverter$ExtendedConverter.unconvert(DynamoDBTypeConverter.java:88) ~[aws-java-sdk-dynamodb-1.12.388.jar:na]
at com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperFieldModel.unconvert(DynamoDBMapperFieldModel.java:146) ~[aws-java-sdk-dynamodb-1.12.388.jar:na]
at com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperFieldModel.unconvertAndSet(DynamoDBMapperFieldModel.java:164) ~[aws-java-sdk-dynamodb-1.12.388.jar:na]
at com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperTableModel.unconvert(DynamoDBMapperTableModel.java:267) ~[aws-java-sdk-dynamodb-1.12.388.jar:na]
at com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper.privateMarshallIntoObject(DynamoDBMapper.java:472) ~[aws-java-sdk-dynamodb-1.12.388.jar:na]
at com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper.marshallIntoObjects(DynamoDBMapper.java:500) ~[aws-java-sdk-dynamodb-1.12.388.jar:na]
at com.amazonaws.services.dynamodbv2.datamodeling.PaginatedScanList.<init>(PaginatedScanList.java:64) ~[aws-java-sdk-dynamodb-1.12.388.jar:na]
at com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper.scan(DynamoDBMapper.java:1571) ~[aws-java-sdk-dynamodb-1.12.388.jar:na]
at com.amazonaws.services.dynamodbv2.datamodeling.AbstractDynamoDBMapper.scan(AbstractDynamoDBMapper.java:236) ~[aws-java-sdk-dynamodb-1.12.388.jar:na]
at com.steeve.test.SensorDataRepository.getAll(SensorDataRepository.java:19) ~[classes/:na]
This is my mapping class:
#DynamoDBTable(tableName = "sensor_data")
public class SensorData {
private Long sample_time;
#DynamoDBHashKey(attributeName = "sample_time")
public Long getSampletime()
{return sample_time;}
public void setSampleTime(Long sample_time)
{ this.sample_time = sample_time;}
#DynamoDBDocument()
public static class device_data {
private String sensorName;
private Float sensorValue;
public void setSensorName(String sensorName)
{this.sensorName = sensorName;}
#DynamoDBAttribute
public String getSensorName()
{return this.sensorName;}
public void setSensorValue(Float sensorValue)
{this.sensorValue = sensorValue;}
#DynamoDBAttribute
public Float getSensorValue()
{return this.sensorValue;}
}
}
Version of AWS SDK library:
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-dynamodb</artifactId>
<version>1.12.388</version>
</dependency>
This makes no sense to me.
I work on simple authentication app using spring security & encounter by an access denied error. I must mention that registration works perfectly & I've already created 1 record with bcrypted password but on login I'm failed to understand that what did I miss. Grateful for the help
User.java
public class User implements UserDetails {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String name;
private String username;
private String email;
private String password;
#OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JsonIgnore
private Set<UserRole> userRoles = new HashSet<>();
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
Set<GrantedAuthority>authorities = new HashSet<>();
userRoles.forEach(ur -> authorities.add(new
Authority(ur.getRole().getName())));
return authorities;
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return true;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return true;
}
}
SecurityConfig
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private UserSecurityService userSecurityService;
public SecurityConfig(UserSecurityService userSecurityService) {
this.userSecurityService = userSecurityService;
}
#Bean
PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/api/**").permitAll()
.antMatchers("/api/auth/**").permitAll()
.anyRequest()
.authenticated()
.and()
.httpBasic();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws
Exception {
auth.userDetailsService(userSecurityService).passwordEncoder
(passwordEncoder());
}
#Override
#Bean
public AuthenticationManager authenticationManagerBean() throws
Exception {return super.authenticationManagerBean();
}
}
UserSecurityService (loaduser)
#Service
public class UserSecurityService implements UserDetailsService {
private static final Logger LOG =
LoggerFactory.getLogger(UserSecurityService.class);
#Autowired
private UserRepository userRepository;
#Override
public UserDetails loadUserByUsername(String username) throws
UsernameNotFoundException {
User user = userRepository.findUserByUsername(username);
if (null == user) {
LOG.warn("Username {} not found", username);
throw new UsernameNotFoundException("Username " + username + "
not found");
}
return user;
}
}
AuthController
#RestController
#RequestMapping("/api/auth")
public class AuthController {
#Autowired
private AuthenticationManager authenticationManager;
#Autowired
private UserRepository userRepository;
#Autowired
private RoleRepository roleRepository;
#Autowired
private PasswordEncoder passwordEncoder;
#Autowired
private UserService userService;
#PostMapping("/register")
public ResponseEntity<User> register(#RequestBody User user) throws Exception {
return new ResponseEntity<>(userService.register(user), HttpStatus.OK);
}
#PostMapping("/login")
public ResponseEntity<String> login(#RequestBody String username, String password ) throws
Exception {
Authentication authentication = authenticationManager.authenticate(new
UsernamePasswordAuthenticationToken(
username, password
));
SecurityContextHolder.getContext().setAuthentication(authentication);
return new ResponseEntity<>("User signed -in succesfully", HttpStatus.OK);
}
}
Error
2022-01-14 14:49:13.604 INFO 24600 --- [ restartedMain]
c.kash.bankingAPI.BankingApiApplication : Starting
BankingApiApplication using Java 11.0.12 on LAPTOP-BQ48GM36 with PID
24600 (B:\spring\bankingAPI\target\classes started by The Kash in
B:\spring\bankingAPI)
2022-01-14 14:49:13.605 INFO 24600 --- [ restartedMain]
c.kash.bankingAPI.BankingApiApplication : No active profile set,
falling back to default profiles: default
2022-01-14 14:49:13.673 INFO 24600 --- [ restartedMain]
.e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults
active! Set 'spring.devtools.add-properties' to 'false' to disable
2022-01-14 14:49:13.674 INFO 24600 --- [ restartedMain]
.e.DevToolsPropertyDefaultsPostProcessor : For additional web related
logging consider setting the 'logging.level.web' property to 'DEBUG'
2022-01-14 14:49:14.557 INFO 24600 --- [ restartedMain]
.s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data
JPA
repositories in DEFAULT mode.
2022-01-14 14:49:14.646 INFO 24600 --- [ restartedMain]
.s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data
repository scanning in 74 ms. Found 2 JPA repository interfaces.
2022-01-14 14:49:15.876 INFO 24600 --- [ restartedMain]
o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with
port(s): 8088 (http)
2022-01-14 14:49:15.890 INFO 24600 --- [ restartedMain]
o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-01-14 14:49:15.890 INFO 24600 --- [ restartedMain]
org.apache.catalina.core.StandardEngine : Starting Servlet engine:
[Apache Tomcat/9.0.56]
2022-01-14 14:49:16.008 INFO 24600 --- [ restartedMain] o.a.c.c.C.
[Tomcat].[localhost].[/] : Initializing Spring embedded
WebApplicationContext
2022-01-14 14:49:16.008 INFO 24600 --- [ restartedMain]
w.s.c.ServletWebServerApplicationContext : Root
WebApplicationContext:
initialization completed in 2334 ms
2022-01-14 14:49:16.264 INFO 24600 --- [ restartedMain]
o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing
PersistenceUnitInfo [name: default]
2022-01-14 14:49:16.332 INFO 24600 --- [ restartedMain]
org.hibernate.Version : HHH000412: Hibernate ORM
core
version 5.6.3.Final
2022-01-14 14:49:16.542 INFO 24600 --- [ restartedMain]
o.hibernate.annotations.common.Version : HCANN000001: Hibernate
Commons Annotations {5.1.2.Final}
2022-01-14 14:49:16.661 INFO 24600 --- [ restartedMain]
com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2022-01-14 14:49:17.128 INFO 24600 --- [ restartedMain]
com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start
completed.
2022-01-14 14:49:17.145 INFO 24600 --- [ restartedMain]
org.hibernate.dialect.Dialect : HHH000400: Using dialect:
org.hibernate.dialect.MySQL57Dialect
2022-01-14 14:49:18.469 INFO 24600 --- [ restartedMain]
o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using
JtaPlatform implementation:
[org.hibernate.engine.transaction.jta.platform.internal.
NoJtaPlatform]
2022-01-14 14:49:18.478 INFO 24600 --- [ restartedMain]
j.LocalContainerEntityManagerFactoryBean : Initialized JPA
EntityManagerFactory for persistence unit 'default'
2022-01-14 14:49:19.173 WARN 24600 --- [ restartedMain]
JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is
enabled by default. Therefore, database queries may be performed
during
view rendering. Explicitly configure spring.jpa.open-in-view to
disable
this warning
2022-01-14 14:49:19.453 DEBUG 24600 --- [ restartedMain]
edFilterInvocationSecurityMetadataSource : Adding web access control
expression [permitAll] for Ant [pattern='/api/**', GET]
2022-01-14 14:49:19.455 DEBUG 24600 --- [ restartedMain]
edFilterInvocationSecurityMetadataSource : Adding web access control
expression [permitAll] for Ant [pattern='/api/auth/**']
2022-01-14 14:49:19.456 DEBUG 24600 --- [ restartedMain]
edFilterInvocationSecurityMetadataSource : Adding web access control
expression [authenticated] for any request
2022-01-14 14:49:19.468 INFO 24600 --- [ restartedMain]
o.s.s.web.DefaultSecurityFilterChain : Will secure any request
with
[org.springframework.security.web.context.request.async.
WebAsyncManagerIntegrationFilter#4b607819,
org.springframework.security.web.context.SecurityContextPersistence
Filter#146dcdcf,
org.springframework.security.web.header.HeaderWriterFilter#74f0174b,
org.springframework.security.web.authentication.logout.
LogoutFilter#839ff7f,
org.springframework.security.web.authentication.www.
BasicAuthenticationFilter#4f78b9a2,
org.springframework.security.web.savedrequest.
RequestCacheAwareFilter#7e2b3eef,
org.springframework.security.web.servletapi.SecurityContextHolder
AwareRequestFilter#1996d59a,
org.springframework.security.web.authentication.Anonymous
AuthenticationFilter#d82cd0b,
org.springframework.security.web.session.SessionManagement
Filter#47842f0b,
org.springframework.security.web.access.ExceptionTranslation
Filter#6fdc8d32, org.springframework.security.web.access.intercept.
FilterSecurityInterceptor#3619bc38]
2022-01-14 14:49:19.922 INFO 24600 --- [ restartedMain]
o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is
running
on port 35729
2022-01-14 14:49:19.959 INFO 24600 --- [ restartedMain]
o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s):
8088 (http) with context path ''
2022-01-14 14:49:19.970 INFO 24600 --- [ restartedMain]
c.kash.bankingAPI.BankingApiApplication : Started
BankingApiApplication
in 6.835 seconds (JVM running for 7.645)
2022-01-14 14:49:51.914 INFO 24600 --- [nio-8088-exec-2] o.a.c.c.C.
[Tomcat].[localhost].[/] : Initializing Spring
DispatcherServlet
'dispatcherServlet'
2022-01-14 14:49:51.915 INFO 24600 --- [nio-8088-exec-2]
o.s.web.servlet.DispatcherServlet : Initializing Servlet
'dispatcherServlet'
2022-01-14 14:49:51.916 INFO 24600 --- [nio-8088-exec-2]
o.s.web.servlet.DispatcherServlet : Completed initialization
in
1 ms
2022-01-14 14:49:51.931 DEBUG 24600 --- [nio-8088-exec-2]
o.s.security.web.FilterChainProxy : Securing POST /api/auth/login
2022-01-14 14:49:51.936 DEBUG 24600 --- [nio-8088-exec-2]
s.s.w.c.SecurityContextPersistenceFilter : Set SecurityContextHolder
to
empty SecurityContext
2022-01-14 14:49:51.939 DEBUG 24600 --- [nio-8088-exec-2]
o.s.s.w.a.AnonymousAuthenticationFilter : Set SecurityContextHolder
to
anonymous SecurityContext
2022-01-14 14:49:51.940 DEBUG 24600 --- [nio-8088-exec-2]
o.s.s.w.session.SessionManagementFilter : Request requested invalid
session id 1E5E812360CC1B8291311CA85ACAC55A
2022-01-14 14:49:51.945 DEBUG 24600 --- [nio-8088-exec-2]
o.s.s.w.a.i.FilterSecurityInterceptor : Authorized filter
invocation
[POST /api/auth/login] with attributes [permitAll]
2022-01-14 14:49:51.946 DEBUG 24600 --- [nio-8088-exec-2]
o.s.security.web.FilterChainProxy : Secured POST
/api/auth/login
Hibernate: select user0_.id as id1_7_, user0_.email as email2_7_,
user0_.name as name3_7_, user0_.password as password4_7_,
user0_.primary_account_id as primary_6_7_, user0_.savings_account_id
as
savings_7_7_, user0_.username as username5_7_ from users user0_ where
user0_.username=?
2022-01-14 14:49:52.305 WARN 24600 --- [nio-8088-exec-2]
c.k.b.s.serviceImpl.UserSecurityService : Username {
"username": "seeshee",
"password": "12345"
} not found
2022-01-14 14:49:52.313 DEBUG 24600 --- [nio-8088-exec-2]
o.s.s.a.dao.DaoAuthenticationProvider : Failed to find user '{
"username": "seeshee",
"password": "1234"
}'
2022-01-14 14:49:52.698 WARN 24600 --- [nio-8088-exec-2]
o.a.c.util.SessionIdGeneratorBase : Creation of SecureRandom
instance for session ID generation using [SHA1PRNG] took [364]
milliseconds.
2022-01-14 14:49:52.700 DEBUG 24600 --- [nio-8088-exec-2]
o.s.s.w.s.HttpSessionRequestCache : Saved request
http://localhost:8088/api/auth/login to session
2022-01-14 14:49:52.701 DEBUG 24600 --- [nio-8088-exec-2]
s.w.a.DelegatingAuthenticationEntryPoint : Trying to match using
Reque
tHeaderRequestMatcher [expectedHeaderName=X-Requested-With, expec
edHeaderValue=XMLHttpRequest]
2022-1-14 14:49:52.701 DEBUG 24600 --- [nio-8088-exec-2]
s.w.a.DelegatingAuthenticationEntryPoint : No match found. Using
default entry point
org.springframework.security.web.authentication.www.
BasicAuthenticationEntryPoint#691634d7
2022-01-14 14:49:52.702 DEBUG 24600 --- [nio-8088-exec-2]
w.c.HttpSessionSecurityContextRepository : Did not store empty
SecurityContext
2022-01-14 14:49:52.702 DEBUG 24600 --- [nio-8088-exec-2]
w.c.HttpSessionSecurityContextRepository : Did not store empty
SecurityContext
2022-01-14 14:49:52.702 DEBUG 24600 --- [nio-8088-exec-2]
s.s.w.c.SecurityContextPersistenceFilter : Cleared
SecurityContextHolder
to complete request
2022-01-14 14:49:52.705 DEBUG 24600 --- [nio-8088-exec-2]
o.s.security.web.FilterChainProxy : Securing POST /error
2022-01-14 14:49:52.705 DEBUG 24600 --- [nio-8088-exec-2]
s.s.w.c.SecurityContextPersistenceFilter : Set SecurityContextHolder
to
empty SecurityContext
2022-01-14 14:49:52.706 DEBUG 24600 --- [nio-8088-exec-2]
o.s.s.w.a.AnonymousAuthenticationFilter : Set SecurityContextHolder
to
anonymous SecurityContext
2022-01-14 14:49:52.706 DEBUG 24600 --- [nio-8088-exec-2]
o.s.security.web.FilterChainProxy : Secured POST /error
2022-01-14 14:49:52.721 DEBUG 24600 --- [nio-8088-exec-2]
a.DefaultWebInvocationPrivilegeEvaluator : filter invocation [/error]
denied for AnonymousAuthenticationToken [Principal=anonymousUser,
Credentials=[PROTECTED], Authenticated=true,
Details=WebAuthenticationDetails [RemoteIpAddress=0:0:0:0:0:0:0:1,
SessionId=BAFE9322A4A2705325C4B6540915129E], Granted Authorities=
[ROLE_ANONYMOUS]]
org.springframework.security.access.AccessDeniedException: Access is
denied
at
org.springframework.security.access.vote.AffirmativeBased.
decide(AffirmativeBased.java:73)
~[spring-security-core-5.6.1.jar:5.6.1]
at org.springframework.security.web.access.
DefaultWebInvocationPrivilegeEvaluator.isAllowed
(DefaultWe
bInvocationPrivilegeEvaluator.java:100) ~[spring-security-web-
5.6.1.jar:5.6.1]
at org.springframework.security.web.access.
DefaultWebInvocationPrivilegeEvaluator.isAllowed
(DefaultWebInvocationPrivilegeEvaluator.java:67) ~[spring-security-
web-
5.6.1.jar:5.6.1]
at
org.springframework.boot.web.servlet.filter.ErrorPageSecurityFilter.
isAllowed
(ErrorPageSecurityFilter.java:84) ~[spring-boot-2.6.2.jar:2.6.2]
at
org.springframework.boot.web.servlet.filter.ErrorPageSecurityFilter.
doFilter
(ErrorPageSecurityFilter.java:72) ~[spring-boot-2.6.2.jar:2.6.2]
at
org.springframework.boot.web.servlet.filter.ErrorPageSecurityFilter.
doFilter
(ErrorPageSecurityFilter.java:66) ~[spring-boot-2.6.2.jar:2.6.2]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(
ApplicationFilterChain.
java:189) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationFilterChain.doFilter
(ApplicationFilterChain.java:162) ~
[tomcat-embed-core-9.0.56.jar:9.0.56]
at
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.
doFilter
(FilterChainProxy.jav
a:327) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.access.intercept.
FilterSecurityInterceptor.invoke
(FilterSecurityInterceptor.java:106) ~[spring-security-web-
5.6.1.jar:5.6.1]
at org.springframework.security.web.access.intercept.
FilterSecurityInterceptor.doFilter
(FilterSecurityInterceptor.java:81) ~[spring-security-web-
5.6.1.jar:5.6.1]
at org.springframework.security.web.FilterChainProxy$
VirtualFilterChain.doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.access.
ExceptionTranslationFilter.doFilter
(ExceptionTranslationFilter.java:122) ~[spring-security-web-
5.6.1.jar:5.6.1]
at
org.springframework.security.web.access.ExceptionTranslationFilter.
doFilter
(ExceptionTranslationFilter.java:116) ~[spring-security-web-
5.6.1.jar:5.6.1]
at org.springframework.security.web.FilterChainProxy$
VirtualFilterChain.doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.session.SessionManagementFilter
.doFilter
(SessionManagementFilter.java:87) ~[spring-security-web-
5.6.1.jar:5.6.1]
at org.springframework.security.web.session.SessionManagementFilter.
doFilter
(SessionManagementFilter.java:81) ~[spring-security-web-
5.6.1.jar:5.6.1]
at
org.springframework.security.web.FilterChainProxy$VirtualFilterChain
.doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.authentication.
AnonymousAuthenticationFilter.doFilter
(AnonymousAuthenticationFilter.java:109) ~[spring-security-web-
5.6.1.jar:5.6.1]
at org.springframework.security.web.FilterChainProxy$
VirtualFilterChain.doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.servletapi.
SecurityContextHolderAwareRequestFilter.
doFilter(SecurityContextHolderAwareRequestFilter.java:149) ~[spring-
security-web-
5.6.1.jar:5.6.1]
at org.springframework.security.web.FilterChainProxy$
VirtualFilterChain.doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.savedrequest.
RequestCacheAwareFilter.doFilter
(RequestCacheAwareFilter.java:63) ~[spring-security-web-
5.6.1.jar:5.6.1]
at org.springframework.security.web.FilterChainProxy$
VirtualFilterChain.doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.web.filter.OncePerRequestFilter.doFilter
(OncePerRequestFilter.java:102) ~[spring-web-5.3.14.jar:5.3.14]
at org.springframework.security.web.FilterChainProxy$
VirtualFilterChain.doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.authentication.logout.
LogoutFilter.doFilter
(LogoutFilter.java:103) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.authentication.logout.
LogoutFilter.doFilter
(LogoutFilter.java:89) ~[spring-security-web-5.6.1.jar:5.6.1]
at
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.
doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(
OncePerRequestFilter.java:102)
~[spring-web-5.3.14.jar:5.3.14]
at org.springframework.security.web.FilterChainProxy$VirtualFilter
Chain.doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at
org.springframework.security.web.context.SecurityContextPersistence
Filter.doFilter
(SecurityContextPersistenceFilter.java:110) ~[spring-security-web-
5.6.1.jar:5.6.1]
at
org.springframework.security.web.context.SecurityContextPersistence
Filter.doFilter
(SecurityContextPersistenceFilter.java:80) ~[spring-security-web-
5.6.1.jar:5.6.1]
at
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.
doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.web.filter.OncePerRequestFilter.doFilter
(OncePerRequestFilter.java:102) ~[spring-web-5.3.14.jar:5.3.14]
at
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.
doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.FilterChainProxy.doFilterInternal
(FilterChainProxy.java:211) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.FilterChainProxy.doFilter
(FilterChainProxy.java:183) ~[spring-security-web-5.6.1.jar:5.6.1]
at
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate
(DelegatingFilterProxy.java:354) ~[spring-web-5.3.14.jar:5.3.14]
at org.springframework.web.filter.DelegatingFilterProxy.doFilter
(DelegatingFilterProxy.java:267) ~
[spring-web-5.3.14.jar:5.3.14]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter
(ApplicationFilterChain.java:189) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationFilterChain.doFilter
(ApplicationFilterChain.java:162) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at
org.springframework.web.filter.RequestContextFilter.doFilterInternal
(RequestContextFilter.java:100) ~[spring-web-5.3.14.jar:5.3.14]
at org.springframework.web.filter.OncePerRequestFilter.doFilter
(OncePerRequestFilter.java:117) ~[spring-web-5.3.14.jar:5.3.14]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter
(ApplicationFilterChain.java:189) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationFilterChain.doFilter
(ApplicationFilterChain.java:162) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.springframework.web.filter.OncePerRequestFilter.doFilter
(OncePerRequestFilter.java:102) ~[spring-web-5.3.14.jar:5.3.14]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter
(ApplicationFilterChain.java:189) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationFilterChain.doFilter
(ApplicationFilterChain.java:162) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.springframework.web.filter.OncePerRequestFilter.doFilter
(OncePerRequestFilter.java:102) ~[spring-web-5.3.14.jar:5.3.14]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter
(ApplicationFilterChain.java:189) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationFilterChain.doFilter
(ApplicationFilterChain.java:162) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationDispatcher.invoke
(ApplicationDispatcher.java:711) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationDispatcher.processRequest
(ApplicationDispatcher.java:461) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationDispatcher.doForward
(ApplicationDispatcher.java:385) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationDispatcher.forward
(ApplicationDispatcher.java:313) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.StandardHostValve.custom
(StandardHostValve.java:403) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.StandardHostValve.status
(StandardHostValve.java:249) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
[tomcat-embed-core-9.0.56.jar:9.0.56]
at
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run
(TaskThread.java:61) ~
[tomcat-embed-core-9.0.56.jar:9.0.56]
at java.base/java.lang.Thread.run(Thread.java:834) ~[na:na]
2022-01-14 00:49:13.289 DEBUG 21332 --- [nio-8088-exec-2]
w.c.HttpSessionSecurityContextRepository : Did not store anonymous
SecurityContext
2022-01-14 00:49:13.289 DEBUG 21332 --- [nio-8088-exec-2]
w.c.HttpSessionSecurityContextRepository : Did not store anonymous
SecurityContext
2022-01-14 00:49:13.289 DEBUG 21332 --- [nio-8088-exec-2]
s.s.w.c.SecurityContextPersistenceFilter : Cleared
SecurityContextHolder to complete request
Your logs say this:
2022-01-14 14:49:52.305 WARN 24600 --- [nio-8088-exec-2] c.k.b.s.serviceImpl.UserSecurityService :
Username { "username": "seeshee", "password": "12345" } not found
If we look in your code we can see the following line:
login(#RequestBody String username, String password )
This is your faulty code line, as it doesn't do what you think it does. You think it will take the json and extract the two parameters username and password and set these. But what it actually does is that the #RequestBody will take the entire body (the json) and set it to the parameter that is defined on, which is username.
So what spring is doing is that it will extract the entire json body and place it into the username string.
Then you try to use that to login, and then you get the error message posted above.
What you need to do is to create a holder class that spring can deserialize into.
public class RequestBody {
public RequestBody(String username, String password) {
this.username = username;
this.password = password;
}
// getters, setters
}
#PostMapping("/login")
public ResponseEntity<String> login(#RequestBody RequestBody requestBody ) throws Exception {
Authentication authentication = authenticationManager.authenticate(new
UsernamePasswordAuthenticationToken(
requestBody.getUsername(), requestBody.getPassword()
));
SecurityContextHolder.getContext().setAuthentication(authentication);
return new ResponseEntity<>("User signed -in succesfully", HttpStatus.OK);
}
You can read about how to use requestbody here:
Spring’s RequestBody and ResponseBody Annotation
I am trying to fetch data from database in my spring boot application. I am using hibernate libraries. Below is my entity class:
#SuppressWarnings("serial")
#Entity
#Table(name = "MU_GM_CIRCULARS")
public class GmCirculars extends ParentEntity implements Serializable {
private BigDecimal id;
private Date createdOn;
private String title;
private BigDecimal serialNo;
private BigDecimal year;
private BigDecimal active;
private BigDecimal organizationId;
private BigDecimal showOnDashboard;
public GmCirculars() {
super();
}
public GmCirculars(BigDecimal id) {
super();
this.id = id;
}
public GmCirculars(BigDecimal id, BigDecimal createdById, Date createdOn, String title, BigDecimal serialNo,
BigDecimal year ,BigDecimal documentId, BigDecimal typeId) {
super();
this.id = id;
this.createdOn = createdOn;
this.title = title;
this.serialNo = serialNo;
this.year = year;
}
#Id
#Column(name = "ID")
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="MU_GM_CIRCULARS_SEQ")
#SequenceGenerator(name="MU_GM_CIRCULARS_SEQ",sequenceName="MU_GM_CIRCULARS_SEQ",allocationSize=1)
public BigDecimal getId() {
return id;
}
public void setId(BigDecimal id) {
this.id = id;
}
#Column(name="created_on")
public Date getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Date createdOn) {
this.createdOn = createdOn;
}
#Column(name="title")
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Column(name="serial_no")
public BigDecimal getSerialNo() {
return serialNo;
}
public void setSerialNo(BigDecimal serialNo) {
this.serialNo = serialNo;
}
#Column(name="year")
public BigDecimal getYear() {
return year;
}
public void setYear(BigDecimal year) {
this.year = year;
}
#Column(name = "org_id")
public BigDecimal getOrganizationId() {
return organizationId;
}
public void setOrganizationId(BigDecimal organizationId) {
this.organizationId = organizationId;
}
#Column(name="show_on_dashboard")
public BigDecimal getShowOnDashboard() {
return showOnDashboard;
}
public void setShowOnDashboard(BigDecimal showOnDashboard) {
this.showOnDashboard = showOnDashboard;
}
#Column(name = "active")
public BigDecimal isActive() {
return active;
}
public void setActive(BigDecimal active) {
this.active = active;
}
}
Here's the class with the method that fetches the data:
#Repository
#Transactional
#SuppressWarnings("unchecked")
public class GmCircularsDaoImpl extends ParentDAO implements IGmCircularsDAO {
#Override
public List<GmCirculars> find(GmCirculars obj, boolean activeOnly, int startOffset, int maxRows) {
Session session = null;
List<GmCirculars> discounts = null;
try {
if (null != obj) {
session= this.getSession();
Criteria criteria = session.createCriteria(GmCirculars.class);
if (null != obj.getId() && !BigDecimal.ZERO.equals(obj.getId())) {
criteria.add(Restrictions.eq("id", obj.getId()));
}
if (StringUtil.isNotNullOrEmpty(obj.getTitle())) {
criteria.add(Restrictions.ilike("title", obj.getTitle(), MatchMode.ANYWHERE));
}
if(null != obj.getOrganizationId()) {
criteria.add(Restrictions.eq("organizationId", obj.getOrganizationId()));
}
if (null != obj.getSerialNo() && !BigDecimal.ZERO.equals(obj.getSerialNo())) {
criteria.add(Restrictions.eq("serialNo", obj.getSerialNo()));
}
if (null != obj.getYear() && !BigDecimal.ZERO.equals(obj.getYear())) {
criteria.add(Restrictions.eq("year", obj.getYear()));
}
if (activeOnly) {
criteria.add(Restrictions.eq("active", BigDecimal.ONE));
} else {
criteria.add(Restrictions.or(Restrictions.ne("active", CommonConstants.DELETED_STATUS), Restrictions.isNull("active"))); //Except for deleted ones -> NVL(active,2)
}
criteria.setFirstResult(startOffset);
criteria.setMaxResults(maxRows);
criteria.addOrder(Order.desc("id"));
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
System.out.println("criteria: "+ criteria.toString());
discounts = criteria.list();
System.out.println("returned list from db:"+discounts);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
session.close();
}
return discounts;
}
I try to access the database exactly on the line:
discounts = criteria.list();
which is in the method find(GmCirculars obj, boolean activeOnly, int startOffset, int maxRows)
When I run my code, I am getting the following errors.
java.sql.SQLSyntaxErrorException: ORA-00942: table or view does not exist
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:447) ~[ojdbc6-11.1.0.6.0.jar:11.2.0.4.0]
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:396) ~[ojdbc6-11.1.0.6.0.jar:11.2.0.4.0]
at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:951) ~[ojdbc6-11.1.0.6.0.jar:11.2.0.4.0]
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:513) ~[ojdbc6-11.1.0.6.0.jar:11.2.0.4.0]
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:227) ~[ojdbc6-11.1.0.6.0.jar:11.2.0.4.0]
at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:531) ~[ojdbc6-11.1.0.6.0.jar:11.2.0.4.0]
at oracle.jdbc.driver.T4CStatement.doOall8(T4CStatement.java:195) ~[ojdbc6-11.1.0.6.0.jar:11.2.0.4.0]
at oracle.jdbc.driver.T4CStatement.executeForDescribe(T4CStatement.java:876)
~[ojdbc6-11.1.0.6.0.jar:11.2.0.4.0]
at oracle.jdbc.driver.OracleStatement.executeMaybeDescribe(OracleStatement.java:1175)
~[ojdbc6-11.1.0.6.0.jar:11.2.0.4.0]
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1296)
~[ojdbc6-11.1.0.6.0.jar:11.2.0.4.0]
at oracle.jdbc.driver.OracleStatement.executeQuery(OracleStatement.java:1498)
~[ojdbc6-11.1.0.6.0.jar:11.2.0.4.0]
at oracle.jdbc.driver.OracleStatementWrapper.executeQuery(OracleStatementWrapper.java:406)
~[ojdbc6-11.1.0.6.0.jar:11.2.0.4.0]
at org.apache.commons.dbcp.DelegatingStatement.executeQuery(DelegatingStatement.java:208)
~[commons-dbcp-1.4.jar:1.4]
at org.hibernate.tool.schema.extract.internal.SequenceInformationExtractorLegacyImpl.extractMetadata(SequenceInformationExtractorLegacyImpl.java:42)
~[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentImpl.sequenceInformationList(JdbcEnvironmentImpl.java:403)
[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentImpl.(JdbcEnvironmentImpl.java:268)
[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:114)
[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35)
[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:101)
[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:263)
[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237)
[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214)
[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory.injectServices(DefaultIdentifierGeneratorFactory.java:152)
[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.injectDependencies(AbstractServiceRegistryImpl.java:286)
[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:243)
[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214)
[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.(InFlightMetadataCollectorImpl.java:175)
[hibernate-core-5.4.10.Final.jar:5.4.10.Final]
................................................................................
2020-02-03 09:16:11.269 INFO 9952 --- [ restartedMain] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-02-03 09:16:11.281 INFO 9952 --- [ restartedMain] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-02-03 09:16:11.299 INFO 9952 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2020-02-03 09:16:11.367 WARN 9952 --- [ restartedMain] c.n.c.sources.URLConfigurationSource : No URLs will be polled as dynamic configuration sources.
2020-02-03 09:16:11.368 INFO 9952 --- [ restartedMain] c.n.c.sources.URLConfigurationSource : To enable URLs as dynamic configuration sources, define System property archaius.configurationSource.additionalUrls or make config.properties available on classpath.
2020-02-03 09:16:11.470 WARN 9952 --- [ restartedMain] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2020-02-03 09:16:11.646 INFO 9952 --- [ restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-02-03 09:16:12.754 WARN 9952 --- [ restartedMain] ockingLoadBalancerClientRibbonWarnLogger : You already have RibbonLoadBalancerClient on your classpath. It will be used by default. As Spring Cloud Ribbon is in maintenance mode. We recommend switching to BlockingLoadBalancerClient instead. In order to use it, set the value of spring.cloud.loadbalancer.ribbon.enabled to false or remove spring-cloud-starter-netflix-ribbon from your project.
2020-02-03 09:16:12.794 INFO 9952 --- [ restartedMain] o.s.b.a.e.web.EndpointLinksResolver : Exposing 2 endpoint(s) beneath base path '/actuator'
2020-02-03 09:16:12.846 INFO 9952 --- [ restartedMain] o.s.c.n.eureka.InstanceInfoFactory : Setting initial instance status as: STARTING
2020-02-03 09:16:12.900 INFO 9952 --- [ restartedMain] com.netflix.discovery.DiscoveryClient : Initializing Eureka in region us-east-1
2020-02-03 09:16:13.231 INFO 9952 --- [ restartedMain] c.n.d.provider.DiscoveryJerseyProvider : Using JSON encoding codec LegacyJacksonJson
2020-02-03 09:16:13.231 INFO 9952 --- [ restartedMain] c.n.d.provider.DiscoveryJerseyProvider : Using JSON decoding codec LegacyJacksonJson
2020-02-03 09:16:13.385 INFO 9952 --- [ restartedMain] c.n.d.provider.DiscoveryJerseyProvider : Using XML encoding codec XStreamXml
2020-02-03 09:16:13.385 INFO 9952 --- [ restartedMain] c.n.d.provider.DiscoveryJerseyProvider : Using XML decoding codec XStreamXml
2020-02-03 09:16:13.586 INFO 9952 --- [ restartedMain] c.n.d.s.r.aws.ConfigClusterResolver : Resolving eureka endpoints via configuration
2020-02-03 09:16:13.751 INFO 9952 --- [ restartedMain] com.netflix.discovery.DiscoveryClient : Disable delta property : false
2020-02-03 09:16:13.751 INFO 9952 --- [ restartedMain] com.netflix.discovery.DiscoveryClient : Single vip registry refresh property : null
2020-02-03 09:16:13.751 INFO 9952 --- [ restartedMain] com.netflix.discovery.DiscoveryClient : Force full registry fetch : false
2020-02-03 09:16:13.751 INFO 9952 --- [ restartedMain] com.netflix.discovery.DiscoveryClient : Application is null : false
2020-02-03 09:16:13.751 INFO 9952 --- [ restartedMain] com.netflix.discovery.DiscoveryClient : Registered Applications size is zero : true
2020-02-03 09:16:13.751 INFO 9952 --- [ restartedMain] com.netflix.discovery.DiscoveryClient : Application version is -1: true
2020-02-03 09:16:13.751 INFO 9952 --- [ restartedMain] com.netflix.discovery.DiscoveryClient : Getting all instance registry info from the eureka server
2020-02-03 09:16:13.932 INFO 9952 --- [ restartedMain] com.netflix.discovery.DiscoveryClient : The response status is 200
2020-02-03 09:16:13.935 INFO 9952 --- [ restartedMain] com.netflix.discovery.DiscoveryClient : Starting heartbeat executor: renew interval is: 30
2020-02-03 09:16:13.937 INFO 9952 --- [ restartedMain] c.n.discovery.InstanceInfoReplicator : InstanceInfoReplicator onDemand update allowed rate per min is 4
2020-02-03 09:16:13.940 INFO 9952 --- [ restartedMain] com.netflix.discovery.DiscoveryClient : Discovery Client initialized at timestamp 1580706973939 with initial instances count: 1
2020-02-03 09:16:13.943 INFO 9952 --- [ restartedMain] o.s.c.n.e.s.EurekaServiceRegistry : Registering application CIRCULARS-MICROSERVICE with eureka with status UP
2020-02-03 09:16:13.944 INFO 9952 --- [ restartedMain] com.netflix.discovery.DiscoveryClient : Saw local status change event StatusChangeEvent [timestamp=1580706973943, current=UP, previous=STARTING]
2020-02-03 09:16:13.947 INFO 9952 --- [nfoReplicator-0] com.netflix.discovery.DiscoveryClient :
DiscoveryClient_CIRCULARS-MICROSERVICE/HQTPM00184606D.ADM.local:circulars-microservice:8081: registering service...
2020-02-03 09:16:14.002 INFO 9952 --- [nfoReplicator-0] com.netflix.discovery.DiscoveryClient :
DiscoveryClient_CIRCULARS-MICROSERVICE/HQTPM00184606D.ADM.local:circulars-microservice:8081 - registration status: 204
2020-02-03 09:16:14.029 INFO 9952 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8081 (http) with context path ''
2020-02-03 09:16:14.031 INFO 9952 --- [ restartedMain] .s.c.n.e.s.EurekaAutoServiceRegistration : Updating port to 8081
2020-02-03 09:16:14.266 INFO 9952 --- [ restartedMain] ae.gov.adm.CircularsMicroservice : Started
CircularsMicroservice in 10.925 seconds (JVM running for 11.768) done
2020-02-03 09:16:19.478 INFO 9952 --- [nio-8081-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-02-03 09:16:19.479 INFO 9952 --- [nio-8081-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2020-02-03 09:16:19.498 INFO 9952 --- [nio-8081-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in
18 ms
Circular Microservice called.....Params are:1, false, 0
entity manager instantiated...
2020-02-03 09:16:19.829 WARN 9952 --- [nio-8081-exec-1] org.hibernate.orm.deprecation : HHH90000022: Hibernate's
legacy org.hibernate.Criteria API is deprecated; use the JPA
javax.persistence.criteria.CriteriaQuery instead
criteria: CriteriaImpl(ae.gov.adm.saeed.hibernate.entity.GmCirculars:this[][organizationId=1, active<>2 or active is null])
2020-02-03 09:16:19.973 WARN 9952 --- [nio-8081-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 923, SQLState:
42000
2020-02-03 09:16:19.973 ERROR 9952 --- [nio-8081-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : ORA-00923: FROM keyword not
found where expected
org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:63)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:113)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:99)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:67)
at org.hibernate.loader.Loader.getResultSet(Loader.java:2292)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:2050)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:2012)
at org.hibernate.loader.Loader.doQuery(Loader.java:953)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:354)
at org.hibernate.loader.Loader.doList(Loader.java:2815)
at org.hibernate.loader.Loader.doList(Loader.java:2797)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2629)
at org.hibernate.loader.Loader.list(Loader.java:2624)
at org.hibernate.loader.criteria.CriteriaLoader.list(CriteriaLoader.java:109)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1859)
at org.hibernate.internal.CriteriaImpl.list(CriteriaImpl.java:370)
at ae.gov.adm.saeed.dao.impl.GmCircularsDaoImpl.find(GmCircularsDaoImpl.java:111)
at ae.gov.adm.saeed.dao.impl.GmCircularsDaoImpl$$FastClassBySpringCGLIB$$464553b0.invoke()
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:769)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:747)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:747)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:366)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:99)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:747)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:689)
at ae.gov.adm.saeed.dao.impl.GmCircularsDaoImpl$$EnhancerBySpringCGLIB$$aedf9fbb.find()
at ae.gov.adm.saeed.service.CircularsService.fetchAllCircularsForOrganization(CircularsService.java:66)
at ae.gov.adm.CircularsMicroservice.getAllCircularsForOrganization(CircularsMicroservice.java:54)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:888)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:523)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:590)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:108)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:367)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:860)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1598)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.sql.SQLSyntaxErrorException: ORA-00923: FROM keyword not found where expected
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:447)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:396)
at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:951)
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:513)
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:227)
at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:531)
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:208)
at oracle.jdbc.driver.T4CPreparedStatement.executeForDescribe(T4CPreparedStatement.java:886)
at oracle.jdbc.driver.OracleStatement.executeMaybeDescribe(OracleStatement.java:1175)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1296)
at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3613)
at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:3657)
at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeQuery(OraclePreparedStatementWrapper.java:1495)
at org.apache.commons.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:96)
at org.apache.commons.dbcp.DelegatingPreparedStatement.executeQuery(DelegatingPreparedStatement.java:96)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:57)
... 83 more
try to check if the table "MU_GM_CIRCULARS" exists in the database (probably yes) and whether you have access to it (probably not).
Connect the database using the credentials your code is using. Try the following
select * from dba_tables where table_name = 'MU_GM_CIRCULARS';
If there are any records, it means table exists in the system.
Next try this
select * from all_tables where table_name = 'MU_GM_CIRCULARS';
This will show if user has access to the table. If the table appears to be in the result, then check the "owner" column and try to reach the table using the following format
select * from owner.table_name
Hope this will help
It is a configuration issue of the database. I was adding a config.xml file, which is NOT needed in Spring Boot. Rather, I added these values to my application.properties file, and then everything worked fine.
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:#xxxxxxxxxxx
spring.datasource.username=xxxxx
spring.datasource.password=xxxxx
I am implementing global error handling in my project using Spring boot. I am throwing a "ResourceNotFoundException" when my "Customer" object is "null". But the Spring exception handler is not catching it.
My RestController class:
#RestController
#Path("/customer")
public class CustomerEndpoint {
private static final Logger LOGGER = LoggerFactory.getLogger(CustomerEndpoint.class);
#Autowired
private ICustomerService customerService;
#GET
#Path("/{id}")
#Produces(MediaType.APPLICATION_JSON)
public Response getCustomerById(#PathParam("id") Integer id) throws ResourceNotFoundException {
CustomerVO article = customerService.getCustomerById(id);
if (article == null) {
throw new ResourceNotFoundException(customerId, "Customer not found");
}
return Response.ok(article).build();
}
}
My ExceptionHandler:
#ControllerAdvice
public class GlobalExceptionHandlerController extends ResponseEntityExceptionHandler {
#ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<ExceptionResponse> resourceNotFound(ResourceNotFoundException ex) {
ExceptionResponse response = new ExceptionResponse();
response.setErrorCode("resource not found");
response.setErrorMessage(ex.getMessage());
return new ResponseEntity<>(response, HttpStatus.NOT_FOUND);
}
}
ExceptionResponse:
public class ExceptionResponse {
private String errorCode;
private String errorMessage;
public ExceptionResponse() {
}
public String getErrorCode() {
return errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}
ResourceNotFoundException class:
public class ResourceNotFoundException extends RuntimeException{
private long resourceId;
private String message;
public ResourceNotFoundException(long resourceId, String message) {
super(message);
this.resourceId = resourceId;
this.message = message;
}
public ResourceNotFoundException(String message) {
super(message);
this.message = message;
}
#Override
public String getMessage() {
return message;
}
}
Please observe the RestController class. When I get a request for a customer with an id , if the customer is not present it throws ResourceNotFound exception. By default this needs to be catched by the ExceptionHandler. But instead of this I am getting the stackTrace like following. Please help me in catching this exception globally.
com.finsol.qunatotrade.exception.ResourceNotFoundException: Customer not found
at com.finsol.qunatotrade.service.CustomerService.getCustomerById(CustomerService.java:50) ~[classes/:na]
at com.finsol.qunatotrade.service.CustomerService$$FastClassBySpringCGLIB$$5c04d986.invoke(<generated>) ~[classes/:na]
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) ~[spring-core-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:738) ~[spring-aop-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) ~[spring-aop-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99) ~[spring-tx-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282) ~[spring-tx-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) ~[spring-tx-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:673) ~[spring-aop-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at com.finsol.qunatotrade.service.CustomerService$$EnhancerBySpringCGLIB$$ddc81d1f.getCustomerById(<generated>) ~[classes/:na]
at com.finsol.qunatotrade.api.endpoint.CustomerEndpoint.getCustomerById(CustomerEndpoint.java:50) ~[classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_144]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_144]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_144]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_144]
at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81) ~[jersey-server-2.25.1.jar:na]
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:144) ~[jersey-server-2.25.1.jar:na]
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:161) ~[jersey-server-2.25.1.jar:na]
at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:160) ~[jersey-server-2.25.1.jar:na]
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:99) ~[jersey-server-2.25.1.jar:na]
at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:389) ~[jersey-server-2.25.1.jar:na]
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:347) ~[jersey-server-2.25.1.jar:na]
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:102) ~[jersey-server-2.25.1.jar:na]
at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:326) ~[jersey-server-2.25.1.jar:na]
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271) ~[jersey-common-2.25.1.jar:na]
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267) ~[jersey-common-2.25.1.jar:na]
at org.glassfish.jersey.internal.Errors.process(Errors.java:315) ~[jersey-common-2.25.1.jar:na]
at org.glassfish.jersey.internal.Errors.process(Errors.java:297) ~[jersey-common-2.25.1.jar:na]
at org.glassfish.jersey.internal.Errors.process(Errors.java:267) ~[jersey-common-2.25.1.jar:na]
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317) ~[jersey-common-2.25.1.jar:na]
at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:305) ~[jersey-server-2.25.1.jar:na]
at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154) ~[jersey-server-2.25.1.jar:na]
at org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:473) ~[jersey-container-servlet-core-2.25.1.jar:na]
at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:427) ~[jersey-container-servlet-core-2.25.1.jar:na]
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:388) ~[jersey-container-servlet-core-2.25.1.jar:na]
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:341) ~[jersey-container-servlet-core-2.25.1.jar:na]
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:228) ~[jersey-container-servlet-core-2.25.1.jar:na]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ~[tomcat-embed-websocket-8.5.23.jar:8.5.23]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:108) ~[spring-web-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81) ~[spring-web-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) ~[spring-web-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) ~[spring-web-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
at com.finsol.qunatotrade.api.filter.CORSFilter.doFilter(CORSFilter.java:34) ~[classes/:na]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199) ~[tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459) [tomcat-embed-core-8.5.23.jar:8.5.23]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-8.5.23.jar:8.5.23]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_144]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_144]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.5.23.jar:8.5.23]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_144]
2018-01-29 17:37:20.264 DEBUG 2304 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing servlet 'dispatcherServlet'
2018-01-29 17:37:20.265 INFO 2304 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring FrameworkServlet 'dispatcherServlet'
2018-01-29 17:37:20.266 INFO 2304 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started
2018-01-29 17:37:20.266 DEBUG 2304 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Using MultipartResolver [org.springframework.web.multipart.support.StandardServletMultipartResolver#13ba49b5]
2018-01-29 17:37:20.274 DEBUG 2304 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Unable to locate LocaleResolver with name 'localeResolver': using default [org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver#18ee3eeb]
2018-01-29 17:37:20.280 DEBUG 2304 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Unable to locate ThemeResolver with name 'themeResolver': using default [org.springframework.web.servlet.theme.FixedThemeResolver#583d7e84]
2018-01-29 17:37:20.289 DEBUG 2304 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Unable to locate RequestToViewNameTranslator with name 'viewNameTranslator': using default [org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator#6611f464]
2018-01-29 17:37:20.303 DEBUG 2304 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Unable to locate FlashMapManager with name 'flashMapManager': using default [org.springframework.web.servlet.support.SessionFlashMapManager#29de5bb4]
2018-01-29 17:37:20.303 DEBUG 2304 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Published WebApplicationContext of servlet 'dispatcherServlet' as ServletContext attribute with name [org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcherServlet]
2018-01-29 17:37:20.303 INFO 2304 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 37 ms
2018-01-29 17:37:20.303 DEBUG 2304 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Servlet 'dispatcherServlet' configured successfully
2018-01-29 17:37:20.305 DEBUG 2304 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/error]
2018-01-29 17:37:20.310 DEBUG 2304 --- [nio-8080-exec-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /error
2018-01-29 17:37:20.330 DEBUG 2304 --- [nio-8080-exec-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Returning handler method [public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)]
2018-01-29 17:37:20.331 DEBUG 2304 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Last-Modified value for [/error] is: -1
2018-01-29 17:37:20.451 DEBUG 2304 --- [nio-8080-exec-1] o.s.w.s.m.m.a.HttpEntityMethodProcessor : Written [{timestamp=Mon Jan 29 17:37:20 IST 2018, status=500, error=Internal Server Error, exception=com.finsol.qunatotrade.exception.ResourceNotFoundException, message=Customer not found, path=/qtregistration/customer/1}] as "application/json" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter#6344227]
2018-01-29 17:37:20.452 DEBUG 2304 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
2018-01-29 17:37:20.452 DEBUG 2304 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Successfully completed request
enter code here
As already mentioned, #ControllerAdvice cannot be used for Jersey. You can use ExceptionMapper with the annotation #Provider that maps Java exceptions to Jersey response.
The ExceptionHandler:
#Provider
public class GlobalExceptionHandlerController implements ExceptionMapper<ResourceNotFoundException> {
#Override
public Response toResponse(ResourceNotFoundException e) {
ExceptionResponse response = new ExceptionResponse();
response.setErrorCode("resource not found");
response.setErrorMessage(e.getMessage());
return Response.status(404).entity(response)
.type("application/json").build();
}
}
Don't forget to register this GlobalExceptionHandlerController just like your CustomerEndpoint:
#Configuration
public class JerseyConfig extends ResourceConfig {
public JerseyConfig() {
register(GlobalExceptionHandlerController.class);
register(CustomerEndpoint.class); // your existing controller
}
}
It seems that GlobalExceptionHandlerController is NOT visible to spring. See how are doing it for service classes. If GlobalExceptionHandlerController is under a package which is getting scanned alright, then you could try this code instead:
#Provider
public class ErrorResponseHandler implements ExceptionMapper<Throwable>{
private static final Logger logger = LoggerFactory.getLogger(ErrorResponseHandler.class);
#Override
public Response toResponse(Throwable error) {
if (error instanceof ResourceNotFoundException) {
....
....
}
else if (error instanceof JsonProcessingException) {
logger.error("Could not interpret incoming request", error);
return Response.status(Response.Status.BAD_REQUEST).entity(error.getMessage()).build();
}
else{
return response;
}
}
}
I'm trying to make my application thread safe, so I have:
companyManagment.deleteQuestionToQuestionnaire(questions_assigned_to_questionnaires_id);
#Override
#Transactional
public synchronized void deleteQuestionToQuestionnaire(Long questions_assigned_to_questionnaires_id) {
String methodname = " " + Thread.currentThread().getName() + " deleteQuestionToQuestionnaire ";
logger.info(methodname + " questions_assigned_to_questionnaires_id["+ (questions_assigned_to_questionnaires_id!=null?questions_assigned_to_questionnaires_id.toString():null) +"]");
QuestionsAssignedToQuestionnaires questionsAssignedToQuestionnairesInDatabase = getQuestionsAssignedToQuestionnaires(questions_assigned_to_questionnaires_id);
if(questionsAssignedToQuestionnairesInDatabase != null) {
logger.info(methodname + " questionsAssignedToQuestionnairesInDatabase != null");
questionsAssignedToQuestionnairesRepository.delete(questions_assigned_to_questionnaires_id);
} else {
logger.info(methodname + " questionsAssignedToQuestionnairesInDatabase == null");
}
}
I have Mysql on my local server. When 2 requests sent to the server, I put a break point on the fist line in the deleteQuestionToQuestionnaire() method. The problem is that JPA does not see that the row has been deleted.
I'm using a link to pass up the information I want to delete so it's easy for me to click that a few times. Could this be the problem?
Anyway, I have the logs:
2016-01-10 10:44:19.667 INFO 9880 --- [nio-8080-exec-8] data.service.CompanyManagmentImpl : http-nio-8080-exec-8 deleteQuestionToQuestionnaire questions_assigned_to_questionnaires_id[56]
2016-01-10 10:44:19.669 INFO 9880 --- [nio-8080-exec-8] data.service.CompanyManagmentImpl : http-nio-8080-exec-8 deleteQuestionToQuestionnaire questionsAssignedToQuestionnairesInDatabase != null
2016-01-10 10:44:19.688 INFO 9880 --- [nio-8080-exec-5] data.service.CompanyManagmentImpl : http-nio-8080-exec-5 deleteQuestionToQuestionnaire questions_assigned_to_questionnaires_id[56]
2016-01-10 10:44:19.689 INFO 9880 --- [nio-8080-exec-5] data.service.CompanyManagmentImpl : http-nio-8080-exec-5 deleteQuestionToQuestionnaire questionsAssignedToQuestionnairesInDatabase != null
2016-01-10 10:44:19.691 INFO 9880 --- [nio-8080-exec-4] data.service.CompanyManagmentImpl : http-nio-8080-exec-4 deleteQuestionToQuestionnaire questions_assigned_to_questionnaires_id[56]
2016-01-10 10:44:19.697 INFO 9880 --- [nio-8080-exec-4] data.service.CompanyManagmentImpl : http-nio-8080-exec-4 deleteQuestionToQuestionnaire questionsAssignedToQuestionnairesInDatabase != null
2016-01-10 10:44:19.735 INFO 9880 --- [nio-8080-exec-3] data.service.CompanyManagmentImpl : http-nio-8080-exec-3 deleteQuestionToQuestionnaire questions_assigned_to_questionnaires_id[56]
2016-01-10 10:44:19.764 INFO 9880 --- [nio-8080-exec-4] o.h.e.j.b.internal.AbstractBatchImpl : HHH000010: On release of batch it still contained JDBC statements
2016-01-10 10:44:19.811 INFO 9880 --- [nio-8080-exec-5] tAssignedQuestionsToQuestionnaireWrapper : Removing QuestionDraw[3] from mapAllQuestionDrawsForCompany
2016-01-10 10:44:19.812 INFO 9880 --- [nio-8080-exec-8] o.h.e.j.b.internal.AbstractBatchImpl : HHH000010: On release of batch it still contained JDBC statements
2016-01-10 10:44:19.839 INFO 9880 --- [nio-8080-exec-3] data.service.CompanyManagmentImpl : http-nio-8080-exec-3 deleteQuestionToQuestionnaire questionsAssignedToQuestionnairesInDatabase != null
2016-01-10 10:44:19.846 INFO 9880 --- [nio-8080-exec-5] tAssignedQuestionsToQuestionnaireWrapper : Removing QuestionYesNo[5] from mapAllQuestionYesNosForCompany
2016-01-10 10:44:19.860 INFO 9880 --- [nio-8080-exec-3] o.h.e.j.b.internal.AbstractBatchImpl : HHH000010: On release of batch it still contained JDBC statements
2016-01-10 10:44:19.889 ERROR 9880 --- [nio-8080-exec-8] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.orm.ObjectOpt
imisticLockingFailureException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1; nested exception is org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected:
1] with root cause
org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
at org.hibernate.jdbc.Expectations$BasicExpectation.checkBatched(Expectations.java:81)
at org.hibernate.jdbc.Expectations$BasicExpectation.verifyOutcome(Expectations.java:73)
at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:63)
at org.hibernate.persister.entity.AbstractEntityPersister.delete(AbstractEntityPersister.java:3400)
at org.hibernate.persister.entity.AbstractEntityPersister.delete(AbstractEntityPersister.java:3630)
at org.hibernate.action.internal.EntityDeleteAction.execute(EntityDeleteAction.java:114)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:465)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:351)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:350)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:56)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1258)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:425)
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:177)
at org.hibernate.jpa.internal.TransactionImpl.commit(TransactionImpl.java:77)
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:517)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:757)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:726)
at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:521)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:291)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy93.deleteQuestionToQuestionnaire(Unknown Source)
at controler.CompanyAdminController.assignQuestionsToQuestionnaire(CompanyAdminController.java:1478)
at controler.CompanyAdminController$$FastClassBySpringCGLIB$$b1a0a1d2.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:717)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:68)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:653)
at controler.CompanyAdminController$$EnhancerBySpringCGLIB$$3e616d1e.assignQuestionsToQuestionnaire(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
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)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:858)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:316)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:126)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:90)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:122)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:168)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:48)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilterInternal(BasicAuthenticationFilter.java:158)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:205)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:120)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:91)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:53)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:213)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:176)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:85)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1521)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1478)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
2016-01-10 10:44:19.894 ERROR 9880 --- [nio-8080-exec-3] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.orm.ObjectOpt
imisticLockingFailureException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1; nested exception is org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected:
1] with root cause