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

Add App Identity example to assert identity to Google APIs. #50

Merged
merged 3 commits into from
Jan 8, 2016
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
10 changes: 10 additions & 0 deletions appengine/appidentity/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,23 @@ Copyright 2015 Google Inc. All Rights Reserved.
<artifactId>appengine-api-1.0-sdk</artifactId>
<version>${appengine.target.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>19.0</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<type>jar</type>
<scope>provided</scope>
</dependency>
<dependency>
Copy link
Contributor

Choose a reason for hiding this comment

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

Ok for now, but I think we should probably move our samples to GSON or something else.

<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20151123</version>
</dependency>

<!-- Test Dependencies -->
<dependency>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
/**
* Copyright 2016 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.appengine.appidentity;

import com.google.appengine.api.appidentity.AppIdentityService;
import com.google.appengine.api.appidentity.AppIdentityServiceFactory;
import com.google.common.io.CharStreams;

import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;

@SuppressWarnings("serial")
class UrlShortener {
// [START asserting_identity_to_Google_APIs]
/**
* Returns a shortened URL by calling the Google URL Shortener API.
*
* <p>Note: Error handling elided for simplicity.
*/
public String createShortUrl(String longUrl) throws Exception {
ArrayList<String> scopes = new ArrayList<String>();
scopes.add("https://www.googleapis.com/auth/urlshortener");
AppIdentityService appIdentity = AppIdentityServiceFactory.getAppIdentityService();
AppIdentityService.GetAccessTokenResult accessToken = appIdentity.getAccessToken(scopes);
// The token asserts the identity reported by appIdentity.getServiceAccountName()
JSONObject request = new JSONObject();
request.put("longUrl", longUrl);

URL url = new URL("https://www.googleapis.com/urlshortener/v1/url?pp=1");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.addRequestProperty("Content-Type", "application/json");
connection.addRequestProperty("Authorization", "Bearer " + accessToken.getAccessToken());

OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
request.write(writer);
writer.close();

if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// Note: Should check the content-encoding.
// Any JSON parser can be used; this one is used for illustrative purposes.
JSONTokener response_tokens = new JSONTokener(connection.getInputStream());
JSONObject response = new JSONObject(response_tokens);
return (String) response.get("id");
} else {
try (InputStream s = connection.getErrorStream();
InputStreamReader r = new InputStreamReader(s, StandardCharsets.UTF_8)) {
throw new RuntimeException(String.format(
"got error (%d) response %s from %s",
connection.getResponseCode(),
CharStreams.toString(r),
connection.toString()));
}
}
}
// [END asserting_identity_to_Google_APIs]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/**
* Copyright 2016 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.appengine.appidentity;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;

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

@SuppressWarnings("serial")
public class UrlShortenerServlet extends HttpServlet {
private final UrlShortener shortener;

public UrlShortenerServlet() {
shortener = new UrlShortener();
}

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
PrintWriter w = resp.getWriter();
w.println("<!DOCTYPE html>");
w.println("<form method='post'>");
w.println("<label for='longUrl'>URL:</label>");
w.println("<input id='longUrl' name='longUrl' type='text'>");
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 been a while since I did this, but shouldn't it be />?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

That's for xhtml, not for HTML5. Google Style guide recommends the HTML5 style https://google.github.io/styleguide/htmlcssguide.xml?showone=Document_Type#Document_Type

w.println("<input type='submit' value='Shorten'>");
Copy link
Contributor

Choose a reason for hiding this comment

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

ditto

w.println("</form>");
}

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setContentType("text/plain");
String longUrl = req.getParameter("longUrl");
if (longUrl == null) {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "missing longUrl parameter");
return;
}

String shortUrl;
PrintWriter w = resp.getWriter();
try {
shortUrl = shortener.createShortUrl(longUrl);
} catch (Exception e) {
resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
w.println("error shortening URL: " + longUrl);
e.printStackTrace(w);
return;
}

w.print("long URL: ");
w.println(longUrl);
w.print("short URL: ");
w.println(shortUrl);
}
}
8 changes: 8 additions & 0 deletions appengine/appidentity/src/main/webapp/WEB-INF/web.xml
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,16 @@
<servlet-name>appidentity</servlet-name>
<servlet-class>com.example.appengine.appidentity.IdentityServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>urlshortener</servlet-name>
<servlet-class>com.example.appengine.appidentity.UrlShortenerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>appidentity</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>urlshortener</servlet-name>
<url-pattern>/shorten</url-pattern>
</servlet-mapping>
</web-app>