bufferedreader disconnect suddenly - bufferedreader

I requested some data from server. So, i started asyncrontask. getGrup is get request of server.
getGrup="http://192.168.56.1:8084/Server/grup/getGrupId/tarihVeSaat/"
+grup.getGrupTarihVeSaat().getTime()+"/yoneticiId/"+grup.getYoneticiId()+";";
new GrupOlusturRequest().execute(getGrup);
sendUyeler="http://192.168.56.1:8084/Server/grupUyeleri/ekle";
while(true){
if(getGId){
hazırlaGrupUyeleri();
break;
}
But, Sometimes br.readline() returns null, i tested someone else rest client . it is always working. try-catch didn't throw exception. I can't understand that why it returns null variable.
url = new URL(param);
connection=(HttpURLConnection) url.openConnection();
connection.connect();
connection.setReadTimeout(100);
connection.setConnectTimeout(100);
is=connection.getInputStream();
br=new BufferedReader(new InputStreamReader(is,"UTF-8"));
String satir;
while((satir=br.readLine())!=null){
json2=new JSONObject(satir);
}
status=connection.getResponseCode();
Serverside:
Data sends as json from server. This method is resteasy get method. This method always works on postman rest client.
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("/getGrupId/tarihVeSaat/{tarihVeSaat}/yoneticiId/{yoneticiId}")
public Grup getGrupId(#PathParam ("tarihVeSaat") String tarihVeSaat,#PathParam ("yoneticiId") int yoneticiId){
Grup grup=null;
Timestamp tarih=new Timestamp(new java.util.Date(Long.parseLong(tarihVeSaat)).getTime());
try{
VeritabaniIslemleri vi=new VeritabaniIslemleri();
vi.baglan();
grup=vi.getGrupId(TarihVeSaat.tarihZamanGoster(tarih),yoneticiId);
vi.baglantiyiKes();
}catch(Exception e){
Logger.getLogger(KullaniciRestController.class.getName()).log(Level.SEVERE,null,e);
}
return grup;
}

According to the JavaDocs for BufferedReader.readLine() the only reason the method should return null is reaching the end of stream:
Returns:
A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached
If a timeout or communication problem occurred you should get an exception thrown.
Is it possible the web application you're connecting to is terminating the connection without flushing its output buffer? It sounds like the issue is probably on the other end of the connection.

Related

How to configure Spring's Rabbit Template to throw exception on timeout

I've been looking on google for a bit by now and I can't find a solution to my problem.
The problem is the default behavior of RabbitTemplate's methods, namely convertSendAndReceive() and convertSendAndReceiveAsType().
When you invoke these methods and they are not processed and replied to (default direct reply-to with queue=amq.rabbitmq.reply-to) the RabbitTemplate simply returns null response instead of indicating that message was not replied to.
That is pretty important when you send almost empty body on queue and expect to receive like user's books or something similar, with null response you can't tell if user has no books or if message wasn't processed in time.
Example invocation
final List<String> messages = rabbitTemplate.convertSendAndReceiveAsType("getMessagesQueue", 0, new ParameterizedTypeReference<>() {});
I found a workaround for this - using AsyncRabbitTemplate as it's RabbitConverterFuture throws exception on method .get(timeout), but that's not my go-to. I don't want to have to use AsyncRabbitTemplate just to get notified on unprocessed message.
Example
final AsyncRabbitTemplate.RabbitConverterFuture<List<String>> messages = asyncRabbitTemplate.convertSendAndReceiveAsType("getMessagesQueue", 0, new ParameterizedTypeReference<>() {});
try {
messages.get(5000, TimeUnit.MILLISECONDS);
} catch (InterruptedException | ExecutionException | TimeoutException e) {
// message not processed
}
My problem is how to configure RabbitTemplate (configure template itself, not wrap template calls with aspects, decorator, proxy or similar) to actually throw some exception instead of returning null values.
There is currently no such feature; feel free to open a new feature request on GitHub. https://github.com/spring-projects/spring-amqp/issues

Complete WebClient asynchronous example with Spring WebFlux

I am new to Reactive programming paradigm, but recently I have decided to base a simple Http client on Spring WebClient, since the old sync RestTemplate is already under maintenance and might be deprecated in upoming releases.
So first I had a look at Spring documentation and, after that, I've searched the web for examples.
I must say that (only for the time being) I have consciously decided not to go through the Reactor lib documentation, so beyond the Publisher-Subscriber pattern, my knowledge about Mono's and Flux's is scarce. I focused instead on having something working.
My scenario is a simple POST to send a callback to a Server from which the client is only interested in response status code. No body is returned. So I finally came up with this code snippet that works:
private void notifyJobSuccess(final InternalJobData jobData) {
SuccessResult result = new SuccessResult();
result.setJobId(jobData.getJobId());
result.setStatus(Status.SUCCESS);
result.setInstanceId(jobData.getInstanceId());
log.info("Result to send back:" + System.lineSeparator() + "{}", result.toString());
this.webClient.post()
.uri(jobData.getCallbackUrl())
.body(Mono.just(result), ReplaySuccessResult.class)
.retrieve()
.onStatus(s -> s.equals(HttpStatus.OK), resp -> {
log.info("Expected CCDM response received with HttpStatus = {}", HttpStatus.OK);
return Mono.empty();
})
.onStatus(HttpStatus::is4xxClientError, resp -> {
log.error("CCDM response received with unexpected Client Error HttpStatus {}. "
+ "The POST request sent by EDA2 stub did not match CCDM OpenApi spec", resp.statusCode());
return Mono.empty();
})
.onStatus(HttpStatus::is5xxServerError, resp -> {
log.error("CCDM response received with unexpected Server Error HttpStatus {}", resp.statusCode());
return Mono.empty();
}).bodyToMono(Void.class).subscribe(Eda2StubHttpClient::handleResponseFromCcdm);
}
My poor understanding of how the reactive WebClient works starts with the call to subscribe. None of the tens of examples that I checked before coding my client included such a call, but the fact is that before I included that call, the Server was sitting forever waiting for the request.
Then I bumped into the mantra "Nothing happens until you subscribe". Knowing the pattern Plublisher-Subscriber I knew that, but I (wrongly) assumed that the subscription was handled by WebClient API, in any of the exchage, or bodyToMono methods... block() definitely must subscribe, because when you block it, the request gets out at once.
So my first question is: is this call to subscribe() really needed?
Second question is why the method StubHttpClient::handleResponse is never called back. For this, the only explanation that I find is that as the Mono returned is a Mono<Void>, because there is nothing in the response besides the status code, as it is never instantiated, the method is totally dummy... I could even replace it by just .subscribe(). Is this a correct assumption.
Last, is it too much to ask for a complete example of a a method receiving a body in a Mono that is later consumed? All examples I find just focus on getting the request out, but how the Mono or Flux is later consumed is now beyond my understanding... I know that I have to end up checking the Reactor doc sooner better than later, but I would appreciate a bit of help because I am having issues with Exceptions and errors handlin.
Thanks!
Some time has passed since I asked for help here. Now I'd like not to edit but to add an answer to my previous question, so that the answer remains clear and separate from he original question and comments.
So here goes a complete example.
CONTEXT: An application, acting as a client, that requests an Access Token from an OAuth2 Authorization server. The Access Token is requested asynchronously to avoid blocking the appliction's thread while the token request is processed at the other end and the response arrives.
First, this is a class that serves Access Token to its clients (method getAccessToken): if the Access Token is already initialized and it's valid, it returns the value stored; otherwise fetches a new one calling the internal method fetchAccessTokenAsync:
public class Oauth2ClientBroker {
private static final String OAUHT2_SRVR_TOKEN_PATH= "/auth/realms/oam/protocol/openid-connect/token";
private static final String GRANT_TYPE = "client_credentials";
#Qualifier("oAuth2Client")
private final WebClient oAuth2Client;
private final ConfigurationHolder CfgHolder;
#GuardedBy("this")
private String token = null;
#GuardedBy("this")
private Instant tokenExpireTime;
#GuardedBy("this")
private String tokenUrlEndPoint;
public void getAccessToken(final CompletableFuture<String> completableFuture) {
if (!isTokenInitialized() || isTokenExpired()) {
log.trace("Access Token not initialized or has exired: go fetch a new one...");
synchronized (this) {
this.token = null;
}
fetchAccessTokenAsync(completableFuture);
} else {
log.trace("Reusing Access Token (not expired)");
final String token;
synchronized (this) {
token = this.token;
}
completableFuture.complete(token);
}
}
...
}
Next, we will see that fetchAccessTokenAsync does:
private void fetchAccessTokenAsync(final CompletableFuture<String> tokenReceivedInFuture) {
Mono<String> accessTokenResponse = postAccessTokenRequest();
accessTokenResponse.subscribe(tr -> processResponseBodyInFuture(tr, tokenReceivedInFuture));
}
Two things happen here:
The method postAccessTokenRequest() builds a POST request and declares how the reponse will be consumed (when WebFlux makes it available once it is received), by using exchangeToMono:
private Mono postAccessTokenRequest() {
log.trace("Request Access Token for OAuth2 client {}", cfgHolder.getClientId());
final URI uri = URI.create(cfgHolder.getsecServiceHostAndPort().concat(OAUHT2_SRVR_TOKEN_PATH));
} else {
uri = URI.create(tokenUrlEndPoint);
}
}
log.debug("Access Token endpoint OAuth2 Authorization server: {}", uri.toString());
return oAuth2Client.post().uri(uri)
.body(BodyInserters.fromFormData("client_id", cfgHolder.getEdaClientId())
.with("client_secret", cfgHolder.getClientSecret())
.with("scope", cfgHolder.getClientScopes()).with("grant_type", GRANT_TYPE))
.exchangeToMono(resp -> {
if (resp.statusCode().equals(HttpStatus.OK)) {
log.info("Access Token successfully obtained");
return resp.bodyToMono(String.class);
} else if (resp.statusCode().equals(HttpStatus.BAD_REQUEST)) {
log.error("Bad request sent to Authorization Server!");
return resp.bodyToMono(String.class);
} else if (resp.statusCode().equals(HttpStatus.UNAUTHORIZED)) {
log.error("OAuth2 Credentials exchange with Authorization Server failed!");
return resp.bodyToMono(String.class);
} else if (resp.statusCode().is5xxServerError()) {
log.error("Authorization Server could not generate a token due to a server error");
return resp.bodyToMono(String.class);
} else {
log.error("Authorization Server returned an unexpected status code: {}",
resp.statusCode().toString());
return Mono.error(new Exception(
String.format("Authorization Server returned an unexpected status code: %s",
resp.statusCode().toString())));
}
}).onErrorResume(e -> {
log.error(
"Access Token could not be obtained. Process ends here");
return Mono.empty();
});
}
The exchangeToMono method does most of the magic here: tells WebFlux to return a Mono that will asynchronously receive a signal as soon as the response is received, wrapped in a ClientResponse, the parameter resp consumed in the lambda. But it is important to keep in mind that NO request has been sent out yet at this point; we are just passing in the Function that will take the ClientResponse when it arrives and will return a Mono<String> with the part of the body of our interest (the Access Token, as we will see).
Once the POST is built and the Mono returned, then the real thing starts when we subscribe to the Mono<String> returned before. As the Reacive mantra says: nothing happens until you subscribe or, in our case, the request is not actually sent until something attempts to read or wait for the response. There are other ways in WebClient fluent API to implicitly subscribe, but we have chosen here the explicit way of returing the Mono -which implements the reactor Publisher interface- and subscribe to it. Here we blocking the thread no more, releasing CPU for other stuff, probably more useful than just waiting for an answer.
So far, so good: we have sent out the request, released CPU, but where the processing will continue whenever the response comes? The subscribe() method takes as an argument a Consumer parameterized in our case with a String, being nothing less than the body of the response we are waiting for, wrapped in Mono. When the response comes, WebFlux will notify the event to our Mono, which will call the method processResponseBodyInFuture, where we finally receive the response body:
private void processResponseBodyInFuture(final String body, final CompletableFuture<String> tokenReceivedInFuture) {
DocumentContext jsonContext = JsonPath.parse(body);
try {
log.info("Access Token response received: {}", body);
final String aTkn = jsonContext.read("$.access_token");
log.trace("Access Token parsed: {}", aTkn);
final int expiresIn = jsonContext.read("$.expires_in");
synchronized (this) {
this.token = aTkn;
this.tokenExpireTime = Instant.now().plusSeconds(expiresIn);
}
log.trace("Signal Access Token request completion. Processing will continue calling client...");
tokenReceivedInFuture.complete(aTkn);
} catch (PathNotFoundException e) {
try {
log.error(e.getMessage());
log.info(String.format(
"Could not extract Access Token. The response returned corresponds to the error %s: %s",
jsonContext.read("$.error"), jsonContext.read("$.error_description")));
} catch (PathNotFoundException e2) {
log.error(e2.getMessage().concat(" - Unexpected json content received from OAuth2 Server"));
}
}
}
The invocation of this method happens as soon as the Mono is signalled about the reception of the response. So here we try to parse the json content with an Access Token and do something with it... In this case call complete() onto the CompletableFuture passed in by the caller of the initial method getAccessToken, that hopefully will know what to do with it. Our job is done here... Asynchronously!
Summary:
To summarize, these are the basic considerations to have your request sent out and the responses processed when you ise reactive WebClient:
Consider having a method in charge of preparing the request by means of the WebClient fluent API (to set http method, uri, headers and body). Remember: by doing this you are not sending any request yet.
Think on the strategy you will use to obtain the Publisher that will be receive the http client events (response or errors). retreive() is the most straight forward, but it has less power to manipulate the response than exchangeToMono.
Subscribe... or nothing will happen.
Many examples you will find around will cheat you: they claim to use WebClient for asyncrhony, but then they "forget" about subscribing to the Publisher and call block() instead. Well, while this makes things easier and they seem to work (you will see responses received and passed to your application), the thing is that this is not asynchronous anymore: your Mono (or Flux, whatever you use) will be blocking until the response arrives. No good.
Have a separate method (being the Consumer passed in the subscribe() method) where the response body is processed.

