Commit aed725c1 authored by sumet's avatar sumet

work

parents
logs
target
build
/.idea
/.idea_modules
/.classpath
/.project
/.settings
/.gradle
/RUNNING_PID
License
-------
Written in 2016 by Lightbend <info@lightbend.com>
To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty.
You should have received a copy of the CC0 Public Domain Dedication along with this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
[<img src="https://img.shields.io/travis/playframework/play-java-starter-example.svg"/>](https://travis-ci.org/playframework/play-java-starter-example)
# play-java-starter-example
This is a starter application that shows how Play works. Please see the documentation at https://www.playframework.com/documentation/latest/Home for more details.
## Running
Run this using [sbt](http://www.scala-sbt.org/). If you downloaded this project from http://www.playframework.com/download then you'll find a prepackaged version of sbt in the project directory:
```
sbt run
```
And then go to http://localhost:9000 to see the running web application.
## Controllers
There are several demonstration files available in this template.
- HomeController.java:
Shows how to handle simple HTTP requests.
- AsyncController.java:
Shows how to do asynchronous programming when handling a request.
- CountController.java:
Shows how to inject a component into a controller and use the component when
handling requests.
## Components
- Module.java:
Shows how to use Guice to bind all the components needed by your application.
- Counter.java:
An example of a component that contains state, in this case a simple counter.
- ApplicationTimer.java:
An example of a component that starts when the application starts and stops
when the application stops.
## Filters
- ExampleFilter.java
A simple filter that adds a header to every response.
\ No newline at end of file
import com.google.inject.AbstractModule;
import java.time.Clock;
import services.ApplicationTimer;
import services.AtomicCounter;
import services.Counter;
/**
* This class is a Guice module that tells Guice how to bind several
* different types. This Guice module is created when the Play
* application starts.
*
* Play will automatically use any class called `Module` that is in
* the root package. You can create modules in other locations by
* adding `play.modules.enabled` settings to the `application.conf`
* configuration file.
*/
public class Module extends AbstractModule {
@Override
public void configure() {
// Use the system clock as the default implementation of Clock
bind(Clock.class).toInstance(Clock.systemDefaultZone());
// Ask Guice to create an instance of ApplicationTimer when the
// application starts.
bind(ApplicationTimer.class).asEagerSingleton();
// Set AtomicCounter as the implementation for Counter.
bind(Counter.class).to(AtomicCounter.class);
}
}
package controllers;
import akka.actor.ActorSystem;
import javax.inject.*;
import akka.actor.Scheduler;
import play.*;
import play.mvc.*;
import java.util.concurrent.Executor;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.TimeUnit;
import scala.concurrent.ExecutionContext;
import scala.concurrent.duration.Duration;
import scala.concurrent.ExecutionContextExecutor;
/**
* This controller contains an action that demonstrates how to write
* simple asynchronous code in a controller. It uses a timer to
* asynchronously delay sending a response for 1 second.
*/
@Singleton
public class AsyncController extends Controller {
private final ActorSystem actorSystem;
private final ExecutionContextExecutor exec;
/**
* @param actorSystem We need the {@link ActorSystem}'s
* {@link Scheduler} to run code after a delay.
* @param exec We need a Java {@link Executor} to apply the result
* of the {@link CompletableFuture} and a Scala
* {@link ExecutionContext} so we can use the Akka {@link Scheduler}.
* An {@link ExecutionContextExecutor} implements both interfaces.
*/
@Inject
public AsyncController(ActorSystem actorSystem, ExecutionContextExecutor exec) {
this.actorSystem = actorSystem;
this.exec = exec;
}
/**
* An action that returns a plain text message after a delay
* of 1 second.
*
* The configuration in the <code>routes</code> file means that this method
* will be called when the application receives a <code>GET</code> request with
* a path of <code>/message</code>.
*/
public CompletionStage<Result> message() {
return getFutureMessage(1, TimeUnit.SECONDS).thenApplyAsync(Results::ok, exec);
}
private CompletionStage<String> getFutureMessage(long time, TimeUnit timeUnit) {
CompletableFuture<String> future = new CompletableFuture<>();
actorSystem.scheduler().scheduleOnce(
Duration.create(time, timeUnit),
() -> future.complete("Hi!"),
exec
);
return future;
}
}
package controllers;
import play.mvc.Controller;
import play.mvc.Result;
import services.Counter;
import javax.inject.Inject;
import javax.inject.Singleton;
/**
* This controller demonstrates how to use dependency injection to
* bind a component into a controller class. The class contains an
* action that shows an incrementing count to users. The {@link Counter}
* object is injected by the Guice dependency injection system.
*/
@Singleton
public class CountController extends Controller {
private final Counter counter;
@Inject
public CountController(Counter counter) {
this.counter = counter;
}
/**
* An action that responds with the {@link Counter}'s current
* count. The result is plain text. This action is mapped to
* <code>GET</code> requests with a path of <code>/count</code>
* requests by an entry in the <code>routes</code> config file.
*/
public Result count() {
return ok(Integer.toString(counter.nextCount()));
}
}
package controllers;
import play.mvc.*;
import views.html.*;
import play.Logger;
import play.i18n.*;
public class HomeController extends Controller {
public Result login(){
Messages messages = Http.Context.current().messages();
String user = messages.at ("Username");
String pass = messages.at ("Password");
String log = messages.at ("Login");
return ok(login.render(user,pass,log));
}
public Result index() {
Messages messages = Http.Context.current().messages();
String header = messages.at ("Hello");
Logger.warn("hello = "+header);
return ok(index.render(header));
}
}
package filters;
import play.mvc.EssentialAction;
import play.mvc.EssentialFilter;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.util.concurrent.Executor;
/**
* This is a simple filter that adds a header to all requests.
*/
@Singleton
public class ExampleFilter extends EssentialFilter {
private final Executor exec;
/**
* @param exec This class is needed to execute code asynchronously.
*/
@Inject
public ExampleFilter(Executor exec) {
this.exec = exec;
}
@Override
public EssentialAction apply(EssentialAction next) {
return EssentialAction.of(request ->
next.apply(request).map(result ->
result.withHeader("X-ExampleFilter", "foo"), exec)
);
}
}
package services;
import java.time.Clock;
import java.time.Instant;
import java.util.concurrent.CompletableFuture;
import javax.inject.*;
import play.Logger;
import play.inject.ApplicationLifecycle;
/**
* This class demonstrates how to run code when the
* application starts and stops. It starts a timer when the
* application starts. When the application stops it prints out how
* long the application was running for.
*
* This class is registered for Guice dependency injection in the
* {@link Module} class. We want the class to start when the application
* starts, so it is registered as an "eager singleton". See the code
* in the {@link Module} class to see how this happens.
*
* This class needs to run code when the server stops. It uses the
* application's {@link ApplicationLifecycle} to register a stop hook.
*/
@Singleton
public class ApplicationTimer {
private final Clock clock;
private final ApplicationLifecycle appLifecycle;
private final Instant start;
private final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger("application");
@Inject
public ApplicationTimer(Clock clock, ApplicationLifecycle appLifecycle) {
this.clock = clock;
this.appLifecycle = appLifecycle;
// This code is called when the application starts.
start = clock.instant();
logger.info("ApplicationTimer demo: Starting application at " + start);
// When the application starts, register a stop hook with the
// ApplicationLifecycle object. The code inside the stop hook will
// be run when the application stops.
appLifecycle.addStopHook(() -> {
Instant stop = clock.instant();
Long runningTime = stop.getEpochSecond() - start.getEpochSecond();
logger.info("ApplicationTimer demo: Stopping application at " + clock.instant() + " after " + runningTime + "s.");
return CompletableFuture.completedFuture(null);
});
}
}
package services;
import java.util.concurrent.atomic.AtomicInteger;
import javax.inject.*;
/**
* This class is a concrete implementation of the {@link Counter} trait.
* It is configured for Guice dependency injection in the {@link Module}
* class.
*
* This class has a {@link Singleton} annotation because we need to make
* sure we only use one counter per application. Without this
* annotation we would get a new instance every time a {@link Counter} is
* injected.
*/
@Singleton
public class AtomicCounter implements Counter {
private final AtomicInteger atomicCounter = new AtomicInteger();
@Override
public int nextCount() {
return atomicCounter.getAndIncrement();
}
}
package services;
/**
* This interface demonstrates how to create a component that is injected
* into a controller. The interface represents a counter that returns a
* incremented number each time it is called.
*
* The {@link Modules} class binds this interface to the
* {@link AtomicCounter} implementation.
*/
public interface Counter {
int nextCount();
}
@(header : String)
<!DOCTYPE html>
<html>
<head>
<title>@header</title>
</head>
<body background="/assets/images/A.jpg">
</body>
</html>
\ No newline at end of file
@(user : String , pass : String , log : String)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="robots" content="noindex, nofollow">
<title>Login Form - Bootsnipp.com</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<link rel="stylesheet" href="/assets/stylesheets/main.css">
<style type="text/css">
* { -webkit-box-sizing:border-box; -moz-box-sizing:border-box; -ms-box-sizing:border-box; -o-box-sizing:border-box; box-sizing:border-box; }
html { width: 100%; height:100%; overflow:hidden; }
body {
width: 100%;
height:100%;
font-family: 'Open Sans', sans-serif;
background: #092756;
background: -moz-radial-gradient(0% 100%, ellipse cover, rgba(104,128,138,.4) 10%,rgba(138,114,76,0) 40%),-moz-linear-gradient(top, rgba(57,173,219,.25) 0%, rgba(42,60,87,.4) 100%), -moz-linear-gradient(-45deg, #670d10 0%, #092756 100%);
background: -webkit-radial-gradient(0% 100%, ellipse cover, rgba(104,128,138,.4) 10%,rgba(138,114,76,0) 40%), -webkit-linear-gradient(top, rgba(57,173,219,.25) 0%,rgba(42,60,87,.4) 100%), -webkit-linear-gradient(-45deg, #670d10 0%,#092756 100%);
background: -o-radial-gradient(0% 100%, ellipse cover, rgba(104,128,138,.4) 10%,rgba(138,114,76,0) 40%), -o-linear-gradient(top, rgba(57,173,219,.25) 0%,rgba(42,60,87,.4) 100%), -o-linear-gradient(-45deg, #670d10 0%,#092756 100%);
background: -ms-radial-gradient(0% 100%, ellipse cover, rgba(104,128,138,.4) 10%,rgba(138,114,76,0) 40%), -ms-linear-gradient(top, rgba(57,173,219,.25) 0%,rgba(42,60,87,.4) 100%), -ms-linear-gradient(-45deg, #670d10 0%,#092756 100%);
background: -webkit-radial-gradient(0% 100%, ellipse cover, rgba(104,128,138,.4) 10%,rgba(138,114,76,0) 40%), linear-gradient(to bottom, rgba(57,173,219,.25) 0%,rgba(42,60,87,.4) 100%), linear-gradient(135deg, #670d10 0%,#092756 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#3E1D6D', endColorstr='#092756',GradientType=1 );
}
.login {
position: absolute;
top: 50%;
left: 50%;
margin: -150px 0 0 -150px;
width:300px;
height:300px;
}
.login h1 { color: #fff;text-shadow: 0 0 10px rgba(0,0,0,0.3); letter-spacing:10px; text-align:center; }
input {
width: 100%;
margin-bottom: 10px;
background: rgba(0,0,0,0.3);
border: none;
outline: none;
padding: 10px;
font-size: 13px;
color: #fff;
text-shadow: 1px 1px 1px rgba(0,0,0,0.3);
border: 1px solid rgba(0,0,0,0.3);
border-radius: 4px;
box-shadow: inset 0 -5px 45px rgba(100,100,100,0.2), 0 1px 1px rgba(255,255,255,0.2);
-webkit-transition: box-shadow .5s ease;
-moz-transition: box-shadow .5s ease;
-o-transition: box-shadow .5s ease;
-ms-transition: box-shadow .5s ease;
transition: box-shadow .5s ease;
}
input:focus { box-shadow: inset 0 -5px 45px rgba(100,100,100,0.4), 0 1px 1px rgba(255,255,255,0.2); }
</style>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
</head>
<body class="background-info">
<div class="login">
<h1></h1>
<form method="post">
<input type="text" name="u" placeholder=@user required="required" />
<input type="password" name="p" placeholder=@pass required="required" />
<button type="submit" class="btn btn-primary btn-block btn-large">@log.</button>
</form>
<br>
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- login bootsnipp -->
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-9155049400353686"
data-ad-slot="9589048256"
data-ad-format="auto"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<script type="text/javascript">
/*
I built this login form to block the front end of most of my freelance wordpress projects during the development stage.
This is just the HTML / CSS of it but it uses wordpress's login system.
Nice and Simple
*/
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<link rel="stylesheet" media="screen" href="@routes.Assets.versioned("stylesheets/main.css")">
<link rel="shortcut icon" type="image/png" href="@routes.Assets.versioned("images/favicon.png")">
<script src="@routes.Assets.versioned("javascripts/hello.js")" type="text/javascript"></script>
</head>
<body>
</body>
</html>
@(message: String, style: String = "java")
@defining(play.core.PlayVersion.current) { version =>
<section id="top">
<div class="wrapper">
<h1><a href="https://playframework.com/documentation/@version/Home">@message</a></h1>
</div>
</section>
<div id="content" class="wrapper doc">
<article>
<h1>Welcome to Play</h1>
<p>
Congratulations, you’ve just created a new Play application. This page will help you with the next few steps.
</p>
<blockquote>
<p>
You’re using Play @version
</p>
</blockquote>
<h2>Why do you see this page?</h2>
<p>
The <code>conf/routes</code> file defines a route that tells Play to invoke the <code>HomeController.index</code> action
whenever a browser requests the <code>/</code> URI using the GET method:
</p>
<pre><code># Home page
GET / controllers.HomeController.index</code></pre>
<p>
Play has invoked the <code>controllers.HomeController.index</code> method:
</p>
<pre><code>public Result index() {
return ok(index.render("Your new application is ready."));
}</code></pre>
<p>
An action method handles the incoming HTTP request, and returns the HTTP result to send back to the web client.
Here we send a <code>200 OK</code> response, using a template to fill its content.
</p>
<p>
The template is defined in the <code>app/views/index.scala.html</code> file and compiled as a standard Java class.
</p>
<pre><code>@@(message: String)
@@main("Welcome to Play") {
@@play20.welcome(message, style = "Java")
}</code></pre>
<p>
The first line of the template defines the function signature. Here it just takes a single <code>String</code> parameter.
Then this template calls another function defined in <code>app/views/main.scala.html</code> which displays the HTML layout, and another
function that displays this welcome message. You can freely add any HTML fragment mixed with Scala code in this file.
</p>
<blockquote>
<p>
<strong>Note</strong> that Scala is fully compatible with Java, so if you don’t know Scala don’t panic, a Scala statement is very similar to a Java one.
</p>
</blockquote>
<p>You can read more about <a href="https://www.playframework.com/documentation/@version/ScalaTemplates">Twirl</a>, the template language used by Play, and how Play handles <a href="https://www.playframework.com/documentation/@version/JavaActions">actions</a>.</p>
<h2>Async Controller</h2>
Now that you've seen how Play renders a page, take a look at <code>AsyncController.java</code>, which shows how to do asynchronous programming when handling a request. The code is almost exactly the same as <code>HomeController.java</code>, but instead of returning <code>Result</code>, the action returns <code>CompletionStage&lt;Result&gt;</code> to Play. When the execution completes, Play can use a thread to render the result without blocking the thread in the mean time.
<p>
<a href="@routes.AsyncController.message">Click here for the AsyncController action!</a>
</p>
<p>
You can read more about <a href="https://www.playframework.com/documentation/@version/JavaAsync">asynchronous actions</a> in the documentation.
</p>
<h2>Count Controller</h2>
<p>
Both the HomeController and AsyncController are very simple, and typically controllers present the results of the interaction of several services. As an example, see the <code>CountController</code>, which shows how to inject a component into a controller and use the component when handling requests. The count controller increments every time you click on it, so keep clicking to see the numbers go up.
</p>
<p>
<a href="@routes.CountController.count">Click here for the CountController action!</a>
</p>
<p>
You can read more about <a href="https://www.playframework.com/documentation/@version/JavaDependencyInjection">dependency injection</a> in the documentation.
</p>
<h2>Need more info on the console?</h2>
<p>
For more information on the various commands you can run on Play, i.e. running tests and packaging applications for production, see <a href="https://playframework.com/documentation/@version/PlayConsole">Using the Play console</a>.
</p>
<h2>Need to set up an IDE?</h2>
<p>
You can start hacking your application right now using any text editor. Any changes will be automatically reloaded at each page refresh,
including modifications made to Scala source files.
</p>
<p>
If you want to set-up your application in <strong>IntelliJ IDEA</strong> or any other Java IDE, check the
<a href="https://www.playframework.com/documentation/@version/IDE">Setting up your preferred IDE</a> page.
</p>
<h2>Need more documentation?</h2>
<p>
Play documentation is available at <a href="https://www.playframework.com/documentation/@version">https://www.playframework.com/documentation</a>.
</p>
<p>
Play comes with lots of example templates showcasing various bits of Play functionality at <a href="https://www.playframework.com/download#examples">https://www.playframework.com/download#examples</a>.
</p>
<h2>Need more help?</h2>
<p>
Play questions are asked and answered on Stackoverflow using the "playframework" tag: <a href="https://stackoverflow.com/questions/tagged/playframework">https://stackoverflow.com/questions/tagged/playframework</a>
</p>
<p>
The <a href="https://discuss.playframework.com">Discuss Play Forum</a> is where Play users come to seek help,
announce projects, and discuss issues and new features.
</p>
<p>
Gitter is a real time chat channel, like IRC. The <a href="https://gitter.im/playframework/playframework">playframework/playframework</a> channel is used by Play users to discuss the ins and outs of writing great Play applications.
</p>
</article>
<aside>
<h3>Browse</h3>
<ul>
<li><a href="https://playframework.com/documentation/@version">Documentation</a></li>
<li><a href="https://playframework.com/documentation/@version/api/@style/index.html">Browse the @{style.capitalize} API</a></li>
</ul>
<h3>Start here</h3>
<ul>
<li><a href="https://playframework.com/documentation/@version/PlayConsole">Using the Play console</a></li>
<li><a href="https://playframework.com/documentation/@version/IDE">Setting up your preferred IDE</a></li>
<li><a href="https://playframework.com/download#examples">Example Projects</a>
</ul>
<h3>Help here</h3>
<ul>
<li><a href="https://stackoverflow.com/questions/tagged/playframework">Stack Overflow</a></li>
<li><a href="https://discuss.playframework.com">Discuss Play Forum</a> </li>
<li><a href="https://gitter.im/playframework/playframework">Gitter Channel</a></li>
</ul>
</aside>
</div>
}
plugins {
id 'play'
id 'idea'
}
def playVersion = "2.6.12"
def scalaVersion = System.getProperty("scala.binary.version", /* default = */ "2.12")
model {
components {
play {
platform play: playVersion, scala: scalaVersion, java: '1.8'
injectedRoutesGenerator = true
sources {
twirlTemplates {
defaultImports = TwirlImports.JAVA
}
}
}
}
}
dependencies {
play "com.typesafe.play:play-guice_$scalaVersion:$playVersion"
play "com.typesafe.play:play-logback_$scalaVersion:$playVersion"
play "com.h2database:h2:1.4.196"
playTest "org.assertj:assertj-core:3.6.2"
playTest "org.awaitility:awaitility:2.0.0"
}
repositories {
jcenter()
maven {
name "lightbend-maven-releases"
url "https://repo.lightbend.com/lightbend/maven-release"
}
ivy {
name "lightbend-ivy-release"
url "https://repo.lightbend.com/lightbend/ivy-releases"
layout "ivy"
}
}
name := """play-java-starter-example"""
version := "1.0-SNAPSHOT"
lazy val root = (project in file(".")).enablePlugins(PlayJava)
scalaVersion := "2.12.4"
crossScalaVersions := Seq("2.11.12", "2.12.4")
libraryDependencies += guice
// Test Database
libraryDependencies += "com.h2database" % "h2" % "1.4.196"
// Testing libraries for dealing with CompletionStage...
libraryDependencies += "org.assertj" % "assertj-core" % "3.6.2" % Test
libraryDependencies += "org.awaitility" % "awaitility" % "2.0.0" % Test
// Make verbose tests
testOptions in Test := Seq(Tests.Argument(TestFrameworks.JUnit, "-a", "-v"))
This diff is collapsed.
<!-- https://www.playframework.com/documentation/latest/SettingsLogger -->
<configuration>
<conversionRule conversionWord="coloredLevel" converterClass="play.api.libs.logback.ColoredLevel" />
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<file>${application.home:-.}/logs/application.log</file>
<encoder>
<pattern>%date [%level] from %logger in %thread - %message%n%xException</pattern>
</encoder>
</appender>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%coloredLevel %logger{15} - %message%n%xException{10}</pattern>
</encoder>
</appender>
<appender name="ASYNCFILE" class="ch.qos.logback.classic.AsyncAppender">
<appender-ref ref="FILE" />
</appender>
<appender name="ASYNCSTDOUT" class="ch.qos.logback.classic.AsyncAppender">
<appender-ref ref="STDOUT" />
</appender>
<logger name="play" level="INFO" />
<logger name="application" level="DEBUG" />
<!-- Off these ones as they are annoying, and anyway we manage configuration ourselves -->
<logger name="com.gargoylesoftware.htmlunit.javascript" level="OFF" />
<root level="WARN">
<appender-ref ref="ASYNCFILE" />
<appender-ref ref="ASYNCSTDOUT" />
</root>
</configuration>
Hello=สวัสดี
Username=ชื่อผู้ใช้
Password=รหัสผ่าน
Login=เข้าสู่ระบบ
\ No newline at end of file
# Routes
# This file defines all application routes (Higher priority routes first)
# ~~~~
GET /login controllers.HomeController.login
GET / controllers.HomeController.index
GET /count controllers.CountController.count
GET /message controllers.AsyncController.message
GET /assets/*file controllers.Assets.versioned(path="/public", file: Asset)
distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-bin.zip
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStorePath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
#!/usr/bin/env sh
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
<?xml version="1.0" encoding="UTF-8"?>
<module external.linked.project.id="play-java-starter-example" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$" external.system.id="GRADLE" external.system.module.group="" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/.gradle" />
<excludeFolder url="file://$MODULE_DIR$/build" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
// The Play plugin
addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.6.12")
// Play enhancer - this automatically generates getters/setters for public fields
// and rewrites accessors of these fields to use the getters/setters. Remove this
// plugin if you prefer not to have this feature, or disable on a per project
// basis using disablePlugins(PlayEnhancer) in your build.sbt
addSbtPlugin("com.typesafe.sbt" % "sbt-play-enhancer" % "1.2.2")
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
if (window.console) {
console.log("Welcome to your Play application's JavaScript!");
}
!function(a){"use strict";a('a.js-scroll-trigger[href*="#"]:not([href="#"])').click(function(){if(location.pathname.replace(/^\//,"")==this.pathname.replace(/^\//,"")&&location.hostname==this.hostname){var e=a(this.hash);if((e=e.length?e:a("[name="+this.hash.slice(1)+"]")).length)return a("html, body").animate({scrollTop:e.offset().top-48},1e3,"easeInOutExpo"),!1}}),a(".js-scroll-trigger").click(function(){a(".navbar-collapse").collapse("hide")}),a("body").scrollspy({target:"#mainNav",offset:54});var e=function(){a("#mainNav").offset().top>100?a("#mainNav").addClass("navbar-shrink"):a("#mainNav").removeClass("navbar-shrink")};e(),a(window).scroll(e)}(jQuery);
\ No newline at end of file
This diff is collapsed.
#!/usr/bin/env bash
./sbt-dist/bin/sbt "$@"
\ No newline at end of file
#!/usr/bin/env bash
### ------------------------------- ###
### Helper methods for BASH scripts ###
### ------------------------------- ###
realpath () {
(
TARGET_FILE="$1"
FIX_CYGPATH="$2"
cd "$(dirname "$TARGET_FILE")"
TARGET_FILE=$(basename "$TARGET_FILE")
COUNT=0
while [ -L "$TARGET_FILE" -a $COUNT -lt 100 ]
do
TARGET_FILE=$(readlink "$TARGET_FILE")
cd "$(dirname "$TARGET_FILE")"
TARGET_FILE=$(basename "$TARGET_FILE")
COUNT=$(($COUNT + 1))
done
# make sure we grab the actual windows path, instead of cygwin's path.
if [[ "x$FIX_CYGPATH" != "x" ]]; then
echo "$(cygwinpath "$(pwd -P)/$TARGET_FILE")"
else
echo "$(pwd -P)/$TARGET_FILE"
fi
)
}
# Uses uname to detect if we're in the odd cygwin environment.
is_cygwin() {
local os=$(uname -s)
case "$os" in
CYGWIN*) return 0 ;;
*) return 1 ;;
esac
}
# TODO - Use nicer bash-isms here.
CYGWIN_FLAG=$(if is_cygwin; then echo true; else echo false; fi)
# This can fix cygwin style /cygdrive paths so we get the
# windows style paths.
cygwinpath() {
local file="$1"
if [[ "$CYGWIN_FLAG" == "true" ]]; then
echo $(cygpath -w $file)
else
echo $file
fi
}
. "$(dirname "$(realpath "$0")")/sbt-launch-lib.bash"
declare -r noshare_opts="-Dsbt.global.base=project/.sbtboot -Dsbt.boot.directory=project/.boot -Dsbt.ivy.home=project/.ivy"
declare -r sbt_opts_file=".sbtopts"
declare -r etc_sbt_opts_file="${sbt_home}/conf/sbtopts"
declare -r win_sbt_opts_file="${sbt_home}/conf/sbtconfig.txt"
usage() {
cat <<EOM
Usage: $script_name [options]
-h | -help print this message
-v | -verbose this runner is chattier
-d | -debug set sbt log level to debug
-no-colors disable ANSI color codes
-sbt-create start sbt even if current directory contains no sbt project
-sbt-dir <path> path to global settings/plugins directory (default: ~/.sbt)
-sbt-boot <path> path to shared boot directory (default: ~/.sbt/boot in 0.11 series)
-ivy <path> path to local Ivy repository (default: ~/.ivy2)
-mem <integer> set memory options (default: $sbt_mem, which is $(get_mem_opts $sbt_mem))
-no-share use all local caches; no sharing
-no-global uses global caches, but does not use global ~/.sbt directory.
-jvm-debug <port> Turn on JVM debugging, open at the given port.
-batch Disable interactive mode
# sbt version (default: from project/build.properties if present, else latest release)
-sbt-version <version> use the specified version of sbt
-sbt-jar <path> use the specified jar as the sbt launcher
-sbt-rc use an RC version of sbt
-sbt-snapshot use a snapshot version of sbt
# java version (default: java from PATH, currently $(java -version 2>&1 | grep version))
-java-home <path> alternate JAVA_HOME
# jvm options and output control
JAVA_OPTS environment variable, if unset uses "$java_opts"
SBT_OPTS environment variable, if unset uses "$default_sbt_opts"
.sbtopts if this file exists in the current directory, it is
prepended to the runner args
/etc/sbt/sbtopts if this file exists, it is prepended to the runner args
-Dkey=val pass -Dkey=val directly to the java runtime
-J-X pass option -X directly to the java runtime
(-J is stripped)
-S-X add -X to sbt's scalacOptions (-S is stripped)
In the case of duplicated or conflicting options, the order above
shows precedence: JAVA_OPTS lowest, command line options highest.
EOM
}
process_my_args () {
while [[ $# -gt 0 ]]; do
case "$1" in
-no-colors) addJava "-Dsbt.log.noformat=true" && shift ;;
-no-share) addJava "$noshare_opts" && shift ;;
-no-global) addJava "-Dsbt.global.base=$(pwd)/project/.sbtboot" && shift ;;
-sbt-boot) require_arg path "$1" "$2" && addJava "-Dsbt.boot.directory=$2" && shift 2 ;;
-sbt-dir) require_arg path "$1" "$2" && addJava "-Dsbt.global.base=$2" && shift 2 ;;
-debug-inc) addJava "-Dxsbt.inc.debug=true" && shift ;;
-batch) exec </dev/null && shift ;;
-sbt-create) sbt_create=true && shift ;;
*) addResidual "$1" && shift ;;
esac
done
# Now, ensure sbt version is used.
[[ "${sbt_version}XXX" != "XXX" ]] && addJava "-Dsbt.version=$sbt_version"
}
loadConfigFile() {
cat "$1" | sed '/^\#/d' | while read line; do
eval echo $line
done
}
# TODO - Pull in config based on operating system... (MSYS + cygwin should pull in txt file).
# Here we pull in the global settings configuration.
[[ -f "$etc_sbt_opts_file" ]] && set -- $(loadConfigFile "$etc_sbt_opts_file") "$@"
# -- Windows behavior stub'd
# JAVA_OPTS=$(cat "$WDIR/sbtconfig.txt" | sed -e 's/\r//g' -e 's/^#.*$//g' | sed ':a;N;$!ba;s/\n/ /g')
# Pull in the project-level config file, if it exists.
[[ -f "$sbt_opts_file" ]] && set -- $(loadConfigFile "$sbt_opts_file") "$@"
run "$@"
#!/usr/bin/env bash
#
# A library to simplify using the SBT launcher from other packages.
# Note: This should be used by tools like giter8/conscript etc.
# TODO - Should we merge the main SBT script with this library?
declare -a residual_args
declare -a java_args
declare -a scalac_args
declare -a sbt_commands
declare java_cmd=java
declare java_version
declare -r sbt_bin_dir="$(dirname "$(realpath "$0")")"
declare -r sbt_home="$(dirname "$sbt_bin_dir")"
echoerr () {
echo 1>&2 "$@"
}
vlog () {
[[ $verbose || $debug ]] && echoerr "$@"
}
dlog () {
[[ $debug ]] && echoerr "$@"
}
jar_file () {
echo "$(cygwinpath "${sbt_home}/bin/sbt-launch.jar")"
}
acquire_sbt_jar () {
sbt_jar="$(jar_file)"
if [[ ! -f "$sbt_jar" ]]; then
echoerr "Could not find launcher jar: $sbt_jar"
exit 2
fi
}
execRunner () {
# print the arguments one to a line, quoting any containing spaces
[[ $verbose || $debug ]] && echo "# Executing command line:" && {
for arg; do
if printf "%s\n" "$arg" | grep -q ' '; then
printf "\"%s\"\n" "$arg"
else
printf "%s\n" "$arg"
fi
done
echo ""
}
# THis used to be exec, but we loose the ability to re-hook stty then
# for cygwin... Maybe we should flag the feature here...
"$@"
}
addJava () {
dlog "[addJava] arg = '$1'"
java_args=( "${java_args[@]}" "$1" )
}
addSbt () {
dlog "[addSbt] arg = '$1'"
sbt_commands=( "${sbt_commands[@]}" "$1" )
}
addResidual () {
dlog "[residual] arg = '$1'"
residual_args=( "${residual_args[@]}" "$1" )
}
addDebugger () {
addJava "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=$1"
}
get_mem_opts () {
# if we detect any of these settings in ${JAVA_OPTS} or ${JAVA_TOOL_OPTIONS} we need to NOT output our settings.
# The reason is the Xms/Xmx, if they don't line up, cause errors.
if [[ "${JAVA_OPTS}" == *-Xmx* ]] || [[ "${JAVA_OPTS}" == *-Xms* ]] || [[ "${JAVA_OPTS}" == *-XX:MaxPermSize* ]] || [[ "${JAVA_OPTS}" == *-XX:MaxMetaspaceSize* ]] || [[ "${JAVA_OPTS}" == *-XX:ReservedCodeCacheSize* ]]; then
echo ""
elif [[ "${JAVA_TOOL_OPTIONS}" == *-Xmx* ]] || [[ "${JAVA_TOOL_OPTIONS}" == *-Xms* ]] || [[ "${JAVA_TOOL_OPTIONS}" == *-XX:MaxPermSize* ]] || [[ "${JAVA_TOOL_OPTIONS}" == *-XX:MaxMetaspaceSize* ]] || [[ "${JAVA_TOOL_OPTIONS}" == *-XX:ReservedCodeCacheSize* ]]; then
echo ""
elif [[ "${SBT_OPTS}" == *-Xmx* ]] || [[ "${SBT_OPTS}" == *-Xms* ]] || [[ "${SBT_OPTS}" == *-XX:MaxPermSize* ]] || [[ "${SBT_OPTS}" == *-XX:MaxMetaspaceSize* ]] || [[ "${SBT_OPTS}" == *-XX:ReservedCodeCacheSize* ]]; then
echo ""
else
# a ham-fisted attempt to move some memory settings in concert
# so they need not be messed around with individually.
local mem=${1:-1024}
local codecache=$(( $mem / 8 ))
(( $codecache > 128 )) || codecache=128
(( $codecache < 512 )) || codecache=512
local class_metadata_size=$(( $codecache * 2 ))
local class_metadata_opt=$([[ "$java_version" < "1.8" ]] && echo "MaxPermSize" || echo "MaxMetaspaceSize")
local arg_xms=$([[ "${java_args[@]}" == *-Xms* ]] && echo "" || echo "-Xms${mem}m")
local arg_xmx=$([[ "${java_args[@]}" == *-Xmx* ]] && echo "" || echo "-Xmx${mem}m")
local arg_rccs=$([[ "${java_args[@]}" == *-XX:ReservedCodeCacheSize* ]] && echo "" || echo "-XX:ReservedCodeCacheSize=${codecache}m")
local arg_meta=$([[ "${java_args[@]}" == *-XX:${class_metadata_opt}* ]] && echo "" || echo "-XX:${class_metadata_opt}=${class_metadata_size}m")
echo "${arg_xms} ${arg_xmx} ${arg_rccs} ${arg_meta}"
fi
}
require_arg () {
local type="$1"
local opt="$2"
local arg="$3"
if [[ -z "$arg" ]] || [[ "${arg:0:1}" == "-" ]]; then
echo "$opt requires <$type> argument"
exit 1
fi
}
is_function_defined() {
declare -f "$1" > /dev/null
}
process_args () {
while [[ $# -gt 0 ]]; do
case "$1" in
-h|-help) usage; exit 1 ;;
-v|-verbose) verbose=1 && shift ;;
-d|-debug) debug=1 && shift ;;
-ivy) require_arg path "$1" "$2" && addJava "-Dsbt.ivy.home=$2" && shift 2 ;;
-mem) require_arg integer "$1" "$2" && sbt_mem="$2" && shift 2 ;;
-jvm-debug) require_arg port "$1" "$2" && addDebugger $2 && shift 2 ;;
-batch) exec </dev/null && shift ;;
-sbt-jar) require_arg path "$1" "$2" && sbt_jar="$2" && shift 2 ;;
-sbt-version) require_arg version "$1" "$2" && sbt_version="$2" && shift 2 ;;
-java-home) require_arg path "$1" "$2" && java_cmd="$2/bin/java" && shift 2 ;;
-D*) addJava "$1" && shift ;;
-J*) addJava "${1:2}" && shift ;;
*) addResidual "$1" && shift ;;
esac
done
is_function_defined process_my_args && {
myargs=("${residual_args[@]}")
residual_args=()
process_my_args "${myargs[@]}"
}
java_version=$("$java_cmd" -Xmx512M -version 2>&1 | awk -F '"' '/version/ {print $2}')
vlog "[process_args] java_version = '$java_version'"
}
# Detect that we have java installed.
checkJava() {
local required_version="$1"
# Now check to see if it's a good enough version
if [[ "$java_version" == "" ]]; then
echo
echo No java installations was detected.
echo Please go to http://www.java.com/getjava/ and download
echo
exit 1
elif [[ ! "$java_version" > "$required_version" ]]; then
echo
echo The java installation you have is not up to date
echo $script_name requires at least version $required_version+, you have
echo version $java_version
echo
echo Please go to http://www.java.com/getjava/ and download
echo a valid Java Runtime and install before running $script_name.
echo
exit 1
fi
}
run() {
# no jar? download it.
[[ -f "$sbt_jar" ]] || acquire_sbt_jar "$sbt_version" || {
# still no jar? uh-oh.
echo "Download failed. Obtain the sbt-launch.jar manually and place it at $sbt_jar"
exit 1
}
# process the combined args, then reset "$@" to the residuals
process_args "$@"
set -- "${residual_args[@]}"
argumentCount=$#
# TODO - java check should be configurable...
checkJava "1.6"
#If we're in cygwin, we should use the windows config, and terminal hacks
if [[ "$CYGWIN_FLAG" == "true" ]]; then
stty -icanon min 1 -echo > /dev/null 2>&1
addJava "-Djline.terminal=jline.UnixTerminal"
addJava "-Dsbt.cygwin=true"
fi
# run sbt
execRunner "$java_cmd" \
$(get_mem_opts $sbt_mem) \
${JAVA_OPTS} \
${SBT_OPTS:-$default_sbt_opts} \
${java_args[@]} \
-jar "$sbt_jar" \
"${sbt_commands[@]}" \
"${residual_args[@]}"
exit_code=$?
# Clean up the terminal from cygwin hacks.
if [[ "$CYGWIN_FLAG" == "true" ]]; then
stty icanon echo > /dev/null 2>&1
fi
exit $exit_code
}
@REM SBT launcher script
@REM
@REM Envioronment:
@REM JAVA_HOME - location of a JDK home dir (mandatory)
@REM SBT_OPTS - JVM options (optional)
@REM Configuration:
@REM sbtconfig.txt found in the SBT_HOME.
@REM ZOMG! We need delayed expansion to build up CFG_OPTS later
@setlocal enabledelayedexpansion
@echo off
set SBT_HOME=%~dp0
rem FIRST we load the config file of extra options.
set FN=%SBT_HOME%\..\conf\sbtconfig.txt
set CFG_OPTS=
FOR /F "tokens=* eol=# usebackq delims=" %%i IN ("%FN%") DO (
set DO_NOT_REUSE_ME=%%i
rem ZOMG (Part #2) WE use !! here to delay the expansion of
rem CFG_OPTS, otherwise it remains "" for this loop.
set CFG_OPTS=!CFG_OPTS! !DO_NOT_REUSE_ME!
)
rem We use the value of the JAVACMD environment variable if defined
set _JAVACMD=%JAVACMD%
if "%_JAVACMD%"=="" (
if not "%JAVA_HOME%"=="" (
if exist "%JAVA_HOME%\bin\java.exe" set "_JAVACMD=%JAVA_HOME%\bin\java.exe"
)
)
if "%_JAVACMD%"=="" set _JAVACMD=java
rem We use the value of the JAVA_OPTS environment variable if defined, rather than the config.
set _JAVA_OPTS=%JAVA_OPTS%
if "%_JAVA_OPTS%"=="" set _JAVA_OPTS=%CFG_OPTS%
:run
"%_JAVACMD%" %_JAVA_OPTS% %SBT_OPTS% -cp "%SBT_HOME%sbt-launch.jar" xsbt.boot.Boot %*
if ERRORLEVEL 1 goto error
goto end
:error
@endlocal
exit /B 1
:end
@endlocal
exit /B 0
# Set the java args to high
-Xmx512M
-XX:MaxPermSize=256m
-XX:ReservedCodeCacheSize=128m
# Set the extra SBT options
-Dsbt.log.format=true
# ------------------------------------------------ #
# The SBT Configuration file. #
# ------------------------------------------------ #
# Disable ANSI color codes
#
#-no-colors
# Starts sbt even if the current directory contains no sbt project.
#
-sbt-create
# Path to global settings/plugins directory (default: ~/.sbt)
#
#-sbt-dir /etc/sbt
# Path to shared boot directory (default: ~/.sbt/boot in 0.11 series)
#
#-sbt-boot ~/.sbt/boot
# Path to local Ivy repository (default: ~/.ivy2)
#
#-ivy ~/.ivy2
# set memory options
#
#-mem <integer>
# Use local caches for projects, no sharing.
#
#-no-share
# Put SBT in offline mode.
#
#-offline
# Sets the SBT version to use.
#-sbt-version 0.11.3
# Scala version (default: latest release)
#
#-scala-home <path>
#-scala-version <version>
# java version (default: java from PATH, currently $(java -version |& grep version))
#
#-java-home <path>
@REM SBT launcher script
.\sbt-dist\bin\sbt.bat %*
#!/usr/bin/env bash
set -e
set -o pipefail
java_version=$(java -version 2>&1 | java -version 2>&1 | awk -F '"' '/version/ {print $2}')
if [[ $java_version = 9* ]] ; then
echo "The build is using Java 9 ($java_version). We need additional JVM parameters"
export _JAVA_OPTIONS="$_JAVA_OPTIONS --add-modules=java.xml.bind"
else
echo "The build is NOT using Java 9 ($java_version). No addional JVM params needed."
fi
#!/usr/bin/env bash
. "$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )/script-helper"
# Using cut because TRAVIS_SCALA_VERSION is the full Scala
# version (for example 2.12.4), but Gradle expects just the
# binary version (for example 2.12)
scala_binary_version=$(echo $TRAVIS_SCALA_VERSION | cut -c1-4)
echo "+------------------------------+"
echo "| Executing tests using Gradle |"
echo "+------------------------------+"
./gradlew -Dscala.binary.version=$scala_binary_version check -i --stacktrace
#!/usr/bin/env bash
. "$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )/script-helper"
echo "+----------------------------+"
echo "| Executing tests using sbt |"
echo "+----------------------------+"
sbt ++$TRAVIS_SCALA_VERSION test
import org.junit.Test;
import play.Application;
import play.test.Helpers;
import play.test.TestBrowser;
import play.test.WithBrowser;
import static org.junit.Assert.assertTrue;
import static play.test.Helpers.*;
public class BrowserTest extends WithBrowser {
protected Application provideApplication() {
return fakeApplication(inMemoryDatabase());
}
protected TestBrowser provideBrowser(int port) {
return Helpers.testBrowser(port);
}
/**
* add your integration test here
* in this example we just check if the welcome page is being shown
*/
@Test
public void test() {
browser.goTo("http://localhost:" + play.api.test.Helpers.testServerPort());
assertTrue(browser.pageSource().contains("Your new application is ready."));
}
}
import org.junit.Test;
import play.test.WithApplication;
import play.twirl.api.Content;
import static org.assertj.core.api.Assertions.assertThat;
/**
* A functional test starts a Play application for every test.
*
* https://www.playframework.com/documentation/latest/JavaFunctionalTest
*/
public class FunctionalTest extends WithApplication {
@Test
public void renderTemplate() {
// If you are calling out to Assets, then you must instantiate an application
// because it makes use of assets metadata that is configured from
// the application.
Content html = views.html.index.render("Your new application is ready.");
assertThat("text/html").isEqualTo(html.contentType());
assertThat(html.body()).contains("Your new application is ready.");
}
}
import akka.actor.ActorSystem;
import controllers.AsyncController;
import controllers.CountController;
import org.junit.Test;
import play.mvc.Result;
import scala.concurrent.ExecutionContextExecutor;
import java.util.concurrent.CompletionStage;
import static org.assertj.core.api.Assertions.assertThat;
import static org.awaitility.Awaitility.await;
import static play.test.Helpers.contentAsString;
/**
* Unit testing does not require Play application start up.
*
* https://www.playframework.com/documentation/latest/JavaTest
*/
public class UnitTest {
@Test
public void simpleCheck() {
int a = 1 + 1;
assertThat(a).isEqualTo(2);
}
// Unit test a controller
@Test
public void testCount() {
final CountController controller = new CountController(() -> 49);
Result result = controller.count();
assertThat(contentAsString(result)).isEqualTo("49");
}
// Unit test a controller with async return
@Test
public void testAsync() {
final ActorSystem actorSystem = ActorSystem.create("test");
try {
final ExecutionContextExecutor ec = actorSystem.dispatcher();
final AsyncController controller = new AsyncController(actorSystem, ec);
final CompletionStage<Result> future = controller.message();
// Block until the result is completed
await().until(() -> {
assertThat(future.toCompletableFuture()).isCompletedWithValueMatching(result -> {
return contentAsString(result).equals("Hi!");
});
});
} finally {
actorSystem.terminate();
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment