Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

updating Firebase on App Engine sample to use latest libs #862

Merged
merged 3 commits into from
Sep 25, 2017
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 24 additions & 20 deletions appengine/firebase-tictactoe/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,11 @@ for realtime notifications when the board changes.
## Prerequisites

* Install [Apache Maven][maven] 3.0.5 or later
* Install the [Google Cloud SDK][sdk]
* Create a project in the [Firebase Console][fb-console]
* In the [Overview section][fb-overview] of the Firebase console, click 'Add
Firebase to your web app' and replace the contents of the file
`src/main/webapp/WEB-INF/view/firebase_config.jspf` with that code snippet.
* If using the development appserver to run the app locally, you must supply
credentials that would otherwise be inferred from the App Engine environment.
Download [service account credentials][creds] and set the
`GOOGLE_APPLICATION_CREDENTIALS` environment variable to its path:

export GOOGLE_APPLICATION_CREDENTIALS=/path/to/your/credentials.json
* [Enable the Identity API](https://console.cloud.google.com/apis/api/identitytoolkit.googleapis.com/overview)


[fb-console]: https://console.firebase.google.com
Expand All @@ -29,26 +23,36 @@ for realtime notifications when the board changes.
[fb-overview]: https://console.firebase.google.com/project/_/overview
[maven]: https://maven.apache.org

## Setup

* If you haven't already, Download and initialize the [Cloud SDK](https://cloud.google.com/sdk/)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't this be a Prerequisite?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

```
gcloud init
```
* If you haven't already, Create an App Engine app within the current Google Cloud Project
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Redundant phrase

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cleaned up

```
gcloud app create
```
* If you haven't already, setup
[Application Default Credentials](https://developers.google.com/identity/protocols/application-default-credentials)
to run your application locally:
Download [service account credentials][creds] and set the `GOOGLE_APPLICATION_CREDENTIALS`
environment variable to its path:
```
export GOOGLE_APPLICATION_CREDENTIALS=/path/to/your/credentials.json
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we have them set GOOGLE_CLOUD_PROJECT? Look at gcloud config to verify their project?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

given we still ask users to use gcloud init : added a note there that this sets the project.

```

## Run the sample

* To run the app locally using the development appserver:
### Running locally

```sh
$ mvn appengine:run
```

## Troubleshooting
When running locally, the page does not automatically refresh,
please reload the page manually after each move.

* If you see the error `Google Cloud SDK path was not provided ...`:
* Make sure you've installed the [Google Cloud SDK][sdk]
* Make sure the Google Cloud SDK's `bin/` directory is in your `PATH`. If
you prefer it not to be, you can also set the environment variable
`GOOGLE_CLOUD_SDK_HOME` to point to where you installed the SDK:
### Deploying to App Engine Standard

```sh
export GOOGLE_CLOUD_SDK_HOME=/path/to/google-cloud-sdk
```
$ mvn appengine:deploy

## Contributing changes

Expand Down
132 changes: 45 additions & 87 deletions appengine/firebase-tictactoe/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -25,92 +25,50 @@
<version>1.0.0</version>
<relativePath>..</relativePath>
</parent>
<properties>
<objectify.version>5.1.21</objectify.version>
<servlet-api.version>2.5</servlet-api.version>
<gson.version>2.7</gson.version>
<guava.version>20.0</guava.version>
<google-api-client.version>1.22.0</google-api-client.version>
<junit.version>4.12</junit.version>
<mockito.version>1.10.19</mockito.version>
<google-truth.version>0.35</google-truth.version>
<appengine-maven.version>1.3.1</appengine-maven.version>
</properties>
<!-- [START set_versions] -->
<!-- [END set_versions] -->
<dependencies>
<dependency>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-api-1.0-sdk</artifactId>
<version>${appengine.sdk.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${servlet-api.version}</version>
<type>jar</type>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.1</version>
</dependency>
<dependency>
<groupId>com.googlecode.objectify</groupId>
<artifactId>objectify</artifactId>
<version>${objectify.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>com.google.api-client</groupId>
<artifactId>google-api-client-appengine</artifactId>
<version>${google-api-client.version}</version>
</dependency>


<!-- Test Dependencies -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-testing</artifactId>
<version>${appengine.sdk.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-api-stubs</artifactId>
<version>${appengine.sdk.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-tools-sdk</artifactId>
<version>${appengine.sdk.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.truth</groupId>
<artifactId>truth</artifactId>
<version>${google-truth.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<dependencies>
<dependency>
<groupId>com.googlecode.objectify</groupId>
<artifactId>objectify</artifactId>
<version>5.1.21</version>
</dependency>
<dependency>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-api-1.0-sdk</artifactId>
<version>1.9.56</version>
</dependency>
<dependency>
<groupId>com.google.api-client</groupId>
<artifactId>google-api-client-appengine</artifactId>
<version>1.22.0</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.1</version>
</dependency>
<!-- Test dependences -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-api-stubs</artifactId>
<version>1.9.56</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-testing</artifactId>
<version>1.9.56</version>
</dependency>
</dependencies>
<build>
<!-- for hot reload of the web application -->
<outputDirectory>${project.build.directory}/${project.build.finalName}/WEB-INF/classes
Expand All @@ -119,7 +77,7 @@
<plugin>
<groupId>com.google.cloud.tools</groupId>
<artifactId>appengine-maven-plugin</artifactId>
<version>${appengine-maven.version}</version>
<version>1.3.1</version>
</plugin>
</plugins>
</build>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,6 @@ public void doPost(HttpServletRequest request, HttpServletResponse response)
String currentUserId = userService.getCurrentUser().getUserId();

// TODO(you): In practice, first validate that the user has permission to delete the Game
game.deleteChannel(currentUserId);
game.deleteChannel(getServletContext(), currentUserId);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,13 @@
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.util.Preconditions;
import com.google.appengine.api.appidentity.AppIdentityService;
import com.google.appengine.api.appidentity.AppIdentityServiceFactory;
import com.google.common.io.BaseEncoding;
import com.google.common.io.CharStreams;
import com.google.gson.Gson;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
Expand All @@ -39,6 +39,7 @@
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContext;

/**
* Utility functions for communicating with the realtime communication channel using Firebase.
Expand All @@ -47,7 +48,7 @@
* Firebase.
*/
public class FirebaseChannel {
private static final String FIREBASE_SNIPPET_PATH = "WEB-INF/view/firebase_config.jspf";
private static final String FIREBASE_SNIPPET_PATH = "/WEB-INF/view/firebase_config.jspf";
static InputStream firebaseConfigStream = null;
private static final Collection FIREBASE_SCOPES = Arrays.asList(
"https://www.googleapis.com/auth/firebase.database",
Expand All @@ -67,9 +68,9 @@ public class FirebaseChannel {
* FirebaseChannel is a singleton, since it's just utility functions.
* The class derives auth information when first instantiated.
*/
public static FirebaseChannel getInstance() {
public static FirebaseChannel getInstance(ServletContext servletContext) {
if (instance == null) {
instance = new FirebaseChannel();
instance = new FirebaseChannel(servletContext);
}
return instance;
}
Expand All @@ -81,11 +82,13 @@ public static FirebaseChannel getInstance() {
* communicate with Firebase is derived from App Engine's default credentials, and given
* Firebase's OAuth scopes.
*/
private FirebaseChannel() {
private FirebaseChannel(ServletContext servletContext) {
try {
// This variables exist primarily so it can be stubbed out in unit tests.
if (null == firebaseConfigStream) {
firebaseConfigStream = new FileInputStream(FIREBASE_SNIPPET_PATH);
Preconditions.checkNotNull(servletContext,
"Servlet context expected to initialize Firebase channel");
firebaseConfigStream = servletContext.getResourceAsStream(FIREBASE_SNIPPET_PATH);
}

String firebaseSnippet = CharStreams.toString(new InputStreamReader(
Expand Down Expand Up @@ -176,7 +179,6 @@ public String createFirebaseToken(Game game, String userId) {

// The following methods are to illustrate making various calls to Firebase from App Engine
// Standard

public HttpResponse firebasePut(String path, Object object) throws IOException {
// Make requests auth'ed using Application Default Credentials
Credential credential = GoogleCredential.getApplicationDefault().createScoped(FIREBASE_SCOPES);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,11 @@
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import javax.servlet.ServletContext;

/**
* The datastore-persisted Game object. This holds the entire game state - from a representation of
* the board, to the players are and whose turn it is, and who the winner is and how they won.
*
* It also contains some convenience functions for communicating updates to the board to the
* clients, via Firebase.
*/
Expand Down Expand Up @@ -109,26 +109,26 @@ public String getChannelKey(String userId) {
return userId + id;
}

public void deleteChannel(String userId)
public void deleteChannel(ServletContext servletContext, String userId)
throws IOException {
if (userId != null) {
String channelKey = getChannelKey(userId);
FirebaseChannel.getInstance().sendFirebaseMessage(channelKey, null);
FirebaseChannel.getInstance(servletContext).sendFirebaseMessage(channelKey, null);
}
}

private void sendUpdateToUser(String userId)
private void sendUpdateToUser(ServletContext servletContext, String userId)
throws IOException {
if (userId != null) {
String channelKey = getChannelKey(userId);
FirebaseChannel.getInstance().sendFirebaseMessage(channelKey, this);
FirebaseChannel.getInstance(servletContext).sendFirebaseMessage(channelKey, this);
}
}

public void sendUpdateToClients()
public void sendUpdateToClients(ServletContext servletContext)
throws IOException {
sendUpdateToUser(userX);
sendUpdateToUser(userO);
sendUpdateToUser(servletContext, userX);
sendUpdateToUser(servletContext, userO);
}
// [END send_updates]

Expand All @@ -152,7 +152,7 @@ public void checkWin() {
}
}

public boolean makeMove(int position, String userId) {
public boolean makeMove(ServletContext servletContext, int position, String userId) {
String currentMovePlayer;
char value;
if (getMoveX()) {
Expand All @@ -170,7 +170,7 @@ public boolean makeMove(int position, String userId) {
checkWin();
setMoveX(!getMoveX());
try {
sendUpdateToClients();
sendUpdateToClients(servletContext);
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "Error sending Game update to Firebase", e);
throw new RuntimeException(e);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public void doPost(HttpServletRequest request, HttpServletResponse response)
String currentUserId = userService.getCurrentUser().getUserId();

int cell = new Integer(request.getParameter("cell"));
if (!game.makeMove(cell, currentUserId)) {
if (!game.makeMove(getServletContext(), cell, currentUserId)) {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
} else {
ofy.save().entity(game).now();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example.appengine.firetactoe;

import com.googlecode.objectify.ObjectifyService;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,6 @@ public void doPost(HttpServletRequest request, HttpServletResponse response)
String gameId = request.getParameter("gameKey");
Objectify ofy = ObjectifyService.ofy();
Game game = ofy.load().type(Game.class).id(gameId).safe();
game.sendUpdateToClients();
game.sendUpdateToClients(getServletContext());
}
}
Loading