netty-readtimeout and return customized response to front end - timeout

I have a question regarding configuration of timeouts on a netty TCP server.
Currently we have configured readTimeOut as 120s. Set the connect timout like this:
socketChannel.pipeline().addLast(new ReadTimeoutHandler(120, TimeUnit.SECONDS));
But if the read time exceeds 120s, service doesn't response to front end correctly. If tested from postman, got the "Could not get any response" as response.
Following is the netty config we using:
public class EventLoopNettyCustomizer implements NettyServerCustomizer {
#Override
public HttpServer apply(HttpServer httpServer) {
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workGroup = new NioEventLoopGroup();
return httpServer.tcpConfiguration(tcpServer -> tcpServer
.bootstrap(serverBootstrap -> serverBootstrap
.group(bossGroup, workGroup)
.option(ChannelOption.SO_BACKLOG, 10000)
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 30000)
.childHandler(new ChannelInitializer<SocketChannel>() {
#Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline().addLast(new ReadTimeoutHandler(120, TimeUnit.SECONDS));
socketChannel.pipeline().addLast(new WriteTimeoutHandler(120, TimeUnit.SECONDS));
}
})
.channel(NioServerSocketChannel.class)));
}
}
How can I config the netty so that it is able to return customized response? Including http status and message.

Related

Request processing failed; nested exception is feign.RetryableException: Read timed out executing POST

I have made POST call with feignClient with "XYZ" object request message, then I didn't get response within "5" seconds (This is expected), so I sent "ERROR" object request to the same service but I didn't get any response and causing below error.
Request processing failed; nested exception is feign.RetryableException: Read timed out executing POST xyz.com/third-party/abc/1212 with root cause java.net.SocketTimeoutException: Read timed out
Code:
try {
ResponseEntity<Object> successResponseEntity = sapService.callService(XYZ);
} catch (RetryableException e) {
ResponseEntity<Object> errorResponseEntity = sapService.callService(ERROR);
}
// fiegn client
#FeignClient(name = "sapService", url = "${abc.url}", configuration = FeignClientInterceptorConfiguration.class)
public interface SapService {
#PostMapping(path = "${endpoint}")
ResponseEntity<Object> callService(#PathVariable(value = "name") String name, #RequestBody Object request);
}
public class FeignClientInterceptorConfiguration {
#Bean
public Retryer retryer(ApplicationContext applicationContext) {
return Retryer.NEVER_RETRY;
}
}
Application.yaml
feign:
client:
config:
SapService:
readTimeout: 5000
connectTimeout: 5000

How To Consume Stream HTTP Response In Java?

I'm having trouble trying to consume the Response of an HTTP Endpoint which Streams real-time events continously. It's actually one of Docker's endpoints: https://docs.docker.com/engine/api/v1.40/#operation/SystemEvents
I am using Apache HTTP Client 4.5.5 and it just halts indefinitely when I try to consume the content InputStream:
HttpEntity entity = resp.getEntity();
EntityUtils.consume(entity);//it just hangs here.
//Even if I don't call this method, Apache calls it automatically
//after running all my ResponseHandlers
Apparently, it can be done by using JDK's raw URL: Stream a HTTP response in Java
But I cannot do that since local Docker communicates over a Unix Socket which I only managed to configure in Apache's HTTP Client with a 3rd party library for Unix Sockets in Java.
If there is a smarter HTTP Client library which I could switch to, that would also be an option.
Any ideas would be greatly appreciated. Thank you!
I managed to solve this issue by generating an infinite java.util.stream.Stream of JsonObject from the response InputStream (I know the json reading part is not the most elegant solution but there is no better way with that API and also, Docker doesn't send any separator between the jsons).
final InputStream content = response.getEntity().getContent();
final Stream<JsonObject> stream = Stream.generate(
() -> {
JsonObject read = null;
try {
final byte[] tmp = new byte[4096];
while (content.read(tmp) != -1) {
try {
final JsonReader reader = Json.createReader(
new ByteArrayInputStream(tmp)
);
read = reader.readObject();
break;
} catch (final Exception exception) {
//Couldn't parse byte[] to Json,
//try to read more bytes.
}
}
} catch (final IOException ex) {
throw new IllegalStateException(
"IOException when reading streamed JsonObjects!"
);
}
return read;
}
).onClose(
() -> {
try {
((CloseableHttpResponse) response).close();
} catch (final IOException ex) {
//There is a bug in Apache HTTPClient, when closing
//an infinite InputStream: IOException is thrown
//because the client still tries to read the remainder
// of the closed Stream. We should ignore this case.
}
}
);
return stream;

ActiveMQ test connection

I am trying to test ActiveMQ connection and return a value. it crashes on line:
httpResponse = client.execute(theHttpGet);
It is not my code I am trying to debug it. Can anyone help me to understand why the code is using HttpGet?
public ActivemqBrokerInfo(String serverAddress, int port, String apiUrl, int timeout) {
// Default Activemq location
this.serverAddress = String.format("http://%s:%s/%s", serverAddress, port, apiUrl);
int timeoutInMs = timeout;
HttpClientBuilder builder = HttpClientBuilder.create();
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeoutInMs).build();
builder.setDefaultRequestConfig(requestConfig);
client = builder.build();
}
public ActivemqBrokerInfo(String serverAddress) {
this(serverAddress, DEFAULT_PORT, DEFAULT_API_URL, DEFAULT_TIMEOUT);
}
#Override
public boolean testConnection() {
HttpGet theHttpGet = new HttpGet(serverAddress);
theHttpGet.addHeader("test-header-name", "test-header-value");
HttpResponse httpResponse = null;
try{
httpResponse = client.execute(theHttpGet);// Code is crashing on this line
} catch (IOException ex){
LOGGER.error("Broker down: ", ex);
}
return httpResponse != null;
}
When ActiveMQ runs is normally starts an embedded web server. This web server is used to host the web admin console as well as the Jolokia endpoint which acts as an HTTP facade in front of the broker's MBeans. In other words, any client can send HTTP requests to specially formed URLs on the broker to get results from the underlying management beans. This is exactly what your bit of code appears to be doing. It appears to be sending an HTTP request to the Jolokia endpoint (i.e. api/jolokia) in order to determine if the broker is alive or not.
Based on the information provided it is impossible to determine why testConnection() is not returning successfully since you've included no information about the configuration or state of the broker.
I recommend you add additional logging to see what may be happening and also catch Exception rather than just IOException.

Volley android "javax.net.ssl.SSLHandshakeException: Handshake failed"

Hi I'm rebuilding a API call using volley library
this is my test code to send XML data and receive xml response (I just need to successfully receive response in string format)
String url ="https://prdesb1.singpost.com/ma/FilterOverseasPostalInfo";
final String payload = "<OverseasPostalInfoDetailsRequest xmlns=\"http://singpost.com/paw/ns\"><Country>AFAFG</Country><Weight>100</Weight><DeliveryServiceName></DeliveryServiceName><ItemType></ItemType><PriceRange>999</PriceRange><DeliveryTimeRange>999</DeliveryTimeRange></OverseasPostalInfoDetailsRequest>\n";
RequestQueue mRequestQueue;
// Instantiate the cache
Cache cache = new DiskBasedCache(getCacheDir(), 1024 * 1024); // 1MB cap
// Set up the network to use HttpURLConnection as the HTTP client.
Network network = new BasicNetwork(new HurlStack());
// Instantiate the RequestQueue with the cache and network.
mRequestQueue = new RequestQueue(cache, network);
// Start the queue
mRequestQueue.start();
// Formulate the request and handle the response.
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Do something with the response
Log.v("tesResponse","testResponseS");
Log.v("response",response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Handle error
Log.v("tesResponse","testResponseF");
Log.v("error",error.toString());
}
}
){
#Override
public String getBodyContentType() {
return "application/xml; charset=" +
getParamsEncoding();
}
#Override
public byte[] getBody() throws AuthFailureError {
String postData = payload;
try {
return postData == null ? null :
postData.getBytes(getParamsEncoding());
} catch (UnsupportedEncodingException uee) {
// TODO consider if some other action should be taken
return null;
}
}
};
// stringRequest.setRetryPolicy(new DefaultRetryPolicy(5*DefaultRetryPolicy.DEFAULT_TIMEOUT_MS, 0, 0));
stringRequest.setRetryPolicy(new DefaultRetryPolicy(0, 0, 0));
// Add the request to the RequestQueue.
mRequestQueue.add(stringRequest);
I have test the String url and the payload on POSTMAN and give successful result. But don't know why my android app give this error
08-22 19:44:24.335 16319-16518/com.example.victory1908.test1 D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
[ 08-22 19:44:24.355 16319:16319 D/ ]
HostConnection::get() New Host Connection established 0x7f67de64eac0, tid 16319
[ 08-22 19:44:24.399 16319:16518 D/ ]
HostConnection::get() New Host Connection established 0x7f67de64edc0, tid 16518
08-22 19:44:24.410 16319-16518/com.example.victory1908.test1 I/OpenGLRenderer: Initialized EGL, version 1.4
08-22 19:44:24.662 16319-16319/com.example.victory1908.test1 V/tesResponse: testResponseF
08-22 19:44:24.662 16319-16319/com.example.victory1908.test1 V/error: com.android.volley.NoConnectionError: javax.net.ssl.SSLHandshakeException: Handshake failed
Just notice problem only with API 23+ (android 6.0 and above) API 22 is working fine!
I have tried set the retry policy but does not work. Anyone know what wrong with the code. Thanks in advance

