HTTP Post request handler in java - java

I hope someone will be able to help me understand how to create an endpoint HTTP server listener. I'm trying to create a POST request handler that can save all post requests made to a text file.
The purpose is for a Game state integration between My application and Counter-Strike. Ive read their documentation (csgo GSI documentation) and the example given in here is almost exactly what I'm looking for. But its written in nodejs and I will need it to work with Java.
I have only been able to create a HTTPServer but can't seem to understand how I can create a POST request handler which records the data sent to "data" request.
How can I create a handler which can record all requests sent to data?

I believe the easiest & fastest way is to grab a SpringBoot app from https://start.spring.io/ (add Web dependency). And then create a Spring #RestController like that:
#RestController
#RequestMapping(value = "/cs")
public class CsController {
#RequestMapping(value = "", method = RequestMethod.POST)
public void processCsData(#RequestBody CsData csData) {
processCsData(csData);
}
}
where CsData is a POJO class that they send to you. processCsData() is your method to do whatever you like with the data.
Now you need to host it somewhere so that it would be reachable from the Internet or you can use https://ngrok.com/ to create a tunnel for test purposes.

Related

Quarkus GraphQL Client with Keycloak

I'm trying this for days right now and I'm not sure if i missed something.
I have a Quarkus GraphQL Service , like here : https://quarkus.io/guides/smallrye-graphql
And I have setup Keycloak to secure it.
Now I wanted to create a client with Qute and GraphQL Smallrye client like here : https://quarkus.io/guides/smallrye-graphql-client
The client can connect to the service, but I always get an "Data Fetching Error: io.quarkus.security.UnauthorizedException".
It seems like the GraphQL client is not sending the headers correctly or it doesn't send any ...
Does anyone know how I can tell the client to send the Authorization header from keycloak with every call?
PS: I tested it with a short react frontend and there it's working, so it seems to be an graphql client issue with the headers... Some ideas?
Not sure if you're using a dynamic or typesafe client, so I'll describe both.
For both types, if you have a key that doesn't change during the life of the application, you can configure that by adding a configuration property like this:
quarkus.smallrye-graphql-client.CLIENT_NAME.header.HEADER_NAME=HEADER_VALUE
(see https://quarkus.io/guides/all-config#quarkus-smallrye-graphql-client_quarkus-smallrye-graphql-client-smallrye-graphql-client)
If the value can change over time, I would probably recommend using the programmatic builder instead of using a statically configured client, like this:
DynamicGraphQLClientBuilder.newBuilder()
.header("KEY", "VALUE") // obtain the correct value from Keycloak and pass it here
....
and build a new client instance if the value changes.
For typesafe clients, an annotation-based way is described in https://smallrye.io/smallrye-graphql/1.4.3/typesafe-client-headers/
I don't know much about Keycloak though so I can't comment on the way how you obtain the header value from it.
Let me know some of this works for you
There doesn't seem to be a dynamic way of adding keycloak headers to the call.
I found a solution, to at least work as long as the token is valid.
For this I'm using a Client Class, which has an Interface Object of the GraphQL client and injects the header inside the constructor.I will need to add some code to renew the token, but it's enough to work with it right now :)
For those who want some code:
#Singleton
public class Client {
public IClient client;
public Client(JsonWebToken accessToken) {
client = TypesafeGraphQLClientBuilder.newBuilder()
.header("Authorization", "Bearer " + accessToken.getRawToken())
.build(IClient.class);
}
}
With this the Client can be build like shown at the Quarkus Guides :)

Best way to use Websocket with Spring Boot and Vuejs

I try to use Websocket with spring boot backend (as an API) and Vuejs frontend.
I take a simple use case to expose my question. Some users are logged on my website, and there is a messaging feature. User A send a message to User B. User B is actually logged, and I want to notify User B that a new message is arrived.
I see 3 ways to do it with websockets :
1 - When User A send message, an Axios post is call to the API for saving message, and, if the Axios response is success, I call something like
this.stompClient.send("/app/foo", JSON.stringify(bar), {})
2 - When User A send message, I only call something like
this.stompClient.send("/app/foo", JSON.stringify(bar), {})
and it's my controller's method (annotated with #MessageMapping("/xxxx") #SendTo("/topic/yyyy")) that call facade, service, dao to first, save message, then return message to subscribers
3 - I keep my actuals controllers, facade, services and DAO, and juste add when save is successfull something like :
#Autowired SimpMessagingTemplate webSocket;
...
#GetMapping("/send-message")
public ResponseEntity sendMessage(#AuthenticationPrincipal User user, ....) {
service.saveMessage(....);
webSocket.convertAndSend("/ws/message-from", message);
without a new controller contains #MessageMapping("/xxxx") #SendTo("/topic/yyyy"). User B is just subscibed to "/ws/message-from"
Could you help me.
In the 3 way there is a good method ?
Thanks you.
The one and two method has no much difference as you use axios from npm for sending request and the other one you can directly,while the third one you use controller,and facade dao at single place.it is about architecture and how you wanna send your requests for your framework,as a requirement.
They serve best at their level,till you come with specific requirement.
The suggestion would be to use axios.
It has advantages:
supports older browsers (Fetch needs a polyfill)
has a way to abort a request
has a way to set a response timeout
has built-in CSRF protection
supports upload progress
performs automatic JSON data transformation
works in Node.js

SPRING - Can't retrieve a ResponseEntity with Feign while sent correctly formated

I'm trying to communicate information between two micro services in Spring. One is sending a ResponseEntity with an Object in the body, but on the other side I can't seem to get the correct response. All the fields are null.
this is the controller of my first microservice
this is what is returned when called directly
this is the code inspection of the response before it's sent
Then I try to recuperate this response in another micro service.
This is the client
This is the call to the first API
This is the response I get
So I'm stuck there, not getting why my client can't access the data. I have set breakpoints in both of the application and the first one is correctly called.
You can find my code there : https://github.com/Shikatamo/B3Examples
I have tried for 3-4h, and I'm really stuck there. It looks like something really stupid from my part but I can't seem to put my finger on it. All help is greatly appreciated at this point.
Try to get rid of ResponseEntity in your client:
#Component
#FeignClient("CourseStudent")
public interface ICourseStudentClient {
#RequestLine("GET /{id}")
CourseStudents getOneById(#Param("id") Long id);
}

Encrypting URL parameters in spring MVC

I am creating an application using spring mvc, in all of my application i have written the methods using #Request Mapping in the following manner:
#RequestMapping(value = "/txnMst/{portNumber}", method = RequestMethod.GET)
As you can see that in the request mapping i am passing the portNumber which is displayed later in the URL like this (portNumber is 3333 in the example):
http://localhost:8080/admin/txnScript/txnMst/3333
Now i want to hide these data i.e the portNumber, is there any way how i can achieve this.
Please provide some help.
If the client doesn't need this data why are you storing it in URL? An alternative place to store that data is in the session.
Storing server values in client, expecting that them will be returned unaltered is a bad idea.

Spring REST client - force response before method finishes

I'm writing a REST service with Spring Web 4.0.5 and one of called methods is sending e-mail (with javax mail). Sending mail takes some time, but I would like to be able to send HTTP response (no matter what response, e.g. 200) BEFORE this method finishes - so before the mail is sent. Is it even possible? Preferably without multithreading?
#RestController
#RequestMapping(value = "/mails", produces = "application/json")
public class RestMailService{
#Autowired
MailService mailService;
#RequestMapping(value="/test", method = RequestMethod.GET)
public void sendMail(){
mailService.sendMail();
}
}
I believe all possible solutions include multithreading. The thread will be either directly started by you or hidden behind messaging or something similar.
if you were to go with multi-threading after all please use some Executor instead of below suggested new Thread(...).start()
I would also note that returning HTTP 200 before the operation finishes may somewhat confuse the user as the code suggests the operation was successful where in fact the operation maybe didn't even start yet.

Categories

Resources