Skip to content

Commit 102e868

Browse files
committed
add the standard HelloWorld sample app as a gradle subproject. fixes #14
1 parent b92dc51 commit 102e868

File tree

9 files changed

+408
-44
lines changed

9 files changed

+408
-44
lines changed

sample/HelloWorld/README.md

Lines changed: 225 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,225 @@
1+
# OpenTok Hello World Java
2+
3+
This is a simple demo app that shows how you can use the OpenTok Java SDK to create Sessions,
4+
generate Tokens with those Sessions, and then pass these values to a JavaScript client that can
5+
connect and conduct a group chat.
6+
7+
## Running the App
8+
9+
First, add your own API Key and API Secret to the system properties. For your convenience, the
10+
`build.gradle` file is set up for you to place your values into it.
11+
12+
```
13+
run.systemProperty 'API_KEY', '000000'
14+
run.systemProperty 'API_SECRET', 'abcdef1234567890abcdef01234567890abcdef'
15+
```
16+
17+
Next, start the server using Gradle (which handles dependencies and setting up the environment).
18+
19+
```
20+
$ gradle :sample/HelloWorld:run
21+
```
22+
23+
Or if you are using the Gradle Wrapper that is distributed with the project:
24+
25+
```
26+
$ ./gradlew :sample/HelloWorld:run
27+
```
28+
29+
Visit <http://localhost:4567> in your browser. Open it again in a second window. Smile! You've just
30+
set up a group chat.
31+
32+
## Walkthrough
33+
34+
This demo application uses the [Spark micro web framework](http://www.sparkjava.com/). It is similar to
35+
many other popular web frameworks. We are only covering the very basics of the framework, but you can
36+
learn more by following the link above.
37+
38+
### Main Application (src/main/java/com/example/HelloWorldServer.java)
39+
40+
The first thing done in this file is to import the dependencies we will be using. In this case that
41+
is the Spark web framework, a couple collection classes, and most importantly some classes from the
42+
OpenTok SDK.
43+
44+
```java
45+
import static spark.Spark.*;
46+
import spark.*;
47+
48+
import java.util.Map;
49+
import java.util.HashMap;
50+
51+
import com.opentok.OpenTok;
52+
import com.opentok.exception.OpenTokException;
53+
```
54+
55+
Next, we set up a main class for the application.
56+
57+
```java
58+
public class HelloWorldServer {
59+
60+
// We will set up some class variables here
61+
62+
public static void main(String[] args) throws OpenTokException {
63+
// The application will start here
64+
}
65+
}
66+
```
67+
68+
Next this application performs some basic checks on the environment. If it cannot find the `API_KEY`and
69+
`API_SECRET` system properties, there is no point in continuing.
70+
71+
72+
```java
73+
public class HelloWorldServer {
74+
75+
private static final String apiKey = System.getProperty("API_KEY");
76+
private static final String apiSecret = System.getProperty("API_SECRET");
77+
78+
public static void main(String[] args) throws OpenTokException {
79+
80+
if (apiKey == null || apiKey.isEmpty() || apiSecret == null || apiSecret.isEmpty()) {
81+
System.out.println("You must define API_KEY and API_SECRET system properties in the build.gradle file.");
82+
System.exit(-1);
83+
}
84+
85+
}
86+
}
87+
```
88+
89+
The first thing the application does is to initialize an instance of `OpenTok` and store it as
90+
a static class variable.
91+
92+
```java
93+
public class HelloWorldServer {
94+
95+
// ...
96+
private static final OpenTok opentok = new OpenTok(Integer.parseInt(apiKey), apiSecret);
97+
98+
public static void main(String[] args) throws OpenTokException {
99+
// ...
100+
}
101+
}
102+
```
103+
104+
Now, lets discuss the Hello World application's functionality. We want to set up a group chat so
105+
that any client that visits a page will connect to the same OpenTok Session. Once they are connected
106+
they can Publish a Stream and Subscribe to all the other streams in that Session. So we just need
107+
one Session object, and it needs to be accessible every time a request is made. The next line of our
108+
application simply calls the `OpenTok` instance's `createSession()` method and pulls out the
109+
`String sessionId` using the `getSessionId()` method on the resulting `Session` instance. This is
110+
stored in another class variable. Alternatively, `sessionId`s are commonly stored in databses for
111+
applications that have many of them.
112+
113+
```java
114+
public class HelloWorldServer {
115+
116+
// ...
117+
private static String sessionId;
118+
119+
public static void main(String[] args) throws OpenTokException {
120+
// ...
121+
122+
sessionId = opentok.createSession().getSessionId();
123+
}
124+
}
125+
```
126+
127+
Spark uses the `externalStaticFileLocation()` method to specify which directory to serve static
128+
files from.
129+
130+
```java
131+
public class HelloWorldServer {
132+
133+
// ...
134+
135+
public static void main(String[] args) throws OpenTokException {
136+
// ...
137+
138+
externalStaticFileLocation("./public");
139+
}
140+
}
141+
```
142+
143+
We only need one page, so we create one route handler for any HTTP GET requests to trigger.
144+
145+
```java
146+
public class HelloWorldServer {
147+
148+
// ...
149+
150+
public static void main(String[] args) throws OpenTokException {
151+
// ...
152+
153+
get(new FreeMarkerTemplateView("/") {
154+
@Override
155+
public ModelAndView handle(Request request, Response response) {
156+
157+
// This is where we handle the request and are responsible for returning a response
158+
159+
}
160+
});
161+
162+
}
163+
}
164+
165+
```
166+
167+
Now all we have to do is serve a page with the three values the client will need to connect to the
168+
session: `apiKey`, `sessionId`, and `token`. The first two are available as class variables. The
169+
`token` is generated freshly on this request by calling `opentok.generateToken()`, and passing in
170+
the `sessionId`. This is because a Token is a piece of information that carries a specific client's
171+
permissions in a certain Session. Ideally, as we've done here, you generate a unique token for each
172+
client that will connect.
173+
174+
```java
175+
get(new FreeMarkerTemplateView("/") {
176+
@Override
177+
public ModelAndView handle(Request request, Response response) {
178+
179+
String token = null;
180+
try {
181+
token = opentok.generateToken(sessionId);
182+
} catch (OpenTokException e) {
183+
e.printStackTrace();
184+
}
185+
186+
// Now we have apiKey, sessionId, and token
187+
188+
}
189+
});
190+
```
191+
192+
Now all we have to do is serve a page with those three values. To do so, we put together a Map of
193+
values that our template system (freemarker) will use to render an HTML page. This is done by
194+
returning an instance of `ModelAndView` that groups this map with the name of a view.
195+
196+
```java
197+
get(new FreeMarkerTemplateView("/") {
198+
@Override
199+
public ModelAndView handle(Request request, Response response) {
200+
// ...
201+
202+
Map<String, Object> attributes = new HashMap<String, Object>();
203+
attributes.put("apiKey", apiKey);
204+
attributes.put("sessionId", sessionId);
205+
attributes.put("token", token);
206+
207+
return new ModelAndView(attributes, "index.ftl");
208+
}
209+
});
210+
```
211+
212+
### Main Template (src/main/resources/com/example/freemarker/index.ftl)
213+
214+
This file simply sets up the HTML page for the JavaScript application to run, imports the
215+
JavaScript library, and passes the values created by the server into the JavaScript application
216+
inside `public/js/helloworld.js`
217+
218+
### JavaScript Applicaton (public/js/helloworld.js)
219+
220+
The group chat is mostly implemented in this file. At a high level, we connect to the given
221+
Session, publish a stream from our webcam, and listen for new streams from other clients to
222+
subscribe to.
223+
224+
For more details, read the comments in the file or go to the
225+
[JavaScript Client Library](http://tokbox.com/opentok/libraries/client/js/) for a full reference.

sample/HelloWorld/build.gradle

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
apply plugin:'application'
2+
mainClassName = "com.example.HelloWorldServer"
3+
4+
repositories {
5+
mavenCentral()
6+
}
7+
8+
dependencies {
9+
compile project(':')
10+
compile group: 'com.github.codingricky', name: 'spark-core-16', version: '1.1'
11+
compile group: 'org.freemarker', name: 'freemarker', version: '2.3.19'
12+
compile group: 'org.slf4j', name: 'slf4j-simple', version: '1.7.6'
13+
}
14+
15+
run.systemProperty 'API_KEY', '854511'
16+
run.systemProperty 'API_SECRET', '93936990b97ffede04378028766bdc1755562cce'
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
// Initialize an OpenTok Session object
2+
var session = TB.initSession(sessionId);
3+
4+
// Initialize a Publisher, and place it into the element with id="publisher"
5+
var publisher = TB.initPublisher(apiKey, 'publisher');
6+
7+
// Attach event handlers
8+
session.on({
9+
10+
// This function runs when session.connect() asynchronously completes
11+
sessionConnected: function(event) {
12+
// Publish the publisher we initialzed earlier (this will trigger 'streamCreated' on other
13+
// clients)
14+
session.publish(publisher);
15+
},
16+
17+
// This function runs when another client publishes a stream (eg. session.publish())
18+
streamCreated: function(event) {
19+
// Create a container for a new Subscriber, assign it an id using the streamId, put it inside
20+
// the element with id="subscribers"
21+
var subContainer = document.createElement('div');
22+
subContainer.id = 'stream-' + event.stream.streamId;
23+
document.getElementById('subscribers').appendChild(subContainer);
24+
25+
// Subscribe to the stream that caused this event, put it inside the container we just made
26+
session.subscribe(event.stream, subContainer);
27+
}
28+
29+
});
30+
31+
// Connect to the Session using the 'apiKey' of the application and a 'token' for permission
32+
session.connect(apiKey, token);

sample/HelloWorld/public/test.html

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
<!doctype html>
2+
<html>
3+
<head lang="en">
4+
<meta charset="utf-8">
5+
</head>
6+
<body>
7+
<h1>Just a test, lets see if Spark serves this.</h1>
8+
</body>
9+
</html>
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package com.example;
2+
3+
/**
4+
* Created by ankur on 4/16/14.
5+
*/
6+
7+
import freemarker.template.Configuration;
8+
import freemarker.template.Template;
9+
import freemarker.template.TemplateException;
10+
import spark.ModelAndView;
11+
import spark.TemplateViewRoute;
12+
13+
import java.io.IOException;
14+
import java.io.StringWriter;
15+
16+
public abstract class FreeMarkerTemplateView extends TemplateViewRoute {
17+
18+
private Configuration configuration;
19+
20+
protected FreeMarkerTemplateView(String path) {
21+
super(path);
22+
this.configuration = createFreemarkerConfiguration();
23+
}
24+
25+
protected FreeMarkerTemplateView(String path, String acceptType) {
26+
super(path, acceptType);
27+
this.configuration = createFreemarkerConfiguration();
28+
}
29+
30+
@Override
31+
public String render(ModelAndView modelAndView) {
32+
try {
33+
StringWriter stringWriter = new StringWriter();
34+
35+
Template template = configuration.getTemplate(modelAndView.getViewName());
36+
template.process(modelAndView.getModel(), stringWriter);
37+
38+
return stringWriter.toString();
39+
40+
} catch (IOException e) {
41+
throw new IllegalArgumentException(e);
42+
} catch (TemplateException e) {
43+
throw new IllegalArgumentException(e);
44+
}
45+
}
46+
47+
private Configuration createFreemarkerConfiguration() {
48+
Configuration retVal = new Configuration();
49+
retVal.setClassForTemplateLoading(FreeMarkerTemplateView.class, "freemarker");
50+
return retVal;
51+
}
52+
53+
}
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package com.example;
2+
3+
import static spark.Spark.*;
4+
import spark.*;
5+
6+
import java.util.Map;
7+
import java.util.HashMap;
8+
9+
import com.opentok.OpenTok;
10+
import com.opentok.exception.OpenTokException;
11+
12+
public class HelloWorldServer {
13+
14+
private static final String apiKey = System.getProperty("API_KEY");
15+
private static final String apiSecret = System.getProperty("API_SECRET");
16+
private static final OpenTok opentok = new OpenTok(Integer.parseInt(apiKey), apiSecret);
17+
private static String sessionId;
18+
19+
public static void main(String[] args) throws OpenTokException {
20+
21+
if (apiKey == null || apiKey.isEmpty() || apiSecret == null || apiSecret.isEmpty()) {
22+
System.out.println("You must define API_KEY and API_SECRET system properties in the build.gradle file.");
23+
System.exit(-1);
24+
}
25+
26+
sessionId = opentok.createSession().getSessionId();
27+
28+
externalStaticFileLocation("./public");
29+
30+
get(new FreeMarkerTemplateView("/") {
31+
@Override
32+
public ModelAndView handle(Request request, Response response) {
33+
34+
String token = null;
35+
try {
36+
token = opentok.generateToken(sessionId);
37+
} catch (OpenTokException e) {
38+
e.printStackTrace();
39+
}
40+
41+
Map<String, Object> attributes = new HashMap<String, Object>();
42+
attributes.put("apiKey", apiKey);
43+
attributes.put("sessionId", sessionId);
44+
attributes.put("token", token);
45+
46+
return new ModelAndView(attributes, "index.ftl");
47+
}
48+
});
49+
50+
}
51+
}

0 commit comments

Comments
 (0)