play.libs.F Java Examples
The following examples show how to use
play.libs.F.
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: Items.java From thunderbit with GNU Affero General Public License v3.0 | 6 votes |
@SubjectPresent public F.Promise<Result> delete(Long id) { Item item = Item.find.byId(id); if (item == null) { // If there is no item with the provided id returns a 404 Result return F.Promise.pure(notFound()); } else { // Deletes the item from the database item.delete(); // Returns a promise of deleting the stored file return storage.delete(item.storageKey, item.name) .map((F.Function<Void, Result>) aVoid -> ok()) // If an error occurs when deleting the item returns a 500 Result .recover(throwable -> internalServerError()); } }
Example #2
Source File: AmazonS3Storage.java From thunderbit with GNU Affero General Public License v3.0 | 6 votes |
@Override public F.Promise<Result> getDownload(String key, String name) { GeneratePresignedUrlRequest generatePresignedUrlRequest = new GeneratePresignedUrlRequest(bucketName, key); ResponseHeaderOverrides responseHeaders = new ResponseHeaderOverrides(); responseHeaders.setContentDisposition("attachment; filename="+name); generatePresignedUrlRequest.setResponseHeaders(responseHeaders); AmazonS3 amazonS3 = new AmazonS3Client(credentials); try { URL url = amazonS3.generatePresignedUrl(generatePresignedUrlRequest); return F.Promise.pure(redirect(url.toString())); } catch (AmazonClientException ace) { logAmazonClientException (ace); return F.Promise.pure(internalServerError(error.render())); } }
Example #3
Source File: NotificationTest.java From htwplus with MIT License | 6 votes |
/** * Tests, if no notification is created, when no recipient is set. */ @Test public void testNoNotification() throws Throwable { final MockNotifiable notifiable = new MockNotifiable(); notifiable.sender = this.getTestAccount(1); notifiable.rendered = "MOCK NO NOTIFICATION"; NotificationService.getInstance().createNotification(notifiable); this.sleep(5); // sleep to ensure, that Akka would be done with notification creation JPA.withTransaction(new F.Callback0() { @Override @SuppressWarnings("unused") public void invoke() throws Throwable { List<Notification> notifications = Notification.findByRenderedContent(notifiable.rendered); assertThat(notifications.size()).isEqualTo(0); } }); }
Example #4
Source File: SecurityTest.java From htwplus with MIT License | 6 votes |
/** * Tests, if the method "isMemberOfGroup()" works as expected. */ @Test public void testIsMemberOfGroup() { final Account testAccount1 = this.getTestAccount(1); final Account testAccount2 = this.getTestAccount(2); final Account testAccount3 = this.getTestAccount(3); final Group testGroup = this.getTestGroup(1, testAccount1); this.establishGroupMembership(testAccount2, testGroup); this.removeGroupMembership(testAccount3, testGroup); // test, that we have exactly one notification JPA.withTransaction(new F.Callback0() { @Override public void invoke() throws Throwable { assertThat(Secured.isMemberOfGroup(testGroup, testAccount1)).isTrue(); assertThat(Secured.isMemberOfGroup(testGroup, testAccount2)).isTrue(); assertThat(Secured.isMemberOfGroup(testGroup, testAccount3)).isFalse(); } }); }
Example #5
Source File: AuthenticatedAction.java From pfe-samples with MIT License | 5 votes |
@Override public F.Promise<Result> call(Http.Context ctx) throws Throwable { return Authentication.authenticated(ctx, username -> { ctx.args.put(Authentication.USER_KEY, username); return delegate.call(ctx); }, () -> F.Promise.pure(redirect(routes.Authentication.login(ctx.request().uri())))); }
Example #6
Source File: HttpUtil.java From pay with Apache License 2.0 | 5 votes |
/** * 进行get访问 * @param url * @return */ public static String doGet(String url){ return ws.url(url).get().map(new F.Function<WSResponse, String>() { @Override public String apply(WSResponse wsResponse) throws Throwable { return wsResponse.getBody(); } }).get(HTTP_TIME_OUT); }
Example #7
Source File: AmazonS3Storage.java From thunderbit with GNU Affero General Public License v3.0 | 5 votes |
@Override public F.Promise<Void> store(Path path, String key, String name) { Promise<Void> promise = Futures.promise(); TransferManager transferManager = new TransferManager(credentials); try { Upload upload = transferManager.upload(bucketName, key, path.toFile()); upload.addProgressListener((ProgressListener) progressEvent -> { if (progressEvent.getEventType().isTransferEvent()) { if (progressEvent.getEventType().equals(ProgressEventType.TRANSFER_COMPLETED_EVENT)) { transferManager.shutdownNow(); promise.success(null); } else if (progressEvent.getEventType().equals(ProgressEventType.TRANSFER_FAILED_EVENT)) { transferManager.shutdownNow(); logger.error(progressEvent.toString()); promise.failure(new Exception(progressEvent.toString())); } } }); } catch (AmazonServiceException ase) { logAmazonServiceException (ase); } catch (AmazonClientException ace) { logAmazonClientException(ace); } return F.Promise.wrap(promise.future()); }
Example #8
Source File: HttpUtil.java From pay with Apache License 2.0 | 5 votes |
public static String doPost(String url, String data){ return ws.url(url).post(data).map(new F.Function<WSResponse, String>() { @Override public String apply(WSResponse wsResponse) throws Throwable { return wsResponse.getBody(); } }).get(HTTP_TIME_OUT); }
Example #9
Source File: AmazonS3Storage.java From thunderbit with GNU Affero General Public License v3.0 | 5 votes |
@Override public F.Promise<Void> delete(String key, String name) { Promise<Void> promise = Futures.promise(); AmazonS3 amazonS3 = new AmazonS3Client(credentials); DeleteObjectRequest request = new DeleteObjectRequest(bucketName, key); request.withGeneralProgressListener(progressEvent -> { if (progressEvent.getEventType().isTransferEvent()) { if (progressEvent.getEventType().equals(ProgressEventType.TRANSFER_COMPLETED_EVENT)) { promise.success(null); } else if (progressEvent.getEventType().equals(ProgressEventType.TRANSFER_FAILED_EVENT)) { logger.error(progressEvent.toString()); promise.failure(new Exception(progressEvent.toString())); } } }); try { amazonS3.deleteObject(request); } catch (AmazonServiceException ase) { logAmazonServiceException (ase); } catch (AmazonClientException ace) { logAmazonClientException(ace); } return F.Promise.wrap(promise.future()); }
Example #10
Source File: FakeApplicationTest.java From htwplus with MIT License | 5 votes |
/** * Removes a friendship between test accounts. * * @param testAccountA First test account * @param testAccountB Second test account */ public void removeFriendshipTestAccounts(final Account testAccountA, final Account testAccountB) { JPA.withTransaction(new F.Callback0() { @Override public void invoke() throws Throwable { if (Friendship.alreadyFriendly(testAccountA, testAccountB)) { Friendship.findFriendLink(testAccountA, testAccountB).delete(); } if (Friendship.alreadyFriendly(testAccountB, testAccountA)) { Friendship.findFriendLink(testAccountB, testAccountA).delete(); } } }); }
Example #11
Source File: FakeApplicationTest.java From htwplus with MIT License | 5 votes |
/** * Returns a group by title. * * @param title Title of group to fetch * @return Group instance */ public Group getGroupByTitle(final String title) { try { return JPA.withTransaction(new F.Function0<Group>() { @Override public Group apply() throws Throwable { return Group.findByTitle(title); } }); } catch (Throwable throwable) { throwable.printStackTrace(); return null; } }
Example #12
Source File: FakeApplicationTest.java From htwplus with MIT License | 5 votes |
/** * Returns a test group, creates one before if not exists. * * @param number Number of test group * @param groupOwner the optional group owner * @return Group instance */ public Group getTestGroup(final int number, final Account groupOwner) { final String testGroupTitle = "Test Group " + String.valueOf(number); Group storedTestGroup = this.getGroupByTitle(testGroupTitle); // if there is this test group, return if (storedTestGroup != null) { return storedTestGroup; } // there is no test account with that number right now, create a persistent one try { return JPA.withTransaction(new F.Function0<Group>() { @Override public Group apply() throws Throwable { Group testGroup = new Group(); testGroup.groupType = GroupType.close; testGroup.setTitle(testGroupTitle); if (groupOwner != null) { testGroup.createWithGroupAccount(groupOwner); } else { testGroup.create(); } return testGroup; } }); } catch (Throwable throwable) { throwable.printStackTrace(); return null; } }
Example #13
Source File: FakeApplicationTest.java From htwplus with MIT License | 5 votes |
/** * Returns a group account for an account to a group. * * @param account Account * @param group Group * @return GroupAccount instance if found, otherwise null */ public GroupAccount getGroupAccount(final Account account, final Group group) { try { return JPA.withTransaction(new F.Function0<GroupAccount>() { @Override public GroupAccount apply() throws Throwable { return GroupAccount.find(account, group); } }); } catch (Throwable throwable) { throwable.printStackTrace(); return null; } }
Example #14
Source File: FakeApplicationTest.java From htwplus with MIT License | 5 votes |
/** * Establishes a group membership of an account to a group. * * @param account Account * @param group Group */ public void establishGroupMembership(final Account account, final Group group) { JPA.withTransaction(new F.Callback0() { @Override public void invoke() throws Throwable { if (!Group.isMember(group, account)) { groupAccount.account = account; groupAccount.group = group; groupAccount.linkType = LinkType.establish; testGroupAccount.create(); group.update(); } } }); }
Example #15
Source File: SecurityTest.java From htwplus with MIT License | 5 votes |
/** * Tests, if the method "isOwnerOfAccount()" works as expected. */ @Test public void testIsOwnerOfAccount() { final Account testAccount1 = this.getTestAccount(1); final Account testAccount2 = this.getTestAccount(2); this.loginAccount(testAccount1); JPA.withTransaction(new F.Callback0() { @Override public void invoke() throws Throwable { assertThat(Secured.isOwnerOfAccount(testAccount1.id)).isTrue(); assertThat(Secured.isOwnerOfAccount(testAccount2.id)).isFalse(); } }); }
Example #16
Source File: SecurityTest.java From htwplus with MIT License | 5 votes |
/** * Tests, if the method "viewGroup()" works as expected. */ @Test public void testViewGroup() { Account testAccount1 = this.getTestAccount(1); final Group testGroup = this.getTestGroup(1, testAccount1); // test, if admin is allowed to view this.loginAdminAccount(); JPA.withTransaction(new F.Callback0() { @Override public void invoke() throws Throwable { assertThat(Secured.viewGroup(testGroup)).isTrue(); } }); // test, if member of group is allowed to view this.loginAccount(testAccount1); JPA.withTransaction(new F.Callback0() { @Override public void invoke() throws Throwable { assertThat(Secured.viewGroup(testGroup)).isTrue(); } }); // test, if no member of group is disallowed to view Account testAccount3 = this.getTestAccount(3); this.removeGroupMembership(testAccount3, testGroup); this.loginAccount(testAccount3); JPA.withTransaction(new F.Callback0() { @Override public void invoke() throws Throwable { assertThat(Secured.viewGroup(testGroup)).isFalse(); } }); }
Example #17
Source File: FakeApplicationTest.java From htwplus with MIT License | 5 votes |
/** * Removes a membership of an account to a group. * * @param account Account * @param group Group */ public void removeGroupMembership(final Account account, final Group group) { JPA.withTransaction(new F.Callback0() { @Override public void invoke() throws Throwable { if (Group.isMember(group, account)) { GroupAccount groupAccount = GroupAccount.find(account, group); groupAccount.delete(); } } }); }
Example #18
Source File: Authentication.java From pfe-samples with MIT License | 5 votes |
public static <A> A authenticated(Http.Context ctx, F.Function<String, A> f, F.Function0<A> g) throws Throwable { String username = ctx.session().get(USER_KEY); if (username != null) { return f.apply(username); } else { return g.apply(); } }
Example #19
Source File: OAuth.java From pfe-samples with MIT License | 5 votes |
public F.Promise<Result> callback() { String code = request().getQueryString("code"); if (code != null) { String state = request().getQueryString("state"); String returnTo = state != null ? state : configuration.defaultReturnUrl; return ws.url(configuration.tokenEndpoint) .setContentType(Http.MimeTypes.FORM) .post(URL.encode(Scala.varargs( param("code", code), param("client_id", configuration.clientId), param("client_secret", configuration.clientSecret), param("redirect_uri", routes.OAuth.callback().absoluteURL(request())), param("grant_type", "authorization_code") ))).map(response -> { JsonNode accessTokenJson = response.asJson().get("access_token"); if (accessTokenJson == null || !accessTokenJson.isTextual()) { return internalServerError(); } else { String accessToken = accessTokenJson.asText(); session().put(configuration.tokenKey, accessToken); return redirect(returnTo); } }); } else { return F.Promise.pure(internalServerError()); } }
Example #20
Source File: Controller.java From restcommander with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") protected static <T> T await(Future<T> future) { if(future != null) { Request.current().args.put(ActionInvoker.F, future); } else if(Request.current().args.containsKey(ActionInvoker.F)) { // Since the continuation will restart in this code that isn't intstrumented by javaflow, // we need to reset the state manually. StackRecorder.get().isCapturing = false; StackRecorder.get().isRestoring = false; StackRecorder.get().value = null; future = (Future<T>)Request.current().args.get(ActionInvoker.F); // Now reset the Controller invocation context ControllerInstrumentation.stopActionCall(); storeOrRestoreDataStateForContinuations( true ); } else { throw new UnexpectedException("Lost promise for " + Http.Request.current() + "!"); } if(future.isDone()) { try { return future.get(); } catch(Exception e) { throw new UnexpectedException(e); } } else { Request.current().isNew = false; verifyContinuationsEnhancement(); storeOrRestoreDataStateForContinuations( false ); Continuation.suspend(future); return null; } }
Example #21
Source File: Controller.java From restcommander with Apache License 2.0 | 5 votes |
protected static <T> void await(Future<T> future, F.Action<T> callback) { Request.current().isNew = false; Request.current().args.put(ActionInvoker.F, future); Request.current().args.put(ActionInvoker.A, callback); Request.current().args.put(ActionInvoker.CONTINUATIONS_STORE_RENDER_ARGS, Scope.RenderArgs.current()); throw new Suspend(future); }
Example #22
Source File: Http.java From restcommander with Apache License 2.0 | 5 votes |
public void writeChunk(Object o) { this.chunked = true; if (writeChunkHandlers.isEmpty()) { throw new UnsupportedOperationException("Your HTTP server doesn't yet support chunked response stream"); } for (F.Action<Object> handler : writeChunkHandlers) { handler.invoke(o); } }
Example #23
Source File: Http.java From restcommander with Apache License 2.0 | 5 votes |
@Override public Option<WebSocketClose> match(WebSocketEvent o) { if (o instanceof WebSocketClose) { return F.Option.Some((WebSocketClose) o); } return F.Option.None(); }
Example #24
Source File: Http.java From restcommander with Apache License 2.0 | 5 votes |
@Override public Option<String> match(WebSocketEvent o) { if (o instanceof WebSocketFrame) { WebSocketFrame frame = (WebSocketFrame) o; if (!frame.isBinary) { return F.Option.Some(frame.textData); } } return F.Option.None(); }
Example #25
Source File: Http.java From restcommander with Apache License 2.0 | 5 votes |
@Override public Option<byte[]> match(WebSocketEvent o) { if (o instanceof WebSocketFrame) { WebSocketFrame frame = (WebSocketFrame) o; if (frame.isBinary) { return F.Option.Some(frame.binaryData); } } return F.Option.None(); }
Example #26
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 #27
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 #28
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 #29
Source File: Admin.java From openseedbox with GNU General Public License v3.0 | 5 votes |
public static void nodeStatus(long id) { final Node n = Node.findById(id); F.Promise<GenericJobResult> p = new GenericJob() { @Override public Object doGenericJob() { return n.getNodeStatus(); } }.now(); GenericJobResult res = await(p); if (res.hasError()) { resultError(res.getError()); } result(res.getResult()); }
Example #30
Source File: HomeController.java From tutorials with MIT License | 5 votes |
private CompletionStage<F.Either<Result, Flow<JsonNode, JsonNode, ?>>> createActorFlow2(Http.RequestHeader request) { return CompletableFuture.completedFuture( request.session() .getOptional("username") .map(username -> F.Either.<Result, Flow<JsonNode, JsonNode, ?>>Right( createFlowForActor())) .orElseGet(() -> F.Either.Left(forbidden()))); }