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()) {
...
}
Related
Getting the Error
com.oracle.bmc.model.BmcException: (-1, null, false) Processing exception while communicating to: https://objectstorage.eu-frankfurt-1.oraclecloud.com (outbound opc-request-id: 610055D587CD432284C75AA1C52A6446)
I have taken the code units from the Oracle https://docs.oracle.com/en-us/iaas/api/#/en/objectstorage/20160918/PreauthenticatedRequest/CreatePreauthenticatedRequest but it does not work
Code
final ConfigFileReader.ConfigFile configFile = ConfigFileReader.parseDefault();
final AuthenticationDetailsProvider provider = new ConfigFileAuthenticationDetailsProvider(configFile);
ObjectStorageClient client = new ObjectStorageClient(provider);
log.debug("Client Created = "+client.getEndpoint());
/* Create a request and dependent object(s). */
CreatePreauthenticatedRequestDetails createPreauthenticatedRequestDetails = CreatePreauthenticatedRequestDetails.builder()
.name("EXAMPLE-name-Value")
.bucketListingAction(PreauthenticatedRequest.BucketListingAction.ListObjects)
.objectName("230222082346340.pdf")
.accessType(CreatePreauthenticatedRequestDetails.AccessType.ObjectReadWrite)
.timeExpires(new Date("Wed Nov 26 03:00:33 UTC 2042")).build();
log.debug("createPreauthenticatedRequestDetails Created..."+createPreauthenticatedRequestDetails.getName() );
CreatePreauthenticatedRequestRequest createPreauthenticatedRequestRequest = CreatePreauthenticatedRequestRequest.builder()
.namespaceName("namespacename")
.bucketName("temp")
.createPreauthenticatedRequestDetails(createPreauthenticatedRequestDetails)
.opcClientRequestId("ocid1.test.oc1.."+UUID.randomUUID().toString()+"-opcClientRequestId-Value")
.build();
CreatePreauthenticatedRequestResponse response = client.createPreauthenticatedRequest(createPreauthenticatedRequestRequest);
Is there anything I am missing?
Complete Error Log:
09:02:25 INFO [co.or.bm.ht.ApacheConfigurator]Setting connector provider to ApacheConnectorProvider
09:02:25 INFO [co.or.bm.ob.ObjectStorageClient]Setting endpoint to https://objectstorage.eu-frankfurt-1.oraclecloud.com
09:02:25 DEBUG[or.fr.co.DocStoreOracleService]Client Created = https://objectstorage.eu-frankfurt-1.oraclecloud.com
09:02:25 DEBUG[or.fr.co.DocStoreOracleService]createPreauthenticatedRequestDetails Created...EXAMPLE-name-Value
com.oracle.bmc.model.BmcException: (-1, null, false) Processing exception while communicating to: https://objectstorage.eu-frankfurt-1.oraclecloud.com (outbound opc-request-id: 813E7CD051BD44FB9303B033D912F187)
at com.oracle.bmc.http.internal.RestClient.convertToBmcException(RestClient.java:994)
at com.oracle.bmc.http.internal.RestClient.post(RestClient.java:306)
at com.oracle.bmc.objectstorage.ObjectStorageClient.lambda$null$12(ObjectStorageClient.java:684)
at com.oracle.bmc.retrier.BmcGenericRetrier.doFunctionCall(BmcGenericRetrier.java:89)
at com.oracle.bmc.retrier.BmcGenericRetrier.lambda$execute$0(BmcGenericRetrier.java:60)
at com.oracle.bmc.waiter.GenericWaiter.execute(GenericWaiter.java:55)
at com.oracle.bmc.retrier.BmcGenericRetrier.execute(BmcGenericRetrier.java:51)
at com.oracle.bmc.objectstorage.ObjectStorageClient.lambda$createPreauthenticatedRequest$13(ObjectStorageClient.java:680)
at com.oracle.bmc.retrier.BmcGenericRetrier.doFunctionCall(BmcGenericRetrier.java:89)
at com.oracle.bmc.retrier.BmcGenericRetrier.lambda$execute$0(BmcGenericRetrier.java:60)
at com.oracle.bmc.waiter.GenericWaiter.execute(GenericWaiter.java:55)
at com.oracle.bmc.retrier.BmcGenericRetrier.execute(BmcGenericRetrier.java:51)
at com.oracle.bmc.objectstorage.ObjectStorageClient.createPreauthenticatedRequest(ObjectStorageClient.java:674)
at org.freshfood.controller.DocStoreOracleService.generatePAUNew(DocStoreOracleService.java:774)
at org.freshfood.controller.DocStoreOracleService_Subclass.generatePAUNew$$superforward1(Unknown Source)
at org.freshfood.controller.DocStoreOracleService_Subclass$$function$$8.apply(Unknown Source)
at io.quarkus.arc.impl.AroundInvokeInvocationContext.proceed(AroundInvokeInvocationContext.java:54)
at io.quarkus.arc.runtime.devconsole.InvocationInterceptor.proceed(InvocationInterceptor.java:62)
at io.quarkus.arc.runtime.devconsole.InvocationInterceptor.monitor(InvocationInterceptor.java:49)
at io.quarkus.arc.runtime.devconsole.InvocationInterceptor_Bean.intercept(Unknown Source)
at io.quarkus.arc.impl.InterceptorInvocation.invoke(InterceptorInvocation.java:41)
at io.quarkus.arc.impl.AroundInvokeInvocationContext.perform(AroundInvokeInvocationContext.java:41)
at io.quarkus.arc.impl.InvocationContexts.performAroundInvoke(InvocationContexts.java:32)
at org.freshfood.controller.DocStoreOracleService_Subclass.generatePAUNew(Unknown Source)
at org.freshfood.controller.DocStoreOracleService_ClientProxy.generatePAUNew(Unknown Source)
at org.freshfood.controller.DocumentResource.getPreAuthURL(DocumentResource.java:36)
at org.freshfood.controller.DocumentResource_Subclass.getPreAuthURL$$superforward1(Unknown Source)
at org.freshfood.controller.DocumentResource_Subclass$$function$$4.apply(Unknown Source)
at io.quarkus.arc.impl.AroundInvokeInvocationContext.proceed(AroundInvokeInvocationContext.java:54)
at io.quarkus.arc.runtime.devconsole.InvocationInterceptor.proceed(InvocationInterceptor.java:62)
at io.quarkus.arc.runtime.devconsole.InvocationInterceptor.monitor(InvocationInterceptor.java:49)
at io.quarkus.arc.runtime.devconsole.InvocationInterceptor_Bean.intercept(Unknown Source)
at io.quarkus.arc.impl.InterceptorInvocation.invoke(InterceptorInvocation.java:41)
at io.quarkus.arc.impl.AroundInvokeInvocationContext.perform(AroundInvokeInvocationContext.java:41)
at io.quarkus.arc.impl.InvocationContexts.performAroundInvoke(InvocationContexts.java:32)
at org.freshfood.controller.DocumentResource_Subclass.getPreAuthURL(Unknown Source)
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.jboss.resteasy.core.MethodInjectorImpl.invoke(MethodInjectorImpl.java:170)
at org.jboss.resteasy.core.MethodInjectorImpl.invoke(MethodInjectorImpl.java:130)
at org.jboss.resteasy.core.ResourceMethodInvoker.internalInvokeOnTarget(ResourceMethodInvoker.java:660)
at org.jboss.resteasy.core.ResourceMethodInvoker.invokeOnTargetAfterFilter(ResourceMethodInvoker.java:524)
at org.jboss.resteasy.core.ResourceMethodInvoker.lambda$invokeOnTarget$2(ResourceMethodInvoker.java:474)
at org.jboss.resteasy.core.interception.jaxrs.PreMatchContainerRequestContext.filter(PreMatchContainerRequestContext.java:364)
at org.jboss.resteasy.core.ResourceMethodInvoker.invokeOnTarget(ResourceMethodInvoker.java:476)
at org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:434)
at org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:408)
at org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:69)
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:492)
at org.jboss.resteasy.core.SynchronousDispatcher.lambda$invoke$4(SynchronousDispatcher.java:261)
at org.jboss.resteasy.core.SynchronousDispatcher.lambda$preprocess$0(SynchronousDispatcher.java:161)
at org.jboss.resteasy.core.interception.jaxrs.PreMatchContainerRequestContext.filter(PreMatchContainerRequestContext.java:364)
at org.jboss.resteasy.core.SynchronousDispatcher.preprocess(SynchronousDispatcher.java:164)
at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:247)
at io.quarkus.resteasy.runtime.standalone.RequestDispatcher.service(RequestDispatcher.java:73)
at io.quarkus.resteasy.runtime.standalone.VertxRequestHandler.dispatch(VertxRequestHandler.java:151)
at io.quarkus.resteasy.runtime.standalone.VertxRequestHandler$1.run(VertxRequestHandler.java:91)
at io.quarkus.vertx.core.runtime.VertxCoreRecorder$13.runWith(VertxCoreRecorder.java:543)
at org.jboss.threads.EnhancedQueueExecutor$Task.run(EnhancedQueueExecutor.java:2449)
at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1478)
at org.jboss.threads.DelegatingRunnable.run(DelegatingRunnable.java:29)
at org.jboss.threads.ThreadLocalResettingRunnable.run(ThreadLocalResettingRunnable.java:29)
at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: javax.ws.rs.ProcessingException: RESTEASY004655: Unable to invoke request: javax.ws.rs.ProcessingException: RESTEASY003215: could not find writer for content-type application/json type: java.lang.String
at org.jboss.resteasy.client.jaxrs.engines.ManualClosingApacheHttpClient43Engine.invoke(ManualClosingApacheHttpClient43Engine.java:321)
at org.jboss.resteasy.client.jaxrs.internal.ClientInvocation.invoke(ClientInvocation.java:494)
at org.jboss.resteasy.client.jaxrs.internal.ClientInvocation.invoke(ClientInvocation.java:69)
at org.jboss.resteasy.client.jaxrs.internal.ClientInvocationBuilder.post(ClientInvocationBuilder.java:226)
at com.oracle.bmc.http.internal.ForwardingInvocationBuilder.post(ForwardingInvocationBuilder.java:157)
at com.oracle.bmc.http.internal.RestClient.lambda$post$4(RestClient.java:304)
at com.oracle.bmc.circuitbreaker.internal.JaxRsCircuitBreakerImpl.lambda$decorateSupplier$0(JaxRsCircuitBreakerImpl.java:83)
at io.github.resilience4j.circuitbreaker.CircuitBreaker.lambda$decorateSupplier$4(CircuitBreaker.java:198)
at com.oracle.bmc.circuitbreaker.internal.JaxRsCircuitBreakerImpl.lambda$decorateSupplier$1(JaxRsCircuitBreakerImpl.java:93)
at com.oracle.bmc.http.internal.RestClient.lambda$decorateSupplier$0(RestClient.java:175)
at com.oracle.bmc.http.internal.RestClient.post(RestClient.java:304)
... 64 more
Caused by: javax.ws.rs.ProcessingException: RESTEASY003215: could not find writer for content-type application/json type: java.lang.String
at org.jboss.resteasy.core.interception.jaxrs.ClientWriterInterceptorContext.throwWriterNotFoundException(ClientWriterInterceptorContext.java:50)
at org.jboss.resteasy.core.interception.jaxrs.AbstractWriterInterceptorContext.getWriter(AbstractWriterInterceptorContext.java:302)
at org.jboss.resteasy.core.interception.jaxrs.AbstractWriterInterceptorContext.syncProceed(AbstractWriterInterceptorContext.java:240)
at org.jboss.resteasy.core.interception.jaxrs.AbstractWriterInterceptorContext.proceed(AbstractWriterInterceptorContext.java:224)
at org.jboss.resteasy.client.jaxrs.internal.ClientInvocation.writeRequestBody(ClientInvocation.java:446)
at org.jboss.resteasy.client.jaxrs.engines.ManualClosingApacheHttpClient43Engine.writeRequestBodyToOutputStream(ManualClosingApacheHttpClient43Engine.java:625)
at org.jboss.resteasy.client.jaxrs.engines.ManualClosingApacheHttpClient43Engine.buildEntity(ManualClosingApacheHttpClient43Engine.java:584)
at org.jboss.resteasy.client.jaxrs.engines.ManualClosingApacheHttpClient43Engine.loadHttpMethod(ManualClosingApacheHttpClient43Engine.java:489)
at org.jboss.resteasy.client.jaxrs.engines.ManualClosingApacheHttpClient43Engine.invoke(ManualClosingApacheHttpClient43Engine.java:299)
... 74 more
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";
}
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'm trying to make a simple UDP socket server for a Unity3D game I'm making, and I've got it mostly working. I can send messages to it and read the messages. But when I'm trying to send the message back to the client (for testing purposes, at the moment), I get a BufferOverFlowException.
Before sending the data back, I'm converting it to json using groovy.json.JsonBuilder. The data has a very simple structure:
[data: "Hello World"]
But for whatever reason, JsonBuilder is building it as
{
"data": "Hello World\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\..."
}
the \u0000's go on for a while. Long enough to make my 1024 byte long ByteBuffer overflow.
This is the class that's responsible for sending the data back to the client:
import groovy.json.JsonBuilder
import groovy.transform.CompileStatic
import groovyx.gpars.actor.DynamicDispatchActor
import java.nio.ByteBuffer
import java.nio.channels.DatagramChannel
#CompileStatic
class SenderActor extends DynamicDispatchActor{
//takes message of type [data: Object, receiver: SocketAddress]
void onMessage(Map message){
println(message.data) //prints "Hello World"
def json = new JsonBuilder([data: message.data]).toString()
println("Sending: $json") //prints '{"data": "Hello World\u0000\u0000..."}'
def channel = DatagramChannel.open()
channel.connect(message.receiver as SocketAddress)
def buffer = ByteBuffer.allocate(1024)
buffer.clear()
buffer.put(json.getBytes())
buffer.flip()
channel.send(buffer, message.receiver as SocketAddress)
}
}
And this is the stack trace I get:
An exception occurred in the Actor thread Actor Thread 2
java.nio.BufferOverflowException
at java.nio.HeapByteBuffer.put(HeapByteBuffer.java:189)
at java.nio.ByteBuffer.put(ByteBuffer.java:859)
at Croquet.Actors.SenderActor.onMessage(SenderActor.groovy:28)
at Croquet.Actors.SenderActor$onMessage.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
at Croquet.Actors.ProcessorActor$onMessage.call(Unknown Source)
at groovyx.gpars.actor.impl.DDAClosure$_createDDAClosure_closure1.doCall(DDAClosure.groovy:38)
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:497)
at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:324)
at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:292)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1016)
at groovy.lang.Closure.call(Closure.java:423)
at groovy.lang.Closure.call(Closure.java:439)
at groovyx.gpars.actor.AbstractLoopingActor.runEnhancedWithoutRepliesOnMessages(AbstractLoopingActor.java:293)
at groovyx.gpars.actor.AbstractLoopingActor.access$400(AbstractLoopingActor.java:30)
at groovyx.gpars.actor.AbstractLoopingActor$1.handleMessage(AbstractLoopingActor.java:93)
at groovyx.gpars.util.AsyncMessagingCore.run(AsyncMessagingCore.java:132)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
The data in question is encoded as UTF-8, if that helps.
This is the client code that is responsible for sending data to the server (written in C#):
void sendTestMessage(UdpClient udpClient, UdpState udpState){
byte[] data = Encoding.UTF8.GetBytes("Hello World");
udpClient.BeginSend(
data,
data.Length,
udpState.e, //IPEndPoint
result =>{
messageSent = true;
Debug.Log(string.Format("Message '{1}' Sent to {0}", udpState.e, Encoding.UTF8.GetString(data)));
udpClient.EndSend(result);
},
udpState);
}
I solved my problem by changing
def json = new JsonBuilder([data: message.data]).toString()
to
def json = new JsonBuilder([data: message.data]).toString().replace("\\u0000", "")
I've bundled a JavaFx application as a .exe (using ecliplse + Inno), the application is working fine but when an exception is raised I don't get the line number of my code where the exception initiated (it shows "Unknown Source"):
java.io.IOException: The system cannot find the path specified
at java.io.WinNTFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:1012)
at utils.ConfigLoader.<clinit>(Unknown Source)
at ui.MainApplication.start(Unknown Source)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$159(LauncherImpl.java:863)
at com.sun.javafx.application.LauncherImpl$$Lambda$131/998964132.run(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$172(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl$$Lambda$47/1542341592.run(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$null$170(PlatformImpl.java:295)
at com.sun.javafx.application.PlatformImpl$$Lambda$49/625615544.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$171(PlatformImpl.java:294)
at com.sun.javafx.application.PlatformImpl$$Lambda$48/1565153168.run(Unknown Source)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$145(WinApplication.java:101)
at com.sun.glass.ui.win.WinApplication$$Lambda$37/797007557.run(Unknown Source)
at java.lang.Thread.run(Thread.java:745)
I'm redirecting the exception to a TextArea using the below code:
public static void showDialog(Exception e){
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("Exception Dialog");
alert.setHeaderText("A fatal error occured, please send to the application developper");
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
String exceptionText = sw.toString();
Label label = new Label("The exception stacktrace was:");
TextArea textArea = new TextArea(exceptionText);
textArea.setEditable(false);
textArea.setWrapText(true);
textArea.setMaxWidth(Double.MAX_VALUE);
textArea.setMaxHeight(Double.MAX_VALUE);
GridPane.setVgrow(textArea, Priority.ALWAYS);
GridPane.setHgrow(textArea, Priority.ALWAYS);
GridPane expContent = new GridPane();
expContent.setMaxWidth(Double.MAX_VALUE);
expContent.add(label, 0, 0);
expContent.add(textArea, 0, 1);
// Set expandable Exception into the dialog pane.
alert.getDialogPane().setExpandableContent(expContent);
alert.showAndWait();
}