Я пишу приложение Play 2.3.2. У меня есть основное приложение, написанное на Java, и модуль, используемый основным приложением, написанным в Scala.
Мое приложение-модуль предоставляет некоторый REST API, который получает данные от JSON и возвращает выход JSON.
Как я могу вызвать API REST модуля из моего основного приложения?
И как можно анализировать результаты вычисления, возвращаемые модулем Controller?
@редактировать
В моем модульном контроллере у меня есть несколько методов:
object BridgeController extends Controller {
def addTagToUser = CorsAction.async { request =>
//update the tag of a user
def updateTagToUserDB(user: User, tag: Tag): Future[Boolean] = {
println(tag)
val query = Json.obj("id" -> user.id,
"email" -> user.email) //the query object
Users.find(query).toList.flatMap { users =>
val oldUser = if (users.size > 0) users(0) else user
val newUser = oldUser.addTags(List(tag)) //create the updated user
//update the document find, and create if doesn't exists
Users.update(query, newUser, upsert = true).flatMap{error => error match {
case LastError(ok, _, _, _, _,_, _) => Future{true}
case _ => Future{false} //error on update the document
}}
}
}
val jsonData = request.body.asJson //get the json data
jsonData match {
case Some(x) => val user = x \ "user"; val tag = x \ "tag";
(user \ "id", user \ "email", tag \ "category", tag \ "attr") match {
case (userId: JsString, userEmail: JsString,
tagCat: JsString, tagAtr: JsString) => val myUser = new User(userId.as[String], Some(userEmail.as[String]))
val newTag = new Tag(tagCat.as[String], tagAtr.as[String])
updateTagToUserDB(myUser, newTag).flatMap(status => status match {
case true => Future{Ok}//the update was executed correctly
case false => Future{InternalServerError("Cannot access to the db now")}//update fail
}
)
case _ => Future{BadRequest("json bad formed")} // the json is bad formed
}
case None => Future{BadRequest("need a json value")}
}
}
}
В контроллере моего основного приложения у меня может быть что-то вроде этого:
public class Application extends Controller {
public static Result addProduct(Product product) {
User user = product.user()
String category = product.category()
String nameProduct = product.nameProduct()
//here i want to create a json like {"user": {"id" : user.id, "email", //user.email}, tag: {"category": category, "attr", nameProduct}}
//now i want to sent an http request to the controller module and pass the json created
}
}
Если вы хотите использовать службы REST с использованием библиотеки ресурсов PLAY, вы можете использовать WS api
https://www.playframework.com/documentation/2.3.3/ScalaWS
Альтернативой является использование стандартного Java EE
http://docs.oracle.com/javaee/7/tutorial/doc/jaxrs-client001.htm