Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a sample for Java based application with default Twirl Java imports #113

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions src/docs/asciidoc/34-compiler-options.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,13 @@ If your Play application requires additional Scala compiler flags, you can add t
.build.gradle
----
include::{samplesCodeDir}/configure-compiler/groovy/build.gradle[tag=additional-params]
----

When working with Twirl templates in Java-based project, the Java default imports needs to be enabled to include necessary
conversions of Scala objects to Java objects, e.g. Scala forms to Java forms.

[source,groovy]
.build.gradle
----
include::{samplesCodeDir}/basic-java/groovy/build.gradle[tag=enable-java-default-imports-in-templates]
----
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package controllers;

import play.mvc.Controller;
import play.mvc.Result;
import org.apache.commons.lang3.StringUtils;
import play.data.Form;
import play.data.FormFactory;
import javax.inject.*;
import model.*;

@Singleton
public class Application extends Controller {

private FormFactory ff;

@Inject
public Application(FormFactory ff) {
this.ff = ff;
}

public Result index() {

Form<User> userForm = ff.form(User.class).bindFromRequest();

return ok(views.html.indexUserForm.render(
StringUtils.trim(" Your new application is ready. "),
userForm
));
}

}
8 changes: 8 additions & 0 deletions src/docs/samples/basic-java/groovy/app/model/User.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package model;

