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
;
11 import java
.util
.List
;
15 * Connection to the AppEngine hosting service that uses an OAuth 2 token.
17 public class OAuth2ServerConnection
extends AbstractServerConnection
{
20 * Exception type for general OAuth-related failures.
22 public static class OAuthException
extends IOException
{
23 public OAuthException(String s
) {
27 public OAuthException(String s
, Throwable c
) {
34 * Exception type for OAuth failures resulting from invalid/expired tokens.
36 public static class OAuthInvalidTokenException
extends OAuthException
{
37 public OAuthInvalidTokenException(String s
) {
41 public OAuthInvalidTokenException(String s
, Throwable c
) {
46 public OAuth2ServerConnection(ConnectOptions options
) {
51 protected void doHandleSendErrors(int status
, URL url
, HttpURLConnection conn
,
52 BufferedReader connReader
) throws IOException
{
53 String reason
= conn
.getHeaderField("X-OAuth-Error");
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
));
60 throw new HttpIoException(constructHttpErrorMessage(conn
, connReader
),
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.");
74 protected void doPostConnect(String method
, HttpURLConnection conn
, DataPoster data
) {
78 protected void doPreConnect(String method
, HttpURLConnection conn
, DataPoster data
) {
79 if (options
.getOauthToken() != null) {
80 conn
.setRequestProperty("Authorization", "OAuth " + options
.getOauthToken());