How to consume message from RabbitMQ dead letter queue one by one

The requirement is like to process the messages from dead letter queue by exposed a REST service API(Spring Boot).
So that once REST service is called, one message will be consumed from the DL queue and will publish in the main queue again for processing.
#RabbitListener(queues = "QUEUE_NAME") consumes the message immediately which is not required as per the scenario. The message only has to be consumed by the REST service API.
Any suggestion or solution?
I do not think RabbitListener will help here.
However you could implement this behaviour manually.
Spring Boot automatically creates RabbitMq connection factory so you could use it. When http call is made just read single message from the queue manually, you could use basic.get to synchronously get just one message:
#Autowire
private ConnectionFactory factory
void readSingleMessage() {
Connection connection = null;
Channel channel = null;
try {
connection = factory.newConnection();
channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, true, false, false, null);
GetResponse response = channel.basicGet(QUEUE_NAME, true);
if (response != null) {
//Do something with the message
}
} finally {
//Check if not null
channel.close();
connection.close();
}
}
If you are using Spring; you can avoid all the boilerplate in the other answer using RabbitTemplate.receive(...).
EDIT
To manually ack/reject the message, use the execute method instead.
template.execute(channel -> {
GetResponse got = channel.basicGet("foo", false);
// ...
channel.basicAck(got.getEnvelope().getDeliveryTag(), false);
return null;
});
It's a bit lower level, but again, most of the boilerplate is taken care of for you.