JavaMail store.connect() times out - Can't read gmail Inbox through Java

I am trying to connect to my gmail inbox to read messages through Java Application. I am using..
jdk1.6.0_13
javamail-1.4.3 libs - (mail.jar, mailapi.jar, imap.jar)
Below is my code : MailReader.java
import java.util.Properties;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;
public class MailReader
{
public static void main(String[] args)
{
readMail();
}
public static void readMail()
{
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
try
{
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com", "myEmailId#gmail.com", "myPwd");
System.out.println("Store Connected..");
//inbox = (Folder) store.getFolder("Inbox");
//inbox.open(Folder.READ_WRITE);
//Further processing of inbox....
}
catch (MessagingException e)
{
e.printStackTrace();
}
}
}
I expect to get store connected, but call to store.connect() never returns and I get below output :
javax.mail.MessagingException: Connection timed out;
nested
exception is:
java.net.ConnectException: Connection timed out
at
com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:441)
at
javax.mail.Service.connect(Service.java:233)
at
javax.mail.Service.connect(Service.java:134)
at
ReadMail.readMail(ReadMail.java:21)
at ReadMail.main(ReadMail.java:10)
However I am able to SEND email by Java using SMTP, Transport.send() and same gmail account. But cannot read emails.
What can be the solution ?
IMAP work off a different port (143 for non-secure, 993 for secure) to sendmail (25) and I suspect that's blocked. Can you telnet on that port to that server e.g.
telnet imap.gmail.com {port number}
That'll indicate if you have network connectivity.

Resources