loadInitial method not getting called in PositionalDataSource<Item> - java

I'm implementing PositionalDataSource from Paging Library in Java and getting an issue that constructor of PositionalDataSource's child class is getting called but after that loadInitial method is not getting called.
public HistoryPositionalDataSource(List<CallTable> callLogs)
{
this.callLogs = callLogs;
Log.d("PaginationDataSource", "Constructor");
}
#Override
public void loadInitial(#NonNull LoadInitialParams params, #NonNull LoadInitialCallback callback) {
Log.d("PaginationDataSource", "loadInitial");
if (callLogs!=null && !callLogs.isEmpty())
{
int totalCount = computeCount();
int position = computeInitialLoadPosition(params, totalCount);
int loadSize = computeInitialLoadSize(params, position, totalCount);
callback.onResult(loadRangeInternal(position, loadSize), position, totalCount);
}
}
#Override
public void loadRange(#NonNull LoadRangeParams params, #NonNull LoadRangeCallback callback) {
callback.onResult(loadRangeInternal(params.startPosition, params.loadSize));
}
Here's my PageListConfig
private void init() {
pagedListConfig = (new PagedList.Config.Builder()).setEnablePlaceholders(true)
.setInitialLoadSizeHint(Integer.MAX_VALUE).setPageSize(Integer.MAX_VALUE).build();
Executor executor = Executors.newFixedThreadPool(3);
List<CallTable> listLogs = getCallLogs(context);
historyDataSourceFactory = new HistoryDataSourceFactory(listLogs);
LivePagedListBuilder livePagedListBuilder = new LivePagedListBuilder(historyDataSourceFactory, pagedListConfig);
pagedCallLogs = livePagedListBuilder
.setFetchExecutor(executor)
.build();
}
Factory class:
public class HistoryDataSourceFactory extends DataSource.Factory {
private static final String TAG = HistoryDataSourceFactory.class.getSimpleName();
private HistoryPositionalDataSource historyPositionalDataSource;
public HistoryDataSourceFactory(List<CallTable> callLogs)
{
if (callLogs!=null && !callLogs.isEmpty())
{
Log.d("PaginationFactory", "NotNullLogs");
historyPositionalDataSource = new HistoryPositionalDataSource(callLogs);
}
}
#Override
public DataSource create() {
return historyPositionalDataSource;
}
}
My getPagedCallLogs method:
public synchronized LiveData<PagedList<CallTable>> getPagedCallLogs() {
if (pagedCallLogs!=null && pagedCallLogs.getValue()!=null)
{
Log.d("PagingGetData", "Done");
return pagedCallLogs;
}
else
{
Log.d("PagingGetData", "Null");
return null;
}
}
Logs image is given below.

Load size and offset is set
via PagedList.Config so you don't need to calculate load range yourself.
Change your loadInitial function
#Override
public void loadInitial(#NonNull LoadInitialParams params, #NonNull LoadInitialCallback callback) {
Log.d("PaginationDataSource", "loadInitial");
if (callLogs!=null && !callLogs.isEmpty())
{
callback.onResult(loadRangeInternal(0, params.requestedLoadSize), 0);
}
}
Edit:
Try this config aswell
PagedList.Config config =
new PagedList.Config.Builder()
.setPageSize(50)
.setEnablePlaceholders(false)
.setPrefetchDistance(25)
.build();
Edit2:
Try changing extention from DataSource.Factory to DataSource.Factory<Integer, ModelClass> and PositionalDataSource to PositionalDataSource<ModelClass>

