How do I get a byte[] (image) from a webservice using micronaunt HttpClient - download

I am porting a Grails 3.1 library for using some internal webservices to Grails 4.0. One of the services provides an image of a requested employee upon request. I am having difficulty implementing the (micronaut) HttpClient code to process the request - specifically to get a proper byte[] that is the returned image.
A simple curl command on the command line works with the service:
curl -D headers.txt -H 'Authorization:Basic <encodedKeyHere>' https:<serviceUrl> >> image.jpg
and the image is correct. The header.txt is:
HTTP/1.1 200
content-type: image/jpeg;charset=UTF-8
date: Tue, 27 Aug 2019 20:05:43 GMT
x-ratelimit-limit: 100
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 99
x-ratelimit-remaining: 99
X-RateLimit-Reset: 38089
x-ratelimit-reset: 15719
Content-Length: 11918
Connection: keep-alive
The old library uses the groovyx.net.http.HTTPBuilder and simply does:
http.request(Method.GET, ContentType.BINARY) {
uri.path = photoUrlPath
uri.query = queryString
headers.'Authorization' = "Basic $encoded".toString()
response.success = { resp, inputstream ->
log.info "response status: ${resp.statusLine}"
return ['status':resp.status, 'body':inputstream.getBytes()]
}
response.failure = { resp ->
return ['status':resp.status,
'error':resp.statusLine.reasonPhrase,
body:resp.getEntity().getContent().getText()]
}
}
so returning the bytes from an inputStream. This works.
I've tried several things using the micronaut HttpClient, both with the low level API and with the declarative API.
A simple example with the declarative API:
#Get(value='${photo.ws.pathurl}', produces = MediaType.IMAGE_JPEG)
HttpResponse<byte[]> getPhoto(#Header ('Authorization') String authValue,
#QueryValue("emplId") String emplId)
And than in the Service:
HttpResponse<byte[]> resp = photoClient.getPhoto(getBasicAuth(),emplId)
def status = resp.status() // code == 200 --> worked
def bodyStrOne = resp.getBody() // nope: get Optional.empty
// Tried different getBody(class) -> Can't figure out where the byte[]s are
// For example can do:
def buf = resp.getBody(io.netty.buffer.ByteBuf).value // Why need .value?
def bytes = buf.readableBytes() // Returns 11918 --> the expected value
byte[] ans = new byte[buf.readableBytes()]
buf.readBytes(ans) // Throws exception: io.netty.util.IllegalReferenceCountException: refCnt: 0
This "works" but the returned String looses some encoding that I can't reverse:
// Client - use HttpResponse<String>
#Get(value='${photo.ws.pathurl}', produces = MediaType.IMAGE_JPEG)
HttpResponse<String> getPhoto(#Header ('Authorization') String authValue,
#QueryValue("emplId") String emplId)
// Service
HttpResponse<String> respOne = photoClient.getPhoto(getBasicAuth(),emplId)
def status = respOne.status() // code == 200 --> worked
def bodyStrOne = respOne.getBody(String.class) // <-- RETURNS DATA..just NOT an Image..or encoded or something
String str = bodyStrOne.value // get the String data
// But these bytes aren't correct
byte[] ans = str.getBytes() // NOT an image..close but not.
// str.getBytes(StandardCharsets.UTF_8) or any other charset doesn't work
Everything I've tried with the ByteBuf classes throws the io.netty.util.IllegalReferenceCountException: refCnt: 0 exception.
Any direction/help would be greatly appreciated.
Running:
Grails 4.0
JDK 1.8.0_221
Groovy 2.4.7
Windows 10
IntellJ 2019.2

It must be Grails bug.
Add this line into logback.groovy:
logger("io.micronaut.http", TRACE)
Then you should see that the body was not empty but finally it ends with error Unable to convert response body to target type class [B. See the trace:
2019-09-11 11:19:16.235 TRACE --- [ntLoopGroup-1-4] i.m.http.client.DefaultHttpClient : Status Code: 200 OK
2019-09-11 11:19:16.235 TRACE --- [ntLoopGroup-1-4] i.m.http.client.DefaultHttpClient : Content-Type: image/jpeg
2019-09-11 11:19:16.235 TRACE --- [ntLoopGroup-1-4] i.m.http.client.DefaultHttpClient : Content-Length: 11112
2019-09-11 11:19:16.237 TRACE --- [ntLoopGroup-1-4] i.m.http.client.DefaultHttpClient : Accept-Ranges: bytes
2019-09-11 11:19:16.237 TRACE --- [ntLoopGroup-1-4] i.m.http.client.DefaultHttpClient : Response Body
2019-09-11 11:19:16.237 TRACE --- [ntLoopGroup-1-4] i.m.http.client.DefaultHttpClient : ----
2019-09-11 11:19:16.238 TRACE --- [ntLoopGroup-1-4] i.m.http.client.DefaultHttpClient : ���� C
...
2019-09-11 11:19:16.241 TRACE --- [ntLoopGroup-1-4] i.m.http.client.DefaultHttpClient : ----
2019-09-11 11:19:16.243 TRACE --- [ntLoopGroup-1-4] i.m.http.client.DefaultHttpClient : Unable to convert response body to target type class [B
But when you try the same in standalone Microunaut application (add <logger name="io.micronaut.http" level="trace"/> into logback.xml) the result is different:
09:02:48.583 [nioEventLoopGroup-1-5] TRACE i.m.http.client.DefaultHttpClient - Status Code: 200 OK
09:02:48.583 [nioEventLoopGroup-1-5] TRACE i.m.http.client.DefaultHttpClient - Content-Type: image/jpeg
09:02:48.589 [nioEventLoopGroup-1-5] TRACE i.m.http.client.DefaultHttpClient - content-length: 23195
09:02:48.590 [nioEventLoopGroup-1-5] TRACE i.m.http.client.DefaultHttpClient - Response Body
09:02:48.590 [nioEventLoopGroup-1-5] TRACE i.m.http.client.DefaultHttpClient - ----
09:02:48.612 [nioEventLoopGroup-1-5] TRACE i.m.http.client.DefaultHttpClient - ���� C���
...
09:02:48.620 [nioEventLoopGroup-1-5] TRACE i.m.http.client.DefaultHttpClient - ----
Micronaut trace has no error.
Here is an example of declarative HTTP client which downloads random image from https://picsum.photos web site:
import io.micronaut.http.HttpResponse
import io.micronaut.http.MediaType
import io.micronaut.http.annotation.Get
import io.micronaut.http.client.annotation.Client
#Client('https://picsum.photos')
interface LoremPicsumClient {
#Get(value = '{width}/{height}', produces = MediaType.IMAGE_JPEG)
HttpResponse<byte[]> getImage(Integer width, Integer height)
}
And Spock unit test for it:
import io.micronaut.http.HttpStatus
import io.micronaut.test.annotation.MicronautTest
import spock.lang.Specification
import javax.inject.Inject
import java.nio.file.Files
import java.nio.file.Paths
#MicronautTest
class LoremPicsumClientSpec extends Specification {
#Inject
LoremPicsumClient client
void 'image is downloaded'() {
given:
def output = Paths.get('test')
when:
def response = client.getImage(300, 200)
then:
response.status == HttpStatus.OK
response.getBody().isPresent()
when:
Files.write(output, response.getBody().get())
then:
Files.probeContentType(output) == 'image/jpeg'
}
}
In Micronaut the test passes and an image is saved into the test file. But in Grails the test fails because HttpClient is not able to convert the response bytes into byte array or better into anything else then String.

We are currently using this implementation:
#Client(value = "\${image-endpoint}")
interface ImageClient {
#Get("/img")
fun getImageForAddress(
#QueryValue("a") a: String
): CompletableFuture<ByteArray>
}
works fine for us.
When I use the HttpResponse I get an error as well, couldn't make it work with that.

Documentation propose to send bytes via input stream but I didn't manage to make it work. The most brittle thing that HttpClient should Consume bytes but Server should Produce.
#Get(value = "/write", produces = MediaType.TEXT_PLAIN)
HttpResponse<byte[]> write() {
byte[] bytes = "test".getBytes(StandardCharsets.UTF_8);
return HttpResonse.ok(bytes); //
}

Related

Spring WebFlux - WebGraphQlInterceptor has empty request data

I would need to retrieve data from query headers for use in the GraphQl query controller. I searched around a bit and found the WebGraphQlInterceptor, but realized that when the WebGraphQlRequest argument is invoked it is completely devoid of information.
For example, this code:
#Component
class WebRequestInterceptor : WebGraphQlInterceptor {
val logger: Logger by lazy { LoggerFactory.getLogger(WebRequestInterceptor::class.java) }
override fun intercept(request: WebGraphQlRequest, chain: WebGraphQlInterceptor.Chain): Mono<WebGraphQlResponse> {
logger.info("URI", request.uri.toString())
logger.info("HEADERS", request.headers.toString())
logger.info("DOCUMENT", request.document)
return chain.next(request)
}
}
Returns:
2022-09-12 10:57:11.747 INFO 1 --- [or-http-epoll-1] b.s.b.gateway.auth.WebRequestInterceptor : URI *empty string*
2022-09-12 10:57:11.748 INFO 1 --- [or-http-epoll-1] b.s.b.gateway.auth.WebRequestInterceptor : HEADERS *empty string*
2022-09-12 10:57:11.748 INFO 1 --- [or-http-epoll-1] b.s.b.gateway.auth.WebRequestInterceptor : DOCUMENT *empty string*
P.S. The same thing happens if I try to log a single headers element using the request.headers.getFirst(..) function.

Spring Boot : Cannot replace Jackson with Gson , jackson still appears in logs

Gson dependency
implementation("com.google.code.gson:gson:2.9.0")
application-dev.properties
spring.http.converters.preferred-json-mapper=gson
# Format to use when serializing Date objects.
spring.gson.date-format="yyyy-MM-dd HH:mm:ss"
Function to handle incoming post request with data payload
#RequestMapping(path = [ControllerEndPoints.AddCheckingPoint], method = [RequestMethod.POST])
fun addCheckingPoint(#RequestBody reqData: ChartServerVo): ResponseEntity<Ack> {
var ok = true
val data = CheckingPointEntity()
val cpDto = reqData.checkingPointDto
val gson = GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create()
val payload = gson.toJson(reqData)
mLog("json: \n json $payload")
//val gDto = reqData.gDto
data.apply {
name = cpDto.name
description = cpDto.description
cpTypeId = cpDto.cpTypeId
isCumulative = cpDto.isCumulative
cpCategoryGroupId = cpDto.cpCategoryGroupId
isTemplate = cpDto.isTemplate
isTopTemplate = cpDto.isTopTemplate
}
cpr.save(data)
pcRepo.save(reqData.purusharthChartDto.toEntity())
pcMappingrepo.save(reqData.purusharthChartCpMappingDto.toEntity())
return ResponseEntity(Ack(ok), HttpStatus.ACCEPTED)
}
JSON Payload
{"checkingPointDto":{"cpCategoryGroupId":1641785600780,"cpTypeId":1,"description":"","isCumulative":false,"isTemplate":false,"isTopTemplate":false,"name":"asdf","dbCreateDts":"2022-03-05 11:54:01","dbCreateSource":"","dbUpdateDts":"2022-03-05 11:54:01","dbUpdateSource":"","id":0},"purusharthChartCpMappingDto":{"cpId":0,"id":0,"purusharthChartId":1647652877927},"purusharthChartDto":{"adminID":0,"description":"","endDate":"2022-12-30 11:54:01","id":1647652877927,"isSelfChart":false,"name":"asdf","startDate":"2022-03-05 11:54:01","userId":8}}
Error log
POST "/api/v1/cp-add", parameters={}
2022-03-05 16:52:32.118 DEBUG 1360 --- [nio-9000-exec-2] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to in_.co.innerpeacetech.bkp.controller.CheckingPointController#addCheckingPoint(ChartServerVo)
2022-03-05 16:52:32.358 DEBUG 1360 --- [nio-9000-exec-2] o.s.web.method.HandlerMethod : Could not resolve parameter [0] in public org.springframework.http.ResponseEntity<in_.co.innerpeacetech.bkp.dto.Ack> in_.co.innerpeacetech.bkp.controller.CheckingPointController.addCheckingPoint(in_.co.innerpeacetech.bkp.dto.ChartServerVo): JSON parse error: Cannot construct instance of `in_.co.innerpeacetech.bkp.dto.ChartServerVo`, problem: `java.lang.IllegalArgumentException`; nested exception is com.fasterxml.jackson.databind.exc.ValueInstantiationException: Cannot construct instance of `in_.co.innerpeacetech.bkp.dto.ChartServerVo`, problem: `java.lang.IllegalArgumentException`
at [Source: (PushbackInputStream); line: 1, column: 2]
2022-03-05 16:52:32.365 WARN 1360 --- [nio-9000-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot construct instance of `in_.co.innerpeacetech.bkp.dto.ChartServerVo`,
My data class variable from the error log
#JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
var dbCreateDts: Date = Date(),
Why is com.fasterxml.jackson.databind still present in the logs and why is the params empty in the logs POST "/api/v1/cp-add", parameters={}, I am testing the api from postman and the headers and everything is fine and the json is also properly formatted. I am new to spring, what am I missing.

Accessing server and mule context objects in Data weave

I'm trying to access server and mule version info in DW however I get the below message.
DWL looks like below. Please let me know if I'm making any mistakes below. I have tried both the syntaxes to access it.
%dw 1.0
%output application/json
---
{
errorType : payload.errorType,
env: server['host'],
host: server['host'],
ip: server['ip'],
javaVersion: server['javaVersion'],
javaVendor: server['javaVendor'],
osName: server['osName'],
osVersion: server['osVersion'],
muleVersion: mule.version,
clusterId: mule.clusterId,
nodeId: mule.nodeId
}
Message : Exception while executing:
env: server['host'],
^
There is no variable named 'server'.
Payload : {correlationId=046b6c7f-0b8a-43b9-b35d-6489e6daee91, message=This is the test message to test structured log, errorType=ERROR, applicationName=common wrappers - logging wrapper}
Payload Type : java.util.HashMap
Element : /wrapper-logger/processors/1 # common-wrappers:wrapper-logger.xml:16 (Transform Message)
Element XML : <dw:transform-message doc:name="Transform Message" metadata:id="38c29630-7d7c-48fc-a692-2407d0105cab">
<dw:input-payload doc:sample="sample_data\list_HashMap.dwl"></dw:input-payload>
<dw:set-payload>%dw 1.0%output application/json---{errorType : payload.errorType,env: server['host'],host: server['host'],ip: server['ip'],javaVersion: server['javaVersion'],javaVendor: server['javaVendor'],osName: server['osName'],osVersion: server['osVersion'],muleVersion: mule.version,clusterId: mule.clusterId,nodeId: mule.nodeId,applicationName : payload.applicationName,correlationId: payload.correlationId,correlationSequence: "To be decided",correlationGroupSize: 5,timeZone: server.timeZone,timeStamp: server.dateTime,muleFlow: "get-user-record",stackTrace: "A complete Stack Trace",message: payload.message}</dw:set-payload>
</dw:transform-message>
--------------------------------------------------------------------------------
Root Exception stack trace:
com.mulesoft.weave.mule.exception.WeaveExecutionException: Exception while executing:
env: server['host'],
^
There is no variable named 'server'.
at com.mulesoft.weave.mule.exception.WeaveExecutionException$.apply(WeaveExecutionException.scala:10)
You can define a Global function to get the server details and call it from dataweave.
<configuration doc:name="Configuration">
<expression-language>
<import class = "org.mule.util.NetworkUtils"/>
<import class="java.lang.System" />
<global-functions>
def getServerDetails() {
String ip = NetworkUtils.getLocalHost().getHostAddress();
String name = NetworkUtils.getLocalHost().getHostName();
String osName = System.getProperty("os.name");
String osVersion = System.getProperty("os.version");
String javaVersion = System.getProperty("java.version");
String javaVendor = System.getProperty("java.vendor");
return [ip, name, osName, osVersion, javaVersion, javaVendor];
}
</global-functions>
</expression-language>
</configuration>
Calling from dataweave
{
ip: getServerDetails()[0],
host: getServerDetails()[1],
osName: getServerDetails()[2],
osVersion: getServerDetails()[3],
javaVersion: getServerDetails()[4],
javaVendor: getServerDetails()[5]
}

Spock test - RESTClient: HttpResponseException: Not Found

I want to write a test for a GET request when the API returns 404.
My test:
def "Should return 404 - object deleted before"() {
setup:
def advertisementEndpoint = new RESTClient( 'http://localhost:8080/' )
when:
def resp = advertisementEndpoint.get(
path: 'api/advertisement/1',
contentType: groovyx.net.http.ContentType.JSON
)
then:
resp.status == 404
}
My error:
14:24:59.294 [main] DEBUG o.a.h.impl.client.DefaultHttpClient -
Connection can be kept alive indefinitely 14:24:59.305 [main] DEBUG
groovyx.net.http.RESTClient - Response code: 404; found handler:
org.codehaus.groovy.runtime.MethodClosure#312aa7c 14:24:59.306 [main]
DEBUG groovyx.net.http.RESTClient - Parsing response as:
application/json 14:24:59.443 [main] DEBUG org.apache.http.wire - <<
"ba[\r][\n]" 14:24:59.444 [main] DEBUG org.apache.http.wire - <<
"{"timestamp":1436358299234,"status":404,"error":"Not
Found","exception":"com.pgssoft.exparo.web.ResourceNotFoundException","message":"No
message available","path":"/api/advertisement/1"}" 14:24:59.445 [main]
DEBUG org.apache.http.wire - << "[\r][\n]" 14:24:59.445 [main] DEBUG
org.apache.http.wire - << "0[\r][\n]" 14:24:59.446 [main] DEBUG
org.apache.http.wire - << "[\r][\n]" 14:24:59.446 [main] DEBUG
o.a.h.i.c.BasicClientConnectionManager - Releasing connection
org.apache.http.impl.conn.ManagedClientConnectionImpl#2ab4bc72
14:24:59.446 [main] DEBUG o.a.h.i.c.BasicClientConnectionManager -
Connection can be kept alive indefinitely 14:24:59.449 [main] DEBUG
groovyx.net.http.RESTClient - Parsed data to instance of: class
groovy.json.internal.LazyMap
groovyx.net.http.HttpResponseException: Not Found at
groovyx.net.http.RESTClient.defaultFailureHandler(RESTClient.java:263)
at groovy.lang.Closure.call(Closure.java:423) at
groovyx.net.http.HTTPBuilder$1.handleResponse(HTTPBuilder.java:503)
at
org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:218)
at
org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:160)
at groovyx.net.http.HTTPBuilder.doRequest(HTTPBuilder.java:515) at
groovyx.net.http.RESTClient.get(RESTClient.java:119) at
AdvertisementTest.Should return 404 - object delete
before(AdvertisementTest.groovy:79)
You need a failure handler for the underlying HTTPBuilder. From the HTTPBuilder javadoc:
You can also set a default response handler called for any status code
399 that is not matched to a specific handler. Setting the value outside a request closure means it will apply to all future requests
with this HTTPBuilder instance:
http.handler.failure = { resp ->
println "Unexpected failure: ${resp.statusLine}" }
Therefore:
#Grapes(
#Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.7.1')
)
import groovyx.net.*
import groovyx.net.http.*
def restClient = new RESTClient('http://localhost/wrong')
restClient.handler.failure = { resp -> resp.status }
def response = restClient.get([:])
assert response == 404

Play framework - java.nio.channels.ClosedChannelException

Here is the scenario.
I am using Play framework. Inside a given handler, the play framework calls my API webservice and returns the API response to the client. The client is calling the handler through an Ajax call. Sometimes the response comes fine but often i am seeing error response on the client side. Checking the logs of play framework, i see a java.nio.channels.ClosedChannelException.
I am using Play 2.1.1.
My API Webservice is running on localhost:8888. Play framework is running on 9000.
The API service response is correct. Play frameworks also executes the Callback correctly as i can see the logs. The error happens after the ok() call has been made from Play.
Here are the error logs for a failed request -
[debug] application - find...
[debug] application - id = 647110558
[trace] c.jolbox.bonecp - Check out connection [9 leased]
[trace] c.jolbox.bonecp - Check in connection [9 leased]
[debug] application - socialUser = SocialUser(UserId(647110558,facebook),Arvind,Batra,Arvind Batra,Some(arvindbatra#gmail.com),null,AuthenticationMethod(oauth2),null,Some(OAuth2Info(CAAHNVOUuNZAEBAMa3CPLUEsZA2Tp5xWGXylO9HggBY0TCfwsIn4iGUdlRMpuNPLxYcObKO5ZBZCU0ghS9ymHZC3s9YXpsfPix9AM1EhNyETvDR85HHYg8j7JO0h2WzGZBsKJdbFPhPmkD6ZBZAq6KTT8RLSQrmpfnHQZD,null,null,null)),null)
[info] application - Calling interest for fff
[info] application - user is not null
[trace] c.jolbox.bonecp - Check out connection [9 leased]
[info] application - interest=fff, userInfo:models.EBUser#14a420e1
[info] application - http://localhost:8888/api/add_interest/1/fff
[debug] c.n.h.c.p.n.NettyAsyncHttpProvider - Using cached Channel [id: 0x9d1dee2d, /127.0.0.1:50316 => localhost/127.0.0.1:8888]
for uri http://localhost:8888/api/add_interest/1/fff
[debug] c.n.h.c.p.n.NettyAsyncHttpProvider -
Using cached Channel [id: 0x9d1dee2d, /127.0.0.1:50316 => localhost/127.0.0.1:8888]
for request
DefaultHttpRequest(chunked: false)
GET /api/add_interest/1/fff HTTP/1.1
Host: localhost:8888
Connection: keep-alive
Accept: */* User-Agent: NING/1.0
[debug] c.n.h.c.p.n.NettyAsyncHttpProvider -
Request DefaultHttpRequest(chunked: false)
GET /api/add_interest/1/fff HTTP/1.1
Host: localhost:8888
Connection: keep-alive
Accept: */*
User-Agent: NING/1.0
Response DefaultHttpResponse(chunked: true)
HTTP/1.1 200 OK
Content-Type: text/plain
Date: Thu, 04 Jul 2013 12:14:40 GMT
Transfer-Encoding: chunked
[debug] c.n.h.c.p.n.NettyConnectionsPool - Adding uri: http://localhost:8888 for channel [id: 0x9d1dee2d, /127.0.0.1:50316 => localhost/127.0.0.1:8888]
[info] application - {"status":"success"}
[info] application - {"status":"ok","exists":false}
[trace] play - Sending simple result: SimpleResult(200, Map(Content-Type -> application/json; charset=utf-8, Set-Cookie -> ))
[debug] play - java.nio.channels.ClosedChannelException
[trace] application - Exception caught in Netty
java.nio.channels.ClosedChannelException: null
at org.jboss.netty.channel.socket.nio.AbstractNioWorker.cleanUpWriteBuffer(AbstractNioWorker.java:409) ~[netty.jar:na]
at org.jboss.netty.channel.socket.nio.AbstractNioWorker.writeFromUserCode(AbstractNioWorker.java:127) ~[netty.jar:na]
at org.jboss.netty.channel.socket.nio.NioServerSocketPipelineSink.handleAcceptedSocket(NioServerSocketPipelineSink.java:99) ~[netty.jar:na]
at org.jboss.netty.channel.socket.nio.NioServerSocketPipelineSink.eventSunk(NioServerSocketPipelineSink.java:36) ~[netty.jar:na]
at org.jboss.netty.channel.Channels.write(Channels.java:725) ~[netty.jar:na]
at org.jboss.netty.handler.codec.oneone.OneToOneEncoder.doEncode(OneToOneEncoder.java:71) ~[netty.jar:na]
[debug] c.n.h.c.p.n.NettyConnectionsPool - Entry count for : http://localhost:8888 : 2
Here is my sample code -
public static Result addInterestCallback(WS.Response response) {
if (response == null) {
return badRequest();
}
ObjectNode result = (ObjectNode) response.asJson();
try {
Logger.info(result.toString());
if (result.has("status")) {
String status = result.get("status").getTextValue();
if(status.equals("error")) {
result.put("error", "Oops, cannot process your request. Sorry.");
Logger.info("error");
return badRequest(result);
}
else if(status.equals("exists")) {
result.put("exists",true);
}
else {
result.put("exists",false);
}
result.put("status", "ok");
} else {
//do something
Logger.info("result has no status");
}
Logger.info(result.toString());
} catch (Exception e) {
e.printStackTrace();
}
return ok(result);
}
#BodyParser.Of(BodyParser.Json.class)
#SecureSocial.UserAwareAction
public static Result addInterest() {
JsonNode json = request().body().asJson();
String interestName = json.findPath("interestName").getTextValue();
Logger.info("Calling interest for " + interestName);
Identity user = (Identity) ctx().args.get(SecureSocial.USER_KEY);
if (user == null) {
ObjectNode result = Json.newObject();
result.put("error", "requires-login");
Http.Context ctx = Http.Context.current();
ctx.flash().put("error", play.i18n.Messages.get("securesocial.loginRequired"));
result.put("redirect", RoutesHelper.login().absoluteURL(ctx.request(), IdentityProvider.sslEnabled()));
return ok(result);
}
Logger.info("user is not null");
if(interestName == null) {
ObjectNode result = Json.newObject();
result.put("error", "Empty input");
return badRequest(result);
}
//get user
EBUser ebUser = Application.getEBUser();
Logger.info("interest="+interestName+", userInfo:" + ebUser.toString());
//Call addInterst API.
String apiEndpoint = Play.application().configuration().getString(AppConstants.EB_API_ENDPOINT);
String url = "";
try {
url = apiEndpoint + "add_interest/" + ebUser.getId() + "/" + URLEncoder.encode(interestName, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
ObjectNode result = Json.newObject();
result.put("error", "Cant parse interest properly");
Logger.info("error " + result.toString());
return badRequest(result);
}
Logger.info(url);
Promise<WS.Response> promiseOfAPI = WS.url(url).get();
Promise<Result> promiseOfResult = promiseOfAPI.map(
new Function<WS.Response, Result>() {
#Override
public Result apply(WS.Response response) throws Throwable {
return addInterestCallback(response);
}
});
return async(promiseOfResult);
}
Name of Handler is addInterest.
Any pointers on what could be happening here?
java.nio.channels.ClosedChannelException
This means you have closed the channel and then continued to use it.

Resources