I need to make a POST request to /user/auth with 'username' and 'password' json body to retrieve user auth from spring security endpoint.
I have a thymeleaf login form. it sends 'username' and 'password' to my custom authentication filter endpoint.
The endpoint is being triggered, but the object it receives is null.
I'm able to use postman to send a json body to the endpoint and i can login with success, but when using the thymeleaf form, the object i send is null.
Something I've tried:
using a pre-auth endpoint to intercept the request and processes the thymeleaf object into json.
I think I'm missing the mark on how to use the RestTemplate, though.
#PostMapping(value = "/preauth", produces = "application/json")
#ResponseBody
public UserDto preAuth(#ModelAttribute LoginRequestModel loginRequestModel) {
log.info("username to test: {}", loginRequestModel.getUsername());
log.info("password to test: {}", loginRequestModel.getPassword());
// ^^ these are coming back correct ^^
JSONObject jsonObject = new JSONObject();
jsonObject.put("username", loginRequestModel.getUsername());
jsonObject.put("password", loginRequestModel.getPassword());
jsonObject.toMap().forEach((s, o) -> System.out.println(s + " : " + o));
// ^^ this also comes back correct ^^
// dont understand how to get this JSONObject inserted into the Rest Template
RestTemplate restTemplate = new RestTemplate(jsonObject);
restTemplate.exchange("http://localhost:8080/user/auth", loginRequestModel, LoginRequestModel.class);
return userInfo;
}
<form action="#" method="POST" th:action="#{/user/auth/preauth}" th:object="${loginRequestModel}">
<p>Username: <input th:field="*{username}" type="text"/></p>
<p>Password: <input th:field="*{password}" type="text"/></p>
<p><input type="submit" value="Submit"/> <input type="reset" value="Reset"/></p>
public class AuthenticationFilter extends UsernamePasswordAuthenticationFilter {
#Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
log.info("attempting to authenticate user");
try {
log.info("trying to map object");
LoginRequestModel creds = new ObjectMapper()
.readValue(request.getInputStream(), LoginRequestModel.class);
return getAuthenticationManager().authenticate(
new UsernamePasswordAuthenticationToken(
creds.getUsername(),
creds.getPassword(),
new ArrayList<>()
)
);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
for whatever reason, the request.getInputStream() is returning as null when i try to call it directly from thymeleaf form in the browser.
[http-nio-8080-exec-3] DEBUG o.s.s.w.FilterChainProxy - /user/auth?username=admin&password=admin at position 5 of 12 in additional filter chain; firing Filter: 'AuthenticationFilter'
[http-nio-8080-exec-3] DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/user/auth'; against '/user/auth'
[http-nio-8080-exec-3] DEBUG t.j.w.j.a.s.AuthenticationFilter - Request is to process authentication
[http-nio-8080-exec-3] INFO t.j.w.j.a.s.AuthenticationFilter - attempting to authenticate user
[http-nio-8080-exec-3] INFO t.j.w.j.a.s.AuthenticationFilter - trying to map object
[http-nio-8080-exec-3] INFO t.j.w.j.a.s.AuthenticationFilter - the exception was caught!
[http-nio-8080-exec-3] INFO t.j.w.j.a.s.AuthenticationFilter - the headers::
[http-nio-8080-exec-3] INFO t.j.w.j.a.s.AuthenticationFilter - null
[http-nio-8080-exec-3] INFO t.j.w.j.a.s.AuthenticationFilter - null
[http-nio-8080-exec-3] DEBUG o.s.s.w.h.w.HstsHeaderWriter - Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher#46b257b6
[http-nio-8080-exec-3] DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
[http-nio-8080-exec-3] DEBUG o.s.s.w.c.SecurityContextPersistenceFilter - SecurityContextHolder now cleared, as request processing completed
[http-nio-8080-exec-3] ERROR o.a.c.c.C.[.[.[.[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception
java.lang.RuntimeException: com.fasterxml.jackson.databind.exc.MismatchedInputException: No content to map due to end-of-input
at [Source: (org.apache.catalina.connector.CoyoteInputStream); line: 1, column: 0]
at tech.jdevmin.web.jdevminweb.app.security.AuthenticationFilter.attemptAuthentication(AuthenticationFilter.java:72)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:212)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:92)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:77)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:358)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:271)
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.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:94)
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:526)
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:408)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:860)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1589)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: com.fasterxml.jackson.databind.exc.MismatchedInputException: No content to map due to end-of-input
at [Source: (org.apache.catalina.connector.CoyoteInputStream); line: 1, column: 0]
at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:59)
at com.fasterxml.jackson.databind.ObjectMapper._initForReading(ObjectMapper.java:4146)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4001)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3071)
at tech.jdevmin.web.jdevminweb.app.security.AuthenticationFilter.attemptAuthentication(AuthenticationFilter.java:49)
... 51 common frames omitted
I think you should get the userName and password as below when you are using UsernamePasswordAuthenticationToken
#Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException {
// TODO Auto-generated method stub
request.getSession().setMaxInactiveInterval(sessionTimeout);
CustomUsernamePasswordAuthenticationToken authRequest = getAuthRequest(request);
_log.info("");
setDetails(request, authRequest);
return this.getAuthenticationManager().authenticate(authRequest);
}
private CustomUsernamePasswordAuthenticationToken getAuthRequest(HttpServletRequest request) {
String username = obtainUsername(request);
String password = obtainPassword(request);
_log.info("UserName IN Filter : "+username);
_log.info("UserName IN Filter : "+password);
return new CustomUsernamePasswordAuthenticationToken(username, password);
}
I fixed it! just had to send the thymeleaf object to the preauth endpoint and use HttpServletRequest to request.login() with the username and password directly from the html. no mapping to json required.
#PostMapping(value = "/preauth", produces = "application/json")
public String preAuth(#ModelAttribute LoginRequestModel loginRequestModel, HttpServletRequest request) throws IOException, ServletException {
request.login(loginRequestModel.getUsername(),loginRequestModel.getPassword());
return "index";
}
Related
Controller :
#RequestMapping(value = {"/load"}, method = {RequestMethod.POST})
public Response<Void> load(#RequestBody Request request) {
try {
service.load(request.getSqlStmt());
return Response.success();
} catch (SQLException ex) {
LOGGER.info(ex);
return Response.error(404, " Load Failed for : " + request.getSqlStmt());
}
Java POJO :
#Data
#NoArgsConstructor
#AllArgsConstructor
#Builder
public class Request implements Serializable {
private static final long serialVersionUID = 1L;
#NotBlank private String sa;
#NotBlank private String tableName;
#NotBlank private String jobEnv;
#NotBlank private String uowTo;
#NotBlank private String sqlStmt;
#NotBlank private String type;
}
A) Tried without escape quotes or characters first :-
curl -s -k --negotiate -u : -H "Content-Type: application/json" -X POST -d '{"sqlStmt": "CALL CORE_LIB.SP_LOAD_STATUS_COMPLETE('2021-02-11',76,' ')", "uowTo": "20210815", "tableName": "tableName1", "jobEnv": "env1", "sa": "sa1", "type": "target"}' http://example.com:443/load
SQL statement changed from "CALL CORE_LIB.SP_LOAD_STATUS_COMPLETE('2021-02-11',76,' ')" to CALL CORE_LIB.SP_LOAD_STATUS_COMPLETE(2021-02-11,76,) instead of CALL CORE_LIB.SP_LOAD_STATUS_COMPLETE('2021-02-11',76,'')
The jdbc execute statement method call fails due to malformed string.
B) After adding escape characters :-
curl -s -k --negotiate -u : -H "Content-Type: application/json" -X POST -d '{"sqlStmt": "CALL CORE_LIB.SP_LOAD_STATUS_COMPLETE(\\'2021-02-11\\',76,\\'\\')", "uowTo": "20210815", "tableName": "tableName1", "jobEnv": "env1", "sa": "sa1", "type": "target"}' http://example.com:443/load
Error :-
2021-08-17 18:17:51.823 ERROR 7 --- [http-nio-8080-exec-3]
.e.a.d.n.e.s.c.ControllerAdvice :
org.springframework.http.converter.HttpMessageNotReadableException:
JSON parse error: Unrecognized character escape ‘,’ (code 44); nested
exception is com.fasterxml.jackson.databind.JsonMappingException:
Unrecognized character escape ‘,’ (code 44) at [Source:
(PushbackInputStream); line: 1, column: 66] (through reference chain:
c.e.a.d.n.e.s.m.Request[“sqlStmt”])
org.springframework.http.converter.HttpMessageNotReadableException:
JSON parse error: Unrecognized character escape ‘,’ (code 44); nested
exception is com.fasterxml.jackson.databind.JsonMappingException:
Unrecognized character escape ‘,’ (code 44) at [Source:
(PushbackInputStream); line: 1, column: 66] (through reference chain:
c.e.a.d.n.e.s.m.Request[“sqlStmt”])
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:275)
~[spring-web-5.2.7.RELEASE.jar!/:5.2.7.RELEASE]
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.read(AbstractJackson2HttpMessageConverter.java:257)
~[spring-web-5.2.7.RELEASE.jar!/:5.2.7.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver.readWithMessageConverters(AbstractMessageConverterMethodArgumentResolver.java:205)
~[spring-webmvc-5.2.7.RELEASE.jar!/:5.2.7.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.readWithMessageConverters(RequestResponseBodyMethodProcessor.java:158)
~[spring-webmvc-5.2.7.RELEASE.jar!/:5.2.7.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.resolveArgument(RequestResponseBodyMethodProcessor.java:131)
~[spring-webmvc-5.2.7.RELEASE.jar!/:5.2.7.RELEASE]
at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121)
~[spring-web-5.2.7.RELEASE.jar!/:5.2.7.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:167)
~[spring-web-5.2.7.RELEASE.jar!/:5.2.7.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:134)
~[spring-web-5.2.7.RELEASE.jar!/:5.2.7.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105)
~[spring-webmvc-5.2.7.RELEASE.jar!/:5.2.7.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:879)
~[spring-webmvc-5.2.7.RELEASE.jar!/:5.2.7.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793)
~[spring-webmvc-5.2.7.RELEASE.jar!/:5.2.7.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
~[spring-webmvc-5.2.7.RELEASE.jar!/:5.2.7.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
~[spring-webmvc-5.2.7.RELEASE.jar!/:5.2.7.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
~[spring-webmvc-5.2.7.RELEASE.jar!/:5.2.7.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
[spring-webmvc-5.2.7.RELEASE.jar!/:5.2.7.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
[spring-webmvc-5.2.7.RELEASE.jar!/:5.2.7.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:665) [javax.servlet-api-4.0.1.jar!/:4.0.1]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
[spring-webmvc-5.2.7.RELEASE.jar!/:5.2.7.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:750) [javax.servlet-api-4.0.1.jar!/:4.0.1]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
[tomcat-embed-core-9.0.36.jar!/:9.0.36]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
[tomcat-embed-core-9.0.36.jar!/:9.0.36]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
[tomcat-embed-websocket-9.0.36.jar!/:9.0.36]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
[tomcat-embed-core-9.0.36.jar!/:9.0.36]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
[tomcat-embed-core-9.0.36.jar!/:9.0.36]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
[spring-web-5.2.7.RELEASE.jar!/:5.2.7.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
[spring-web-5.2.7.RELEASE.jar!/:5.2.7.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
[tomcat-embed-core-9.0.36.jar!/:9.0.36]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
[tomcat-embed-core-9.0.36.jar!/:9.0.36]
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
[spring-web-5.2.7.RELEASE.jar!/:5.2.7.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
[spring-web-5.2.7.RELEASE.jar!/:5.2.7.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
[tomcat-embed-core-9.0.36.jar!/:9.0.36]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
[tomcat-embed-core-9.0.36.jar!/:9.0.36]
at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:93)
[spring-boot-actuator-2.3.1.RELEASE.jar!/:2.3.1.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
[spring-web-5.2.7.RELEASE.jar!/:5.2.7.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
[tomcat-embed-core-9.0.36.jar!/:9.0.36]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
[tomcat-embed-core-9.0.36.jar!/:9.0.36]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
[spring-web-5.2.7.RELEASE.jar!/:5.2.7.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
[spring-web-5.2.7.RELEASE.jar!/:5.2.7.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
[tomcat-embed-core-9.0.36.jar!/:9.0.36]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
[tomcat-embed-core-9.0.36.jar!/:9.0.36]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
[tomcat-embed-core-9.0.36.jar!/:9.0.36]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
[tomcat-embed-core-9.0.36.jar!/:9.0.36]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
[tomcat-embed-core-9.0.36.jar!/:9.0.36]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
[tomcat-embed-core-9.0.36.jar!/:9.0.36]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
[tomcat-embed-core-9.0.36.jar!/:9.0.36]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
[tomcat-embed-core-9.0.36.jar!/:9.0.36]
at org.apache.catalina.valves.RemoteIpValve.invoke(RemoteIpValve.java:747)
[tomcat-embed-core-9.0.36.jar!/:9.0.36]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
[tomcat-embed-core-9.0.36.jar!/:9.0.36]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373)
[tomcat-embed-core-9.0.36.jar!/:9.0.36]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
[tomcat-embed-core-9.0.36.jar!/:9.0.36]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
[tomcat-embed-core-9.0.36.jar!/:9.0.36]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590)
[tomcat-embed-core-9.0.36.jar!/:9.0.36]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
[tomcat-embed-core-9.0.36.jar!/:9.0.36]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
[na:1.8.0_242]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
[na:1.8.0_242]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
[tomcat-embed-core-9.0.36.jar!/:9.0.36]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_242] Caused by: com.fasterxml.jackson.databind.JsonMappingException: Unrecognized
character escape ‘,’ (code 44) at [Source: (PushbackInputStream);
line: 1, column: 66] (through reference chain:
c.e.a.d.n.e.s.m.Request[“sqlStmt”])
at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:397)
~[jackson-databind-2.11.0.jar!/:2.11.0]
at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:356)
~[jackson-databind-2.11.0.jar!/:2.11.0]
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.wrapAndThrow(BeanDeserializerBase.java:1714)
~[jackson-databind-2.11.0.jar!/:2.11.0]
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:373)
~[jackson-databind-2.11.0.jar!/:2.11.0]
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:164)
~[jackson-databind-2.11.0.jar!/:2.11.0]
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4482)
~[jackson-databind-2.11.0.jar!/:2.11.0]
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3487)
~[jackson-databind-2.11.0.jar!/:2.11.0]
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:269)
~[spring-web-5.2.7.RELEASE.jar!/:5.2.7.RELEASE] Caused by:
com.fasterxml.jackson.core.JsonParseException: Unrecognized character
escape ‘,’ (code 44) at [Source: (PushbackInputStream); line: 1,
column: 66]
at com.fasterxml.jackson.core.JsonParser._constructError(JsonParser.java:1851)
~[jackson-core-2.11.0.jar!/:2.11.0]
Any pointers on how I can resolve the above issue currently facing?
I was writing a feature to insert records from XML file to MySQL database in Spring using EntityManager and JpaContext.
I was trying on two files, one with 50 records, second with duplication of them up to 100 records. In my function, for every 50 records persisted, I call flush(), clear() and print message.
I'm uploading Users and they require to encode the password and properly set a Role attribute that is in a different table as a key.
I have a for loop that gets the User from the list and whole operation with entityManager starts.
Firstly, I had that user setting in the same loop.
public void insertInBatch(List<User> usersList) {
EntityManager entityManager = jpaContext.getEntityManagerByManagedType(User.class);
setUsersRoleAndEncodePasswords(usersList);
for(int i = 0; i < usersList.size(); i++){
User user = usersList.get(i);
// Setting User attributes
Role role = roleRepository.findByRole("ROLE_USER");
user.setRoles(new HashSet<Role>(Arrays.asList(role)));
user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
entityManager.persist(user);
if(i % 50 == 0 && i > 0){
entityManager.flush();
entityManager.clear();
System.out.println("****\t Loaded " + i + " records from " + usersList.size() + "\t****");
}
}
}
And that code worked for 50 and 100 records files.
As Users are taken from the List, I wrote a function that sets the attributes to make code cleaner and called it before the for loop.
public void insertInBatch(List<User> usersList) {
EntityManager entityManager = jpaContext.getEntityManagerByManagedType(User.class);
setUsersRoleAndEncodePasswords(usersList); // Setting User attributes
for(int i = 0; i < usersList.size(); i++){
User user = usersList.get(i);
entityManager.persist(user);
if(i % 50 == 0 && i > 0){
entityManager.flush();
entityManager.clear();
System.out.println("****\t Loaded " + i + " records from " + usersList.size() + "\t****");
}
}
}
private void setUsersRoleAndEncodePasswords(List<User> usersList){
for (User user : usersList){
Role role = roleRepository.findByRole("ROLE_USER");
user.setRoles(new HashSet<Role>(Arrays.asList(role)));
user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
}
}
And this works fine for 50 record file, but does not for 100, throwing an expection right after the message is shown (at 50 records file, message is not shown).
javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist: stanislaw.appdemo.user.Role
Why is this, when the code logic is nearly the same, and both works for 50 records? I'm assuming that flush() or clear() have to modify the usersList somehow, but how? Full logs from error.
Hibernate: insert into user_role (user_id, role_id) values (?, ?)
Hibernate: insert into user_role (user_id, role_id) values (?, ?)
**** Loaded 50 records from 100 ****
Hibernate: insert into user (active, email, last_name, name, password) values (?, ?, ?, ?, ?)
2020-02-01 22:50:01.612 DEBUG 12592 --- [nio-8080-exec-8] o.s.web.servlet.view.RedirectView : View name 'redirect:', model {}
2020-02-01 22:50:01.612 DEBUG 12592 --- [nio-8080-exec-8] o.s.web.servlet.DispatcherServlet : Completed 302 FOUND
javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist: stanislaw.appdemo.user.Role
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:154)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:181)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:188)
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:732)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:694)
at org.hibernate.engine.spi.CascadingActions$7.cascade(CascadingActions.java:298)
at org.hibernate.engine.internal.Cascade.cascadeToOne(Cascade.java:492)
at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:416)
at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:218)
at org.hibernate.engine.internal.Cascade.cascadeCollectionElements(Cascade.java:525)
at org.hibernate.engine.internal.Cascade.cascadeCollection(Cascade.java:456)
at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:419)
at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:218)
at org.hibernate.engine.internal.Cascade.cascade(Cascade.java:151)
at org.hibernate.event.internal.AbstractSaveEventListener.cascadeAfterSave(AbstractSaveEventListener.java:464)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:298)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:198)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:128)
at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:192)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:135)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:62)
at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:108)
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:702)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:688)
at jdk.internal.reflect.GeneratedMethodAccessor90.invoke(Unknown Source)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:368)
at com.sun.proxy.$Proxy110.persist(Unknown Source)
at jdk.internal.reflect.GeneratedMethodAccessor90.invoke(Unknown Source)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:314)
at com.sun.proxy.$Proxy110.persist(Unknown Source)
at stanislaw.appdemo.admin.AdminServiceImpl.insertInBatch(AdminServiceImpl.java:70)
at stanislaw.appdemo.admin.AdminServiceImpl$$FastClassBySpringCGLIB$$158389f3.invoke(<generated>)
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.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 stanislaw.appdemo.admin.AdminServiceImpl$$EnhancerBySpringCGLIB$$7bf6db3c.insertInBatch(<generated>)
at stanislaw.appdemo.admin.AdminPageController.importUsersFromXML(AdminPageController.java:133)
at stanislaw.appdemo.admin.AdminPageController$$FastClassBySpringCGLIB$$413b934d.invoke(<generated>)
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.security.access.intercept.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:69)
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 stanislaw.appdemo.admin.AdminPageController$$EnhancerBySpringCGLIB$$deac85ce.importUsersFromXML(<generated>)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
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:660)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
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.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320)
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:334)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:118)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:158)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:92)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:77)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:358)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:271)
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.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:526)
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:1591)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: org.hibernate.PersistentObjectException: detached entity passed to persist: stanislaw.appdemo.user.Role
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:127)
at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:118)
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:726)
... 136 more
2020-02-01 22:50:01.618 DEBUG 12592 --- [nio-8080-exec-9] o.s.web.servlet.DispatcherServlet : GET "/admin/users/1", parameters={}
2020-02-01 22:50:01.619 DEBUG 12592 --- [nio-8080-exec-9] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to stanislaw.appdemo.admin.AdminPageController#showAdminAllUsersPage(int, String, Model)
Hibernate: select user0_.user_id as user_id1_1_, user0_.active as active2_1_, user0_.email as email3_1_, user0_.last_name as last_nam4_1_, user0_.name as name5_1_, user0_.password as password6_1_ from user user0_ limit ?
Hibernate: select count(user0_.user_id) as col_0_0_ from user user0_
Hibernate: select roles0_.user_id as user_id1_2_0_, roles0_.role_id as role_id2_2_0_, role1_.role_id as role_id1_0_1_, role1_.role as role2_0_1_ from user_role roles0_ inner join role role1_ on roles0_.role_id=role1_.role_id where roles0_.user_id=?
Hibernate: select roles0_.user_id as user_id1_2_0_, roles0_.role_id as role_id2_2_0_, role1_.role_id as role_id1_0_1_, role1_.role as role2_0_1_ from user_role roles0_ inner join role role1_ on roles0_.role_id=role1_.role_id where roles0_.user_id=?
Hibernate: select roles0_.user_id as user_id1_2_0_, roles0_.role_id as role_id2_2_0_, role1_.role_id as role_id1_0_1_, role1_.role as role2_0_1_ from user_role roles0_ inner join role role1_ on roles0_.role_id=role1_.role_id where roles0_.user_id=?
2020-02-01 22:50:01.626 DEBUG 12592 --- [nio-8080-exec-9] o.s.w.s.v.ContentNegotiatingViewResolver : Selected 'text/html' given [text/html, application/xhtml+xml, image/webp, image/apng, application/xml;q=0.9, application/signed-exchange;v=b3;q=0.9, */*;q=0.8]
2020-02-01 22:50:01.626 DEBUG 12592 --- [nio-8080-exec-9] o.s.web.servlet.view.JstlView : View name 'admin/users', model {totalPagesNumber=86, currentPageNumber=1, usersList=[stanislaw.appdemo.user.User#915e2d3, stanislaw.appdemo.user.User#3736d882, stanislaw.appdemo.user.User#38d60924], recordCounterStart=0, searchParam=}
2020-02-01 22:50:01.626 DEBUG 12592 --- [nio-8080-exec-9] o.s.web.servlet.view.JstlView : Forwarding to [/WEB-INF/jsp/admin/users.jsp]
2020-02-01 22:50:01.630 DEBUG 12592 --- [nio-8080-exec-9] o.s.web.servlet.DispatcherServlet : Completed 200 OK
Calling entityManager.clear() will remove all entities from persistence context. This includes Role entities that are already assigned to Userentities
In first version of code Role assigned to User always remains in persistence context until entityManager.persist() is called:
//1) now role is in persistence context
user.setRoles(new HashSet<Role>(Arrays.asList(role)));
user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
//2) so persisting User with Role is not an issue
entityManager.persist(user);
In second example, Role is actively removed from persistence context:
//1) now we have role in persistenceContext
EntityManager entityManager = jpaContext.getEntityManagerByManagedType(User.class);
setUsersRoleAndEncodePasswords(usersList); // Setting User attributes
for(int i = 0; i < usersList.size(); i++){
User user = usersList.get(i);
//2) for 50 first Users this will succeed, because role is in persistence context
//but for after that it will fail, because role will be removed in 3)
entityManager.persist(user);
if(i % 50 == 0 && i > 0){
entityManager.flush();
// 3) after this call persistence context is empty, role will not be there
entityManager.clear();
System.out.println("****\t Loaded " + i + " records from " + usersList.size() + "\t****");
}
}
Has anyone tried the sawtooth-java-sdk v1.0.3 to create events on the Hyperledger Sawtooth?
I am getting the following exception
com.google.protobuf.InvalidProtocolBufferException: Protocol message had invalid UTF-8.
at com.google.protobuf.InvalidProtocolBufferException.invalidUtf8(InvalidProtocolBufferException.java:148) ~[protobuf-java-3.6.1.jar:na]
at com.google.protobuf.CodedInputStream$ArrayDecoder.readStringRequireUtf8(CodedInputStream.java:841) ~[protobuf-java-3.6.1.jar:na]
at sawtooth.sdk.protobuf.Event.<init>(Event.java:49) ~[sawtooth-sdk-protos-v0.1.3.jar:na]
at sawtooth.sdk.protobuf.Event$1.parsePartialFrom(Event.java:1677) ~[sawtooth-sdk-protos-v0.1.3.jar:na]
at sawtooth.sdk.protobuf.Event$1.parsePartialFrom(Event.java:1671) ~[sawtooth-sdk-protos-v0.1.3.jar:na]
at com.google.protobuf.AbstractParser.parsePartialFrom(AbstractParser.java:105) ~[protobuf-java-3.6.1.jar:na]
at com.google.protobuf.AbstractParser.parseFrom(AbstractParser.java:125) ~[protobuf-java-3.6.1.jar:na]
at com.google.protobuf.AbstractParser.parseFrom(AbstractParser.java:130) ~[protobuf-java-3.6.1.jar:na]
at com.google.protobuf.AbstractParser.parseFrom(AbstractParser.java:49) ~[protobuf-java-3.6.1.jar:na]
at sawtooth.sdk.protobuf.Event.parseFrom(Event.java:994) ~[sawtooth-sdk-protos-v0.1.3.jar:na]
at my.events.EventListener.run(EventListener.java:257) ~[classes/:na]
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na]
at java.base/java.lang.Thread.run(Thread.java:834) ~[na:na]
This is how I am creating the event in the TransactionHandler#apply()
ByteString eventdata = ByteString.copyFrom("This is a test....".getBytes("UTF-8"));
Map<String, String> attributesMap = new HashMap<String, String>();
attributesMap.put("address", address);
attributesMap.put("namespace", address.substring(0,6));
Collection<Map.Entry<String, String>> attributes = attributesMap.entrySet();
state.addEvent("rootevent/myevent", attributes, eventdata);
Here's my Event Listener code:
byte[] resp = socket.recv(0);
message = Message.parseFrom(resp);
sawToothEvent = Event.parseFrom(message.getContent());
Event.parseFrom throws the exception.
The events come in within an EventList, as opposed to a single bare Event. So it should be more like
byte[] resp = socket.recv(0);
message = Message.parseFrom(resp);
evtList = EventList.parseFrom(message.getContent());
for (Event evt : evtList.getEventsList()) {
...
}
I'm trying to post a json using feign but i get an error from the url that parameters were not sent. This is my code:
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "Rabbit SEO");
jsonObject.put("price", "10");
jsonObject.put("test", "true");
jsonObject.put("return_url", "https://www.rabbitseo.com/shopifyPaidGuest");
String content = jsonObject.toString();
System.out.println("content = " + content);
String result = myClient.postRecurringPayment(content);
#RequestLine("POST /admin/recurring_application_charges.json")
#Headers("Content-Type: application/json")
String postRecurringPayment(String content);
return Feign.builder()
.requestInterceptors(requestInterceptors)
.target(MyApiClient.class, myShopifyUrl);
I tried also with the gson decoder and encoder:
return Feign.builder()
.decoder(new GsonDecoder())
.encoder(new GsonEncoder())
.requestInterceptors(requestInterceptors)
.target(MyApiClient.class, myShopifyUrl);
Error:
feign.FeignException: status 400 reading MyApiClient#postRecurringPayment(String); content:
{"errors":{"recurring_application_charge":"Required parameter missing or invalid"}}
at feign.FeignException.errorStatus(FeignException.java:62)
at feign.codec.ErrorDecoder$Default.decode(ErrorDecoder.java:91)
at feign.SynchronousMethodHandler.executeAndDecode(SynchronousMethodHandler.java:126)
at feign.SynchronousMethodHandler.invoke(SynchronousMethodHandler.java:74)
at feign.ReflectiveFeign$FeignInvocationHandler.invoke(ReflectiveFeign.java:94)
at com.sun.proxy.$Proxy4.postRecurringPayment(Unknown Source)
at com.test.TestOauth.testShopifyProducts2(TestOauth.java:49)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:76)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.junit.runner.JUnitCore.run(JUnitCore.java:157)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:62)
Looking at log http error code 400 mean BadRequest
"errors":{"recurring_application_charge":"Required parameter missing or invalid"
You must pass recurring_application_charge as part of JSON to be accepted by API
But, you need to post complete error log and MyClient class would help advise more.
I have issue with primefaces 5.0 component p:fileDownload , I have following bean store DefaultStreamedContent , and I get the value stored to download it simply :
Bean :
public class EBMail implements Serializable {
private DefaultStreamedContent attachment;
// # here setter and getter too .
}
and from XHTML file :
<p:commandLink ajax="false" value="Download Attachment" rendered="#{mbMail.attachment != null}">
<p:fileDownload value="#{mbMail.attachment}" />
</p:commandLink>
I get mail attachment file for first time, in 2nd time I get the following exception :
WARNING: java.io.IOException: Stream Closed
javax.faces.FacesException: java.io.IOException: Stream Closed
at org.primefaces.component.filedownload.FileDownloadActionListener.processAction(FileDownloadActionListener.java:87)
at javax.faces.event.ActionEvent.processListener(ActionEvent.java:88)
at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:813)
at javax.faces.component.UICommand.broadcast(UICommand.java:300)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.tomee.catalina.OpenEJBValve.invoke(OpenEJBValve.java:44)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:744)
Caused by: java.io.IOException: Stream Closed
at java.io.FileInputStream.readBytes(Native Method)
at java.io.FileInputStream.read(FileInputStream.java:243)
at org.primefaces.component.filedownload.FileDownloadActionListener.processAction(FileDownloadActionListener.java:77)
... 30 more
org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [FacesServlet] in context with path [/faces] threw exception
java.lang.IllegalStateException: getOutputStream() has already been called for this response
at org.apache.catalina.connector.Response.getWriter(Response.java:648)
at org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:213)
at com.sun.faces.context.ExternalContextImpl.getResponseOutputWriter(ExternalContextImpl.java:846)
at com.sun.faces.context.PartialViewContextImpl.createPartialResponseWriter(PartialViewContextImpl.java:504)
at com.sun.faces.context.PartialViewContextImpl.access$300(PartialViewContextImpl.java:79)
at com.sun.faces.context.PartialViewContextImpl$DelayedInitPartialResponseWriter.getWrapped(PartialViewContextImpl.java:642)
at javax.faces.context.PartialResponseWriter.startDocument(PartialResponseWriter.java:120)
at org.omnifaces.context.OmniPartialViewContext$OmniPartialResponseWriter.startDocument(OmniPartialViewContext.java:270)
at org.primefaces.context.PrimePartialResponseWriter.startDocument(PrimePartialResponseWriter.java:152)
at com.sun.faces.context.AjaxExceptionHandlerImpl.handlePartialResponseError(AjaxExceptionHandlerImpl.java:201)
at com.sun.faces.context.AjaxExceptionHandlerImpl.handle(AjaxExceptionHandlerImpl.java:126)
at javax.faces.context.ExceptionHandlerWrapper.handle(ExceptionHandlerWrapper.java:100)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:119)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.tomee.catalina.OpenEJBValve.invoke(OpenEJBValve.java:44)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:744)
I'm running on JFS 2.2.7 , Primefaces 5.0 , I upload file into bean my issue when I download it for 2nd time, even for another object 'mail' .
Any solution, I looked after many solutions around nothing helped me or I've already tested it.
I solved issue finally, I make new class store my data, and action that prepare stream to download from my class object, and when download file I read bytes from my class bytes, like the following:
Class:
public class Attachment implements Serializable {
private String name;
private String type;
private String encoding;
private byte[] data;
// ... Setters and getters ...
public Attachment () {
this.encoding = "UTF-8";
}
}
Bean:
public class MailBean implements Serializable {
// alot of properties
private Attachment attachment;
// setters and getters
}
Managed Bean :
public class MailManagedBean implements Serializable {
private DefaultStreamedContent attachmentToDownload;
private MailBean mail;
// # here setter and getter too .
public void prepare() {
InputStream stream = new ByteArrayInputStream(mail.getAttachment.getData());
attachmentToDownload = new DefaultStreamedContent(stream, mail.getAttachment.getType(), mail.getAttachment.getName(), mail.getAttachment.getEncoding());
}
}
In XHTML file (I added action) :
<p:commandLink ajax="false" value="Download Attachment"
rendered="#{mbMail.mail.attachment != null}" action="#{mbMail.prepare()}">
<p:fileDownload value="#{mbMail.attachmentToDownload}" />
</p:commandLink>
public StreamedContent getExportFile() {
Field field = exportFile.getStream().getClass().getDeclaredField("path");
field.setAccessible(true);
String path = (String)field.get(exportFile.getStream());
InputStream tempStream = new FileInputStream(path);
exportFile = new DefaultStreamedContent(tempStream,exportFile.getContentType(), exportFile.getName());
return exportFile;
}