After too many struggle, I become able to resolve my issue. The issue was with my getPagedCallLog method.
I wrote:
public synchronized LiveData<PagedList<CallTable>> getPagedCallLogs() {
if (pagedCallLogs!=null && pagedCallLogs.getValue()!=null)
{
Log.d("PagingGetData", "Done");
return pagedCallLogs;
}
else
{
Log.d("PagingGetData", "Null");
return null;
}
}
I was taking Google I/O '18, in which he said that loadInitial is called by the pageList, then I realise that it wasn't getting called in my case. And it is working fine after removing pagedCallLogs.getValue()!=null which was my stupid mistake.
Now it looks like this:
public synchronized LiveData<PagedList<CallTable>> getPagedCallLogs() {
if (pagedCallLogs!=null)
{
Log.d("PagingGetData", "Done");
return pagedCallLogs;
}
else
{
Log.d("PagingGetData", "Null");
return null;
}
}

Related

Strange uncaught error with GWT, UmbrellaException

I'm building a project through GWT and Eclipse for the realization of a site similar to Yahoo Answer, until a few days ago it was working perfectly but since yesterday I noticed a bug that I didn't see before and it's very strange because I would have noticed. Basically on the console of Google Chrome I receive an Uncaught error when I try to visualize the answers related to a question, it seems as if the database (mapdb 1.0.9) does not return anything
For compatibility problems i'm using Eclipse Mars for Java 7 (1.7) and GWT 2.8.0
I will post the part of the code that is not reproduced by clicking on the question
public class MostraRisposte {
private VerticalPanel verticalPanel = null;
public MostraRisposte(VerticalPanel verticalPanel) {
this.verticalPanel = verticalPanel;
}
public void onModuleLoad(Domanda currentSelection) {
this.verticalPanel.add(new HTML("<br>"));
this.verticalPanel.add(new HTML("<br>"));
final Grid answerGridPanel = new Grid(8, 2);
answerGridPanel.setWidget(0, 0, new Label("Utente: "));
answerGridPanel.setWidget(0, 1, new Label(currentSelection.getUserName()));
answerGridPanel.setWidget(1, 0, new Label("Testo: "));
answerGridPanel.setWidget(1, 1, new Label(currentSelection.getText()));
answerGridPanel.setWidget(2, 0, new Label("Data: "));
answerGridPanel.setWidget(2, 1, new Label(currentSelection.getDay()));
answerGridPanel.setWidget(4, 0, new Label("Link1: "));
answerGridPanel.setWidget(4, 1, new Label(currentSelection.getLinkList().get(0)));
answerGridPanel.setWidget(5, 0, new Label("Link2: "));
answerGridPanel.setWidget(5, 1, new Label(currentSelection.getLinkList().get(1)));
answerGridPanel.setWidget(6, 0, new Label("Link3: "));
answerGridPanel.setWidget(6, 1, new Label(currentSelection.getLinkList().get(2)));
answerGridPanel.setWidget(7, 0, new Label("Link4: "));
answerGridPanel.setWidget(7, 1, new Label(currentSelection.getLinkList().get(3)));
this.verticalPanel.add(answerGridPanel);
final GwaServiceAsync gwanswer = GWT.create(GwaService.class);
final int id = currentSelection.getIdQuestion();
gwanswer.ordinaRisposte(id, new AsyncCallback<List<Risposta>>() {
#Override
public void onFailure(Throwable caught) {
PopupPanel popup = new PopupPanel(true);
popup.setWidget(new HTML("<font color='red'>Errore</font>"));
popup.center();
}
#Override
public void onSuccess(List<Risposta> response) {
final CellTable<Risposta> questionsTable = new CellTable<>(20);
questionsTable.addColumn(new TextColumn<Risposta>() {
#Override
public String getValue(Risposta risposta) {
return risposta.getText();
}
}, "Risposta");
questionsTable.addColumn(new TextColumn<Risposta>() {
#Override
public String getValue(Risposta answer) {
return answer.getUserName();
}
}, "Utente");
questionsTable.addColumn(new TextColumn<Risposta>() {
#Override
public String getValue(Risposta risposta) {
return risposta.getDay();
}
}, "Giorno");
questionsTable.addColumn(new TextColumn<Risposta>() {
#Override
public String getValue(Risposta risposta) {
return risposta.getTime();
}
}, "Ora");
questionsTable.addColumn(new TextColumn<Risposta>() {
#Override
public String getValue(Risposta risposta) {
return risposta.getJudgeEmail();
}
}, "Giudice");
final TextColumn<Risposta> ratingTextColumn = new TextColumn<Risposta>() {
#Override
public String getValue(Risposta risposta) {
return risposta.getRating();
}
};
questionsTable.addColumn(ratingTextColumn, "Voto");
ratingTextColumn.setSortable(true);
questionsTable.addColumn(new TextColumn<Risposta>() {
#Override
public String getValue(Risposta risposta) {
return risposta.getLinkList().get(0);
}
}, "Link");
questionsTable.addColumn(new TextColumn<Risposta>() {
#Override
public String getValue(Risposta risposta) {
return risposta.getLinkList().get(1);
}
}, "Link");
questionsTable.addColumn(new TextColumn<Risposta>() {
#Override
public String getValue(Risposta risposta) {
return risposta.getLinkList().get(2);
}
}, "Link");
questionsTable.addColumn(new TextColumn<Risposta>() {
#Override
public String getValue(Risposta risposta) {
return risposta.getLinkList().get(3);
}
}, "Link");
final ListDataProvider<Risposta> dataProvider = new ListDataProvider<>();
dataProvider.addDataDisplay(questionsTable);
final List<Risposta> list = dataProvider.getList();
for (Iterator<Risposta> iterator = response.iterator(); iterator.hasNext();) {
final Risposta risposta = iterator.next();
list.add(risposta);
}
final ListHandler<Risposta> columnSortHandler = new ListHandler<>(list);
columnSortHandler.setComparator(ratingTextColumn, new Comparator<Risposta>() {
#Override
public int compare(Risposta option1, Risposta option2) {
if (option1.getRating().equals(option2.getRating())) {
if (!option1.getDate().after(option2.getDate())) {
return -1;
} else {
return 1;
}
} else {
return (option2 != null && option1 != null) ? option1.getRating().compareTo(option2.getRating())
: 1;
}
}
});
questionsTable.addColumnSortHandler(columnSortHandler);
questionsTable.getColumnSortList().push(ratingTextColumn);
questionsTable.setKeyboardSelectionPolicy(KeyboardSelectionPolicy.ENABLED);
final SingleSelectionModel<Risposta> selectionModel = new SingleSelectionModel<>();
questionsTable.setSelectionModel(selectionModel);
selectionModel.addSelectionChangeHandler(new Handler() {
#Override
public void onSelectionChange(SelectionChangeEvent event) {
if (UtenteAttuale.accountType == 1) {
final Risposta currentSelection1 = selectionModel.getSelectedObject();
if (currentSelection1 != null) {
final AggiungiVoto iv = new AggiungiVoto(MostraRisposte.this.verticalPanel);
iv.onModuleLoad(currentSelection1);
}
}
}
});
questionsTable.setRowCount(response.size(), true);
questionsTable.setRowData(0, response);
MostraRisposte.this.verticalPanel.add(questionsTable);
}
});
}
}
I expect to display a grid (Grid) with the information of who made the question I selected (CurrentSelection) and immediately below the table containing the answers, I checked and the questions and answers are correctly entered in the database but unfortunately only the answers do not appear.
The error on Chrome console:
Try to catch all uncaught exceptions, and unwrap the umbrella.
Somewhere in the beginnen of your onModuleLoad method
GWT.setUncaughtExceptionHandler(e -> showError(e));
And in showError do something like
Throwable unwrapped = unwrap(e);
GWT.log("Uncaught exception catched", unwrapped);
/**
* Unwrap the given exception.
* #param e The exception.
* #return Unwrapped version of the exception
*/
private static Throwable unwrap(Throwable e)
{
if (e instanceof UmbrellaException)
{
UmbrellaException ue = (UmbrellaException) e;
if (ue.getCauses().size() == 1)
{
return unwrap(ue.getCauses().iterator().next());
}
}
return e;
}
This way you have a much cleaner stacktrace to see what has happened.

