Last active
October 24, 2016 20:11
-
-
Save peterszatmary/4df94851e835f1f85ca9c4d2d7ab655e to your computer and use it in GitHub Desktop.
Example of writing functional java non blocking code with Play! framework 2.4. Results are in json format. For more see https://github.com/peterszatmary/play-service-one and https://github.com/peterszatmary/play-main-microservice-app
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package controllers; | |
import com.google.inject.Inject; | |
import core.CalculationSystem; | |
import play.libs.F; | |
import play.libs.Json; | |
import play.mvc.Controller; | |
import play.mvc.Result; | |
import java.util.HashMap; | |
import java.util.Map; | |
import static core.PlayPropertiesHelper.*; | |
/** | |
* just mock for long and quick computation | |
* Play! app / non-blocking, functional | |
*/ | |
public class Application extends Controller { | |
@Inject | |
private CalculationSystem calculationSystem; | |
public F.Promise<Result> doSmallCalculation() { | |
return F.Promise.promise(() -> calculationSystem.calculationSmall()) // non-blocking with F.Promise.promise | |
.map(x -> { | |
Map<String, Integer> data = new HashMap<>(); | |
data.put("result", x); | |
return data; | |
}) | |
.map(Json::toJson) | |
.map(jsonResponse -> (Result) ok(jsonResponse)) | |
.recover(t -> badRequest(t.getMessage() + "\n")); | |
} | |
public F.Promise<Result> doBigCalculation() { | |
return F.Promise.promise(() -> calculationSystem.calculationBig()) // non-blocking with F.Promise.promise | |
.map(x -> { | |
Map<String, Integer> data = new HashMap<>(); | |
data.put("result", x); | |
return data; | |
}) | |
.map(Json::toJson) | |
.map(jsonResponse -> (Result) ok(jsonResponse)) | |
.recover(t -> badRequest(t.getMessage() + "\n")); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment