Following the question Does OkHttp support HTTP/2 server push?, are there any examples available on how receiving pushed content on the client side could be implemented?
How will the interaction of OkHttpClient, Request, Response and Http2Connection be? I understand that the Http2Connection has a PushObserver, but how will it play together with OkHttpClient and Request/Response?
Consider the snippet below. There is a client and a request. How would they come together with the PushObserver?
OkHttpClient client = getOkHttpClient();
Request request = new Request.Builder()
.url("https://nghttp2.org:443") // The Http2Server should be running here.
.build();
try {
Socket socket = client.socketFactory().createSocket();
Http2Connection con = new Http2Connection.Builder(true)
.socket(socket)
.pushObserver(new PushObserver(){
#Override
public boolean onRequest(int streamId, List<Header> requestHeaders) {
// do something here
return true;
}
#Override
public boolean onHeaders(int streamId,
List<Header> responseHeaders, boolean last) {
// do something here
return true;
}
#Override
public boolean onData(int streamId, BufferedSource source,
int byteCount, boolean last) throws IOException {
// do something here
return true;
}
#Override
public void onReset(int streamId, ErrorCode errorCode) {
// do something
}
}).build();
} catch (IOException e) {
LOG.error("IOException", e);
}
OkHttp has no public APIs for server push and it is unlikely to gain them. We’re building mechanisms to persist pushed responses into the cache, but it’s unlikely this will be visible to application code. You just get a faster response sometimes because the server pushed it into the cache.
If you need this kind of behavior please look at web sockets.
Related
I want to add code that would simulate latency in my WebClient calls so I could ensure my timeouts/retries/etc are working correctly.
Since WebClient is reactive and uses a thread pool, it seems like Thread.sleep would block the thread in a way that WebClient wouldn't typically be blocked in real usage.
Is there a better way to simulate that latency?
(Inspired by https://github.com/fletchgqc/chaos-monkey-spring-boot/pull/2/files#diff-7f7c533cc2b344aa04848a17d0eff0cda404a5ab3cc55a47bba9ed019fba82e3R9
public class LatencyInducingRequestInterceptor implements ClientHttpRequestInterceptor {
public ClientHttpResponse intercept(
HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
ClientHttpResponse response = execution.execute(request, body);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// do nothing
}
return response;
}
}
The answer is to use delayElement (The code I had posted above was for RestTemplate, that explains why Thread.sleep was used.
ExchangeFilterFunction latencyAddingFilterFunction =
(clientRequest, nextFilter) -> {
return nextFilter.exchange(clientRequest).delayElement(Duration.ofSeconds(2));
};
Following this tutorial, I am trying to set up a Sse Emitter. When I open the html page I get a
Resolved [org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation]
On client side (javascript) it sais it cannot connect to the server. I have tried various other tutorials, but I am clueless on why my code isnt working.
I set up a clean test project containing only and exactly the tutorial code.
I Was in the middle of doing something else when I got the same issue.
The code below fixed it.
Simply put Mismatch Media type.
#GetMapping(value = "/api/push/notification",headers = "Accept=*/*", consumes = MediaType.ALL_VALUE, produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public String doNotify(#RequestParam("authToken") String token, #RequestParam("clientId") String clientId, HttpServletResponse response) throws InterruptedException, IOException {
response.addHeader("charset","UTF-8");
final SseEmitter emitter = new SseEmitter(30000l);
service.addEmitter(clientId,emitter);
service.sendConnectedNotification(clientId);
emitter.onCompletion(() -> service.removeEmitter(clientId));
emitter.onTimeout(() -> service.removeEmitter(clientId));
return "Connected OK";
}
any my event handler
#Async
public void doNotify(String clientId, Object data) {
SseEmitter emitter= emitters.get(clientId);
if(emitter!=null) {
try {
emitter .send(SseEmitter.event() .reconnectTime(30000)
.data(data,MediaType.APPLICATION_JSON)
.id(UUID.randomUUID().toString())
.name("Notification")
.comment("Client connection notification")
);
} catch (Exception e) {
emitters.remove(clientId);
}
}
}
I have a GWT client which needs to call a Spring Boot MicroService. I think it can be similar to calling a rest web service, but is there any better way to do this ?
You can probably use RequestBuilder to call your API from the client side of your GWT app:
import com.google.gwt.http.client.RequestBuilder;
// ....
try {
new RequestBuilder(
RequestBuilder.GET, // GET, POST, etc.
url // url of your microservice endpoint
).sendRequest(null, new RequestCallback() { // replace null with your req body if needed
#Override
public void onResponseReceived(Request req, Response resp) {
// Parse resp.getText() which is hopefully a JSON string
}
#Override
public void onError(Request res, Throwable throwable) {
// handle errors
}
});
} catch (RequestException e) {
// log, rethrow... the usual
}
I am working on a micro-services based architecture which includes Spring-Boot, Eureka, Zuul at key level. My problem is as follows:
Service1 : /api/v1/service1 POST
Service2 : /api/v2/service2 POST
application.yml looks like
zuul:
routes:
service1:
path: /api/v1/**
service2:
path: /api/v1/**
common:
path: /common/endpoint
Also I have written a filter where I am trying to take input via this common endpoint and deduct based on post request where to enroute the request i.e. to service1 or service2. But here I am stuck and nothing seems to work out, even after several google searches and checking out other people's problem I am not yet able to found my solution.
here is how my Filter looks like:
public class CommonEndpointFilter extends ZuulFilter {
#Override
public boolean shouldFilter() {
RequestContext ctx = RequestContext.getCurrentContext();
if ((ctx.get("proxy") != null) && ctx.get("proxy").equals("common")) {
return true;
}
return false;
}
#Override
public Object run() {
RequestContext ctx = RequestContext.getCurrentContext();
HttpServletRequest request = ctx.getRequest();
InputStream in = (InputStream) ctx.get("requestEntity");
if (in == null) {
try {
in = request.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
String body = null;
try {
body = StreamUtils.copyToString(in, Charset.forName("UTF-8"));
if (body.indexOf("somethingrelatedtoservice1") != -1) {
//forward the request to Service1: /api/v1/service1
} else if (body.indexOf("somethingrelatedtoservice2") != -1) {
//forward the request to Service2: /api/v1/service2
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
public String filterType() {
return FilterConstants.ROUTE_TYPE;
}
#Override
public int filterOrder() {
return 0;
}
}
I am not able to figure out how to forward the request further to those services and then obtain response to send back via common endpoint.
What am I doing wrong here ? How can I proceed so I don't have to use hardcoded url of any of the service. Please guide me through this.
I have tried out some of the things like:
1. using DiscoveryClient to obtain instance and use setRouteHost method of context. It always throws a zuulfilter exception URL is not proper common/endpoint is appended after the url of service obtained via DiscoveryClient.
2. I tried stupidest thing that came to mind, using RestTemplate to make a request and obtain response and put that in context response which didn't work either, however request was forwarded to the service but I wouldn't receive any response.
Any help is appreciated!!
Am using restyGwt to send a request to jersey , I have closed the request using request object at client side(request.cancel) , but i found that the server is processing my request even though i closed at client side , it is never notified to server that the connection is stopped.
I want a way to tell the server as soon as the client cancel a request , to stop proccessing that request
this is my client resty gwt code
#POST
#Produces("application/json")
#Consumes("application/json")
#Path("servicepoint/getAllServicepointAndCount")
public Request findAllServicepointandCount(#QueryParam("startIndex") Integer startIndex,
#QueryParam("maxSize") Integer maxSize,
MethodCallback<ServicepointResponse> methodCallback);
this is the gwt class where am making my request to server
ServicepointRestyService service = GWT
.create(ServicepointRestyService.class);
((RestServiceProxy) service).setResource(resource);
final Request method=service.findAllServicepointandCount( index, length,
new MethodCallback<ServicepointResponse>() {
#Override
public void onFailure(Method method, Throwable exception) {
Window.alert(exception.getMessage());
}
#Override
public void onSuccess(Method method,
ServicepointResponse response) {
Window.alert("response.getMassege");
}
});
Timer t=new Timer() {
#Override
public void run() {
Window.alert("cancelled");
method.cancel();// cancel connection
}
};
t.schedule(2000);
}
jersey impl
#POST
#Produces("application/json")
#Consumes("application/json")
#Path("/getAllServicepointAndCount")
public ServicepointResponse findAllServicepointandCount(
#QueryParam("startIndex") Integer startIndex,
#QueryParam("maxSize") Integer maxSize) {
logger.finer("Entering startIndex" + startIndex + "" + maxSize);
ServicepointResponse data = new ServicepointResponse();
List<ServicepointPojo> spPojos = new ArrayList<>();
try {
while(true){
System.out.println(new Date().getTime());
Thread.sleep(1000);
}catch (Exception e) {
e.printStackTrace();
}
eventhough i stopped my request after 2sec, server still prints the date and time it never stoped , i have written this code to check this functionality