use of com.google.api.client.http.HttpRequestFactory in project google-cloud-java by GoogleCloudPlatform.
the class HttpStorageRpc method open.
@Override
public String open(StorageObject object, Map<Option, ?> options) {
try {
Insert req = storage.objects().insert(object.getBucket(), object);
GenericUrl url = req.buildHttpRequest().getUrl();
String scheme = url.getScheme();
String host = url.getHost();
String path = "/upload" + url.getRawPath();
url = new GenericUrl(scheme + "://" + host + path);
url.set("uploadType", "resumable");
url.set("name", object.getName());
for (Option option : options.keySet()) {
Object content = option.get(options);
if (content != null) {
url.set(option.value(), content.toString());
}
}
JsonFactory jsonFactory = storage.getJsonFactory();
HttpRequestFactory requestFactory = storage.getRequestFactory();
HttpRequest httpRequest = requestFactory.buildPostRequest(url, new JsonHttpContent(jsonFactory, object));
HttpHeaders requestHeaders = httpRequest.getHeaders();
requestHeaders.set("X-Upload-Content-Type", firstNonNull(object.getContentType(), "application/octet-stream"));
String key = Option.CUSTOMER_SUPPLIED_KEY.getString(options);
if (key != null) {
BaseEncoding base64 = BaseEncoding.base64();
HashFunction hashFunction = Hashing.sha256();
requestHeaders.set("x-goog-encryption-algorithm", "AES256");
requestHeaders.set("x-goog-encryption-key", key);
requestHeaders.set("x-goog-encryption-key-sha256", base64.encode(hashFunction.hashBytes(base64.decode(key)).asBytes()));
}
HttpResponse response = httpRequest.execute();
if (response.getStatusCode() != 200) {
GoogleJsonError error = new GoogleJsonError();
error.setCode(response.getStatusCode());
error.setMessage(response.getStatusMessage());
throw translate(error);
}
return response.getHeaders().getLocation();
} catch (IOException ex) {
throw translate(ex);
}
}
use of com.google.api.client.http.HttpRequestFactory in project cogcomp-nlp by CogComp.
the class QueryMQL method getResponse.
public JSONObject getResponse(String mqlQuery) throws IOException, ParseException {
HttpTransport httpTransport = new NetHttpTransport();
HttpRequestFactory requestFactory = httpTransport.createRequestFactory();
JSONParser parser = new JSONParser();
GenericUrl url = new GenericUrl("https://www.googleapis.com/freebase/v1/mqlread");
url.put("query", mqlQuery);
url.put("key", apikey);
logger.debug("Querying Freebase QUERY URL: " + url.toString());
HttpRequest request = requestFactory.buildGetRequest(url);
HttpResponse httpResponse;
try {
httpResponse = request.execute();
} catch (HttpResponseException e) {
e.printStackTrace();
int statusCode = e.getStatusCode();
logger.error("StatusCode " + statusCode);
logger.error("Query URL was " + url.toString());
logger.error("Query was " + mqlQuery);
if (// max limit reached for a day
statusCode == 403) {
System.exit(-1);
}
return null;
} catch (SocketTimeoutException e) {
e.printStackTrace();
return null;
}
JSONObject response = (JSONObject) parser.parse(httpResponse.parseAsString());
return response;
}
use of com.google.api.client.http.HttpRequestFactory in project cogcomp-nlp by CogComp.
the class QueryMQL method getCursorAndResponse.
public JSONObject getCursorAndResponse(String mqlQuery, String cursor) throws IOException, ParseException {
HttpTransport httpTransport = new NetHttpTransport();
HttpRequestFactory requestFactory = httpTransport.createRequestFactory();
JSONParser parser = new JSONParser();
GenericUrl url = new GenericUrl("https://www.googleapis.com/freebase/v1/mqlread");
url.put("query", mqlQuery);
url.put("key", apikey);
url.put("cursor", cursor);
logger.debug("QUERY URL: " + url.toString());
HttpRequest request = requestFactory.buildGetRequest(url);
HttpResponse httpResponse = request.execute();
JSONObject response = (JSONObject) parser.parse(httpResponse.parseAsString());
return response;
}
use of com.google.api.client.http.HttpRequestFactory 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;
}
use of com.google.api.client.http.HttpRequestFactory in project OpenRefine by OpenRefine.
the class DeAuthorizeCommand method doGet.
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Type", "application/json");
String sessionToken = TokenCookie.getToken(request);
if (sessionToken != null) {
// No method to do this in Google's client lib, so roll our own
HttpRequestFactory factory = HTTP_TRANSPORT.createRequestFactory();
GenericUrl url = new GenericUrl("https://accounts.google.com/o/oauth2/revoke?token=" + sessionToken);
HttpRequest rqst = factory.buildGetRequest(url);
HttpResponse resp = rqst.execute();
if (resp.getStatusCode() != 200) {
respond(response, String.valueOf(resp.getStatusCode()), resp.getStatusMessage());
}
TokenCookie.deleteToken(request, response);
}
respond(response, "200 OK", "");
} catch (Exception e) {
respondException(response, e);
}
}
Aggregations