play.libs.F.Promise Java Examples
The following examples show how to use
play.libs.F.Promise.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Client.java From openseedbox with GNU General Public License v3.0 | 6 votes |
protected static Object successOrError(Promise<GenericJobResult> p) { if (p == null) { throw new IllegalArgumentException("You cant give me a null promise!"); } GenericJobResult res = await(p); if (res == null) { return null; } if (res.hasError()) { if (res.getError() instanceof MessageException) { setGeneralErrorMessage(res.getError()); return null; } if (StringUtils.contains(res.getError().getMessage(), "Connection refused")) { setGeneralErrorMessage("Unable to connect to backend! The administrators have been notified."); //TODO: send error email return null; } Logger.info(res.getError(), "Error occured in job."); throw new RuntimeException(res.getError()); } return res.getResult(); }
Example #2
Source File: Client.java From openseedbox with GNU General Public License v3.0 | 6 votes |
public static void torrentInfo(String hash) { //torrent info is seeders, peers, files, tracker stats final UserTorrent fromDb = UserTorrent.getByUser(getCurrentUser(), hash); if (fromDb == null) { resultError("No such torrent for user: " + hash); } Promise<GenericJobResult> p = new GenericJob() { @Override public Object doGenericJob() { //trigger the caching of these objects, inside a job because the WS //calls could take ages fromDb.getTorrent().getPeers(); fromDb.getTorrent().getTrackers(); fromDb.getTorrent().getFiles(); return fromDb; } }.now(); GenericJobResult res = await(p); if (res.hasError()) { resultError(res.getError()); } UserTorrent torrent = (UserTorrent) res.getResult(); renderTemplate("client/torrent-info.html", torrent); }
Example #3
Source File: RMBController.java From NationStatesPlusPlus with MIT License | 6 votes |
public Promise<Result> getPostRatings(final int rmbPost, final int rmbCache) throws SQLException { Promise<JsonNode> promise = Promise.wrap(akka.dispatch.Futures.future((new Callable<JsonNode>() { @Override public JsonNode call() throws Exception { Connection conn = null; try { conn = getConnection(); JsonNode ratings = calculatePostRatings(conn, rmbPost); return ratings; } finally { DbUtils.closeQuietly(conn); } } }), Akka.system().dispatcher())); Promise<Result> result = promise.flatMap(getAsyncResult(request(), response(), rmbCache == -1 ? "10" : "86400")); return result; }
Example #4
Source File: RMBController.java From NationStatesPlusPlus with MIT License | 6 votes |
private static Function<JsonNode, Promise<Result>> getAsyncResult(final Request request, final Response response, final String cacheLen) { return new Function<JsonNode, Promise<Result>>() { @Override public Promise<Result> apply(final JsonNode node) throws Throwable { return Promise.wrap(akka.dispatch.Futures.future((new Callable<Result>() { @Override public Result call() throws Exception { Result result = Utils.handleDefaultGetHeaders(request, response, String.valueOf(node.hashCode()), cacheLen); if (result != null) { return result; } return Results.ok(node).as("application/json"); } }), Akka.system().dispatcher())); } }; }
Example #5
Source File: Job.java From restcommander with Apache License 2.0 | 6 votes |
/** * Start this job in several seconds * @return the job completion */ public Promise<V> in(int seconds) { final Promise<V> smartFuture = new Promise<V>(); JobsPlugin.executor.schedule(new Callable<V>() { public V call() throws Exception { V result = Job.this.call(); smartFuture.invoke(result); return result; } }, seconds, TimeUnit.SECONDS); return smartFuture; }
Example #6
Source File: MyDeadboltHandler.java From thunderbit with GNU Affero General Public License v3.0 | 5 votes |
@Override public Promise<Optional<Subject>> getSubject(final Http.Context context) { if (context.session().get("username") != null && !context.session().get("username").isEmpty()) { // return an anonymous user return Promise.pure(Optional.of(new Subject() { @Override public List<? extends Role> getRoles() { return Collections.emptyList(); } @Override public List<? extends Permission> getPermissions() { return Collections.emptyList(); } @Override public String getIdentifier() { return context.session().get("username"); } })); } else { return Promise.pure(Optional.empty()); } }
Example #7
Source File: GSNDeadboltHandler.java From gsn with GNU General Public License v3.0 | 5 votes |
@Override public F.Promise<Result> onAuthFailure(final Http.Context context, final String content) { // if the user has a cookie with a valid user and the local user has // been deactivated/deleted in between, it is possible that this gets // shown. You might want to consider to sign the user out in this case. return F.Promise.promise(new F.Function0<Result>() { @Override public Result apply() throws Throwable { return forbidden("Forbidden"); } }); }
Example #8
Source File: GSNDeadboltHandler.java From gsn with GNU General Public License v3.0 | 5 votes |
@Override public Promise<Result> beforeAuthCheck(final Http.Context context) { if (PlayAuthenticate.isLoggedIn(context.session())) { // user is logged in return F.Promise.pure(null); } else { // user is not logged in // call this if you want to redirect your visitor to the page that // was requested before sending him to the login page // if you don't call this, the user will get redirected to the page // defined by your resolver final String originalUrl = PlayAuthenticate.storeOriginalUrl(context); System.out.println("-----------------"+originalUrl); context.flash().put("error", "You need to log in first, to view '" + originalUrl + "'"); return F.Promise.promise(new F.Function0<Result>() { @Override public Result apply() throws Throwable { return redirect(PlayAuthenticate.getResolver().login()); } }); } }
Example #9
Source File: ArchivedEventStreamTest.java From restcommander with Apache License 2.0 | 5 votes |
/** * Test method for {@link play.libs.F.ArchivedEventStream#publish(java.lang.Object)}. * @throws ExecutionException * @throws InterruptedException */ @Test public void testPublishMultiple() throws InterruptedException, ExecutionException { Promise<List<IndexedEvent<String>>> p1 = stream.nextEvents(0); Promise<List<IndexedEvent<String>>> p2 = stream.nextEvents(0); Promise<List<IndexedEvent<String>>> p3 = stream.nextEvents(0); stream.publish(VALUE_1); assertTrue(p1.isDone()); assertTrue(p2.isDone()); assertTrue(p3.isDone()); assertEquals(1, p1.get().size()); assertEquals(VALUE_1, p1.get().get(0).data); assertEquals(1, p2.get().size()); assertEquals(VALUE_1, p2.get().get(0).data); assertEquals(1, p2.get().size()); assertEquals(VALUE_1, p2.get().get(0).data); stream.publish(VALUE_2); assertTrue(p1.isDone()); assertTrue(p2.isDone()); assertTrue(p3.isDone()); assertEquals(1, p1.get().size()); assertEquals(VALUE_1, p1.get().get(0).data); assertEquals(1, p2.get().size()); assertEquals(VALUE_1, p2.get().get(0).data); assertEquals(1, p2.get().size()); assertEquals(VALUE_1, p2.get().get(0).data); }
Example #10
Source File: Job.java From restcommander with Apache License 2.0 | 5 votes |
/** * Start this job now (well ASAP) * @return the job completion */ public Promise<V> now() { final Promise<V> smartFuture = new Promise<V>(); JobsPlugin.executor.submit(new Callable<V>() { public V call() throws Exception { V result = Job.this.call(); smartFuture.invoke(result); return result; } }); return smartFuture; }
Example #11
Source File: Invoker.java From restcommander with Apache License 2.0 | 5 votes |
public static <V> void waitFor(Future<V> task, final Invocation invocation) { if (task instanceof Promise) { Promise<V> smartFuture = (Promise<V>) task; smartFuture.onRedeem(new F.Action<F.Promise<V>>() { @Override public void invoke(Promise<V> result) { executor.submit(invocation); } }); } else { synchronized (WaitForTasksCompletion.class) { if (instance == null) { instance = new WaitForTasksCompletion(); Logger.warn("Start WaitForTasksCompletion"); instance.start(); } instance.queue.put(task, invocation); } } }
Example #12
Source File: WSAsync.java From restcommander with Apache License 2.0 | 5 votes |
private Promise<HttpResponse> execute(BoundRequestBuilder builder) { try { final Promise<HttpResponse> smartFuture = new Promise<HttpResponse>(); prepare(builder).execute(new AsyncCompletionHandler<HttpResponse>() { @Override public HttpResponse onCompleted(Response response) throws Exception { HttpResponse httpResponse = new HttpAsyncResponse(response); smartFuture.invoke(httpResponse); return httpResponse; } @Override public void onThrowable(Throwable t) { // An error happened - must "forward" the exception to the one waiting for the result smartFuture.invokeWithException(t); } }); return smartFuture; } catch (Exception e) { throw new RuntimeException(e); } }
Example #13
Source File: MyDeadboltHandler.java From thunderbit with GNU Affero General Public License v3.0 | 5 votes |
@Override public Promise<Optional<Result>> beforeAuthCheck(final Http.Context context) { if (context.session().get("username") != null && !context.session().get("username").isEmpty()) { // user is logged in return Promise.pure(Optional.empty()); } else { // user is not logged in return Promise.promise(() -> Optional.of(redirect(routes.Authentication.login()))); } }
Example #14
Source File: MyDeadboltHandler.java From thunderbit with GNU Affero General Public License v3.0 | 5 votes |
@Override public Promise<Result> onAuthFailure(final Http.Context context, final String content) { if (context.session().get("username") != null && !context.session().get("username").isEmpty()) { return Promise.promise(() -> forbidden("Forbidden")); } else { return Promise.promise(() -> redirect(routes.Authentication.login())); } }
Example #15
Source File: AsyncController.java From glowroot with Apache License 2.0 | 5 votes |
public static Promise<Result> message() { return Promise.delayed(new Function0<Result>() { public Result apply() { new CreateTraceEntry().traceEntryMarker(); return Results.ok("Hi!"); } }, 1, SECONDS); }
Example #16
Source File: AsyncController.java From glowroot with Apache License 2.0 | 5 votes |
public static Promise<Result> message() { final RedeemablePromise<Result> promise = RedeemablePromise.empty(); Akka.system().scheduler().scheduleOnce( Duration.create(1, SECONDS), new Runnable() { public void run() { new CreateTraceEntry().traceEntryMarker(); promise.success(Results.ok("Hi!")); } }, ExecutionContexts.global()); return promise; }
Example #17
Source File: AsyncController.java From glowroot with Apache License 2.0 | 5 votes |
public Promise<Result> message() { RedeemablePromise<Result> promise = RedeemablePromise.empty(); actorSystem.scheduler().scheduleOnce( Duration.create(1, SECONDS), () -> { new CreateTraceEntry().traceEntryMarker(); promise.success(Results.ok("Hi!")); }, exec); return promise; }
Example #18
Source File: WSAsync.java From restcommander with Apache License 2.0 | 5 votes |
/** Execute a GET request asynchronously. */ @Override public Promise<HttpResponse> getAsync() { this.type = "GET"; sign(); return execute(prepareGet()); }
Example #19
Source File: WSAsync.java From restcommander with Apache License 2.0 | 5 votes |
/** Execute a POST request asynchronously.*/ @Override public Promise<HttpResponse> postAsync() { this.type = "POST"; sign(); return execute(preparePost()); }
Example #20
Source File: WSAsync.java From restcommander with Apache License 2.0 | 4 votes |
/** Execute a PUT request asynchronously.*/ @Override public Promise<HttpResponse> putAsync() { this.type = "PUT"; return execute(preparePut()); }
Example #21
Source File: MyDeadboltHandler.java From thunderbit with GNU Affero General Public License v3.0 | 4 votes |
@Override public Promise<Optional<DynamicResourceHandler>> getDynamicResourceHandler(final Http.Context context) { return Promise.pure(Optional.empty()); }
Example #22
Source File: Http.java From restcommander with Apache License 2.0 | 4 votes |
public Promise<WebSocketEvent> nextEvent() { if (!isOpen()) { throw new IllegalStateException("The inbound channel is closed"); } return stream.nextEvent(); }
Example #23
Source File: WSAsync.java From restcommander with Apache License 2.0 | 4 votes |
/** Execute a OPTIONS request asynchronously.*/ @Override public Promise<HttpResponse> optionsAsync() { this.type = "OPTIONS"; return execute(prepareOptions()); }
Example #24
Source File: WS.java From restcommander with Apache License 2.0 | 4 votes |
/** Execute a TRACE request asynchronously.*/ public Promise<HttpResponse> traceAsync() { throw new NotImplementedException(); }
Example #25
Source File: WS.java From restcommander with Apache License 2.0 | 4 votes |
/** Execute a HEAD request asynchronously.*/ public Promise<HttpResponse> headAsync() { throw new NotImplementedException(); }
Example #26
Source File: WS.java From restcommander with Apache License 2.0 | 4 votes |
/** Execute a OPTIONS request asynchronously.*/ public Promise<HttpResponse> optionsAsync() { throw new NotImplementedException(); }
Example #27
Source File: WS.java From restcommander with Apache License 2.0 | 4 votes |
/** Execute a DELETE request asynchronously.*/ public Promise<HttpResponse> deleteAsync() { throw new NotImplementedException(); }
Example #28
Source File: WS.java From restcommander with Apache License 2.0 | 4 votes |
/** Execute a PUT request asynchronously.*/ public Promise<HttpResponse> putAsync() { throw new NotImplementedException(); }
Example #29
Source File: WS.java From restcommander with Apache License 2.0 | 4 votes |
/** Execute a POST request asynchronously.*/ public Promise<HttpResponse> postAsync() { throw new NotImplementedException(); }
Example #30
Source File: WS.java From restcommander with Apache License 2.0 | 4 votes |
/** Execute a GET request asynchronously. */ public Promise<HttpResponse> getAsync() { throw new NotImplementedException(); }