DELETE in Spring RestTemplate with HttpEntity<List>

I don't know why my code is not working, I've tried with Postman and works fine:
But with RestTemplate I can´t get a response while it´s using the same endpoint... .
ResponseEntity<String> responseMS = template.exchange(notificationRestService, HttpMethod.DELETE, new HttpEntity<NotificationRestDTO[]>(arrNotif), String.class);
I've tried with List instead Array[]
When i made a PUT request it´s works fine but with one object:
ResponseEntity<String> responseMS = template.exchange(notificationRestService, HttpMethod.PUT, new HttpEntity<NotificationRestDTO>(notificationDTO), String.class);
Any help?? Thanks!!
From the comments it became clear that you're expecting it to return a 400 Bad Request response. RestTemplate will see these as "client errors" and it will throw a HttpClientErrorException.
If you want to handle cases like this, you should catch this exception, for example:
try {
ResponseEntity<String> responseMS = template.exchange(notificationRestService, HttpMethod.DELETE, new HttpEntity<NotificationRestDTO[]>(arrNotif), String.class);
} catch (HttpClientErrorException ex) {
String message = ex.getResponseBodyAsString();
}
In this case (since you expect a String), you can use the getResponseBodyAsString() method.
The ResponseEntity will only contain the data in case your request can be executed successfully (2xx status code, like 200, 204, ...). So, if you only expect a message to be returned if the request was not successfully, you can actually do what Mouad mentioned in the comments and you can use the delete() method of the RestTemplate.

