use of com.google.api.client.http.HttpRequest in project AndroidSDK-RecipeBook by gabu.
the class Recipe101 method onCreate.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTransport = GoogleTransport.create();
GoogleHeaders headers = (GoogleHeaders) mTransport.defaultHeaders;
// "[company-id]-[app-name]-[app-version]"という形式で
// アプリケーション名をセット
headers.setApplicationName("gabu-recipe-101");
// バージョンをセット
headers.gdataVersion = "2";
// AtomParserを作る
AtomParser parser = new AtomParser();
// GoogleCalendarのネームスペースをセット
parser.namespaceDictionary = Namespace.DICTIONARY;
// GoogleTransportにAtomParserをセット
mTransport.addParser(parser);
// HttpTransportにApacheHttpTransportのインスタンスをセット
// これをやっておかないとExceptionが発生します。
HttpTransport.setLowLevelHttpTransport(ApacheHttpTransport.INSTANCE);
// AccountManagerを取得
AccountManager manager = AccountManager.get(this);
// Googleアカウントの一覧を取得
Account[] accounts = manager.getAccountsByType("com.google");
// サンプルなので暫定的に1つ目を取得
Account acount = accounts[0];
// 認証のためのauth tokenを取得
AccountManagerFuture<Bundle> f = manager.getAuthToken(acount, CAL_AUTH_TOKEN_TYPE, null, this, null, null);
try {
Bundle b = f.getResult();
mAuthToken = b.getString(AccountManager.KEY_AUTHTOKEN);
// Log.d(TAG, "authToken=" + mAuthToken);
} catch (OperationCanceledException e) {
e.printStackTrace();
} catch (AuthenticatorException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// GoogleTransportにauth tokenをセット
// これで認証ヘッダを自動的に付けてくれます。
((GoogleHeaders) mTransport.defaultHeaders).setGoogleLogin(mAuthToken);
// GoogleTransportからGETリクエストを生成
HttpRequest request = mTransport.buildGetRequest();
// Googleカレンダーの一覧を取得するURLを作成
// 共有しているカレンダーも含む
// String url = GOOGLE_CAL_API_URL + "default/allcalendars/full";
// 自分がオーナーのカレンダーのみ
String url = GOOGLE_CAL_API_URL + "default/owncalendars/full";
// URLをセット
request.setUrl(url);
try {
// HTTPリクエストを実行してレスポンスをパース
CalendarFeed feed = request.execute().parseAs(CalendarFeed.class);
for (CalendarEntry entry : feed.entries) {
Log.d(TAG, entry.title + ", " + entry.id);
}
// サンプルのためカレンダーの1つ目を取得
CalendarEntry entry = feed.entries.get(0);
// このuserIDがカレンダーを一意に特定するIDになります。
String userID = entry.getUserID();
// 何も指定せずに予定の一覧を取得
url = GOOGLE_CAL_API_URL + userID + "/private/full";
debug(request, url);
// 2010年6月の予定の一覧を取得
// url = createMonthlyUrl(userID, 2010, 6);
// debug(request, url);
// 2010年6月30日の予定の一覧
// url = createDailyUrl(userID, 2010, 6, 30);
// debug(request, url);
} catch (IOException e) {
handleException(e);
}
}
use of com.google.api.client.http.HttpRequest in project elasticsearch by elastic.
the class RetryHttpInitializerWrapperTests method testRetryWaitTooLong.
public void testRetryWaitTooLong() throws Exception {
TimeValue maxWaitTime = TimeValue.timeValueMillis(10);
int maxRetryTimes = 50;
FailThenSuccessBackoffTransport fakeTransport = new FailThenSuccessBackoffTransport(HttpStatusCodes.STATUS_CODE_SERVER_ERROR, maxRetryTimes);
JsonFactory jsonFactory = new JacksonFactory();
MockGoogleCredential credential = RetryHttpInitializerWrapper.newMockCredentialBuilder().build();
MockSleeper oneTimeSleeper = new MockSleeper() {
@Override
public void sleep(long millis) throws InterruptedException {
Thread.sleep(maxWaitTime.getMillis());
// important number, use this to get count
super.sleep(0);
}
};
RetryHttpInitializerWrapper retryHttpInitializerWrapper = new RetryHttpInitializerWrapper(credential, oneTimeSleeper, maxWaitTime);
Compute client = new Compute.Builder(fakeTransport, jsonFactory, null).setHttpRequestInitializer(retryHttpInitializerWrapper).setApplicationName("test").build();
HttpRequest request1 = client.getRequestFactory().buildRequest("Get", new GenericUrl("http://elasticsearch.com"), null);
try {
request1.execute();
fail("Request should fail if wait too long");
} catch (HttpResponseException e) {
assertThat(e.getStatusCode(), equalTo(HttpStatusCodes.STATUS_CODE_SERVER_ERROR));
// should only retry once.
assertThat(oneTimeSleeper.getCount(), lessThan(maxRetryTimes));
}
}
use of com.google.api.client.http.HttpRequest in project elasticsearch by elastic.
the class RetryHttpInitializerWrapperTests method testSimpleRetry.
public void testSimpleRetry() throws Exception {
FailThenSuccessBackoffTransport fakeTransport = new FailThenSuccessBackoffTransport(HttpStatusCodes.STATUS_CODE_SERVER_ERROR, 3);
MockGoogleCredential credential = RetryHttpInitializerWrapper.newMockCredentialBuilder().build();
MockSleeper mockSleeper = new MockSleeper();
RetryHttpInitializerWrapper retryHttpInitializerWrapper = new RetryHttpInitializerWrapper(credential, mockSleeper, TimeValue.timeValueSeconds(5));
Compute client = new Compute.Builder(fakeTransport, new JacksonFactory(), null).setHttpRequestInitializer(retryHttpInitializerWrapper).setApplicationName("test").build();
HttpRequest request = client.getRequestFactory().buildRequest("Get", new GenericUrl("http://elasticsearch.com"), null);
HttpResponse response = request.execute();
assertThat(mockSleeper.getCount(), equalTo(3));
assertThat(response.getStatusCode(), equalTo(200));
}
use of com.google.api.client.http.HttpRequest in project elasticsearch by elastic.
the class RetryHttpInitializerWrapper method initialize.
@Override
public void initialize(HttpRequest httpRequest) {
final HttpUnsuccessfulResponseHandler backoffHandler = new HttpBackOffUnsuccessfulResponseHandler(new ExponentialBackOff.Builder().setMaxElapsedTimeMillis(((int) maxWait.getMillis())).build()).setSleeper(sleeper);
httpRequest.setInterceptor(wrappedCredential);
httpRequest.setUnsuccessfulResponseHandler(new HttpUnsuccessfulResponseHandler() {
int retry = 0;
@Override
public boolean handleResponse(HttpRequest request, HttpResponse response, boolean supportsRetry) throws IOException {
if (wrappedCredential.handleResponse(request, response, supportsRetry)) {
// and no backoff is desired.
return true;
} else if (backoffHandler.handleResponse(request, response, supportsRetry)) {
// Otherwise, we defer to the judgement of
// our internal backoff handler.
logger.debug("Retrying [{}] times : [{}]", retry, request.getUrl());
return true;
} else {
return false;
}
}
});
httpRequest.setIOExceptionHandler(new HttpBackOffIOExceptionHandler(new ExponentialBackOff.Builder().setMaxElapsedTimeMillis(((int) maxWait.getMillis())).build()).setSleeper(sleeper));
}
use of com.google.api.client.http.HttpRequest in project openhab1-addons by openhab.
the class GCalGoogleOAuth method getCredential.
/**
* <p>
* Perform OAuth2 authorization with Google server based on provided client_id and client_secret and
* stores credential in local persistent store.
* </p>
*
* @param newCredential If true try to obtain new credential (user interaction required)
* @return Authorization credential object.
*/
public static Credential getCredential(boolean newCredential) {
Credential credential = null;
try {
File tokenPath = null;
String userdata = System.getProperty("smarthome.userdata");
if (StringUtils.isEmpty(userdata)) {
tokenPath = new File("etc");
} else {
tokenPath = new File(userdata);
}
File tokenFile = new File(tokenPath, TOKEN_PATH);
FileDataStoreFactory fileDataStoreFactory = new FileDataStoreFactory(tokenFile);
DataStore<StoredCredential> datastore = fileDataStoreFactory.getDataStore("gcal_oauth2_token");
credential = loadCredential("openhab", datastore);
if (credential == null && newCredential) {
if (StringUtils.isBlank(client_id) || StringUtils.isBlank(client_secret)) {
logger.warn("OAuth2 credentials are not provided");
return null;
}
GenericUrl genericUrl = new GenericUrl("https://accounts.google.com/o/oauth2/device/code");
Map<String, String> mapData = new HashMap<String, String>();
mapData.put("client_id", client_id);
mapData.put("scope", CalendarScopes.CALENDAR);
UrlEncodedContent content = new UrlEncodedContent(mapData);
HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() {
@Override
public void initialize(HttpRequest request) {
request.setParser(new JsonObjectParser(JSON_FACTORY));
}
});
HttpRequest postRequest = requestFactory.buildPostRequest(genericUrl, content);
Device device = postRequest.execute().parseAs(Device.class);
// no access token/secret specified so display the authorisation URL in the log
logger.info("################################################################################################");
logger.info("# Google-Integration: U S E R I N T E R A C T I O N R E Q U I R E D !!");
logger.info("# 1. Open URL '{}'", device.verification_url);
logger.info("# 2. Type provided code {} ", device.user_code);
logger.info("# 3. Grant openHAB access to your Google calendar");
logger.info("# 4. openHAB will automatically detect the permiossions and complete the authentication process");
logger.info("# NOTE: You will only have {} mins before openHAB gives up waiting for the access!!!", device.expires_in);
logger.info("################################################################################################");
if (logger.isDebugEnabled()) {
logger.debug("Got access code");
logger.debug("user code : {}", device.user_code);
logger.debug("device code : {}", device.device_code);
logger.debug("expires in: {}", device.expires_in);
logger.debug("interval : {}", device.interval);
logger.debug("verification_url : {}", device.verification_url);
}
mapData = new HashMap<String, String>();
mapData.put("client_id", client_id);
mapData.put("client_secret", client_secret);
mapData.put("code", device.device_code);
mapData.put("grant_type", "http://oauth.net/grant_type/device/1.0");
content = new UrlEncodedContent(mapData);
postRequest = requestFactory.buildPostRequest(new GenericUrl("https://accounts.google.com/o/oauth2/token"), content);
DeviceToken deviceToken;
do {
deviceToken = postRequest.execute().parseAs(DeviceToken.class);
if (deviceToken.access_token != null) {
if (logger.isDebugEnabled()) {
logger.debug("Got access token");
logger.debug("device access token: {}", deviceToken.access_token);
logger.debug("device token_type: {}", deviceToken.token_type);
logger.debug("device refresh_token: {}", deviceToken.refresh_token);
logger.debug("device expires_in: {}", deviceToken.expires_in);
}
break;
}
logger.debug("waiting for {} seconds", device.interval);
Thread.sleep(device.interval * 1000);
} while (true);
StoredCredential dataCredential = new StoredCredential();
dataCredential.setAccessToken(deviceToken.access_token);
dataCredential.setRefreshToken(deviceToken.refresh_token);
dataCredential.setExpirationTimeMilliseconds((long) deviceToken.expires_in * 1000);
datastore.set(TOKEN_STORE_USER_ID, dataCredential);
credential = loadCredential(TOKEN_STORE_USER_ID, datastore);
}
} catch (Exception e) {
logger.warn("getCredential got exception: {}", e.getMessage());
}
return credential;
}
Aggregations