Commit fde1b16d authored by Lê Hoàng Huy's avatar Lê Hoàng Huy

first commit

parents
Pipeline #1990 failed with stages
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/>
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/>.
# play-java-chatroom-example
This is a simple chatroom using Play and Websockets with the Java API.
This project makes use of [dynamic streams](https://pekko.apache.org/docs/pekko/current/java/stream/stream-dynamic.html) from Pekko Streams, notably `BroadcastHub` and `MergeHub`. By [combining MergeHub and BroadcastHub](https://pekko.apache.org/docs/pekko/current/stream/stream-dynamic.html?language=java#dynamic-fan-in-and-fan-out-with-mergehub-broadcasthub-and-partitionhub), you can get publish/subscribe functionality.
## The good bit
The flow is defined once in the controller, and used everywhere from the `chat` action:
```java
public class HomeController extends Controller {
private final Flow userFlow;
@Inject
public HomeController(ActorSystem actorSystem,
Materializer mat) {
org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(this.getClass());
LoggingAdapter logging = Logging.getLogger(actorSystem.eventStream(), logger.getName());
//noinspection unchecked
Source<String, Sink<String, NotUsed>> source = MergeHub.of(String.class)
.log("source", logging)
.recoverWithRetries(-1, new PFBuilder().match(Throwable.class, e -> Source.empty()).build());
Sink<String, Source<String, NotUsed>> sink = BroadcastHub.of(String.class);
Pair<Sink<String, NotUsed>, Source<String, NotUsed>> sinkSourcePair = source.toMat(sink, Keep.both()).run(mat);
Sink<String, NotUsed> chatSink = sinkSourcePair.first();
Source<String, NotUsed> chatSource = sinkSourcePair.second();
this.userFlow = Flow.fromSinkAndSource(chatSink, chatSource).log("userFlow", logging);
}
public Result index() {
Http.Request request = request();
String url = routes.HomeController.chat().webSocketURL(request);
return Results.ok(views.html.index.render(url));
}
public WebSocket chat() {
return WebSocket.Text.acceptOrResult(request -> {
if (sameOriginCheck(request)) {
return CompletableFuture.completedFuture(F.Either.Right(userFlow));
} else {
return CompletableFuture.completedFuture(F.Either.Left(forbidden()));
}
});
}
}
```
## Prerequisites
You will need [JDK 11](https://adoptopenjdk.net/) and [sbt](http://www.scala-sbt.org/) installed.
## Running
```bash
sbt run
```
Go to <http://localhost:9000> and open it in two different browsers. Typing into one browser will cause it to show up in another browser.
## Server backend
By default, the project uses the Pekko HTTP Server backend. To switch to the Netty Server backend, enable the `PlayNettyServer` sbt plugin in the `build.sbt` file.
In the `build.sbt` of this project, you'll find a commented line for this setting; simply uncomment it to make the switch.
For more detailed information, refer to the Play Framework [documentation](https://www.playframework.com/documentation/3.0.x/Server).
## Tributes
This project is originally taken from Johan Andrén's [Akka-HTTP version](https://github.com/johanandren/chat-with-akka-http-websockets/tree/akka-2.4.10):
Johan also has a blog post explaining dynamic streams in more detail:
* <http://markatta.com/codemonkey/blog/2016/10/02/chat-with-akka-http-websockets/>
package controllers;
import org.apache.pekko.NotUsed;
import org.apache.pekko.actor.ActorSystem;
import org.apache.pekko.event.Logging;
import org.apache.pekko.event.LoggingAdapter;
import org.apache.pekko.japi.Pair;
import org.apache.pekko.japi.pf.PFBuilder;
import org.apache.pekko.stream.Materializer;
import org.apache.pekko.stream.javadsl.*;
import org.webjars.play.WebJarsUtil;
import play.libs.F;
import play.mvc.*;
import javax.inject.Inject;
import java.net.URI;
import java.util.List;
import java.util.concurrent.CompletableFuture;
/**
* A very simple chat client using websockets.
*/
public class HomeController extends Controller {
private final Flow<String, String, NotUsed> userFlow;
private final WebJarsUtil webJarsUtil;
@Inject
public HomeController(ActorSystem actorSystem,
Materializer mat,
WebJarsUtil webJarsUtil) {
org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(this.getClass());
LoggingAdapter logging = Logging.getLogger(actorSystem.eventStream(), logger.getName());
//noinspection unchecked
Source<String, Sink<String, NotUsed>> source = MergeHub.of(String.class)
.log("source", logging)
.recoverWithRetries(-1, new PFBuilder().match(Throwable.class, e -> Source.empty()).build());
Sink<String, Source<String, NotUsed>> sink = BroadcastHub.of(String.class);
Pair<Sink<String, NotUsed>, Source<String, NotUsed>> sinkSourcePair = source.toMat(sink, Keep.both()).run(mat);
Sink<String, NotUsed> chatSink = sinkSourcePair.first();
Source<String, NotUsed> chatSource = sinkSourcePair.second();
this.userFlow = Flow.fromSinkAndSource(chatSink, chatSource).log("userFlow", logging);
this.webJarsUtil = webJarsUtil;
}
public Result index(Http.Request request) {
String url = routes.HomeController.chat().webSocketURL(request);
return Results.ok(views.html.index.render(url, webJarsUtil));
}
public WebSocket chat() {
return WebSocket.Text.acceptOrResult(request -> {
if (sameOriginCheck(request)) {
return CompletableFuture.completedFuture(F.Either.Right(userFlow));
} else {
return CompletableFuture.completedFuture(F.Either.Left(forbidden()));
}
});
}
/**
* Checks that the WebSocket comes from the same origin. This is necessary to protect
* against Cross-Site WebSocket Hijacking as WebSocket does not implement Same Origin Policy.
*
* See https://tools.ietf.org/html/rfc6455#section-1.3 and
* http://blog.dewhurstsecurity.com/2013/08/30/security-testing-html5-websockets.html
*/
private boolean sameOriginCheck(Http.RequestHeader request) {
List<String> origins = request.getHeaders().getAll("Origin");
if (origins.size() > 1) {
// more than one origin found
return false;
}
String origin = origins.get(0);
return originMatches(origin);
}
private boolean originMatches(String origin) {
if (origin == null) return false;
try {
URI url = new URI(origin);
return url.getHost().equals("localhost")
&& (url.getPort() == 9000 || url.getPort() == 19001);
} catch (Exception e ) {
return false;
}
}
}
package filters;
import controllers.routes;
import play.core.Execution;
import play.mvc.EssentialAction;
import play.mvc.EssentialFilter;
import play.mvc.Http;
import play.mvc.Result;
public class ContentSecurityPolicyFilter extends EssentialFilter {
@Override
public EssentialAction apply(EssentialAction next) {
return EssentialAction.of((Http.RequestHeader requestHeader) -> {
String webSocketUrl = routes.HomeController.chat().webSocketURL(requestHeader.asScala());
return next.apply(requestHeader).map((Result result) ->
result.withHeader("Content-Security-Policy", "connect-src 'self' " + webSocketUrl), Execution.trampoline());
});
}
}
@(url: String, webJarsUtil: org.webjars.play.WebJarsUtil)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
@webJarsUtil.locate("bootstrap.min.css").css()
@webJarsUtil.locate("bootstrap-theme.min.css").css()
<link rel="stylesheet" media="screen" href="@routes.Assets.at("stylesheets/main.css")">
<link rel="shortcut icon" type="image/png" href="@routes.Assets.at("images/favicon.png")">
<title>Chat Room</title>
</head>
<body>
<div class="wrap">
<div class="container-fluid">
<div>
<h1 class="">Chat Room</h1>
</div>
<div class="row">
<div class="col-lg-12">
<ul id="messages" class="list-unstyled">
</ul>
</div>
</div>
</div>
</div>
<div class="footer navbar-fixed-bottom">
<div class="row">
<div class="col-xs-8 col-sm-9">
<input id="message" placeholder="Type Here" type="text"
autofocus
autocomplete="off" spellcheck="false" autocorrect="off"
class="form-control input-lg" />
</div>
<div class="col-xs-4 col-sm-3">
<button id="send" type="submit" class="btn btn-primary btn-lg btn-block">Send</button>
</div>
</div>
</div>
@webJarsUtil.locate("jquery.min.js").script()
<script language="javascript">
var $messages = $("#messages"),
$send = $("#send"),
$message = $("#message"),
connection = new WebSocket("@url");
$send.prop("disabled", true);
var send = function () {
var text = $message.val();
$message.val("");
connection.send(text);
};
connection.onopen = function () {
$send.prop("disabled", false);
$messages.prepend($("<li class='bg-info' style='font-size: 1.5em'>Connected</li>"));
$send.on('click', send);
$message.keypress(function(event){
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '13'){
send();
}
});
};
connection.onerror = function (error) {
console.log('WebSocket Error ', error);
};
connection.onmessage = function (event) {
$messages.append($("<li style='font-size: 1.5em'>" + event.data + "</li>"))
}
</script>
</body>
</html>
\ No newline at end of file
lazy val root = (project in file("."))
.enablePlugins(PlayJava)
//.enablePlugins(PlayNettyServer).disablePlugins(PlayPekkoHttpServer) // uncomment to use the Netty backend
.settings(
name := """play-java-chatroom-example""",
version := "1.0-SNAPSHOT",
crossScalaVersions := Seq("2.13.14", "3.3.3"),
scalaVersion := crossScalaVersions.value.head,
libraryDependencies ++= Seq(
"org.webjars" %% "webjars-play" % "3.0.1",
"org.webjars" % "flot" % "0.8.3",
"org.webjars" % "bootstrap" % "3.4.1",
guice,
ws,
"org.assertj" % "assertj-core" % "3.12.2" % Test,
"org.awaitility" % "awaitility" % "3.1.6" % Test
),
(Test / javaOptions) += "-Dtestserver.port=19001",
// Needed to make JUnit report the tests being run
(Test / testOptions) := Seq(Tests.Argument(TestFrameworks.JUnit, "-a", "-v")),
javacOptions ++= Seq(
"-Xlint:unchecked",
"-Xlint:deprecation"
)
)
// Enable richer pekko logging
pekko {
loggers = ["org.apache.pekko.event.slf4j.Slf4jLogger"]
loglevel = "DEBUG"
logging-filter = "org.apache.pekko.event.slf4j.Slf4jLoggingFilter"
}
// https://www.playframework.com/documentation/latest/AllowedHostsFilter
play.filters.hosts.allowed = ["localhost:9000", "localhost:19001"]
// Add CSP header in explicitly in a custom filter.
play.filters.enabled += filters.ContentSecurityPolicyFilter
play.http.secret.key = a-long-secret-to-calm-the-rage-of-the-entropy-gods
<?xml version="1.0" encoding="UTF-8" ?>
<!-- https://www.playframework.com/documentation/latest/SettingsLogger -->
<!DOCTYPE configuration>
<configuration>
<import class="ch.qos.logback.classic.encoder.PatternLayoutEncoder"/>
<import class="ch.qos.logback.classic.AsyncAppender"/>
<import class="ch.qos.logback.core.FileAppender"/>
<import class="ch.qos.logback.core.ConsoleAppender"/>
<appender name="FILE" class="FileAppender">
<file>${application.home:-.}/logs/application.log</file>
<encoder class="PatternLayoutEncoder">
<pattern>%date [%level] from %logger in %thread - %message%n%xException</pattern>
</encoder>
</appender>
<appender name="STDOUT" class="ConsoleAppender">
<encoder class="PatternLayoutEncoder">
<pattern>%highlight(%-5level) %logger{15} - %message%n%xException{10}</pattern>
</encoder>
</appender>
<appender name="ASYNCFILE" class="AsyncAppender">
<appender-ref ref="FILE"/>
</appender>
<appender name="ASYNCSTDOUT" class="AsyncAppender">
<appender-ref ref="STDOUT"/>
</appender>
<logger name="controllers.HomeController" level="DEBUG"/>
<root level="INFO">
<appender-ref ref="ASYNCFILE"/>
<appender-ref ref="ASYNCSTDOUT"/>
</root>
</configuration>
# Routes
# This file defines all application routes (Higher priority routes first)
# ~~~~
# An example controller showing a sample home page
GET / controllers.HomeController.index(request: Request)
GET /chat controllers.HomeController.chat
# Map static resources from the /public folder to the /assets URL path
GET /assets/*file controllers.Assets.at(path="/public", file)
-> /webjars webjars.Routes
sbt.version=1.10.0
// The Play plugin
addSbtPlugin("org.playframework" % "sbt-plugin" % "3.0.4")
html, body {
height: 100%;
}
.wrap {
min-height: 100%;
height: 100%;
margin: 0 auto -60px;
}
.footer {
height: 60px;
}
\ No newline at end of file
package controllers;
import play.shaded.ahc.org.asynchttpclient.AsyncHttpClient;
import play.shaded.ahc.org.asynchttpclient.DefaultAsyncHttpClient;
import play.shaded.ahc.org.asynchttpclient.netty.ws.NettyWebSocket;
import play.shaded.ahc.org.asynchttpclient.ws.WebSocket;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import play.libs.ws.WSClient;
import play.libs.ws.WSResponse;
import play.test.WithServer;
import java.io.IOException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import static org.assertj.core.api.Assertions.assertThat;
import static org.awaitility.Awaitility.await;
import static org.junit.Assert.assertEquals;
import static play.mvc.Http.Status.OK;
/**
* Limited functional testing to ensure health checks of build
*/
public class HomeControllerTest extends WithServer {
private AsyncHttpClient asyncHttpClient;
@Before
public void setUp() {
asyncHttpClient = new DefaultAsyncHttpClient();
}
@After
public void tearDown() throws IOException {
asyncHttpClient.close();
}
// Functional test to run through the server and check the page comes ups
@Test
public void testInServer() throws Exception {
int port = this.testServer.getRunningHttpPort().getAsInt();
String url = "http://localhost:" + port + "/";
try (WSClient ws = play.test.WSTestClient.newClient(port)) {
CompletionStage<WSResponse> stage = ws.url(url).get();
WSResponse response = stage.toCompletableFuture().get();
assertEquals(OK, response.getStatus());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// Functional test to check websocket comes up
@Test
public void testWebsocket() throws Exception {
int port = this.testServer.getRunningHttpPort().getAsInt();
String serverURL = "ws://localhost:" + port + "/chat";
WebSocketClient webSocketClient = new WebSocketClient(asyncHttpClient);
WebSocketClient.LoggingListener listener = new WebSocketClient.LoggingListener();
CompletableFuture<NettyWebSocket> future = webSocketClient.call(serverURL, serverURL, listener);
await().untilAsserted(() -> assertThat(future).isDone());
assertThat(future).isCompletedWithValueMatching(NettyWebSocket::isOpen);
}
}
\ No newline at end of file
package controllers;
import play.shaded.ahc.org.asynchttpclient.AsyncHandler;
import play.shaded.ahc.org.asynchttpclient.AsyncHttpClient;
import play.shaded.ahc.org.asynchttpclient.BoundRequestBuilder;
import play.shaded.ahc.org.asynchttpclient.ListenableFuture;
import play.shaded.ahc.org.asynchttpclient.netty.ws.NettyWebSocket;
import play.shaded.ahc.org.asynchttpclient.ws.WebSocket;
import play.shaded.ahc.org.asynchttpclient.ws.WebSocketListener;
import play.shaded.ahc.org.asynchttpclient.ws.WebSocketUpgradeHandler;
import org.slf4j.Logger;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class WebSocketClient {
private AsyncHttpClient client;
public WebSocketClient(AsyncHttpClient c) {
this.client = c;
}
public CompletableFuture<NettyWebSocket> call(String url, String origin, WebSocketListener listener) throws ExecutionException, InterruptedException {
final BoundRequestBuilder requestBuilder = client.prepareGet(url).addHeader("Origin", origin);
final AsyncHandler<NettyWebSocket> handler = new WebSocketUpgradeHandler.Builder().addWebSocketListener(listener).build();
final ListenableFuture<NettyWebSocket> future = requestBuilder.execute(handler);
return future.toCompletableFuture();
}
static class LoggingListener implements WebSocketListener {
private Logger logger = org.slf4j.LoggerFactory.getLogger(LoggingListener.class);
private Throwable throwableFound = null;
public Throwable getThrowable() {
return throwableFound;
}
public void onOpen(WebSocket websocket) {
// do nothing
}
@Override
public void onClose(WebSocket webSocket, int i, String s) {
// do nothing
}
public void onError(Throwable t) {
// do nothing
throwableFound = t;
}
}
}
\ No newline at end of file
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