JUnit needs special permissions?

My builds have been failing due to some of the integration tests I've been running. I'm stuck on why it won't work. Here is an example of the output:
I'm using Maven to first build, then it calls the JUnit tests. I'm seeing this 401 Unauthorized message in every single test, and I believe that's what is causing the builds to fail. In my mind, this means there are some permissions / authentication parameters that need to be set. Where would I go about doing this in JUnit?
Edit
#Test
public void testXmlHorsesNonRunners() throws Exception {
String servletUrl = SERVER + "sd/date/2013-01-13/horses/nonrunners";
Document results = issueRequest(servletUrl, APPLICATION_XML, false);
assertNotNull(results);
// debugDocument(results, "NonRunners");
String count = getXPathStringValue(
"string(count(hrdg:data/hrdg:meeting/hrdg:event/hrdg:nonrunner/hrdg:selection))",
results);
assertEquals("non runners", "45", count);
}
If you can, try to ignore the detail. Effectively, this is making a request. This is a sample of a test that uses the issueRequest method. This method is what makes HTTP requests. (This is a big method, which is why I didn't post it originally. I'll try to make it as readable as possible.
logger.info("Sending request: " + servletUrl);
HttpGet httpGet = null;
// InputStream is = null;
DefaultHttpClient httpclient = null;
try {
httpclient = new DefaultHttpClient();
doFormLogin(httpclient, servletUrl, acceptMime, isIrishUser);
httpGet = new HttpGet(servletUrl);
httpGet.addHeader("accept", acceptMime);
// but more importantly now add the user agent header
setUserAgent(httpGet, acceptMime);
logger.info("executing request" + httpGet.getRequestLine());
// Execute the request
HttpResponse response = httpclient.execute(httpGet);
// Examine the response status
StatusLine statusLine = response.getStatusLine();
logger.info(statusLine);
switch (statusLine.getStatusCode()) {
case 401:
throw new HttpResponseException(statusLine.getStatusCode(),
"Unauthorized");
case 403:
throw new HttpResponseException(statusLine.getStatusCode(),
"Forbidden");
case 404:
throw new HttpResponseException(statusLine.getStatusCode(),
"Not Found");
default:
if (300 < statusLine.getStatusCode()) {
throw new HttpResponseException(statusLine.getStatusCode(),
"Unexpected Error");
}
}
// Get hold of the response entity
HttpEntity entity = response.getEntity();
Document doc = null;
if (entity != null) {
InputStream instream = entity.getContent();
try {
// debugContent(instream);
doc = documentBuilder.parse(instream);
} catch (IOException ex) {
// In case of an IOException the connection will be released
// back to the connection manager automatically
throw ex;
} catch (RuntimeException ex) {
// In case of an unexpected exception you may want to abort
// the HTTP request in order to shut down the underlying
// connection and release it back to the connection manager.
httpGet.abort();
throw ex;
} finally {
// Closing the input stream will trigger connection release
instream.close();
}
}
return doc;
} finally {
// Release the connection.
closeConnection(httpclient);
}
I notice that your test output shows HTTP/1.1 500 Internal Server Error a couple of lines before the 401 error. I wonder if the root cause could be hiding in there. If I were you I'd try looking for more details about what error happened on the server at that point in the test, to see if it could be responsible for the authentication problem (maybe the failure is in a login controller of some sort, or is causing a session to be cancelled?)
Alternately: it looks like you're using the Apache HttpClient library to do the request, inside the issueRequest method. If you need to include authentication credentials in the request, that would be the code you'd need to change. Here's an example of doing HTTP Basic authentication in HttpClient, if that helps. (And more examples, if that one doesn't.)
(I'd second the observation that this problem probably isn't specific to JUnit. If you need to do more research, I'd suggest learning more about HttpClient, and about what this app expects the browser to send. One possibility: use something like Chrome Dev Tools to peek at your communications with the server when you do this manually, and see if there's anything important that the test isn't doing, or is doing differently.
Once you've figured out how to login, it might make sense to do it in a #Before method in your JUnit test.)
HTTP permission denied has nothing to do with JUnit. You probably need to set your credentials while making the request in the code itself. Show us some code.
Also, unit testing is not really meant to access the internet. Its purpose is for testing small, concise parts of your code which shouldn't rely on any external factors. Integration tests should cover that.
If you can, try to mock your network requests using EasyMock or PowerMock and make them return a resource you would load from your local resources folder (e.g. test/resources).

Resources