Skip to content

Add endpoints sample. #248

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

Merged
merged 7 commits into from
Jun 23, 2016
Merged
Show file tree
Hide file tree
Changes from all 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
8 changes: 8 additions & 0 deletions managed_vms/endpoints/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Google Cloud Endpoints on App Engine flexible environment
This sample demonstrates how to use Google Cloud Endpoints on Google App Engine Flexible Environment using Java.

Copy link
Contributor

Choose a reason for hiding this comment

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

Should mention where you need to edit to make this work.

## Running locally
$ mvn jetty:run

## Deploying
$ mvn gcloud:deploy
68 changes: 68 additions & 0 deletions managed_vms/endpoints/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
Copy link
Contributor

Choose a reason for hiding this comment

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

nit. We've been adding license headers to new pom.xml files (has to appear after <?xml ...> line.

Also, the XML attributes to the <project> tag are optional, so we've been leaving them out.

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<groupId>com.example.managedvms</groupId>
<artifactId>managed-vms-endpoints</artifactId>

<parent>
<artifactId>doc-samples</artifactId>
<groupId>com.google.cloud</groupId>
<version>1.0.0</version>
<relativePath>../..</relativePath>
</parent>

<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<type>jar</type>
<scope>provided</scope>
</dependency>
<!-- Gson: Java to Json conversion -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.6.2</version>
<scope>compile</scope>
</dependency>
</dependencies>

<build>
<!-- for hot reload of the web application -->
<outputDirectory>${project.build.directory}/${project.build.finalName}/WEB-INF/classes</outputDirectory>
<plugins>
<plugin>
<groupId>com.google.appengine</groupId>
<artifactId>gcloud-maven-plugin</artifactId>
<version>2.0.9.111.v20160527</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<version>3.3</version>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
Copy link
Contributor

Choose a reason for hiding this comment

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

Didn't want Java 8?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Copied directly from the hello world app.

Copy link
Contributor

Choose a reason for hiding this comment

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

Okay. Java 7 is fine. Might as well use it until you need a Java 8 feature.

Copy link
Contributor

Choose a reason for hiding this comment

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

No - s.b. Java8 for this.

<target>1.7</target>
</configuration>
</plugin>
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.3.8.v20160314</version>
</plugin>
</plugins>
</build>
</project>
3 changes: 3 additions & 0 deletions managed_vms/endpoints/src/main/appengine/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
FROM gcr.io/google_appengine/jetty9

ADD . /app
13 changes: 13 additions & 0 deletions managed_vms/endpoints/src/main/appengine/app.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
runtime: custom
vm: true

handlers:
- url: /.*
script: this field is required, but ignored
secure: always

beta_settings:
# Enable Google Cloud Endpoints API management.
use_endpoints_api_management: true
# Specify the Swagger API specification.
endpoints_swagger_spec_file: swagger.yaml
106 changes: 106 additions & 0 deletions managed_vms/endpoints/src/main/appengine/swagger.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
swagger: "2.0"
Copy link
Contributor

Choose a reason for hiding this comment

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

License header?

Copy link
Contributor

Choose a reason for hiding this comment

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

Should also mention all the places you need to edit to make it work.

host, YOUR-CLIENT-ID, etc.

info:
description: "A simple Google Cloud Endpoints API example."
title: "Endpoints Example"
version: "1.0.0"
host: "YOUR-PROJECT-ID.appspot.com"
basePath: "/"
consumes:
- "application/json"
produces:
- "application/json"
schemes:
- "https"
paths:
"/echo":
post:
description: "Echo back a given message."
operationId: "echo"
produces:
- "application/json"
responses:
200:
description: "Echo"
schema:
$ref: "#/definitions/echoMessage"
parameters:
- description: "Message to echo"
in: body
name: message
required: true
schema:
$ref: "#/definitions/echoMessage"
"/auth/info/googlejwt":
get:
description: "Returns the requests' authentication information."
operationId: "auth_info_google_jwt"
produces:
- "application/json"
responses:
200:
description: "Authenication info."
schema:
$ref: "#/definitions/authInfoResponse"
x-security:
- google_jwt:
audiences:
# This must match the "aud" field in the JWT. You can add multiple
# audiences to accept JWTs from multiple clients.
Copy link
Contributor

Choose a reason for hiding this comment

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

Is this a JWT? https://jwt.io/ I'd like a link to a description of these in the Javadoc for the related servlet, since that seems like what they are outputting.

