├── .gitignore
├── CONTRIB.md
├── LICENSE
├── README.md
├── nbactions.xml
├── pom.xml
└── src
└── main
├── java
└── com
│ └── google
│ └── appengine
│ └── demos
│ └── websocketchat
│ ├── domain
│ ├── ChatRoomParticipants.java
│ └── WebSocketServerNode.java
│ ├── message
│ ├── ChatMessage.java
│ ├── OutgoingMessage.java
│ └── ParticipantListMessage.java
│ ├── server
│ ├── ChatSocketServer.java
│ ├── ChatSocketServerShutdownHook.java
│ └── MetaInfoManager.java
│ └── servlet
│ ├── StartupServlet.java
│ └── StopServlet.java
└── webapp
├── WEB-INF
├── appengine-web.xml
├── logging.properties
└── web.xml
├── chat.jsp
└── stylesheets
└── main.css
/.gitignore:
--------------------------------------------------------------------------------
1 | hotspot.log
2 | *.iml
3 | *.ipr
4 | *.iws
5 | target/
6 | classes/
7 | /var
8 | pom.xml.versionsBackup
9 | test-output/
10 | /atlassian-ide-plugin.xml
11 | .idea
12 | .DS_Store
13 | .classpath
14 | .settings
15 | .project
16 | test-output
17 | .externalToolBuilders
18 | *~
19 |
--------------------------------------------------------------------------------
/CONTRIB.md:
--------------------------------------------------------------------------------
1 | # How to become a contributor and submit your own code
2 |
3 | ## Contributor License Agreements
4 |
5 | We'd love to accept your sample apps and patches! Before we can take them, we have to jump a couple of legal hurdles.
6 |
7 | Please fill out either the individual or corporate Contributor License Agreement (CLA).
8 |
9 | * If you are an individual writing original source code and you're sure you own the intellectual property, then you'll need to sign an [individual CLA](http://code.google.com/legal/individual-cla-v1.0.html).
10 | * If you work for a company that wants to allow you to contribute your work, then you'll need to sign a [corporate CLA](http://code.google.com/legal/corporate-cla-v1.0.html).
11 |
12 | Follow either of the two links above to access the appropriate CLA and instructions for how to sign and return it. Once we receive it, we'll be able to accept your pull requests.
13 |
14 | ## Contributing A Patch
15 |
16 | 1. Submit an issue describing your proposed change to the repo in question.
17 | 1. The repo owner will respond to your issue promptly.
18 | 1. If your proposed change is accepted, and you haven't already done so, sign a Contributor License Agreement (see details above).
19 | 1. Fork the desired repo, develop and test your code changes.
20 | 1. Ensure that your code adheres to the existing style in the sample to which you are contributing. Refer to the [Google Cloud Platform Samples Style Guide](https://github.com/GoogleCloudPlatform/Template/wiki/style.html) for the recommended coding standards for this organization.
21 | 1. Ensure that your code has an appropriate set of unit tests which all pass.
22 | 1. Submit a pull request.
23 |
24 | ## Contributing A New Sample App
25 |
26 | 1. Submit an issue to the GoogleCloudPlatform/Template repo describing your proposed sample app.
27 | 1. The Template repo owner will respond to your enhancement issue promptly. Instructional value is the top priority when evaluating new app proposals for this collection of repos.
28 | 1. If your proposal is accepted, and you haven't already done so, sign a Contributor License Agreement (see details above).
29 | 1. Create your own repo for your app following this naming convention:
30 | * {product}-{app-name}-{language}
31 | * products: appengine, compute, storage, bigquery, prediction, cloudsql
32 | * example: appengine-guestbook-python
33 | * For multi-product apps, concatenate the primary products, like this: compute-appengine-demo-suite-python.
34 | * For multi-language apps, concatenate the primary languages like this: appengine-sockets-python-java-go.
35 | 1. Clone the README.md, CONTRIB.md and LICENSE files from the GoogleCloudPlatform/Template repo.
36 | 1. Ensure that your code adheres to the existing style in the sample to which you are contributing. Refer to the [Google Cloud Platform Samples Style Guide](https://github.com/GoogleCloudPlatform/Template/wiki/style.html) for the recommended coding standards for this organization.
37 | 1. Ensure that your code has an appropriate set of unit tests which all pass.
38 | 1. Submit a request to fork your repo in GoogleCloudPlatform organizationt via your proposal issue.
39 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright [yyyy] [name of copyright owner]
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
203 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | App Engine Java VM Runtime Websocket Chat
2 | Copyright (C) 2010-2015 Google Inc.
3 |
4 | ## Sample websocket chat application for use with App Engine Java VM Runtime.
5 |
6 | Requires [Apache Maven](http://maven.apache.org) 3.1 or greater, and
7 | JDK 7+ in order to run. This application needs to be deployed to the
8 | [App Engine Managed VMs][1].
9 |
10 |
11 | In order to run this application, you also need to configure the
12 | Compute Engine firewall to allow incoming connections to the port 65080
13 | by default.
14 |
15 | Here is how to configure the Compute Engine firewall.
16 |
17 | 1. Go to the [cloud console][https://cloud.google.com/console].
18 | 2. Select your Cloud project.
19 | 3. Select `Compute Engine`
20 | 4. Click the `Network` menu then click the `default` network.
21 | 5. Click `Add Firewall rule` button in the `Firewalls rules` section.
22 | 6. Type `chatservice` in the `Name` field, `0.0.0.0/0` in the Source IP Ranges field
23 | and `tcp:65080` in the
24 | `Allowed protocols or ports` field, then click `Create` button.
25 |
26 | Now you're good to go!
27 |
28 | To build:
29 |
30 | Install the [Cloud SDK for Managed VMs](https://cloud.google.com/appengine/docs/managed-vms/)
31 | To run the application, do the following:
32 |
33 | 1. Set the correct Cloud SDK project via `gcloud config set project YOUR_PROJECT`.
34 | 2. Run `mvn gcloud:deploy`
35 | 3. Visit `http://YOUR_PROJECT.appspot.com`.
36 |
37 | For further information, consult the [Java App
38 | Engine](https://cloud.google.com/appengine/docs/java/managed-vms)
39 | documentation.
40 |
41 | To see all the available goals for the Cloud SDK plugin, run
42 |
43 | mvn help:describe -Dplugin=gcloud
44 |
45 | [1]: https://cloud.google.com/console
46 |
--------------------------------------------------------------------------------
/nbactions.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 | CUSTOM-gcloud
19 | gcloud:run
20 |
21 | gcloud:run
22 |
23 |
24 |
25 | CUSTOM-gcloud
26 | gcloud:deploy
27 |
28 | gcloud:deploy
29 |
30 |
31 |
32 | CUSTOM-update
33 | update
34 |
35 | appengine:update
36 |
37 |
38 |
39 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
21 |
22 | 4.0.0
23 | war
24 | 1.0-SNAPSHOT
25 |
26 | com.google.appengine.demos
27 | websocketchat
28 |
29 |
30 | chat
31 | 1.9.28
32 | UTF-8
33 |
34 |
35 |
36 |
37 |
38 | com.google.appengine
39 | appengine-api-1.0-sdk
40 | ${appengine.target.version}
41 |
42 |
43 | javax.servlet
44 | servlet-api
45 | 2.5
46 | provided
47 |
48 |
49 | jstl
50 | jstl
51 | 1.2
52 |
53 |
54 | org.java-websocket
55 | Java-WebSocket
56 | 1.3.0
57 |
58 |
59 | com.google.code.gson
60 | gson
61 | 2.3.1
62 |
63 |
64 | com.googlecode.objectify
65 | objectify
66 | 4.0b2
67 |
68 |
69 | com.google.guava
70 | guava
71 | 18.0
72 |
73 |
74 |
75 |
76 | junit
77 | junit
78 | 4.12
79 | test
80 |
81 |
82 | org.mockito
83 | mockito-all
84 | 1.10.19
85 | test
86 |
87 |
88 | com.google.appengine
89 | appengine-testing
90 | ${appengine.target.version}
91 | test
92 |
93 |
94 | com.google.appengine
95 | appengine-api-stubs
96 | ${appengine.target.version}
97 | test
98 |
99 |
100 |
101 |
102 |
103 |
104 | org.apache.maven.plugins
105 | maven-compiler-plugin
106 | 2.5.1
107 |
108 | 1.7
109 | 1.7
110 |
111 |
112 |
113 |
114 | org.apache.maven.plugins
115 | maven-war-plugin
116 | 2.6
117 |
118 | true
119 |
120 |
121 |
122 | ${basedir}/src/main/webapp/WEB-INF
123 | true
124 | WEB-INF
125 |
126 |
127 |
128 |
129 |
130 |
131 | com.google.appengine
132 | gcloud-maven-plugin
133 | 2.0.9.88.v20151125
134 |
135 |
136 |
137 |
138 |
139 |
--------------------------------------------------------------------------------
/src/main/java/com/google/appengine/demos/websocketchat/domain/ChatRoomParticipants.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2013 Google Inc. All Rights Reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you
5 | * may not use this file except in compliance with the License. You may
6 | * obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
13 | * implied. See the License for the specific language governing
14 | * permissions and limitations under the License.
15 | */
16 |
17 | package com.google.appengine.demos.websocketchat.domain;
18 |
19 | import com.googlecode.objectify.Key;
20 | import com.googlecode.objectify.annotation.Entity;
21 | import com.googlecode.objectify.annotation.Id;
22 | import com.googlecode.objectify.annotation.Parent;
23 |
24 | import java.util.ArrayList;
25 | import java.util.Collection;
26 | import java.util.List;
27 | import java.util.Set;
28 | import java.util.TreeSet;
29 | import java.util.logging.Logger;
30 |
31 | import static com.googlecode.objectify.ObjectifyService.ofy;
32 |
33 | /**
34 | * An entity class which holds a list of participants for a chat room within a single server node.
35 | *
36 | *
The parentKey parameter should be set with the name of the chat room as the key name. This
37 | * is forced by only providing a single public constructor which has {@code String room} as the
38 | * first parameter.
39 | *
40 | */
41 | @Entity
42 | public class ChatRoomParticipants {
43 |
44 | private static final Logger LOG = Logger.getLogger(ChatRoomParticipants.class.getName());
45 |
46 | /* parentKey has a room name as the key name. */
47 | @Parent
48 | private Key parentKey;
49 |
50 | @Id
51 | private String serverNode;
52 |
53 | private Set participants;
54 |
55 | /* Objectify needs the default constructor. */
56 | private ChatRoomParticipants() {}
57 |
58 | /**
59 | * Returns the global list of participants of the given chat room.
60 | *
61 | *
This method aggregates the participants list among multiple servers and return the
62 | * global list of the given chat room.
63 | *
64 | * @param room a name of the chat room.
65 | * @return the global list of participants of the given chat room.
66 | */
67 | public static Set getParticipants(String room) {
68 | List> serverNodeKeyList = ofy().load()
69 | .type(WebSocketServerNode.class).ancestor(WebSocketServerNode.getRootKey()).keys().list();
70 | List> chatRoomParticipantsKeys = new ArrayList<>();
71 | Key parentKey = Key.create(ChatRoomParticipants.class, room);
72 | for (Key serverNodeKey: serverNodeKeyList) {
73 | Key chatRoomParticipantsKey =
74 | Key.create(parentKey, ChatRoomParticipants.class, serverNodeKey.getName());
75 | LOG.info("chatRoomParticipantsKey: " + chatRoomParticipantsKey);
76 | chatRoomParticipantsKeys.add(chatRoomParticipantsKey);
77 | }
78 | Collection chatRoomParticipantsCollection =
79 | ofy().transaction().load().keys(chatRoomParticipantsKeys).values();
80 | Set participantSet = new TreeSet<>();
81 | for (ChatRoomParticipants participants: chatRoomParticipantsCollection) {
82 | LOG.info("Adding " + participants.getParticipants());
83 | participantSet.addAll(participants.getParticipants());
84 | }
85 | return participantSet;
86 | }
87 |
88 | /**
89 | * Creates an entity representing the list of the participants in a chat room within a single
90 | * server node.
91 | *
92 | * @param room a name of the chat room.
93 | * @param serverNode an identifier of a single server node, in the form of websocket URL,
94 | * e.x. "ws://173.255.112.201:65080/".
95 | * @param participants a set of participants in the given chat room within a single server node.
96 | */
97 | public ChatRoomParticipants(String room, String serverNode, Set participants) {
98 | this.parentKey = Key.create(ChatRoomParticipants.class, room);
99 | this.serverNode = serverNode;
100 | this.participants = new TreeSet<>(participants);
101 | }
102 |
103 | /**
104 | * Returns the list of the participants in this entity.
105 | *
106 | * @return the list of the participants in the given chat room within a single server node.
107 | */
108 | public Set getParticipants() {
109 | if (participants == null) {
110 | return new TreeSet<>();
111 | }
112 | return new TreeSet<>(participants);
113 | }
114 |
115 | /**
116 | * Returns the objectify key object representing this entity.
117 | *
118 | * @return the objectify key object representing this entity.
119 | */
120 | public Key getKey() {
121 | return Key.create(this.parentKey, ChatRoomParticipants.class, serverNode);
122 | }
123 | }
124 |
--------------------------------------------------------------------------------
/src/main/java/com/google/appengine/demos/websocketchat/domain/WebSocketServerNode.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2013 Google Inc. All Rights Reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you
5 | * may not use this file except in compliance with the License. You may
6 | * obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
13 | * implied. See the License for the specific language governing
14 | * permissions and limitations under the License.
15 | */
16 |
17 | package com.google.appengine.demos.websocketchat.domain;
18 |
19 | import com.googlecode.objectify.Key;
20 | import com.googlecode.objectify.annotation.Entity;
21 | import com.googlecode.objectify.annotation.Id;
22 | import com.googlecode.objectify.annotation.Parent;
23 |
24 | /**
25 | * An entity class which represents a single websocket server node and holds a number of
26 | * active connections for this server node.
27 | */
28 | @Entity
29 | public class WebSocketServerNode {
30 |
31 | @Id
32 | private String webSocketUrl;
33 |
34 | @Parent
35 | private Key parentKey;
36 |
37 | private long numberOfParticipants;
38 |
39 | /**
40 | * Returns an objectify key commonly used as the parent key for every instance of this class.
41 | *
42 | * @return an objectify key commonly used as the parent key for every instance of this class.
43 | */
44 | public static Key getRootKey() {
45 | return Key.create(WebSocketServerNode.class, "Root");
46 | }
47 |
48 | /**
49 | * Returns an objectify key representing the given websocket server node.
50 | *
51 | * @param webSocketUrl an identifier of a single server node, in the form of websocket URL,
52 | * e.x. "ws://173.255.112.201:65080/".
53 | * @return an objectify key representing the given websocket server node.
54 | */
55 | public static Key getKeyFromWebSocketUrl(String webSocketUrl) {
56 | return Key.create(getRootKey(), WebSocketServerNode.class, webSocketUrl);
57 | }
58 |
59 | /* Objectify needs the default constructor. */
60 | private WebSocketServerNode() {
61 | }
62 |
63 | /**
64 | * Creates an instance representing a single websocket server node.
65 | *
66 | * @param webSocketUrl an identifier of a single server node, in the form of websocket URL,
67 | * e.x. "ws://173.255.112.201:65080/".
68 | */
69 | public WebSocketServerNode(String webSocketUrl) {
70 | this.parentKey = getRootKey();
71 | this.webSocketUrl = webSocketUrl;
72 | this.numberOfParticipants = 0L;
73 | }
74 |
75 | /**
76 | * Returns an objectify key representing this entity.
77 | *
78 | * @return an objectify key representing this entity.
79 | */
80 | public Key getKey() {
81 | return getKeyFromWebSocketUrl(this.webSocketUrl);
82 | }
83 | }
84 |
--------------------------------------------------------------------------------
/src/main/java/com/google/appengine/demos/websocketchat/message/ChatMessage.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2013 Google Inc. All Rights Reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you
5 | * may not use this file except in compliance with the License. You may
6 | * obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
13 | * implied. See the License for the specific language governing
14 | * permissions and limitations under the License.
15 | */
16 |
17 | package com.google.appengine.demos.websocketchat.message;
18 |
19 | import com.google.gson.Gson;
20 |
21 | /**
22 | * A class that is sent via websocket between the servers and clients.
23 | *
24 | * The instances are serialized by Gson when being sent via the websocket connection.
25 | */
26 | public class ChatMessage implements OutgoingMessage {
27 |
28 | private MessageType type;
29 |
30 | private String name;
31 |
32 | private String room;
33 |
34 | private String message;
35 |
36 | /**
37 | * Returns another ChatMessage instance which can be used for propagating the original
38 | * OutgoingMessage between multiple websocket server nodes.
39 | *
40 | * @param original an original OutgoingMessage instance that you want to wrap.
41 | * @param gson a Gson object which used for serialization.
42 | * @return a new ChatMessage with {@code MessageType = MessageType.PROPAGATE} that wraps the
43 | * given original message in the message property.
44 | */
45 | public static ChatMessage createPropagateMessage(OutgoingMessage original, Gson gson) {
46 | return new ChatMessage(MessageType.PROPAGATE, null, original.getRoom(), original.toJson(gson));
47 | }
48 |
49 | /**
50 | * Creates a ChatMessage instance with given parameters.
51 | *
52 | * @param messageType one of the MessageType enum, represents the type of this message.
53 | * @param name a name of the message owner.
54 | * @param room a name of the chat room that the message belongs to.
55 | * @param message actual message contents.
56 | */
57 | public ChatMessage(MessageType messageType, String name, String room, String message) {
58 | this.type = messageType;
59 | this.name = name;
60 | this.room = room;
61 | this.message = message;
62 | }
63 |
64 | @Override
65 | public MessageType getType() {
66 | return type;
67 | }
68 |
69 | /**
70 | * Returns the name of the owner of this message.
71 | *
72 | * @return the name of the owner of this message.
73 | */
74 | public String getName() {
75 | return name;
76 | }
77 |
78 | /**
79 | * Returns the contents of this message.
80 | *
81 | * @return the contents of this message.
82 | */
83 | public String getMessage() {
84 | return message;
85 | }
86 |
87 | /**
88 | * Returns a JSON object that will be sent to the clients.
89 | *
90 | * If the type of this message is {@code MessageType.PROPAGATE}, the return value will be the
91 | * serialized form of the wrapped message.
92 | *
93 | * @param gson a Gson object for serializing this message.
94 | * @return a JSON object that will be sent to the clients.
95 | */
96 | @Override
97 | public String toJson(Gson gson) {
98 | if (type.equals(MessageType.PROPAGATE)) {
99 | return message;
100 | } else {
101 | return gson.toJson(this);
102 | }
103 | }
104 |
105 | @Override
106 | public boolean shouldSendTo(String room) {
107 | return this.room.equals(room);
108 | }
109 |
110 | @Override
111 | public String getRoom() {
112 | return room;
113 | }
114 | }
115 |
--------------------------------------------------------------------------------
/src/main/java/com/google/appengine/demos/websocketchat/message/OutgoingMessage.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2013 Google Inc. All Rights Reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you
5 | * may not use this file except in compliance with the License. You may
6 | * obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
13 | * implied. See the License for the specific language governing
14 | * permissions and limitations under the License.
15 | */
16 |
17 | package com.google.appengine.demos.websocketchat.message;
18 |
19 | import com.google.gson.Gson;
20 |
21 | /**
22 | * An interface that is supposed to be passed to {@code ChatSocketServer#sendToClients()} method.
23 | */
24 | public interface OutgoingMessage {
25 | /**
26 | * A type of the message.
27 | */
28 | public enum MessageType {
29 | /** A normal chat message. */
30 | MESSAGE,
31 |
32 | /** A message for notifying the participant list. */
33 | PARTICIPANTS,
34 |
35 | /** A system message. */
36 | SYSTEM,
37 |
38 | /** A message indicating someone entered the room. */
39 | ENTER,
40 |
41 | /** A message indicating someone left the room. */
42 | LEAVE,
43 |
44 | /** A special message for propagating various message between multiple server nodes. */
45 | PROPAGATE
46 | }
47 | /**
48 | * Returns the type of this message.
49 | *
50 | * @return the type of this message.
51 | */
52 | public MessageType getType();
53 |
54 | /**
55 | * Returns a JSON object that will be sent to the clients.
56 | *
57 | * @param gson a Gson object for serializing this message.
58 | * @return a JSON object that will be sent to the clients.
59 | */
60 | public String toJson(Gson gson);
61 |
62 | /**
63 | * Returns whether or not we should send this message to the given chat room.
64 | *
65 | * @param room a name of the chat room.
66 | * @return whether or not we should send this message to the given chat room.
67 | */
68 | public boolean shouldSendTo(String room);
69 |
70 | /**
71 | * Returns the name of the chat room that this message belongs to.
72 | *
73 | * @return the name of the chat room that this message belongs to.
74 | */
75 | public String getRoom();
76 | }
77 |
--------------------------------------------------------------------------------
/src/main/java/com/google/appengine/demos/websocketchat/message/ParticipantListMessage.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2013 Google Inc. All Rights Reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you
5 | * may not use this file except in compliance with the License. You may
6 | * obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
13 | * implied. See the License for the specific language governing
14 | * permissions and limitations under the License.
15 | */
16 |
17 | package com.google.appengine.demos.websocketchat.message;
18 |
19 | import com.google.common.collect.ImmutableSet;
20 | import com.google.gson.Gson;
21 |
22 | import java.util.Set;
23 |
24 | /**
25 | * A message for notifying the participant list of the chat room.
26 | */
27 | public class ParticipantListMessage implements OutgoingMessage {
28 |
29 | private MessageType type;
30 |
31 | private String room;
32 |
33 | private Set participantSet;
34 |
35 | /**
36 | * Creates a ParticipantListMessage instance with the given parameters.
37 | *
38 | * @param room a name of the chat room.
39 | * @param participantSet a set of the names of the participants.
40 | */
41 | public ParticipantListMessage(String room, Set participantSet) {
42 | this.type = MessageType.PARTICIPANTS;
43 | this.room = room;
44 | this.participantSet = ImmutableSet.copyOf(participantSet);
45 | }
46 |
47 | @Override
48 | public MessageType getType() {
49 | return type;
50 | }
51 |
52 | @Override
53 | public String toJson(Gson gson) {
54 | return gson.toJson(this);
55 | }
56 |
57 | @Override
58 | public boolean shouldSendTo(String room) {
59 | return this.room.equals(room);
60 | }
61 |
62 | @Override
63 | public String getRoom() {
64 | return room;
65 | }
66 |
67 | /**
68 | * Returns the set of the names of the participants.
69 | *
70 | * @return the set of the names of the participants.
71 | */
72 | public Set getParticipantSet() {
73 | return participantSet;
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/src/main/java/com/google/appengine/demos/websocketchat/server/ChatSocketServer.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2013 Google Inc. All Rights Reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you
5 | * may not use this file except in compliance with the License. You may
6 | * obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
13 | * implied. See the License for the specific language governing
14 | * permissions and limitations under the License.
15 | */
16 |
17 | package com.google.appengine.demos.websocketchat.server;
18 |
19 | import java.io.BufferedReader;
20 | import java.io.IOException;
21 | import java.io.InputStreamReader;
22 | import java.net.HttpURLConnection;
23 | import java.net.InetSocketAddress;
24 | import java.net.URI;
25 | import java.net.URISyntaxException;
26 | import java.net.URL;
27 | import java.util.Collection;
28 | import java.util.List;
29 | import java.util.Map;
30 | import java.util.Set;
31 | import java.util.concurrent.ConcurrentHashMap;
32 | import java.util.concurrent.ConcurrentLinkedQueue;
33 | import java.util.concurrent.CopyOnWriteArrayList;
34 | import java.util.logging.Logger;
35 |
36 | import com.google.appengine.api.NamespaceManager;
37 | import com.google.appengine.api.ThreadManager;
38 | import com.google.appengine.api.utils.SystemProperty;
39 | import com.google.appengine.demos.websocketchat.domain.ChatRoomParticipants;
40 | import com.google.appengine.demos.websocketchat.domain.WebSocketServerNode;
41 | import com.google.appengine.demos.websocketchat.message.ChatMessage;
42 | import com.google.appengine.demos.websocketchat.message.OutgoingMessage;
43 | import com.google.appengine.demos.websocketchat.message.ParticipantListMessage;
44 | import com.google.apphosting.api.ApiProxy;
45 | import com.google.common.base.Throwables;
46 | import com.google.gson.Gson;
47 | import com.googlecode.objectify.Key;
48 | import org.java_websocket.WebSocket;
49 | import org.java_websocket.client.WebSocketClient;
50 | import org.java_websocket.handshake.ClientHandshake;
51 | import org.java_websocket.handshake.ServerHandshake;
52 | import org.java_websocket.server.WebSocketServer;
53 |
54 | import static com.googlecode.objectify.ObjectifyService.ofy;
55 |
56 | /**
57 | * A simple WebSocketServerNode implementation. Keeps track of a "websocketchat".
58 | */
59 | public class ChatSocketServer extends WebSocketServer {
60 |
61 | private static final Logger LOG = Logger.getLogger(ChatSocketServer.class.getName());
62 |
63 | private static final int DEFAULT_PORT = 65080;
64 |
65 | private static final Gson GSON = new Gson();
66 |
67 | private static final String NETWORK_INTERFACE_METADATA_URL =
68 | "http://metadata/computeMetadata/v1beta1/instance/network-interfaces/0/access-configs/0/" +
69 | "external-ip";
70 |
71 | private final MetaInfoManager metaInfoManager;
72 |
73 | private ConcurrentLinkedQueue updateAndSendParticipantListQueue;
74 |
75 | private ConcurrentLinkedQueue propagateQueue;
76 |
77 | private String hostname;
78 |
79 | private String getHostname() throws IOException {
80 | if (hostname == null) {
81 | if (SystemProperty.environment.value().equals(SystemProperty.Environment.Value.Production)) {
82 | URL url = new URL(NETWORK_INTERFACE_METADATA_URL);
83 | HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
84 | BufferedReader reader = new BufferedReader(
85 | new InputStreamReader(httpUrlConnection.getInputStream()));
86 | String result, line = reader.readLine();
87 | result = line;
88 | while ((line = reader.readLine()) != null) {
89 | result += line;
90 | }
91 | hostname = result;
92 | } else {
93 | hostname = "localhost";
94 | }
95 | }
96 | return hostname;
97 | }
98 |
99 | /**
100 | * Returns a Websocket URL of this server.
101 | *
102 | * @return a Websocket URL of this server.
103 | * @throws IOException when failed to get the external IP address from the metadata server.
104 | */
105 | public String getWebSocketURL() throws IOException {
106 | return "ws://" + getHostname() + ":" + this.getPort() + "/";
107 | }
108 |
109 | /**
110 | * A class that runs in another thread and becomes a bridge between App Engine and the
111 | * websocket server.
112 | */
113 | public static class ChatServerBridge implements Runnable {
114 |
115 | private ChatSocketServer chatSocketServer;
116 |
117 | private Thread watcherThread;
118 |
119 | private String namespace;
120 |
121 | private static ChatServerBridge chatServerBridge;
122 |
123 | private CopyOnWriteArrayList> chatRoomParticipantsKeyList;
124 |
125 | private ApiProxy.Environment backgroundEnvironment;
126 |
127 | private ChatServerBridge() {
128 | namespace = NamespaceManager.get();
129 | chatRoomParticipantsKeyList = new CopyOnWriteArrayList<>();
130 | }
131 |
132 | /**
133 | * Returns a singleton instance of this class.
134 | *
135 | * @return a singleton instance of this class.
136 | */
137 | public static ChatServerBridge getInstance() {
138 | if (chatServerBridge == null) {
139 | chatServerBridge = new ChatServerBridge();
140 | }
141 | return chatServerBridge;
142 | }
143 |
144 | private void registerWebSocketServerNode() throws IOException {
145 | WebSocketServerNode webSocketServerNode = new WebSocketServerNode(
146 | chatSocketServer.getWebSocketURL());
147 | ofy().save().entity(webSocketServerNode).now();
148 | }
149 |
150 | private void removeWebSocketServerNode() throws IOException {
151 | Key key = WebSocketServerNode.getKeyFromWebSocketUrl(
152 | chatSocketServer.getWebSocketURL());
153 | ofy().delete().key(key).now();
154 | }
155 |
156 | protected ApiProxy.Environment getBackgroundEnvironment() {
157 | return backgroundEnvironment;
158 | }
159 |
160 | /**
161 | * Starts the websocket server, registers necessary information and then starts the bridge
162 | * thread.
163 | */
164 | public void start() {
165 | if (chatSocketServer != null) {
166 | throw new IllegalStateException("We already have a chatSocketServer.");
167 | }
168 | chatSocketServer = new ChatSocketServer(DEFAULT_PORT);
169 | chatSocketServer.start();
170 | LOG.info("Server started on port: " + chatSocketServer.getPort());
171 | try {
172 | registerWebSocketServerNode();
173 | } catch (IOException e) {
174 | LOG.warning(Throwables.getStackTraceAsString(e));
175 | }
176 | ThreadManager.createBackgroundThread(this).start();
177 | }
178 |
179 | /**
180 | * Stops the websocket server, cleans up some info, and then stop the main bridge thread.
181 | */
182 | public void stop() {
183 | try {
184 | removeWebSocketServerNode();
185 | chatSocketServer.stop();
186 | watcherThread.interrupt();
187 | watcherThread.join();
188 | watcherThread = null;
189 | // delete participant list in the datastore
190 | ofy().delete().keys(chatRoomParticipantsKeyList).now();
191 | // initialize variables
192 | chatRoomParticipantsKeyList = new CopyOnWriteArrayList<>();
193 | chatSocketServer = null;
194 | } catch (IOException|InterruptedException e) {
195 | LOG.warning(Throwables.getStackTraceAsString(e));
196 | }
197 | }
198 |
199 | /**
200 | * Pops a name of a chat room from the updateAndSendParticipantListQueue and update the
201 | * participant list in the datastore, then creates the global list of the given chat room and
202 | * distribute it to the clients who is participating to that chat room.
203 | *
204 | * @throws IOException
205 | */
206 | private void updateParticipantListAndDistribute() throws IOException {
207 | if (! chatSocketServer.updateAndSendParticipantListQueue.isEmpty()) {
208 | // Update the participant list in the datastore
209 | String room = chatSocketServer.updateAndSendParticipantListQueue.remove();
210 | ChatRoomParticipants chatRoomParticipants = new ChatRoomParticipants(room,
211 | chatSocketServer.getWebSocketURL(),
212 | chatSocketServer.metaInfoManager.getParticipantList(room));
213 | ofy().save().entity(chatRoomParticipants).now();
214 | chatRoomParticipantsKeyList.add(chatRoomParticipants.getKey());
215 | // Retrieve the full participant list in the room and distribute it
216 | Set participantSet = ChatRoomParticipants.getParticipants(room);
217 | ParticipantListMessage participantListMessage = new ParticipantListMessage(room,
218 | participantSet);
219 | chatSocketServer.sendToClients(participantListMessage);
220 | }
221 | }
222 |
223 | /**
224 | * Propagate a message popped from the propagateQueue to other active server nodes.
225 | *
226 | * @throws IOException
227 | */
228 | private void propagateOneMessage() throws IOException {
229 | if (! chatSocketServer.propagateQueue.isEmpty()) {
230 | // handle message propagation between the server nodes.
231 | OutgoingMessage message = chatSocketServer.propagateQueue.remove();
232 | LOG.info("Handling a propagate message: " + message.toJson(GSON));
233 | Key parentKey = WebSocketServerNode.getRootKey();
234 | List> serverKeys = ofy().load()
235 | .type(WebSocketServerNode.class).ancestor(parentKey).keys().list();
236 | final ChatMessage propagateMessage =
237 | ChatMessage.createPropagateMessage(message, GSON);
238 | for (Key key: serverKeys) {
239 | LOG.info("Server: " + key.getName());
240 | if (! key.getName().equals(chatSocketServer.getWebSocketURL())) {
241 | // Send a propagate message
242 | LOG.info("Trying to send a message to the server: " + key.getName());
243 | try {
244 | final WebSocketClient chatClient = new WebSocketClient(new URI(key.getName())) {
245 | @Override
246 | public void onOpen(ServerHandshake handshakedata) {
247 | // Send propagateMessage itself.
248 | this.send(GSON.toJson(propagateMessage));
249 | this.close();
250 | }
251 |
252 | @Override
253 | public void onMessage(String message) {
254 | LOG.info("Message received: " + message);
255 | }
256 |
257 | @Override
258 | public void onClose(int code, String reason, boolean remote) {
259 | LOG.info("Connection closed.");
260 | }
261 |
262 | @Override
263 | public void onError(Exception ex) {
264 | LOG.warning(Throwables.getStackTraceAsString(ex));
265 | }
266 | };
267 | chatClient.connect();
268 | } catch (URISyntaxException e) {
269 | LOG.warning(Throwables.getStackTraceAsString(e));
270 | }
271 | }
272 | }
273 | }
274 | }
275 |
276 | /**
277 | * A main loop of this bridge thread.
278 | *
279 | *
The chat server requests us the following 2 things.
280 | *
281 | *
Update and distribute the participant list in a particular chat room.
282 | *
Propagate a message to other active server nodes.
283 | *
284 | *
This thread watches the 2 queues on the ChatSocketServer instance,
285 | * and handles those requests in the main loop.
286 | *
If this loop becomes the performance bottleneck, distribute these work loads into
287 | * multiple thread worker.
288 | */
289 | public void run() {
290 | if (watcherThread != null) {
291 | throw new IllegalStateException("A watcherThread already exists.");
292 | }
293 | watcherThread = Thread.currentThread();
294 | LOG.info("Namespace is set to " + namespace + " in thread " + watcherThread.toString());
295 | NamespaceManager.set(namespace);
296 | // Store the environment for later use.
297 | backgroundEnvironment = ApiProxy.getCurrentEnvironment();
298 |
299 | while (true) {
300 | if (Thread.currentThread().isInterrupted()) {
301 | LOG.info("ChatServerBridge is stopping.");
302 | return;
303 | } else {
304 | try {
305 | updateParticipantListAndDistribute();
306 | propagateOneMessage();
307 | Thread.sleep(100);
308 | } catch (InterruptedException e) {
309 | Thread.currentThread().interrupt();
310 | break;
311 | } catch (IOException e) {
312 | LOG.warning(Throwables.getStackTraceAsString(e));
313 | }
314 | }
315 | }
316 | }
317 |
318 | /**
319 | * Returns a Websocket URL of the chat server.
320 | *
321 | * @return a Websocket URL of the chat server.
322 | * @throws IOException when failed to get the external IP address from the metadata server.
323 | */
324 | public String getWebSocketURL() throws IOException {
325 | return this.chatSocketServer.getWebSocketURL();
326 | }
327 | }
328 |
329 | /**
330 | * Creates a ChatSoccketServer instance with the given network port.
331 | *
332 | * @param port a port number on which this chat server will listen.
333 | */
334 | public ChatSocketServer(int port) {
335 | super(new InetSocketAddress(port));
336 | metaInfoManager = new MetaInfoManager();
337 | updateAndSendParticipantListQueue = new ConcurrentLinkedQueue<>();
338 | propagateQueue = new ConcurrentLinkedQueue<>();
339 | }
340 |
341 | /**
342 | * Records the incoming connection to the log.
343 | * @param conn a websocket connection object.
344 | * @param handshake a websocket handshake object.
345 | */
346 | @Override
347 | public void onOpen(WebSocket conn, ClientHandshake handshake) {
348 | LOG.info(conn.getRemoteSocketAddress().getAddress().getHostAddress() + " entered the room!");
349 | }
350 |
351 | /**
352 | * Removes a ConnectionInfo object associated with a given websocket connection from the
353 | * MetaInfoManager.
354 | *
355 | * @param conn a websocket connection object.
356 | * @param code an integer code that you can look up at
357 | * {@link org.java_websocket.framing.CloseFrame}.
358 | * @param reason an additional information.
359 | * @param remote Returns whether or not the closing of the connection was initiated by the remote
360 | * host.
361 | */
362 | @Override
363 | public void onClose(WebSocket conn, int code, String reason, boolean remote) {
364 | LOG.info(conn + " has left the room!");
365 | MetaInfoManager.ConnectionInfo connectionInfo = metaInfoManager.getConnectionInfo(conn);
366 | if (connectionInfo != null) {
367 | this.sendToClients(new ChatMessage(OutgoingMessage.MessageType.LEAVE,
368 | connectionInfo.getName(), connectionInfo.getRoom(), null));
369 | metaInfoManager.removeConnection(conn);
370 | if (! updateAndSendParticipantListQueue.contains(connectionInfo.getRoom())) {
371 | updateAndSendParticipantListQueue.add(connectionInfo.getRoom());
372 | }
373 | }
374 | }
375 |
376 | /**
377 | * Handles incoming messages.
378 | *
379 | * If the type of the incoming message is MessageType.ENTER, we need to check the username
380 | * against the current participant list and change the requested name with trailing underscores.
381 | * Regardless of the type, we invoke sendToClient method with every incoming messages.
382 | *
383 | * @param conn a websocket connection object.
384 | * @param rawMessage a raw message from the clients.
385 | */
386 | @Override
387 | public void onMessage(WebSocket conn, String rawMessage) {
388 | // TODO: Make it threadsafe
389 | LOG.info(conn + ": " + rawMessage);
390 | ApiProxy.setEnvironmentForCurrentThread(
391 | ChatServerBridge.getInstance().getBackgroundEnvironment());
392 | ChatMessage message = GSON.fromJson(rawMessage, ChatMessage.class);
393 | if (message.getType().equals(OutgoingMessage.MessageType.ENTER)) {
394 | // Check if there's a participant with the same name in the room.
395 | Set participantSet = ChatRoomParticipants.getParticipants(message.getRoom());
396 | if (participantSet.contains(message.getName())) {
397 | // Adding a trailing underscore until the conflict resolves.
398 | String newName = message.getName() + "_";
399 | while (participantSet.contains(newName)) {
400 | newName = newName + "_";
401 | }
402 | // New name decided.
403 | message = new ChatMessage(message.getType(), newName, message.getRoom(),
404 | message.getMessage());
405 | ChatMessage systemMessage = new ChatMessage(OutgoingMessage.MessageType.SYSTEM, newName,
406 | message.getRoom(), "Changed the name to " + newName + ".");
407 | conn.send(GSON.toJson(systemMessage));
408 | }
409 | metaInfoManager.addConnection(conn, message.getName(), message.getRoom());
410 | if (! updateAndSendParticipantListQueue.contains(message.getRoom())) {
411 | updateAndSendParticipantListQueue.add(message.getRoom());
412 | }
413 | }
414 | this.sendToClients(message);
415 | }
416 |
417 | /**
418 | * Just logs the exception.
419 | * @param conn a websocket connection object.
420 | * @param ex an exception.
421 | */
422 | @Override
423 | public void onError(WebSocket conn, Exception ex) {
424 | LOG.warning(Throwables.getStackTraceAsString(ex));
425 | }
426 |
427 | /**
428 | * Sends message to currently connected WebSocket clients in the same room as the
429 | * message.
430 | *
431 | * @param message An object representing a message to send across the network.
432 | */
433 | public void sendToClients(OutgoingMessage message) {
434 | if (! message.getType().equals(OutgoingMessage.MessageType.PROPAGATE)) {
435 | propagateQueue.add(message);
436 | } else {
437 | ParticipantListMessage participantListMessage = GSON.fromJson(message.toJson(GSON),
438 | ParticipantListMessage.class);
439 | if (participantListMessage.getType().equals(OutgoingMessage.MessageType.PARTICIPANTS)) {
440 | LOG.info("ParticipantList arrived for the room:" + message.getRoom());
441 | }
442 | }
443 | Collection webSocketConnections = connections();
444 | synchronized (webSocketConnections) {
445 | for (WebSocket connection : webSocketConnections) {
446 | MetaInfoManager.ConnectionInfo info = metaInfoManager.getConnectionInfo(connection);
447 | if (info != null) {
448 | if (message.shouldSendTo(info.getRoom())) {
449 | connection.send(message.toJson(GSON));
450 | }
451 | }
452 | }
453 | }
454 | }
455 | }
--------------------------------------------------------------------------------
/src/main/java/com/google/appengine/demos/websocketchat/server/ChatSocketServerShutdownHook.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2013 Google Inc. All Rights Reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you
5 | * may not use this file except in compliance with the License. You may
6 | * obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
13 | * implied. See the License for the specific language governing
14 | * permissions and limitations under the License.
15 | */
16 |
17 | package com.google.appengine.demos.websocketchat.server;
18 |
19 | import com.google.appengine.api.LifecycleManager.ShutdownHook;
20 | import com.google.appengine.api.NamespaceManager;
21 | import com.google.appengine.api.utils.SystemProperty;
22 |
23 | import java.util.logging.Logger;
24 |
25 | /**
26 | * An implementation for the ShutdownHook.
27 | *
28 | * @see
29 | * Backends Java API Overview#Shutdown
30 | */
31 | public class ChatSocketServerShutdownHook implements ShutdownHook{
32 |
33 | private static final Logger LOG = Logger.getLogger(ShutdownHook.class.getName());
34 |
35 | @Override
36 | public void shutdown() {
37 | LOG.info("The ChatSocketServerShutdownHook is called.");
38 | String version = SystemProperty.applicationVersion.get();
39 | String majorVersion = version.substring(0, version.indexOf('.'));
40 | NamespaceManager.set(majorVersion);
41 | LOG.info("Namespace set to " + majorVersion);
42 | ChatSocketServer.ChatServerBridge chatServerBridge =
43 | ChatSocketServer.ChatServerBridge.getInstance();
44 | chatServerBridge.stop();
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/src/main/java/com/google/appengine/demos/websocketchat/server/MetaInfoManager.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2013 Google Inc. All Rights Reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you
5 | * may not use this file except in compliance with the License. You may
6 | * obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
13 | * implied. See the License for the specific language governing
14 | * permissions and limitations under the License.
15 | */
16 |
17 | package com.google.appengine.demos.websocketchat.server;
18 |
19 | import com.google.common.collect.ImmutableSet;
20 | import org.java_websocket.WebSocket;
21 |
22 | import java.util.Map;
23 | import java.util.Set;
24 | import java.util.TreeSet;
25 | import java.util.concurrent.ConcurrentHashMap;
26 | import java.util.concurrent.ConcurrentMap;
27 |
28 | /**
29 | * A class that manages connections from the clients.
30 | */
31 | public class MetaInfoManager {
32 |
33 | /**
34 | * A class that holds the name of the participant and the name of the chat room.
35 | */
36 | public class ConnectionInfo {
37 |
38 | private String name;
39 |
40 | private String room;
41 |
42 | /**
43 | * Creates a ConnectionInfo instance with the given name and room.
44 | *
45 | * @param name a name of the participant.
46 | * @param room a name of the chat room.
47 | */
48 | ConnectionInfo(String name, String room) {
49 | this.name = name;
50 | this.room = room;
51 | }
52 |
53 | /**
54 | * Returns a name of the participant.
55 | *
56 | * @return a name of the participant.
57 | */
58 | public String getName() {
59 | return name;
60 | }
61 |
62 | /**
63 | * Returns a name of the chat room.
64 | *
65 | * @return a name of the chat room.
66 | */
67 | public String getRoom() {
68 | return room;
69 | }
70 | }
71 |
72 | private static final Set EMPTY_PARTICIPANT_SET = ImmutableSet.of();
73 |
74 | private static String createIdFromConnection(WebSocket connection) {
75 | return connection.getRemoteSocketAddress().getAddress().getHostAddress() + ":"
76 | + connection.getRemoteSocketAddress().getPort();
77 | }
78 |
79 | private Map connectionMap;
80 |
81 | private Map> participantMap;
82 |
83 | /**
84 | * Creates a MetaInfoManager with the initialized map objects.
85 | */
86 | public MetaInfoManager() {
87 | connectionMap = new ConcurrentHashMap<>();
88 | participantMap = new ConcurrentHashMap<>();
89 | }
90 |
91 | /**
92 | * Returns a set of the names of the participants in a given chat room.
93 | *
94 | * @param room a name of the chat room.
95 | * @return a set of the names of the participants in a given chat room.
96 | */
97 | public Set getParticipantList(String room) {
98 | if (participantMap.containsKey(room)) {
99 | return participantMap.get(room);
100 | } else {
101 | return EMPTY_PARTICIPANT_SET;
102 | }
103 | }
104 |
105 | /**
106 | * Adds a map entry to the participantMap property with a connection identifier as the key and
107 | * ConnectionInfo with the given name and room as the value.
108 | *
109 | * @param connection a websocket connection object.
110 | * @param name a name of the participant.
111 | * @param room a name of the chatroom.
112 | */
113 | public void addConnection(WebSocket connection, String name, String room) {
114 | connectionMap.put(createIdFromConnection(connection), new ConnectionInfo(name, room));
115 | if (! participantMap.containsKey(room)) {
116 | participantMap.put(room, new TreeSet());
117 | }
118 | participantMap.get(room).add(name);
119 | }
120 |
121 | /**
122 | * Returns a ConnectionInfo object corresponding to a given websocket connection.
123 | * @param connection a websocket connection object.
124 | * @return a ConnectionInfo object corresponding to a given websocket connection.
125 | */
126 | public ConnectionInfo getConnectionInfo(WebSocket connection) {
127 | return connectionMap.get(createIdFromConnection(connection));
128 | }
129 |
130 | /**
131 | * Removes a ConnectionInfo associated to a given websocket connection.
132 | *
133 | * @param connection a websocket connection object.
134 | */
135 | public void removeConnection(WebSocket connection) {
136 | ConnectionInfo connectionInfo = getConnectionInfo(connection);
137 | if (participantMap.containsKey(connectionInfo.getRoom())) {
138 | participantMap.get(connectionInfo.getRoom()).remove(connectionInfo.getName());
139 | }
140 | connectionMap.remove(createIdFromConnection(connection));
141 | }
142 | }
143 |
--------------------------------------------------------------------------------
/src/main/java/com/google/appengine/demos/websocketchat/servlet/StartupServlet.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2013 Google Inc. All Rights Reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you
5 | * may not use this file except in compliance with the License. You may
6 | * obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
13 | * implied. See the License for the specific language governing
14 | * permissions and limitations under the License.
15 | */
16 |
17 | package com.google.appengine.demos.websocketchat.servlet;
18 |
19 | import com.google.appengine.api.LifecycleManager;
20 | import com.google.appengine.api.NamespaceManager;
21 | import com.google.appengine.api.utils.SystemProperty;
22 | import com.google.appengine.demos.websocketchat.domain.ChatRoomParticipants;
23 | import com.google.appengine.demos.websocketchat.domain.WebSocketServerNode;
24 | import com.google.appengine.demos.websocketchat.server.ChatSocketServer;
25 | import com.google.appengine.demos.websocketchat.server.ChatSocketServerShutdownHook;
26 | import com.googlecode.objectify.ObjectifyService;
27 |
28 | import javax.servlet.ServletException;
29 | import javax.servlet.http.HttpServlet;
30 | import javax.servlet.http.HttpServletRequest;
31 | import javax.servlet.http.HttpServletResponse;
32 | import java.io.IOException;
33 | import java.util.logging.Logger;
34 |
35 | /**
36 | * A servlet that is called when accesing /_ah/start.
37 | */
38 | public class StartupServlet extends HttpServlet {
39 |
40 | private static final Logger LOG = Logger.getLogger(StartupServlet.class.getName());
41 |
42 | static {
43 | ObjectifyService.register(WebSocketServerNode.class);
44 | ObjectifyService.register(ChatRoomParticipants.class);
45 | LOG.info("The startup servlet called.");
46 | LifecycleManager.getInstance().setShutdownHook(new ChatSocketServerShutdownHook());
47 | String version = SystemProperty.applicationVersion.get();
48 | String majorVersion = version.substring(0, version.indexOf('.'));
49 | NamespaceManager.set(majorVersion);
50 | LOG.info("Namespace set to " + majorVersion);
51 | ChatSocketServer.ChatServerBridge chatServerBridge =
52 | ChatSocketServer.ChatServerBridge.getInstance();
53 | chatServerBridge.start();
54 | }
55 |
56 | protected void doGet(HttpServletRequest request, HttpServletResponse response)
57 | throws ServletException, IOException {
58 | response.setStatus(204);
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/src/main/java/com/google/appengine/demos/websocketchat/servlet/StopServlet.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2013 Google Inc. All Rights Reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you
5 | * may not use this file except in compliance with the License. You may
6 | * obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
13 | * implied. See the License for the specific language governing
14 | * permissions and limitations under the License.
15 | */
16 |
17 | package com.google.appengine.demos.websocketchat.servlet;
18 |
19 | import com.google.appengine.demos.websocketchat.server.ChatSocketServerShutdownHook;
20 |
21 | import javax.servlet.ServletException;
22 | import javax.servlet.http.HttpServlet;
23 | import javax.servlet.http.HttpServletRequest;
24 | import javax.servlet.http.HttpServletResponse;
25 | import java.io.IOException;
26 | import java.util.logging.Logger;
27 |
28 | /**
29 | * A Servlet called when accessing /_ah/stop.
30 | */
31 | public class StopServlet extends HttpServlet {
32 |
33 | private static final Logger LOG = Logger.getLogger(StopServlet.class.getName());
34 |
35 | protected void doGet(HttpServletRequest request, HttpServletResponse response)
36 | throws ServletException, IOException {
37 | LOG.info("The stop servlet called.");
38 | new ChatSocketServerShutdownHook().shutdown();
39 | response.setStatus(204);
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/src/main/webapp/WEB-INF/appengine-web.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
19 | true
20 | true
21 |
22 |
23 |
24 |
25 |
26 | 3
27 |
28 |
29 | true
30 | false
31 |
32 |
33 |
34 |
35 |
--------------------------------------------------------------------------------
/src/main/webapp/WEB-INF/logging.properties:
--------------------------------------------------------------------------------
1 | #
2 | # Copyright (c) 2013 Google Inc. All Rights Reserved.
3 | #
4 | # Licensed under the Apache License, Version 2.0 (the "License"); you
5 | # may not use this file except in compliance with the License. You may
6 | # obtain a copy of the License at
7 | #
8 | # http://www.apache.org/licenses/LICENSE-2.0
9 | #
10 | # Unless required by applicable law or agreed to in writing, software
11 | # distributed under the License is distributed on an "AS IS" BASIS,
12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
13 | # implied. See the License for the specific language governing
14 | # permissions and limitations under the License.
15 | #
16 |
17 | # A default java.util.logging configuration.
18 | # (All App Engine logging is through java.util.logging by default).
19 | #
20 | # To use this configuration, copy it into your application's WEB-INF
21 | # folder and add the following to your appengine-web.xml:
22 | #
23 | #
24 | #
25 | #
26 | #
27 |
28 | # Set the default logging level for all loggers to INFO
29 | .level = INFO
30 |
--------------------------------------------------------------------------------
/src/main/webapp/WEB-INF/web.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
23 |
24 |
25 | /*
26 |
27 |
28 | *
29 |
30 |
31 |
32 | startup
33 | com.google.appengine.demos.websocketchat.servlet.StartupServlet
34 |
35 | 0
36 |
37 |
38 | startup
39 | /_ah/start
40 |
41 |
42 | stop
43 | com.google.appengine.demos.websocketchat.servlet.StopServlet
44 |
45 |
46 | stop
47 | /_ah/stop
48 |
49 |
50 | ObjectifyFilter
51 | com.googlecode.objectify.ObjectifyFilter
52 |
53 |
54 | ObjectifyFilter
55 | /*
56 |
57 |
58 | chat.jsp
59 |
60 |
61 |
62 | top
63 | /
64 |
65 |
66 | *
67 |
68 |
69 |
70 |
--------------------------------------------------------------------------------
/src/main/webapp/chat.jsp:
--------------------------------------------------------------------------------
1 | <%@ page contentType="text/html;charset=UTF-8" language="java" %>
2 | <%@ page import="com.google.appengine.api.users.User" %>
3 | <%@ page import="com.google.appengine.api.users.UserService" %>
4 | <%@ page import="com.google.appengine.api.users.UserServiceFactory" %>
5 | <%@ page import="com.google.appengine.demos.websocketchat.server.ChatSocketServer" %>
6 |
7 | <%--
8 | ~ Copyright (c) 2013 Google Inc. All Rights Reserved.
9 | ~
10 | ~ Licensed under the Apache License, Version 2.0 (the "License"); you
11 | ~ may not use this file except in compliance with the License. You may
12 | ~ obtain a copy of the License at
13 | ~
14 | ~ http://www.apache.org/licenses/LICENSE-2.0
15 | ~
16 | ~ Unless required by applicable law or agreed to in writing, software
17 | ~ distributed under the License is distributed on an "AS IS" BASIS,
18 | ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
19 | ~ implied. See the License for the specific language governing
20 | ~ permissions and limitations under the License.
21 | --%>
22 |
23 | <%
24 | UserService userService = UserServiceFactory.getUserService();
25 | User user = userService.getCurrentUser();
26 | String webSocketURL = ChatSocketServer.ChatServerBridge.getInstance().getWebSocketURL();
27 | %>
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
WebSocket chat on App Engine VM Runtime
44 | Name:
45 | Room:
46 |
47 |
48 |
49 |
52 |
53 |
54 |
Participants:
55 |
56 |
57 |
58 |
59 |
163 |
164 |
--------------------------------------------------------------------------------
/src/main/webapp/stylesheets/main.css:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2013 Google Inc. All Rights Reserved.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License"); you
5 | * may not use this file except in compliance with the License. You may
6 | * obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
13 | * implied. See the License for the specific language governing
14 | * permissions and limitations under the License.
15 | */
16 |
17 | body, html {
18 | font-family: 'Marmelad', sans-serif;
19 | background-color: #FFFFFF;
20 | padding: 0;
21 | margin: 0;
22 | height: 100%;
23 | }
24 |
25 | input {
26 | padding: .2em .3em;
27 | display: inline-block;
28 | border: 1px solid #ccc;
29 | font-size: .8em;
30 | box-shadow: inset 0 1px 3px #ddd;
31 | border-radius: 4px;
32 | -webkit-transition: .3s linear border;
33 | -moz-transition: .3s linear border;
34 | -ms-transition: .3s linear border;
35 | -o-transition: .3s linear border;
36 | transition: .3s linear border;
37 | -moz-box-sizing: border-box;
38 | -webkit-box-sizing: border-box;
39 | box-sizing: border-box;
40 | -webkit-font-smoothing: antialiased;
41 | }
42 |
43 | h2 {
44 | margin: 0;
45 | }
46 |
47 | #header {
48 | height: 99px;
49 | border-top: 1px solid #FFFFFF;
50 | border-left: 1px solid #FFFFFF;
51 | border-right: 1px solid #FFFFFF;
52 | }
53 |
54 | #header h2 {
55 | margin: 4px;
56 | }
57 |
58 | #container {
59 | width: 100%;
60 | padding: 0;
61 | margin: 0 auto;
62 | background-color: #0e90d2;
63 | height: calc(100% - 102px);
64 | height: -moz-calc(100% - 102px);
65 | height: -webkit-calc(100% - 102px);
66 | }
67 |
68 | #participants {
69 | background: #dd514c;
70 | float: left;
71 | width: 149px;
72 | height: 100%;
73 | overflow: auto;
74 | border-top: 1px solid #FFFFFF;
75 | border-left: 1px solid #FFFFFF;
76 | border-bottom: 1px solid #FFFFFF;
77 | }
78 |
79 | #participants p {
80 | margin: 2px;
81 | }
82 |
83 | #messages {
84 | background: #5eb95e;;
85 | float: right;
86 | width: calc(100% - 152px);
87 | width: -moz-calc(100% - 152px);
88 | width: -webkit-calc(100% - 152px);
89 | height: 100%;
90 | overflow: auto;
91 | border: 1px solid #FFFFFF;
92 | }
93 |
94 | #messages p {
95 | margin: 2px;
96 | }
97 |
98 | .system {
99 | font-style: italic;
100 | color: #dd514c;
101 | }
102 |
--------------------------------------------------------------------------------