├── public ├── stylesheets │ └── main.css ├── images │ └── favicon.png └── javascripts │ └── main.js ├── project ├── build.properties └── plugins.sbt ├── README.md ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── .gitignore ├── conf ├── application.conf ├── routes └── logback.xml ├── scripts ├── test-sbt ├── script-helper └── test-gradle ├── app ├── dagger │ ├── ApplicationLoaderContextModule.java │ ├── ClockModule.java │ ├── ApplicationModule.java │ ├── ApplicationComponent.java │ ├── MyApplicationLoader.java │ ├── MyComponentsFromContext.java │ └── SimpleInjector.java ├── views │ ├── index.scala.html │ └── main.scala.html ├── controllers │ ├── TimeZoneData.java │ └── TimeController.java └── filters │ └── LoggingFilter.java ├── NOTICE ├── .mergify.yml ├── .travis.yml ├── test └── IntegrationTest.java ├── gradlew.bat ├── .github └── settings.yml ├── gradlew └── LICENSE /public/stylesheets/main.css: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /project/build.properties: -------------------------------------------------------------------------------- 1 | sbt.version=1.2.8 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | MOVED TO https://github.com/playframework/play-samples 2 | -------------------------------------------------------------------------------- /project/plugins.sbt: -------------------------------------------------------------------------------- 1 | // The Play plugin 2 | addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.7.0") 3 | -------------------------------------------------------------------------------- /public/images/favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/playframework/play-java-dagger2-example/2.7.x/public/images/favicon.png -------------------------------------------------------------------------------- /public/javascripts/main.js: -------------------------------------------------------------------------------- 1 | if (window.console) { 2 | console.log("Welcome to your Play application's JavaScript!"); 3 | } 4 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/playframework/play-java-dagger2-example/2.7.x/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | logs 2 | target 3 | build 4 | /.idea 5 | /.idea_modules 6 | /.classpath 7 | /.gradle 8 | /.project 9 | /.settings 10 | /RUNNING_PID -------------------------------------------------------------------------------- /conf/application.conf: -------------------------------------------------------------------------------- 1 | # This is the main configuration file for the application. 2 | # https://www.playframework.com/documentation/latest/ConfigFile 3 | 4 | play.application.loader= dagger.MyApplicationLoader 5 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.9-bin.zip 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStorePath=wrapper/dists 5 | zipStoreBase=GRADLE_USER_HOME 6 | -------------------------------------------------------------------------------- /scripts/test-sbt: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | . "$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )/script-helper" 4 | 5 | echo "+----------------------------+" 6 | echo "| Executing tests using sbt |" 7 | echo "+----------------------------+" 8 | sbt ++$TRAVIS_SCALA_VERSION test 9 | -------------------------------------------------------------------------------- /app/dagger/ApplicationLoaderContextModule.java: -------------------------------------------------------------------------------- 1 | package dagger; 2 | 3 | @Module 4 | public abstract class ApplicationLoaderContextModule { 5 | 6 | @Provides 7 | public static play.api.ApplicationLoader.Context providesScalaContext(play.ApplicationLoader.Context context) { 8 | return context.asScala(); 9 | } 10 | 11 | } 12 | -------------------------------------------------------------------------------- /app/dagger/ClockModule.java: -------------------------------------------------------------------------------- 1 | package dagger; 2 | 3 | import java.time.Clock; 4 | 5 | /** 6 | * A module that provides a clock implementation. 7 | */ 8 | @Module 9 | public abstract class ClockModule { 10 | 11 | @Provides 12 | public static Clock clock() { 13 | return java.time.Clock.systemUTC(); 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /app/dagger/ApplicationModule.java: -------------------------------------------------------------------------------- 1 | package dagger; 2 | 3 | import play.Application; 4 | 5 | @Module 6 | public abstract class ApplicationModule { 7 | 8 | @Provides 9 | public static Application providesApplication(MyComponentsFromContext myComponentsFromContext) { 10 | return myComponentsFromContext.application(); 11 | } 12 | 13 | } -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | Written by Lightbend 2 | 3 | To the extent possible under law, the author(s) have dedicated all copyright and 4 | related and neighboring rights to this software to the public domain worldwide. 5 | This software is distributed without any warranty. 6 | 7 | You should have received a copy of the CC0 Public Domain Dedication along with 8 | this software. If not, see . 9 | -------------------------------------------------------------------------------- /conf/routes: -------------------------------------------------------------------------------- 1 | GET / controllers.TimeController.index(request:Request) 2 | POST / controllers.TimeController.indexPost(request:Request) 3 | 4 | GET /ws controllers.TimeController.ws(request:Request) 5 | GET /now controllers.TimeController.now 6 | 7 | # Map static resources from the /public folder to the /assets URL path 8 | GET /assets/*file controllers.Assets.versioned(path="/public", file: Asset) 9 | -------------------------------------------------------------------------------- /scripts/script-helper: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -e 4 | set -o pipefail 5 | 6 | java_version=$(java -version 2>&1 | java -version 2>&1 | awk -F '"' '/version/ {print $2}') 7 | 8 | if [[ $java_version = 1.8* ]] ; then 9 | echo "The build is using Java 8 ($java_version). No addional JVM params needed." 10 | else 11 | echo "The build is using Java 9+ ($java_version). We need additional JVM parameters" 12 | export _JAVA_OPTIONS="$_JAVA_OPTIONS --add-modules=java.xml.bind" 13 | fi 14 | -------------------------------------------------------------------------------- /scripts/test-gradle: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | . "$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )/script-helper" 4 | 5 | # Using cut because TRAVIS_SCALA_VERSION is the full Scala 6 | # version (for example 2.12.4), but Gradle expects just the 7 | # binary version (for example 2.12) 8 | scala_binary_version=$(echo $TRAVIS_SCALA_VERSION | cut -c1-4) 9 | 10 | echo "+------------------------------+" 11 | echo "| Executing tests using Gradle |" 12 | echo "+------------------------------+" 13 | ./gradlew -Dscala.binary.version=$scala_binary_version check -i --stacktrace 14 | -------------------------------------------------------------------------------- /app/dagger/ApplicationComponent.java: -------------------------------------------------------------------------------- 1 | package dagger; 2 | 3 | import javax.inject.Singleton; 4 | 5 | /** 6 | * The application component that specifies all the modules backing 7 | * the injected components. 8 | */ 9 | @Singleton 10 | @Component(modules = { 11 | ApplicationLoaderContextModule.class, 12 | ApplicationModule.class, 13 | ClockModule.class 14 | }) 15 | public interface ApplicationComponent { 16 | play.Application application(); 17 | 18 | @Component.Builder 19 | interface Builder { 20 | @BindsInstance Builder context(play.ApplicationLoader.Context context); 21 | ApplicationComponent build(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /app/views/index.scala.html: -------------------------------------------------------------------------------- 1 | @import play.mvc.Http.Request 2 | @(form: play.data.Form[TimeZoneData], renderedTime: String, timeZones: List[String])(implicit request: Request, messages: play.i18n.Messages) 3 | 4 | @main("Welcome to Play!") { 5 | 6 |

