Skip to content

Commit

Permalink
Merge remote-tracking branch 'play-scala-rest-api-example/2.6.x' into…
Browse files Browse the repository at this point in the history
… 2.6.x

* play-scala-rest-api-example/2.6.x: (73 commits)
  Nest play-scala-rest-api-example
  Updated with template-control on 2019-02-13T20:25:39.695Z (playframework#140)
  Updated with template-control on 2019-02-01T10:40:33.469Z   /.mergify.yml:     wrote /.mergify.yml
  Updated with template-control on 2019-01-17T15:10:57.883Z   /.mergify.yml:     wrote /.mergify.yml
  Updated with template-control on 2019-01-16T12:08:46.083Z   /LICENSE:     wrote /LICENSE   /NOTICE:     wrote /NOTICE   /.mergify.yml:     wrote /.mergify.yml
  Upgrade branch 2.6.x using TemplateControl (playframework#133)
  Updated with template-control on 2019-01-04T17:13:24.057Z (playframework#128)
  Upgrade branch 2.6.x using TemplateControl (playframework#127)
  Updated with template-control on 2018-10-08T19:11:41.384Z   **/plugins.sbt:     addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.6.20")   **build.gradle:     def playVersion = "2.6.20"
  Updated with template-control on 2018-09-11T20:14:50.615Z (playframework#122)
  Updated with template-control on 2018-08-20T20:37:13.956Z (playframework#121)
  Updated with template-control on 2018-07-19T01:58:56.043Z (playframework#119)
  Updated with template-control on 2018-07-16T18:38:45.676Z (playframework#118)
  Upgrade branch 2.6.x using TemplateControl (playframework#117)
  sbt 1.1.6 (playframework#116)
  Fix format issues (playframework#115)
  Update documentation to reflect Play 2.6 changes (playframework#114)
  Use @ref to link to other .md pages (playframework#93)
  Revert gatling version change and update Scala 2.12
  Updated with template-control on 2018-05-27T23:54:09.491Z   **build.sbt:     libraryDependencies += "io.gatling.highcharts" % "gatling-charts-highcharts" % "2.3.1" % Test   **build.sbt:     libraryDependencies += "io.gatling" % "gatling-test-framework" % "2.3.1" % Test   **/plugins.sbt:     addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.6.15")   **build.gradle:     def playVersion = "2.6.15"
  ...
  • Loading branch information
dwijnand committed Apr 23, 2019
2 parents 47be391 + e1b0460 commit a274615
Show file tree
Hide file tree
Showing 43 changed files with 2,266 additions and 0 deletions.
12 changes: 12 additions & 0 deletions play-scala-rest-api-example/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
build
logs
target
/.idea
/.idea_modules
/.classpath
/.gradle
/.project
/.settings
/RUNNING_PID

/.vscode
27 changes: 27 additions & 0 deletions play-scala-rest-api-example/.mergify.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
pull_request_rules:
- name: automatic merge on CI success require review
conditions:
- status-success=Travis CI - Pull Request
- "#approved-reviews-by>=1"
- "#changes-requested-reviews-by=0"
- label!=block-merge
actions:
merge:
method: squash
strict: smart

- name: automatic merge on CI success for TemplateControl
conditions:
- status-success=Travis CI - Pull Request
- label=merge-when-green
- label!=block-merge
actions:
merge:
method: squash
strict: smart

- name: delete branch after merge
conditions:
- merged
actions:
delete_head_branch: {}
50 changes: 50 additions & 0 deletions play-scala-rest-api-example/.travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
language: scala
scala:
- 2.12.8

before_install:
- curl -sL https://github.com/shyiko/jabba/raw/master/install.sh | bash && . ~/.jabba/jabba.sh

env:
global:
- JABBA_HOME=$HOME/.jabba
matrix:
# There is no concise way to specify multi-dimensional build matrix:
# https://github.com/travis-ci/travis-ci/issues/1519
- SCRIPT=scripts/test-sbt [email protected]
- SCRIPT=scripts/test-sbt [email protected]
- SCRIPT=scripts/test-gradle [email protected]
- SCRIPT=scripts/test-gradle [email protected]

# Exclude some combinations from build matrix. See:
# https://docs.travis-ci.com/user/customizing-the-build/#Build-Matrix
matrix:
fast_finish: true
allow_failures:
# Current release of Gradle still does not supports Play 2.7.x releases
# As soon as there is a release of Gradle that fixes that, we can then
# remove this allowed failure.
- env: SCRIPT=scripts/test-gradle [email protected]
- env: SCRIPT=scripts/test-gradle [email protected]
# Java 11 is still not fully supported. It is good that we are already
# testing our sample applications to better discover possible problems
# but we can allow failures here too.
- env: SCRIPT=scripts/test-sbt [email protected]

install:
- $JABBA_HOME/bin/jabba install $TRAVIS_JDK
- unset _JAVA_OPTIONS
- export JAVA_HOME="$JABBA_HOME/jdk/$TRAVIS_JDK" && export PATH="$JAVA_HOME/bin:$PATH" && java -Xmx32m -version

script:
- $SCRIPT

before_cache:
- find $HOME/.ivy2 -name "ivydata-*.properties" -delete
- find $HOME/.sbt -name "*.lock" -delete

cache:
directories:
- "$HOME/.ivy2/cache"
- "$HOME/.gradle/caches"
- "$HOME/.jabba/jdk"
116 changes: 116 additions & 0 deletions play-scala-rest-api-example/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
CC0 1.0 Universal

Statement of Purpose

The laws of most jurisdictions throughout the world automatically confer
exclusive Copyright and Related Rights (defined below) upon the creator and
subsequent owner(s) (each and all, an "owner") of an original work of
authorship and/or a database (each, a "Work").

Certain owners wish to permanently relinquish those rights to a Work for the
purpose of contributing to a commons of creative, cultural and scientific
works ("Commons") that the public can reliably and without fear of later
claims of infringement build upon, modify, incorporate in other works, reuse
and redistribute as freely as possible in any form whatsoever and for any
purposes, including without limitation commercial purposes. These owners may
contribute to the Commons to promote the ideal of a free culture and the
further production of creative, cultural and scientific works, or to gain
reputation or greater distribution for their Work in part through the use and
efforts of others.

For these and/or other purposes and motivations, and without any expectation
of additional consideration or compensation, the person associating CC0 with a
Work (the "Affirmer"), to the extent that he or she is an owner of Copyright
and Related Rights in the Work, voluntarily elects to apply CC0 to the Work
and publicly distribute the Work under its terms, with knowledge of his or her
Copyright and Related Rights in the Work and the meaning and intended legal
effect of CC0 on those rights.

1. Copyright and Related Rights. A Work made available under CC0 may be
protected by copyright and related or neighboring rights ("Copyright and
Related Rights"). Copyright and Related Rights include, but are not limited
to, the following:

i. the right to reproduce, adapt, distribute, perform, display, communicate,
and translate a Work;

ii. moral rights retained by the original author(s) and/or performer(s);

iii. publicity and privacy rights pertaining to a person's image or likeness
depicted in a Work;

iv. rights protecting against unfair competition in regards to a Work,
subject to the limitations in paragraph 4(a), below;

v. rights protecting the extraction, dissemination, use and reuse of data in
a Work;

vi. database rights (such as those arising under Directive 96/9/EC of the
European Parliament and of the Council of 11 March 1996 on the legal
protection of databases, and under any national implementation thereof,
including any amended or successor version of such directive); and

vii. other similar, equivalent or corresponding rights throughout the world
based on applicable law or treaty, and any national implementations thereof.

2. Waiver. To the greatest extent permitted by, but not in contravention of,
applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and
unconditionally waives, abandons, and surrenders all of Affirmer's Copyright
and Related Rights and associated claims and causes of action, whether now
known or unknown (including existing as well as future claims and causes of
action), in the Work (i) in all territories worldwide, (ii) for the maximum
duration provided by applicable law or treaty (including future time
extensions), (iii) in any current or future medium and for any number of
copies, and (iv) for any purpose whatsoever, including without limitation
commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes
the Waiver for the benefit of each member of the public at large and to the
detriment of Affirmer's heirs and successors, fully intending that such Waiver
shall not be subject to revocation, rescission, cancellation, termination, or
any other legal or equitable action to disrupt the quiet enjoyment of the Work
by the public as contemplated by Affirmer's express Statement of Purpose.

3. Public License Fallback. Should any part of the Waiver for any reason be
judged legally invalid or ineffective under applicable law, then the Waiver
shall be preserved to the maximum extent permitted taking into account
Affirmer's express Statement of Purpose. In addition, to the extent the Waiver
is so judged Affirmer hereby grants to each affected person a royalty-free,
non transferable, non sublicensable, non exclusive, irrevocable and
unconditional license to exercise Affirmer's Copyright and Related Rights in
the Work (i) in all territories worldwide, (ii) for the maximum duration
provided by applicable law or treaty (including future time extensions), (iii)
in any current or future medium and for any number of copies, and (iv) for any
purpose whatsoever, including without limitation commercial, advertising or
promotional purposes (the "License"). The License shall be deemed effective as
of the date CC0 was applied by Affirmer to the Work. Should any part of the
License for any reason be judged legally invalid or ineffective under
applicable law, such partial invalidity or ineffectiveness shall not
invalidate the remainder of the License, and in such case Affirmer hereby
affirms that he or she will not (i) exercise any of his or her remaining
Copyright and Related Rights in the Work or (ii) assert any associated claims
and causes of action with respect to the Work, in either case contrary to
Affirmer's express Statement of Purpose.

4. Limitations and Disclaimers.

a. No trademark or patent rights held by Affirmer are waived, abandoned,
surrendered, licensed or otherwise affected by this document.

b. Affirmer offers the Work as-is and makes no representations or warranties
of any kind concerning the Work, express, implied, statutory or otherwise,
including without limitation warranties of title, merchantability, fitness
for a particular purpose, non infringement, or the absence of latent or
other defects, accuracy, or the present or absence of errors, whether or not
discoverable, all to the greatest extent permissible under applicable law.

c. Affirmer disclaims responsibility for clearing rights of other persons
that may apply to the Work or any use thereof, including without limitation
any person's Copyright and Related Rights in the Work. Further, Affirmer
disclaims responsibility for obtaining any necessary consents, permissions
or other rights required for any use of the Work.

d. Affirmer understands and acknowledges that Creative Commons is not a
party to this document and has no duty or obligation with respect to this
CC0 or use of the Work.

For more information, please see
<http://creativecommons.org/publicdomain/zero/1.0/>
8 changes: 8 additions & 0 deletions play-scala-rest-api-example/NOTICE
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
Written by Lightbend <[email protected]>

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/>.
73 changes: 73 additions & 0 deletions play-scala-rest-api-example/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
# Play REST API

[![Build Status](https://travis-ci.org/playframework/play-scala-rest-api-example.svg?branch=2.6.x)](https://travis-ci.org/playframework/play-scala-rest-api-example)

This is the example project for [Making a REST API in Play](http://developer.lightbend.com/guides/play-rest-api/index.html).

## Appendix

### Running

You need to download and install sbt for this application to run.

Once you have sbt installed, the following at the command prompt will start up Play in development mode:

```bash
sbt run
```

Play will start up on the HTTP port at <http://localhost:9000/>. You don't need to deploy or reload anything -- changing any source code while the server is running will automatically recompile and hot-reload the application on the next HTTP request.

### Usage

If you call the same URL from the command line, you’ll see JSON. Using httpie, we can execute the command:

```bash
http --verbose http://localhost:9000/v1/posts
```

and get back:

```routes
GET /v1/posts HTTP/1.1
```

Likewise, you can also send a POST directly as JSON:

```bash
http --verbose POST http://localhost:9000/v1/posts title="hello" body="world"
```

and get:

```routes
POST /v1/posts HTTP/1.1
```

### Load Testing

The best way to see what Play can do is to run a load test. We've included Gatling in this test project for integrated load testing.

Start Play in production mode, by [staging the application](https://www.playframework.com/documentation/2.5.x/Deploying) and running the play script:s

```bash
sbt stage
cd target/universal/stage
bin/play-rest-api-example -Dplay.crypto.secret=testing
```

Then you'll start the Gatling load test up (it's already integrated into the project):

```bash
sbt gatling:test
```

For best results, start the gatling load test up on another machine so you do not have contending resources. You can edit the [Gatling simulation](http://gatling.io/docs/2.2.2/general/simulation_structure.html#simulation-structure), and change the numbers as appropriate.

Once the test completes, you'll see an HTML file containing the load test chart:

```bash
./rest-api/target/gatling/gatlingspec-1472579540405/index.html
```

That will contain your load test results.
81 changes: 81 additions & 0 deletions play-scala-rest-api-example/app/ErrorHandler.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import javax.inject.{Inject, Provider}

import play.api._
import play.api.http.DefaultHttpErrorHandler
import play.api.http.Status._
import play.api.libs.json.Json
import play.api.mvc.Results._
import play.api.mvc._
import play.api.routing.Router
import play.core.SourceMapper

import scala.concurrent._

/**
* Provides a stripped down error handler that does not use HTML in error pages, and
* prints out debugging output.
*
* https://www.playframework.com/documentation/latest/ScalaErrorHandling
*/
class ErrorHandler(environment: Environment,
configuration: Configuration,
sourceMapper: Option[SourceMapper] = None,
optionRouter: => Option[Router] = None)
extends DefaultHttpErrorHandler(environment,
configuration,
sourceMapper,
optionRouter) {

private val logger =
org.slf4j.LoggerFactory.getLogger("application.ErrorHandler")

// This maps through Guice so that the above constructor can call methods.
@Inject
def this(environment: Environment,
configuration: Configuration,
sourceMapper: OptionalSourceMapper,
router: Provider[Router]) = {
this(environment,
configuration,
sourceMapper.sourceMapper,
Some(router.get))
}

override def onClientError(request: RequestHeader,
statusCode: Int,
message: String): Future[Result] = {
logger.debug(
s"onClientError: statusCode = $statusCode, uri = ${request.uri}, message = $message")

Future.successful {
val result = statusCode match {
case BAD_REQUEST =>
Results.BadRequest(message)
case FORBIDDEN =>
Results.Forbidden(message)
case NOT_FOUND =>
Results.NotFound(message)
case clientError if statusCode >= 400 && statusCode < 500 =>
Results.Status(statusCode)
case nonClientError =>
val msg =
s"onClientError invoked with non client error status code $statusCode: $message"
throw new IllegalArgumentException(msg)
}
result
}
}

override protected def onDevServerError(
request: RequestHeader,
exception: UsefulException): Future[Result] = {
Future.successful(
InternalServerError(Json.obj("exception" -> exception.toString)))
}

override protected def onProdServerError(
request: RequestHeader,
exception: UsefulException): Future[Result] = {
Future.successful(InternalServerError)
}
}
20 changes: 20 additions & 0 deletions play-scala-rest-api-example/app/Module.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import javax.inject._

import com.google.inject.AbstractModule
import net.codingwell.scalaguice.ScalaModule
import play.api.{Configuration, Environment}
import v1.post._

/**
* Sets up custom components for Play.
*
* https://www.playframework.com/documentation/latest/ScalaDependencyInjection
*/
class Module(environment: Environment, configuration: Configuration)
extends AbstractModule
with ScalaModule {

override def configure() = {
bind[PostRepository].to[PostRepositoryImpl].in[Singleton]
}
}
Loading

0 comments on commit a274615

Please sign in to comment.