Mockito mock doAnswer returns same value when reused between tests

I have the following tests. When I run them separately they pass. If I run all of them only the first passes.
Business Logic gets a JSON response from the APIServiceTask code. It creates an event to post using EventBus. I am writing tests to verify that EventBus is creating the correct calls.
The JSON Reponses class at the end is just the answers I am trying to post. If I run all of the tests, it seems like the loginFailureChangePasswordJSON is the one posted to the business logic.
public class LoginBusinessLogic {
private static LoginBusinessLogic instance = null;
APIServiceTask apiServiceTask;
public static LoginBusinessLogic getInstance(APIServiceTask apiServiceTask) {
if (instance == null) {
instance = new LoginBusinessLogic();
instance.apiServiceTask = apiServiceTask;
}
return instance;
}
protected void doLogin() {
EventBus.getDefault().register(this);
apiServiceTask.execute();
}
#Subscribe
public void onEvent(ServiceResultEvent event) {
switch (event.event) {
case failed:
handleLoginError(event.result);
break;
case cancelled:
EventBus.getDefault().postSticky(new LoginEvent(LoginEvent.TYPE_CANCELLE, event.result));
break;
case error:
if(event.originatorEvent != LoginEvent.TYPE_TOUCH_TOKEN_DELETE) {
EventBus.getDefault().postSticky(new LoginEvent(LoginEvent.TYPE_ERROR, event.result));
}
break;
default:
break;
}
EventBus.getDefault().unregister(this);
}
private void handleLoginError(String error) {
ErrorModel signInError = new Gson().fromJson(error, ErrorModel.class);
int statusCode = signInError.getMTBStatusCode();
String errMsg;
if (statusCode == 40022) {
errMsg = signInError.getUserMessage();
} else {
errMsg = signInError.getUserMessage().replace("*", "").replace("\"", "");
}
if (statusCode == 40001) {
EventBus.getDefault().postSticky(new LoginEvent(LoginEvent.TYPE_FAILED, statusCode, errMsg, false, false));
} else if (statusCode == 40108) {
EventBus.getDefault().postSticky(new LoginEvent(LoginEvent.TYPE_FAILED, statusCode, errMsg, true, false));
}
else if (statusCode == 40107) {
EventBus.getDefault().postSticky(new LoginEvent(LoginEvent.TYPE_FAILED, statusCode, errMsg, false, false));
} else if (statusCode == 40104) {
EventBus.getDefault().postSticky(new LoginEvent(LoginEvent.TYPE_FAILED, statusCode, errMsg, false, true));
} else {
EventBus.getDefault().postSticky(new LoginEvent(LoginEvent.TYPE_FAILED, statusCode, errMsg, false, false));
}
}
}
public class APIServiceTask {
public APIServiceTask(){
}
#SuppressWarnings("ConstantConditions")
public void execute() {
}
}
public class BusinessLogicTests {
#Mock
APIServiceTask service;
private LoginEvent loginEvent;
private LoginBusinessLogic loginBusinessLogic;
#Before
public void setUp(){
MockitoAnnotations.initMocks(this);
loginBusinessLogic = LoginBusinessLogic.getInstance(service);
EventBus.getDefault().register(this);
}
#After
public void tearDown(){
EventBus.getDefault().unregister(this);
}
#Subscribe
public void onEvent(LoginEvent event){
loginEvent = event;
}
#Test
public void badUsernamePasscode(){
doAnswer(JSONResponses.loginInvalidUsernamePasscodeJSON())
.when(service).execute();
loginBusinessLogic.doLogin();
Assert.assertEquals(40108, loginEvent.mtbStstusCode);
}
#Test
public void accountBlocked(){
doAnswer(JSONResponses.loginAccountBlockedJSON())
.when(service).execute();
loginBusinessLogic.doLogin();
Assert.assertEquals(40104, loginEvent.mtbStstusCode);
}
#Test
public void temporaryPasscode(){
doAnswer(JSONResponses.loginTemporaryPasscodeJSON())
.when(service).execute();
loginBusinessLogic.doLogin();
Assert.assertEquals(40109, loginEvent.mtbStstusCode);
}
#Test
public void changedPasscode(){
doAnswer(JSONResponses.loginFailureChangePasscodeJSON())
.when(service).execute();
loginBusinessLogic.doLogin();
Assert.assertEquals(40107, loginEvent.mtbStstusCode);
}
}
public class JSONResponses {
public static Answer loginFailureChangePasscodeJSON(){
Answer answer = new Answer() {
#Override
public Object answer(InvocationOnMock invocation) throws Throwable {
String result = "{\"MTBStatusCode\":40107, \"UserMessage\":\"Your passcode has changed since last login.\"}";
EventBus.getDefault().post(new ServiceResultEvent(ServiceResultEvent.EVENT_TYPE.failed, result, 0));
return null;
}
};
return answer;
}
public static Answer loginAccountBlockedJSON(){
Answer answer = new Answer() {
#Override
public Object answer(InvocationOnMock invocation) throws Throwable {
String result = "{\"Version\":1,\"MTBStatusCode\":40104,\"HttpStatus\":401,\"UserMessage\":\"\\\"Your account is locked due to too many failed login attempts. <br><br>Reset Passcode >\\\"\",\"DeveloperMessage\":\"\\\"Account locked via multi-factor authentication.\\\"\"}";
EventBus.getDefault().post(new ServiceResultEvent(ServiceResultEvent.EVENT_TYPE.failed, result, 0));
return null;
}
};
return answer;
}
public static Answer loginInvalidUsernamePasscodeJSON(){
Answer answer = new Answer() {
#Override
public Object answer(InvocationOnMock invocation) throws Throwable {
String result = "{\"Version\":1,\"MTBStatusCode\":40108,\"HttpStatus\":401,\"UserMessage\":\"\\\"User ID or Passcode doesn’t match. Try again.\\\"\",\"DeveloperMessage\":\"\\\"Voyager Error -1073739414 : User ID or Passcode doesn’t match. Try again.\\\"\"}";
EventBus.getDefault().post(new ServiceResultEvent(ServiceResultEvent.EVENT_TYPE.failed, result, 0));
return null;
}
};
return answer;
}
public static Answer loginTemporaryPasscodeJSON(){
Answer answer = new Answer() {
#Override
public Object answer(InvocationOnMock invocation) throws Throwable {
String result = "{\"Version\":1,\"MTBStatusCode\":40107,\"HttpStatus\":401,\"UserMessage\":\"\\\"You have logged in with a temporary passcode. Log in to M&T Online Banking to create a new passcode.\\\"\",\"DeveloperMessage\":\"\\\"Password should be changed.\\\"\"}";
EventBus.getDefault().post(new ServiceResultEvent(ServiceResultEvent.EVENT_TYPE.failed, result, 0));
return null;
}
};
return answer;
}
}
For anyone interested, it seems the singleton still exists when the other tests run. 2 ways I found to fix it are nulling out the singleton in a separate method or moving the following statement outside of the if in LoginBusinessLogic.
instance.apiServiceTask = apiServiceTask;

