Java Code Examples for play.libs.F#Promise

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: AmazonS3Storage.java    From thunderbit with GNU Affero General Public License v3.0 6 votes vote down vote up
@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 2
Source File: Items.java    From thunderbit with GNU Affero General Public License v3.0 6 votes vote down vote up
@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 3
Source File: AuthenticatedAction.java    From pfe-samples with MIT License 5 votes vote down vote up
@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 4
Source File: AmazonS3Storage.java    From thunderbit with GNU Affero General Public License v3.0 5 votes vote down vote up
@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 5
Source File: AmazonS3Storage.java    From thunderbit with GNU Affero General Public License v3.0 5 votes vote down vote up
@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 6
Source File: LocalFilesystemStorage.java    From thunderbit with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public F.Promise<Void> store(Path file, String key, String name) {
    F.Promise<Void> promise = F.Promise.promise(() -> {
        Path keyPath = Files.createDirectory(storagePath.resolve(key));
        Files.copy(file, keyPath.resolve(name));
        return null;
    });
    promise.onFailure(throwable -> logger.error("Could not store file", throwable));
    return promise;
}
 
Example 7
Source File: Admin.java    From openseedbox with GNU General Public License v3.0 5 votes vote down vote up
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 8
Source File: LocalFilesystemStorage.java    From thunderbit with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public F.Promise<Void> delete(String key, String name) {
    F.Promise<Void> promise = F.Promise.promise(() -> {
        Files.delete(storagePath.resolve(key).resolve(name));
        Files.delete(storagePath.resolve(key));
        return null;
    });
    promise.onFailure(throwable -> logger.error("Could not delete file", throwable));
    return promise;
}
 
Example 9
Source File: GSNDeadboltHandler.java    From gsn with GNU General Public License v3.0 5 votes vote down vote up
@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 10
Source File: Storage.java    From thunderbit with GNU Affero General Public License v3.0 5 votes vote down vote up
public F.Promise<Result> download(Long id) {
    // Retrieves the item from the database
    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 {
        // Returns a promise of retrieving a download URL for the stored file
        return storage.getDownload(item.storageKey, item.name)
                // If an error occurs when retrieving the download URL returns a 500 Result
                .recover(throwable -> internalServerError(error.render()));
    }
}
 
Example 11
Source File: PayTransaction.java    From pay with Apache License 2.0 4 votes vote down vote up
@Override
public F.Promise<Result> call(Http.Context ctx) throws Throwable {
    return null;
}
 
Example 12
Source File: Storage.java    From thunderbit with GNU Affero General Public License v3.0 4 votes vote down vote up
@SubjectPresent
public F.Promise<Result> upload() {
    Http.MultipartFormData body = request().body().asMultipartFormData();
    Http.MultipartFormData.FilePart file = body.getFile("file");
    List<String> tags = Arrays.asList(body.asFormUrlEncoded().getOrDefault("tags", EMPTY_ARRAY));

    if (file != null) {
        String fileName = file.getFilename();
        String uuid = UUID.randomUUID().toString();
        Date uploadDate = Calendar.getInstance().getTime();
        Long fileSize = file.getFile().length();

        // Returns a promise of storing the file
        return storage.store(file.getFile().toPath(), uuid, file.getFilename())
                // If the file storage is successful saves the Item to the database
                .map(aVoid -> {
                    // Get the list of Tag entities for the new Item
                    List<Tag> tagsList = new ArrayList<>();
                    for (String tagName : tags) {
                        Tag tag = Tag.find.where().eq("name", tagName.toLowerCase()).findUnique();
                        // Create new tags if they doesn't already exist
                        if (tag == null) {
                            tag = new Tag();
                            tag.name = tagName.toLowerCase();
                            tag.save();
                        }
                        tagsList.add(tag);
                    }

                    Item item = new Item();
                    item.name = fileName;
                    item.storageKey = uuid;
                    item.uploadDate = uploadDate;
                    item.fileSize = fileSize;
                    item.setTags(tagsList);
                    item.save();

                    return ok();
                });
    } else {
        return F.Promise.pure(badRequest());
    }
}
 
Example 13
Source File: MockStorage.java    From thunderbit with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public F.Promise<Void> delete(String key, String name) {
    return F.Promise.pure(null);
}
 
Example 14
Source File: SocialNetwork.java    From pfe-samples with MIT License 4 votes vote down vote up
public F.Promise<WSResponse> share(String content, String token) {
    return ws.url(SHARING_ENDPOINT)
            .setQueryParameter("access_token", token)
            .setContentType(Http.MimeTypes.FORM)
            .post(URL.encode(Scala.varargs(URL.param("content", content))));
}
 
Example 15
Source File: MockStorage.java    From thunderbit with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public F.Promise<Void> store(Path file, String key, String name) {
    return F.Promise.pure(null);
}
 
Example 16
Source File: EntityNotFoundGuardAction.java    From judgels with GNU General Public License v2.0 4 votes vote down vote up
private F.Promise<Result> showEntityNotFound(Throwable e) {
    return F.Promise.promise(() -> {
            return Results.notFound();
        }
    );
}
 
Example 17
Source File: Storage.java    From thunderbit with GNU Affero General Public License v3.0 2 votes vote down vote up
/**
 * Gets a download for a stored file
 *
 * @param   key
 *          The stored file key
 * @param   name
 *          The name for the file
 */
F.Promise<Result> getDownload (String key, String name);
 
Example 18
Source File: Storage.java    From thunderbit with GNU Affero General Public License v3.0 2 votes vote down vote up
/**
 * Deletes a stored file
 *
 * @param   key
 *          The stored file key
 * @param   name
 *          The stored file name
 */
F.Promise<Void> delete (String key, String name);
 
Example 19
Source File: Storage.java    From thunderbit with GNU Affero General Public License v3.0 2 votes vote down vote up
/**
 * Stores a file
 *
 * @param   file
 *          The file to store
 * @param   key
 *          A key for the stored file
 * @param   name
 *          A name for the stored file
 */
F.Promise<Void> store (Path file, String key, String name);
 
Example 20
Source File: AuctionRooms.java    From pfe-samples with MIT License 2 votes vote down vote up
/**
 * Subscribe to bid notifications for a given item
 * @param id Item id
 * @param subscriber Notification callback
 * @return A pair containing the current bids and a Subscription object (for un-subscribing)
 */
public F.Promise<F.Tuple<List<Bid>, Subscription>> subscribe(Long id, Consumer<Bid> subscriber) {
    return F.Promise.wrap((Future)ask(ref, new AuctionRoomsActor.Subscribe(id, subscriber), t));
}