- "echo.endpoints.sample.google.com"
"/auth/info/googleidtoken":
get:
description: "Returns the requests' authentication information."
operationId: "authInfoGoogleIdToken"
produces:
- "application/json"
responses:
200:
description: "Authenication info."
schema:
$ref: "#/definitions/authInfoResponse"
x-security:
- google_id_token:
audiences:
# Your OAuth2 client's Client ID must be added here. You can add
# multiple client IDs to accept tokens from multiple clients.
- "YOUR-CLIENT-ID"
definitions:
echoMessage:
properties:
message:
type: "string"
authInfoResponse:
properties:
id:
type: "string"
email:
type: "string"
# This section requires all requests to any path to require an API key.
security:
- api_key: []
securityDefinitions:
# This section configures basic authentication with an API key.
api_key:
type: "apiKey"
name: "key"
in: "query"
# This section configures authentication using Google API Service Accounts
# to sign a json web token. This is mostly used for server-to-server
# communication.
google_jwt:
authorizationUrl: ""
flow: "implicit"
type: "oauth2"
# This must match the 'iss' field in the JWT.
x-issuer: "jwt-client.endpoints.sample.google.com"
# Update this with your service account's email address.
x-jwks_uri: "https://www.googleapis.com/service_accounts/v1/jwk/YOUR-SERVICE-ACCOUNT-EMAIL"
# This section configures authentication using Google OAuth2 ID Tokens.
# ID Tokens can be obtained using OAuth2 clients, and can be used to access
# your API on behalf of a particular user.
google_id_token:
authorizationUrl: ""
flow: "implicit"
type: "oauth2"
x-issuer: "accounts.google.com"
x-jwks_uri: "https://www.googleapis.com/oauth2/v1/certs"
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/**
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example.managedvms.endpoints;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Base64;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.google.gson.JsonObject;

/**
* A servlet that returns authentication information.
* See swagger.yaml for authentication mechanisms (e.g. JWT tokens, Google ID token).
Copy link
Contributor

Choose a reason for hiding this comment

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

Better. Is this a swagger thing or an endpoints thing? Either way could we link to the documentation describing these mechanisms and what kind of tokens this is expected to output?

Copy link
Contributor

Choose a reason for hiding this comment

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

Maybe add a link to the endpoints docs describing the X-Endpoint-API-UserInfo header? Also is the output always one of these? https://jwt.io/ Maybe link to that, too.

*/
@WebServlet("/auth/info/*")
public class AuthInfoServlet extends HttpServlet {
Copy link
Contributor

Choose a reason for hiding this comment

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

It's not 100% clear to me what the purpose of this servlet is. It takes some user info from a header and returns it in the response?

Adding a JavaDoc describing what this does and why it is needed would be helpful.


@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String encodedInfo = req.getHeader("X-Endpoint-API-UserInfo");
Copy link
Contributor

Choose a reason for hiding this comment

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

Javadoc of what this does? or pointer to the list of expected headers, and why they are there?

if (encodedInfo == null || encodedInfo == "") {
JsonObject anon = new JsonObject();
anon.addProperty("id", "anonymous");
new Gson().toJson(anon, resp.getWriter());
return;
}

try {
byte[] authInfo = Base64.getDecoder().decode(encodedInfo);
resp.getOutputStream().write(authInfo);
} catch (IllegalArgumentException iae) {
resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
JsonObject error = new JsonObject();
error.addProperty("code", HttpServletResponse.SC_BAD_REQUEST);
error.addProperty("message", "Could not decode auth info.");
new Gson().toJson(error, resp.getWriter());
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/**
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example.managedvms.endpoints;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.stream.JsonReader;

/**
* A servlet that echoes JSON message bodies.
*/
@WebServlet("/echo")
public class EchoServlet extends HttpServlet {

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.addHeader("Content-Encoding", "application/json");

Object responseBody;
try {
JsonReader jsonReader = new JsonReader(req.getReader());
responseBody = new Gson().fromJson(jsonReader, Map.class);
} catch (JsonParseException je) {
resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
JsonObject error = new JsonObject();
error.addProperty("code", HttpServletResponse.SC_BAD_REQUEST);
error.addProperty("message", "Body was not valid JSON.");
responseBody = error;
}

new Gson().toJson(responseBody, resp.getWriter());
}
}