Check network connection in libGDX

I would like to check network connection with use of libGDX and tried to use code below.
HttpRequestBuilder requestBuilder = new HttpRequestBuilder();
Net.HttpRequest httpRequest = requestBuilder.newRequest().method(Net.HttpMethods.GET).url("https://api.vk.com/").build();
Net.HttpResponseListener httpResponseListener = new httpResponseListener() {
public void handleHttpResponse (Net.HttpResponse httpResponse) {
HttpStatus status = httpResponse.getStatus();
if (status.getStatusCode() >= 200 && status.getStatusCode() < 300) {
// it was successful
} else {
// do something else
}
}
}
Gdx.net.sendHttpRequest(httpRequest, httpResponseListener);
It has several errors, like Gdx.net doesn't have sendHttpRequest() function now. How should I correct this code?
Gdx.net has got sendHttpRequest() method - it seems that you are using not proper HttpRequest instance (why this Net... is starting with uppercase?)
A proper minimal example of how to use Gdx.net is beneath - I have also added a comments where it was necessary
public class HttpManager implements HttpResponseListener
{
public HttpState state;
private String result;
private byte[] byteResult;
HttpRequest request;
public HttpManager()
{
request = new HttpRequest();
request.setMethod(Net.HttpMethods.GET); //or POST
request.setContent(""); //you can put here some PUT/GET content
request.setUrl(url);
Gdx.net.sendHttpRequest(request, this);
}
#Override
public void handleHttpResponse(HttpResponse httpResponse)
{
if( httpResponse.getStatus().getStatusCode() != 200 )
{
//ERROR
float errorCode = httpResponse.getStatus().getStatusCode();
}
else
{
byte[] byteResult = httpResponse.getResult(); //you can also get result as String by using httpResponse.getResultAsString();
}
}
#Override
public void failed(Throwable t)
{
// TODO Auto-generated method stub
}
#Override
public void cancelled()
{
// TODO Auto-generated method stub
}
}

