App Engine Java SDK version 1.7.0
[gae.git] / java / src / main / com / google / appengine / tools / admin / OAuth2ServerConnection.java
blobcfacb9a238a7c91f91ed8bf47def58cf27f6aac1
1 // Copyright 2011 Google Inc. All Rights Reserved.
3 package com.google.appengine.tools.admin;
5 import com.google.appengine.tools.admin.AppAdminFactory.ConnectOptions;
7 import java.io.BufferedReader;
8 import java.io.IOException;
9 import java.net.HttpURLConnection;
10 import java.net.URL;
11 import java.util.List;
12 import java.util.Map;
14 /**
15 * Connection to the AppEngine hosting service that uses an OAuth 2 token.
17 public class OAuth2ServerConnection extends AbstractServerConnection {
19 /**
20 * Exception type for general OAuth-related failures.
22 public static class OAuthException extends IOException {
23 public OAuthException(String s) {
24 super(s);
27 public OAuthException(String s, Throwable c) {
28 super(s);
29 initCause(c);
33 /**
34 * Exception type for OAuth failures resulting from invalid/expired tokens.
36 public static class OAuthInvalidTokenException extends OAuthException {
37 public OAuthInvalidTokenException(String s) {
38 super(s);
41 public OAuthInvalidTokenException(String s, Throwable c) {
42 super(s, c);
46 public OAuth2ServerConnection(ConnectOptions options) {
47 super(options);
50 @Override
51 protected void doHandleSendErrors(int status, URL url, HttpURLConnection conn,
52 BufferedReader connReader) throws IOException {
53 String reason = conn.getHeaderField("X-OAuth-Error");
54 if (status == 401) {
55 if ("InvalidOAuthToken".equals(reason)) {
56 throw new OAuthInvalidTokenException(constructHttpErrorMessage(conn, connReader));
57 } else if ("BadOAuthRequest".equals(reason) || "OAuthError".equals(reason)) {
58 throw new OAuthException(constructHttpErrorMessage(conn, connReader));
59 } else {
60 throw new HttpIoException(constructHttpErrorMessage(conn, connReader),
61 status);
63 } else if (status == 403) {
64 logger.finer(constructHttpErrorMessage(conn, connReader));
65 } else if (status >= 500 && status <= 600) {
66 } else if (status == 302) {
67 Map<String, List<String>> headers = conn.getHeaderFields();
68 String location = headers.get("Location").get(0);
69 logger.finer("Redirect Location: " + location + ", not following redirect.");
73 @Override
74 protected void doPostConnect(String method, HttpURLConnection conn, DataPoster data) {
77 @Override
78 protected void doPreConnect(String method, HttpURLConnection conn, DataPoster data) {
79 if (options.getOauthToken() != null) {
80 conn.setRequestProperty("Authorization", "OAuth " + options.getOauthToken());