@renderedTime

7 | 8 | @request.flash.getOptional("success").orElse("") 9 | 10 | @helper.form(action = routes.TimeController.indexPost()) { 11 | 12 | @helper.select(field = form("timeZone"), options = helper.options(timeZones)) 13 | 14 | } 15 | 16 | See time rendered from a remote REST API 17 | } 18 | -------------------------------------------------------------------------------- /app/views/main.scala.html: -------------------------------------------------------------------------------- 1 | @* 2 | * This template is called from the `index` template. This template 3 | * handles the rendering of the page header and body tags. It takes 4 | * two arguments, a `String` for the title of the page and an `Html` 5 | * object to insert into the body of the page. 6 | *@ 7 | @(title: String)(content: Html) 8 | 9 | 10 | 11 | 12 | @* Here's where we render the page title `String`. *@ 13 | @title 14 | 15 | 16 | 17 | 18 | @* And here's where we render the `Html` object containing 19 | * the page content. *@ 20 | @content 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /app/controllers/TimeZoneData.java: -------------------------------------------------------------------------------- 1 | package controllers; 2 | 3 | import play.data.validation.ValidationError; 4 | 5 | import java.util.TimeZone; 6 | 7 | import static play.data.validation.Constraints.*; 8 | 9 | @Validate 10 | public class TimeZoneData implements Validatable { 11 | 12 | @Required 13 | private String timeZone; 14 | 15 | public TimeZoneData() { 16 | super(); 17 | } 18 | 19 | public TimeZoneData(String timeZone) { 20 | this.timeZone = timeZone; 21 | } 22 | 23 | public String getTimeZone() { 24 | return timeZone; 25 | } 26 | 27 | public void setTimeZone(String timeZone) { 28 | this.timeZone = timeZone; 29 | } 30 | 31 | @Override 32 | public ValidationError validate() { 33 | if (TimeZone.getTimeZone(timeZone) == null) { 34 | return new ValidationError("timeZone", "Invalid time zone"); 35 | } 36 | return null; 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /.mergify.yml: -------------------------------------------------------------------------------- 1 | pull_request_rules: 2 | - name: Merge PRs that are ready 3 | conditions: 4 | - status-success=Travis CI - Pull Request 5 | - status-success=typesafe-cla-validator 6 | - "#approved-reviews-by>=1" 7 | - "#review-requested=0" 8 | - "#changes-requested-reviews-by=0" 9 | - label!=status:block-merge 10 | actions: 11 | merge: 12 | method: squash 13 | strict: smart 14 | 15 | - name: Merge TemplateControl's PRs that are ready 16 | conditions: 17 | - status-success=Travis CI - Pull Request 18 | - "#review-requested=0" 19 | - "#changes-requested-reviews-by=0" 20 | - label!=status:block-merge 21 | - label=status:merge-when-green 22 | - label!=status:block-merge 23 | actions: 24 | merge: 25 | method: squash 26 | strict: smart 27 | 28 | - name: Delete the PR branch after merge 29 | conditions: 30 | - merged 31 | actions: 32 | delete_head_branch: {} 33 | -------------------------------------------------------------------------------- /app/dagger/MyApplicationLoader.java: -------------------------------------------------------------------------------- 1 | package dagger; 2 | 3 | import play.Application; 4 | import play.ApplicationLoader; 5 | import play.LoggerConfigurator; 6 | 7 | import java.util.Optional; 8 | 9 | import static java.util.Collections.*; 10 | 11 | /** 12 | * This class loads an application through Dagger compile time dependency injection. 13 | */ 14 | public class MyApplicationLoader implements ApplicationLoader { 15 | 16 | @Override 17 | public Application load(Context context) 18 | { 19 | final ClassLoader classLoader = context.environment().classLoader(); 20 | final Optional opt = LoggerConfigurator.apply(classLoader); 21 | opt.ifPresent(lc -> lc.configure(context.environment(), context.initialConfig(), emptyMap())); 22 | 23 | ApplicationComponent applicationComponent = DaggerApplicationComponent.builder() 24 | .context(context) 25 | .build(); 26 | 27 | return applicationComponent.application(); 28 | } 29 | } 30 | 31 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: scala 2 | scala: 2.12.8 3 | script: $SCRIPT 4 | 5 | env: 6 | matrix: 7 | - SCRIPT=scripts/test-sbt TRAVIS_JDK=adopt@1.8.202-08 8 | - SCRIPT=scripts/test-sbt TRAVIS_JDK=adopt@1.11.0-2 9 | - SCRIPT=scripts/test-gradle TRAVIS_JDK=adopt@1.8.202-08 10 | - SCRIPT=scripts/test-gradle TRAVIS_JDK=adopt@1.11.0-2 11 | 12 | matrix: 13 | fast_finish: true 14 | allow_failures: 15 | - env: SCRIPT=scripts/test-gradle TRAVIS_JDK=adopt@1.8.202-08 # current gradle doesn't support play 2.7 16 | - env: SCRIPT=scripts/test-gradle TRAVIS_JDK=adopt@1.11.0-2 # current gradle doesn't support play 2.7 17 | - env: SCRIPT=scripts/test-sbt TRAVIS_JDK=adopt@1.11.0-2 # not fully supported but allows problem discovery 18 | 19 | before_install: curl -Ls https://git.io/jabba | bash && . ~/.jabba/jabba.sh 20 | install: jabba install "$TRAVIS_JDK" && jabba use "$_" && java -Xmx32m -version 21 | 22 | cache: 23 | directories: 24 | - "$HOME/.gradle/caches" 25 | - "$HOME/.ivy2/cache" 26 | - "$HOME/.jabba/jdk" 27 | - "$HOME/.sbt" 28 | 29 | before_cache: 30 | - find $HOME/.ivy2 -name "ivydata-*.properties" -delete 31 | - find $HOME/.sbt -name "*.lock" -delete 32 | -------------------------------------------------------------------------------- /conf/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | ${application.home:-.}/logs/application.log 8 | 9 | %date [%level] from %logger in %thread - %message%n%xException 10 | 11 | 12 | 13 | 14 | 15 | %coloredLevel %logger{15} - %message%n%xException{10} 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /app/filters/LoggingFilter.java: -------------------------------------------------------------------------------- 1 | package filters; 2 | 3 | import akka.stream.Materializer; 4 | import org.slf4j.LoggerFactory; 5 | import play.mvc.Filter; 6 | import play.mvc.Http; 7 | import play.mvc.Result; 8 | 9 | import javax.inject.Inject; 10 | import java.util.concurrent.CompletionStage; 11 | import java.util.function.Function; 12 | 13 | public class LoggingFilter extends Filter { 14 | 15 | private org.slf4j.Logger logger = LoggerFactory.getLogger("application"); 16 | 17 | @Inject 18 | public LoggingFilter(Materializer mat) { 19 | super(mat); 20 | } 21 | 22 | @Override 23 | public CompletionStage apply( 24 | Function> nextFilter, 25 | Http.RequestHeader requestHeader) { 26 | long startTime = System.currentTimeMillis(); 27 | return nextFilter.apply(requestHeader).thenApply(result -> { 28 | long endTime = System.currentTimeMillis(); 29 | long requestTime = endTime - startTime; 30 | 31 | logger.info("{} {} took {}ms and returned {}", 32 | requestHeader.method(), requestHeader.uri(), requestTime, result.status()); 33 | 34 | return result.withHeader("Request-Time", "" + requestTime); 35 | }); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /test/IntegrationTest.java: -------------------------------------------------------------------------------- 1 | import dagger.MyApplicationLoader; 2 | import org.junit.Test; 3 | import play.Application; 4 | import play.ApplicationLoader; 5 | import play.Environment; 6 | import play.mvc.Http; 7 | import play.mvc.Result; 8 | import play.test.Helpers; 9 | import play.test.WithApplication; 10 | 11 | import java.util.Arrays; 12 | import java.util.List; 13 | import java.util.TimeZone; 14 | 15 | import static org.junit.Assert.assertEquals; 16 | import static org.junit.Assert.assertTrue; 17 | import static play.test.Helpers.*; 18 | 19 | public class IntegrationTest extends WithApplication { 20 | 21 | @Override 22 | protected Application provideApplication() { 23 | return new MyApplicationLoader().load(ApplicationLoader.create(Environment.simple())); 24 | } 25 | 26 | @Test 27 | public void testIndex() { 28 | Http.RequestBuilder request = Helpers.fakeRequest(); 29 | request.uri(controllers.routes.TimeController.index().url()); 30 | // passing app in explicitly here is key since route() overloads without it use the deprecated 31 | // static Application references 32 | Result result = route(app, request); 33 | assertEquals(result.status(), OK); 34 | String content = contentAsString(result); 35 | 36 | List timezones = Arrays.asList(TimeZone.getAvailableIDs()); 37 | for (String timezone : timezones) { 38 | assertTrue(content.contains(timezone)); 39 | } 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /app/dagger/MyComponentsFromContext.java: -------------------------------------------------------------------------------- 1 | package dagger; 2 | 3 | import controllers.TimeController; 4 | import dagger.SimpleInjector; 5 | import play.ApplicationLoader; 6 | import play.BuiltInComponentsFromContext; 7 | import play.api.routing.Router; 8 | import play.components.AkkaComponents; 9 | import play.components.BodyParserComponents; 10 | import play.controllers.AssetsComponents; 11 | import play.core.j.DefaultJavaHandlerComponents; 12 | import play.core.j.JavaHandlerComponents; 13 | import play.data.FormFactoryComponents; 14 | import play.filters.components.HttpFiltersComponents; 15 | import play.filters.components.NoHttpFiltersComponents; 16 | import play.i18n.I18nComponents; 17 | import play.inject.Injector; 18 | import play.libs.ws.ahc.AhcWSComponents; 19 | import router.Routes; 20 | import scala.concurrent.ExecutionContext; 21 | 22 | import javax.inject.Inject; 23 | import java.time.Clock; 24 | import java.util.HashMap; 25 | import java.util.Map; 26 | import java.util.function.Supplier; 27 | 28 | /** 29 | * A components class that contains a clock instance injected from Dagger. 30 | */ 31 | public class MyComponentsFromContext extends BuiltInComponentsFromContext implements NoHttpFiltersComponents, 32 | AssetsComponents, 33 | AhcWSComponents, 34 | FormFactoryComponents, 35 | BodyParserComponents, 36 | I18nComponents{ 37 | 38 | private final Clock clock; 39 | 40 | @Inject 41 | public MyComponentsFromContext(ApplicationLoader.Context context, Clock clock) { 42 | super(context); 43 | this.clock = clock; 44 | } 45 | 46 | private TimeController timeController() { 47 | return new controllers.TimeController(clock, wsClient(), formFactory(), messagesApi()); 48 | } 49 | 50 | @Override 51 | public play.routing.Router router() { 52 | Router routes = new Routes(scalaHttpErrorHandler(), timeController(), assets()); 53 | return routes.asJava(); 54 | } 55 | 56 | @Override 57 | public ExecutionContext executionContext() { 58 | return actorSystem().dispatcher(); 59 | } 60 | } -------------------------------------------------------------------------------- /app/dagger/SimpleInjector.java: -------------------------------------------------------------------------------- 1 | package dagger; 2 | 3 | import play.api.inject.BindingKey; 4 | import play.inject.Injector; 5 | import scala.reflect.ClassTag; 6 | 7 | import java.util.Map; 8 | import java.util.function.Supplier; 9 | 10 | /** 11 | * A simple injector with additional classes... 12 | */ 13 | public class SimpleInjector implements Injector { 14 | private final Injector injector; 15 | private final Map> mappings; 16 | 17 | public SimpleInjector(Injector injector, Map> mappings) { 18 | this.injector = injector; 19 | this.mappings = mappings; 20 | } 21 | 22 | @Override 23 | @SuppressWarnings("unchecked") 24 | public T instanceOf(Class clazz) { 25 | try { 26 | return injector.instanceOf(clazz); 27 | } catch (Throwable e) { 28 | Supplier objectSupplier = mappings.get(clazz); 29 | if (objectSupplier != null) { 30 | return (T) objectSupplier.get(); 31 | } else { 32 | return null; 33 | } 34 | } 35 | } 36 | 37 | @Override 38 | public T instanceOf(BindingKey key) { 39 | return instanceOf(key.clazz()); 40 | } 41 | 42 | @Override 43 | public play.api.inject.Injector asScala() { 44 | Injector thisInjector = this; 45 | return new play.api.inject.Injector() { 46 | @Override 47 | public Injector asJava() { 48 | return thisInjector; 49 | } 50 | 51 | @Override 52 | public T instanceOf(BindingKey key) { 53 | return thisInjector.instanceOf(key); 54 | } 55 | 56 | @Override 57 | public T instanceOf(Class clazz) { 58 | return thisInjector.instanceOf(clazz); 59 | } 60 | 61 | @Override 62 | @SuppressWarnings("unchecked") 63 | public T instanceOf(ClassTag evidence) { 64 | return thisInjector.instanceOf((Class) evidence.runtimeClass()); 65 | } 66 | }; 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /.github/settings.yml: -------------------------------------------------------------------------------- 1 | # These settings are synced to GitHub by https://probot.github.io/apps/settings/ 2 | repository: 3 | homepage: "https://developer.lightbend.com/start/?group=play" 4 | topics: playframework, example, example-project, sample, sample-app, jvm, webapp 5 | private: false 6 | has_issues: true 7 | # We don't need projects in sample projects 8 | has_projects: false 9 | # We don't need wiki in sample projects 10 | has_wiki: false 11 | has_downloads: true 12 | default_branch: 2.7.x 13 | allow_squash_merge: true 14 | allow_merge_commit: false 15 | allow_rebase_merge: false 16 | 17 | teams: 18 | - name: core 19 | permission: admin 20 | - name: integrators 21 | permission: write 22 | - name: write-bots 23 | permission: write 24 | 25 | branches: 26 | - name: "[0-9].*.x" 27 | protection: 28 | # We don't require reviews for sample applications because they are mainly 29 | # updated by template-control, which is an automated process 30 | required_pull_request_reviews: null 31 | # Required. Require status checks to pass before merging. Set to null to disable 32 | required_status_checks: 33 | # Required. The list of status checks to require in order to merge into this branch 34 | contexts: ["Travis CI - Pull Request", "typesafe-cla-validator"] 35 | 36 | # Labels: tailored list of labels to be used by sample applications 37 | labels: 38 | - color: f9d0c4 39 | name: "closed:declined" 40 | - color: f9d0c4 41 | name: "closed:duplicated" 42 | oldname: duplicate 43 | - color: f9d0c4 44 | name: "closed:invalid" 45 | oldname: invalid 46 | - color: f9d0c4 47 | name: "closed:question" 48 | oldname: question 49 | - color: f9d0c4 50 | name: "closed:wontfix" 51 | oldname: wontfix 52 | - color: 7057ff 53 | name: "good first issue" 54 | - color: 7057ff 55 | name: "Hacktoberfest" 56 | - color: 7057ff 57 | name: "help wanted" 58 | - color: cceecc 59 | name: "status:backlog" 60 | oldname: backlog 61 | - color: b60205 62 | name: "status:block-merge" 63 | oldname: block-merge 64 | - color: b60205 65 | name: "status:blocked" 66 | - color: 0e8a16 67 | name: "status:in-progress" 68 | - color: 0e8a16 69 | name: "status:merge-when-green" 70 | oldname: merge-when-green 71 | - color: fbca04 72 | name: "status:needs-backport" 73 | - color: fbca04 74 | name: "status:needs-forwardport" 75 | - color: fbca04 76 | name: "status:needs-info" 77 | - color: fbca04 78 | name: "status:needs-verification" 79 | - color: 0e8a16 80 | name: "status:ready" 81 | - color: fbca04 82 | name: "status:to-review" 83 | oldname: review 84 | - color: c5def5 85 | name: "topic:build/tests" 86 | - color: c5def5 87 | name: "topic:dev-environment" 88 | - color: c5def5 89 | name: "topic:documentation" 90 | - color: c5def5 91 | name: "topic:jdk-next" 92 | - color: b60205 93 | name: "type:defect" 94 | oldname: bug 95 | - color: 0052cc 96 | name: "type:feature" 97 | - color: 0052cc 98 | name: "type:improvement" 99 | oldname: enhancement 100 | - color: 0052cc 101 | name: "type:updates" 102 | - color: bf0d92 103 | name: "type:template-control" 104 | oldname: template-control 105 | -------------------------------------------------------------------------------- /app/controllers/TimeController.java: -------------------------------------------------------------------------------- 1 | package controllers; 2 | 3 | import com.fasterxml.jackson.databind.JsonNode; 4 | import com.fasterxml.jackson.databind.node.ObjectNode; 5 | import dagger.Lazy; 6 | import play.data.Form; 7 | import play.data.FormFactory; 8 | import play.i18n.MessagesApi; 9 | import play.libs.Json; 10 | import play.libs.ws.WSClient; 11 | import play.mvc.Controller; 12 | import play.mvc.Http; 13 | import play.mvc.Result; 14 | 15 | import javax.inject.Inject; 16 | import java.time.*; 17 | import java.time.format.DateTimeFormatter; 18 | import java.util.Arrays; 19 | import java.util.List; 20 | import java.util.Optional; 21 | import java.util.TimeZone; 22 | import java.util.concurrent.CompletionStage; 23 | 24 | public class TimeController extends Controller { 25 | 26 | private final Clock clock; 27 | private final WSClient ws; 28 | private final Form form; 29 | private MessagesApi messagesApi; 30 | 31 | @Inject 32 | public TimeController(Clock clock, WSClient ws, FormFactory formFactory, MessagesApi messagesApi) { 33 | this.clock = clock; 34 | this.ws = ws; 35 | this.form = formFactory.form(TimeZoneData.class); 36 | this.messagesApi = messagesApi; 37 | } 38 | 39 | public Result index(Http.Request request) { 40 | Optional timezone = request.session().getOptional("timezone"); 41 | Form filledForm; 42 | if (timezone.isPresent()) { 43 | filledForm = form; 44 | } else { 45 | String tz = TimeZone.getDefault().getID(); 46 | filledForm = form.fill(new TimeZoneData(tz)); 47 | } 48 | List timezones = Arrays.asList(TimeZone.getAvailableIDs()); 49 | return ok(views.html.index.render(filledForm, renderTime(request), timezones, request, messagesApi.preferred(request))); 50 | } 51 | 52 | public Result indexPost(Http.Request request) { 53 | final Form boundForm = form.bindFromRequest(request); 54 | String[] timezones = TimeZone.getAvailableIDs(); 55 | if (boundForm.hasErrors()) { 56 | return badRequest(views.html.index.render(boundForm, renderTime(request), Arrays.asList(timezones), request, messagesApi.preferred(request))); 57 | } else { 58 | TimeZoneData tzData = boundForm.get(); 59 | return redirect(routes.TimeController.index()) 60 | .addingToSession(request, "timezone", tzData.getTimeZone()); 61 | } 62 | } 63 | 64 | public Result now() { 65 | String date = DateTimeFormatter.ISO_INSTANT.format(Instant.now()); 66 | ObjectNode dateObj = Json.newObject().put("dateString", date); 67 | return ok(Json.toJson(dateObj)); 68 | } 69 | 70 | // call out to local URL as if it's a remote REST API, since timeapi is down 71 | public CompletionStage ws(Http.Request request) { 72 | String url = "http://localhost:9000/now"; 73 | final Optional timezone = request.session().getOptional("timezone"); 74 | return ws.url(url).get().thenApply(result -> { 75 | final JsonNode jsonNode = result.asJson(); 76 | final String dateString = jsonNode.findValue("dateString").asText(); 77 | final Instant instant = Instant.from(DateTimeFormatter.ISO_INSTANT.parse(dateString)); 78 | final ZoneId zoneId = zoneId(timezone); 79 | final ZonedDateTime zdt = instant.atZone(zoneId); 80 | final String formatted = formattedDate(zdt); 81 | return ok("Hello! The time is " + formatted + " in time zone " + zoneId); 82 | }); 83 | } 84 | 85 | private String renderTime(Http.Request request) { 86 | final Optional timezone = request.session().getOptional("timezone"); 87 | final ZoneId zoneId = zoneId(timezone); 88 | final Instant instant = clock.instant(); 89 | final ZonedDateTime zdt = instant.atZone(zoneId); 90 | return formattedDate(zdt); 91 | } 92 | 93 | private ZoneId zoneId(Optional timezone) { 94 | return timezone.map(ZoneId::of).orElse(ZoneId.systemDefault()); 95 | } 96 | 97 | private String formattedDate(ZonedDateTime zdt) { 98 | return zdt.format(DateTimeFormatter.RFC_1123_DATE_TIME); 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | CC0 1.0 Universal 2 | 3 | Statement of Purpose 4 | 5 | The laws of most jurisdictions throughout the world automatically confer 6 | exclusive Copyright and Related Rights (defined below) upon the creator and 7 | subsequent owner(s) (each and all, an "owner") of an original work of 8 | authorship and/or a database (each, a "Work"). 9 | 10 | Certain owners wish to permanently relinquish those rights to a Work for the 11 | purpose of contributing to a commons of creative, cultural and scientific 12 | works ("Commons") that the public can reliably and without fear of later 13 | claims of infringement build upon, modify, incorporate in other works, reuse 14 | and redistribute as freely as possible in any form whatsoever and for any 15 | purposes, including without limitation commercial purposes. These owners may 16 | contribute to the Commons to promote the ideal of a free culture and the 17 | further production of creative, cultural and scientific works, or to gain 18 | reputation or greater distribution for their Work in part through the use and 19 | efforts of others. 20 | 21 | For these and/or other purposes and motivations, and without any expectation 22 | of additional consideration or compensation, the person associating CC0 with a 23 | Work (the "Affirmer"), to the extent that he or she is an owner of Copyright 24 | and Related Rights in the Work, voluntarily elects to apply CC0 to the Work 25 | and publicly distribute the Work under its terms, with knowledge of his or her 26 | Copyright and Related Rights in the Work and the meaning and intended legal 27 | effect of CC0 on those rights. 28 | 29 | 1. Copyright and Related Rights. A Work made available under CC0 may be 30 | protected by copyright and related or neighboring rights ("Copyright and 31 | Related Rights"). Copyright and Related Rights include, but are not limited 32 | to, the following: 33 | 34 | i. the right to reproduce, adapt, distribute, perform, display, communicate, 35 | and translate a Work; 36 | 37 | ii. moral rights retained by the original author(s) and/or performer(s); 38 | 39 | iii. publicity and privacy rights pertaining to a person's image or likeness 40 | depicted in a Work; 41 | 42 | iv. rights protecting against unfair competition in regards to a Work, 43 | subject to the limitations in paragraph 4(a), below; 44 | 45 | v. rights protecting the extraction, dissemination, use and reuse of data in 46 | a Work; 47 | 48 | vi. database rights (such as those arising under Directive 96/9/EC of the 49 | European Parliament and of the Council of 11 March 1996 on the legal 50 | protection of databases, and under any national implementation thereof, 51 | including any amended or successor version of such directive); and 52 | 53 | vii. other similar, equivalent or corresponding rights throughout the world 54 | based on applicable law or treaty, and any national implementations thereof. 55 | 56 | 2. Waiver. To the greatest extent permitted by, but not in contravention of, 57 | applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and 58 | unconditionally waives, abandons, and surrenders all of Affirmer's Copyright 59 | and Related Rights and associated claims and causes of action, whether now 60 | known or unknown (including existing as well as future claims and causes of 61 | action), in the Work (i) in all territories worldwide, (ii) for the maximum 62 | duration provided by applicable law or treaty (including future time 63 | extensions), (iii) in any current or future medium and for any number of 64 | copies, and (iv) for any purpose whatsoever, including without limitation 65 | commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes 66 | the Waiver for the benefit of each member of the public at large and to the 67 | detriment of Affirmer's heirs and successors, fully intending that such Waiver 68 | shall not be subject to revocation, rescission, cancellation, termination, or 69 | any other legal or equitable action to disrupt the quiet enjoyment of the Work 70 | by the public as contemplated by Affirmer's express Statement of Purpose. 71 | 72 | 3. Public License Fallback. Should any part of the Waiver for any reason be 73 | judged legally invalid or ineffective under applicable law, then the Waiver 74 | shall be preserved to the maximum extent permitted taking into account 75 | Affirmer's express Statement of Purpose. In addition, to the extent the Waiver 76 | is so judged Affirmer hereby grants to each affected person a royalty-free, 77 | non transferable, non sublicensable, non exclusive, irrevocable and 78 | unconditional license to exercise Affirmer's Copyright and Related Rights in 79 | the Work (i) in all territories worldwide, (ii) for the maximum duration 80 | provided by applicable law or treaty (including future time extensions), (iii) 81 | in any current or future medium and for any number of copies, and (iv) for any 82 | purpose whatsoever, including without limitation commercial, advertising or 83 | promotional purposes (the "License"). The License shall be deemed effective as 84 | of the date CC0 was applied by Affirmer to the Work. Should any part of the 85 | License for any reason be judged legally invalid or ineffective under 86 | applicable law, such partial invalidity or ineffectiveness shall not 87 | invalidate the remainder of the License, and in such case Affirmer hereby 88 | affirms that he or she will not (i) exercise any of his or her remaining 89 | Copyright and Related Rights in the Work or (ii) assert any associated claims 90 | and causes of action with respect to the Work, in either case contrary to 91 | Affirmer's express Statement of Purpose. 92 | 93 | 4. Limitations and Disclaimers. 94 | 95 | a. No trademark or patent rights held by Affirmer are waived, abandoned, 96 | surrendered, licensed or otherwise affected by this document. 97 | 98 | b. Affirmer offers the Work as-is and makes no representations or warranties 99 | of any kind concerning the Work, express, implied, statutory or otherwise, 100 | including without limitation warranties of title, merchantability, fitness 101 | for a particular purpose, non infringement, or the absence of latent or 102 | other defects, accuracy, or the present or absence of errors, whether or not 103 | discoverable, all to the greatest extent permissible under applicable law. 104 | 105 | c. Affirmer disclaims responsibility for clearing rights of other persons 106 | that may apply to the Work or any use thereof, including without limitation 107 | any person's Copyright and Related Rights in the Work. Further, Affirmer 108 | disclaims responsibility for obtaining any necessary consents, permissions 109 | or other rights required for any use of the Work. 110 | 111 | d. Affirmer understands and acknowledges that Creative Commons is not a 112 | party to this document and has no duty or obligation with respect to this 113 | CC0 or use of the Work. 114 | 115 | For more information, please see 116 | 117 | --------------------------------------------------------------------------------