How to persist variable value from inner class (Response.Listener) to the outside?

I have this function called facebookCheckEmail() (below) inside a container class, and I want to change a variable value (fbresponse) of the container class inside public void onResponse(FbCheckObject fbCheckObject) {} of facebookCheckEmail(), how do I do that ?
private void facebookCheckEmail( String email ) {
fbCheckEmail_params = new HashMap<String, String>();
fbCheckEmail_params.put("Email", email);
final GsonRequest<FbCheckObject> gsonRequest = ApiRequest.gsonFacebookCheckEmailRequest
(
new Response.Listener<FbCheckObject>() {
#Override
public void onResponse(FbCheckObject fbCheckObject) {
try {
System.out.println("Status = " + fbCheckObject.getStatus());
if (new String(fbCheckObject.getStatus()).equals("ok") == true) {
fbresponse = "ok";
} else if(new String(fbCheckObject.getStatus()).equals("no") == true){
fbresponse = "no";
}
} catch (Exception e) {
Log.d("Web Service Error", e.getMessage());
e.printStackTrace();
}
}
}
,
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Deal with the error here
}
},
fbCheckEmail_params
);
AppController.getInstance().addToRequestQueue(gsonRequest, TAG);
}
my container class is :
public class MainLoginActivity extends Activity {
public String fbresponse = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
.......
}
..........
private void facebookCheckEmail( String email ) {
......
}
}
NOTE: Inside the "#Override public void onResponse(FbCheckObject fbCheckObject) {}", fbresponse value is successfully assigned to "ok" or "no" if unsuccessful, but anywhere outside that scope if I System.out.printIn fbresponse, I will get "null"
Doing what you want is not a good design. You should rather change your method so that it returns the status:
private String facebookCheckEmail( String email ) {
...
}
And set the return value to the response:
fbresponse = facebookCheckEmail(email);