public class User {

public String username;
public String mobile;

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
@(message: String, userForm : play.data.Form[model.User])

@main("Welcome to Play") {

<h1>@message</h1>

<h2>User Form</h2>

@helper.form(action = routes.Application.index, 'id -> "userFormId") {

<div>
@helper.inputText(
field = userForm("username"),
args = '_label -> "Username", 'id -> "username"
)
</div>

<div>
@helper.inputText(
field = userForm("mobile"),
args = '_label -> "Mobile", 'id -> "mobile"
)
</div>

}

}
15 changes: 15 additions & 0 deletions src/docs/samples/basic-java/groovy/app/views/main.scala.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
@(title: String)(content: Html)

<!DOCTYPE html>

<html>
<head>
<title>@title</title>
<link rel="stylesheet" media="screen" href="@routes.Assets.at("stylesheets/main.css")">
<link rel="shortcut icon" type="image/png" href="@routes.Assets.at("images/favicon.png")">
<script src="@routes.Assets.at("javascripts/hello.js")" type="text/javascript"></script>
</head>
<body>
@content
</body>
</html>
2 changes: 2 additions & 0 deletions src/docs/samples/basic-java/groovy/basic-java.sample.conf
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
executable: gradle
args: tasks
48 changes: 48 additions & 0 deletions src/docs/samples/basic-java/groovy/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// tag::use-plugin[]
plugins {
id 'org.gradle.playframework' version '0.9'
}

repositories {
jcenter()
maven {
name "lightbend-maven-release"
url "https://repo.lightbend.com/lightbend/maven-releases"
}
ivy {
name "lightbend-ivy-release"
url "https://repo.lightbend.com/lightbend/ivy-releases"
layout "ivy"
}
}
// end::use-plugin[]

play {
injectedRoutesGenerator = true
}

dependencies {
implementation 'commons-lang:commons-lang:2.6'
testImplementation "com.google.guava:guava:17.0"
testImplementation "org.scalatestplus.play:scalatestplus-play_2.12:3.1.2"
implementation "com.typesafe.play:play-guice_2.12:2.6.15"
implementation "ch.qos.logback:logback-classic:1.2.3"

implementation group: 'com.typesafe.play', name: 'play-java-forms_2.12', version: '2.6.15'
}

// tag::enable-java-default-imports-in-templates[]
sourceSets {
main {
twirl {
defaultImports = org.gradle.playframework.sourcesets.TwirlImports.JAVA
}
}
}

// alternatively
// compilePlayTwirlTemplates {
// defaultImports = org.gradle.playframework.sourcesets.TwirlImports.JAVA
// }

// end::enable-java-default-imports-in-templates[]
44 changes: 44 additions & 0 deletions src/docs/samples/basic-java/groovy/conf/application.conf
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# This is the main configuration file for the application.
# ~~~~~

# Secret key
# ~~~~~
# The secret key is used to secure cryptographics functions.
#
# This must be changed for production, but we recommend not changing it in this file.
#
# See http://www.playframework.com/documentation/latest/ApplicationSecret for more details.
play.http.secret.key="dxbAjiDdqlIV83LY<:;hSxql?tG`CPNgXEXt2asjk>lYQ<xfR`GsdeFJ@uuYBH=0"

# Global object class
# ~~~~~
# Define the Global object class for this application.
# Default to Global in the root package.
# application.global=Global

# Router
# ~~~~~
# Define the Router object to use for this application.
# This router will be looked up first when the application is starting up,
# so make sure this is the entry point.
# Furthermore, it's assumed your route file is named properly.
# So for an application router like `my.application.Router`,
# you may need to define a router file `conf/my.application.routes`.
# Default to Routes in the root package (and conf/routes)
# application.router=my.application.Routes

# Database configuration
# ~~~~~
# You can declare as many datasources as you want.
# By convention, the default datasource is named `default`
#
# db.default.driver=org.h2.Driver
# db.default.url="jdbc:h2:mem:play"
# db.default.user=sa
# db.default.password=""

# Evolutions
# ~~~~~
# You can disable evolutions if needed
# evolutionplugin=disabled

9 changes: 9 additions & 0 deletions src/docs/samples/basic-java/groovy/conf/routes
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Routes
# This file defines all application routes (Higher priority routes first)
# ~~~~

# Home page
GET / @controllers.Application.index

# Map static resources from the /public folder to the /assets URL path
GET /assets/*file @controllers.Assets.at(path="/public", file)
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
if (window.console) {
console.log("Welcome to your Play application's JavaScript!");
}
Empty file.
1 change: 1 addition & 0 deletions src/docs/samples/basic-java/groovy/settings.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
rootProject.name = 'basic-java'
47 changes: 47 additions & 0 deletions src/docs/samples/basic-java/groovy/test/ApplicationSpec.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import com.google.common.collect.Lists
import org.apache.commons.lang.StringUtils
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import org.scalatestplus.play.PlaySpec
import org.scalatestplus.play.guice.GuiceOneAppPerSuite
import play.api.http.Status
import play.api.test.FakeRequest
import play.api.test.Helpers._

@RunWith(classOf[JUnitRunner])
class ApplicationSpec extends PlaySpec with GuiceOneAppPerSuite {

"Application" should {

"send 404 on a bad request" in {
route(app, FakeRequest(GET, "/boum")).map(status(_)) mustBe Some(NOT_FOUND)
}

"render the index page" in {
val home = route(app, FakeRequest(GET, "/")).get

status(home) mustBe Status.OK
contentType(home) mustBe Some("text/html")
contentAsString(home) must include ("Your new application is ready.")
}

"render the index page with a Java form" in {
val home = route(app, FakeRequest(GET, "/?username=testuser&mobile=987654321")).get

status(home) mustBe Status.OK
contentType(home) mustBe Some("text/html")
contentAsString(home) must include ("Your new application is ready.")
contentAsString(home) must include ("""<form action="/" method="GET" id="userFormId">""")
contentAsString(home) must include ("""<input type="text" id="username" name="username" value="testuser" />""")
contentAsString(home) must include ("""<input type="text" id="mobile" name="mobile" value="987654321" />""")
}

"tests can use commons-lang play dependency" in {
StringUtils.reverse("foobar") mustBe "raboof"
}

"tests can use guava play-test dependency" in {
Lists.newArrayList("foo", "bar").size() mustBe 2
}
}
}
22 changes: 22 additions & 0 deletions src/docs/samples/basic-java/groovy/test/IntegrationSpec.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import org.scalatestplus.play._
import org.scalatestplus.play.guice.GuiceOneServerPerTest

@RunWith(classOf[JUnitRunner])
class IntegrationSpec extends PlaySpec
with OneBrowserPerTest
with GuiceOneServerPerTest
with HtmlUnitFactory
with ServerProvider {

"Application" should {

"work from within a browser" in {

go to ("http://localhost:" + port)

pageSource must include ("Your new application is ready.")
}
}
}