playframework-2.3 Akka-Async interaction porting?

I have some old playframework 2.2 java webservice that interacts with akka, and now I should port them to playframework 2.3.
However, async has been deprecated and even after reading the doc about the async porting (http://www.playframework.com/documentation/2.3.x/JavaAsync) I wasn't able to understand how to apply it to my case (code below):
I must make the await for a timeout/akka server reply before starting the construction of my reply (ok()), otherwise I will block the thread.
I should make the actorselection async too.
I should make the akka server reply parsing/reply construction async too
I looked around and I wasn't able to find an example of such interactions, even in typesafe templates.
How could I do that?
/* playframework 2.2 code */
public class Resolve extends Controller {
private final static String RESOLVER_ACTOR = play.Play.application().configuration().getString("actor.resolve");
#CorsRest
#VerboseRest
#RequireAuthentication
#BodyParser.Of(BodyParser.Json.class)
public static Result getJsonTree() {
JsonNode json = request().body().asJson();
ProtoBufMessages.ResolveRequest msg;
ResolveRequestInput input;
try {
input = new ResolveRequestInput(json);
} catch (rest.exceptions.MalformedInputException mie) {
return badRequest(mie.getMessage());
}
msg = ((ProtoBufMessages.ResolveRequest)input.getMessage());
ActorSelection resolver = Akka.system().actorSelection(RESOLVER_ACTOR);
Timeout tim = new Timeout(Duration.create(4, "seconds"));
Future<Object> fut = Patterns.ask(resolver, input.getMessage(), tim);
return async (
F.Promise.wrap(fut).map(
new F.Function<Object, Result>() {
public Result apply(Object response) {
ProtoBufMessages.ResolveReply rsp = ((ProtoBufMessages.ResolveReply)response);
ResolveOutput output = new ResolveOutput(rsp);
return ok(output.getJsonReply());
}
}
)
);
}
}
I came out with the code below
public class Resolve extends Controller {
private final static String RESOLVER_ACTOR = play.Play.application().configuration().getString("actor.resolve");
private final static BrainProtoMessages.ResolveReply request_error = BrainProtoMessages.ResolveReply.newBuilder()
.setReturnCode(BResults.REQUEST_FAILED)
.build();
#CorsRest
#VerboseRest
#RequireAuthentication
#BodyParser.Of(BodyParser.Json.class)
public static Result resolve_map() {
final ResolveRequestInput input;
final F.Promise<ActorSelection> selected_target;
final F.Promise<Future<Object>> backend_request;
final F.Promise<BrainProtoMessages.ResolveReply> backend_reply;
final F.Promise<ObjectNode> decode_json;
final F.Promise<Result> ok_result;
final JsonNode json = request().body().asJson();
try {
input = new ResolveRequestInput(json);
} catch (rest.exceptions.MalformedInputException mie) {
return badRequest(mie.getMessage());
}
selected_target = F.Promise.promise(
new F.Function0<ActorSelection>() {
#Override
public ActorSelection apply() throws Throwable {
return Akka.system().actorSelection(RESOLVER_ACTOR);
}
}
);
backend_request =
selected_target.map(
new F.Function<ActorSelection, Future<Object>>() {
#Override
public Future<Object> apply(ActorSelection actorSelection) throws Throwable {
return Patterns.ask(actorSelection, input.getMessage(),new Timeout(Duration.create(4, "seconds")));
}
}
);
backend_reply = backend_request.map(
new F.Function<Future<Object>, BrainProtoMessages.ResolveReply>() {
#Override
public BrainProtoMessages.ResolveReply apply(Future<Object> akka_reply) throws Throwable {
try {
return (BrainProtoMessages.ResolveReply) Await.result(akka_reply, Duration.create(4, "seconds"));
}catch(Exception error)
{
return request_error;
}
}
}
);
decode_json = backend_reply.map(
new F.Function<BrainProtoMessages.ResolveReply, ObjectNode>() {
#Override
public ObjectNode apply(BrainProtoMessages.ResolveReply response) throws Throwable {
return new ResolveOutput(response).getJsonReply();
}
}
);
ok_result = decode_json.map(
new F.Function<ObjectNode, Result>() {
#Override
public Result apply(ObjectNode reply) {
return ok(reply);
}
}
);
try {
return ok_result.get(8000);
}catch(Exception error)
{
return internalServerError();
}
}
}

Categories

Resources