Search in sources :

Example 1 with HttpRequestFactory

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);
    }
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) HttpHeaders(com.google.api.client.http.HttpHeaders) HttpRequestFactory(com.google.api.client.http.HttpRequestFactory) JsonFactory(com.google.api.client.json.JsonFactory) HttpResponse(com.google.api.client.http.HttpResponse) LowLevelHttpResponse(com.google.api.client.http.LowLevelHttpResponse) GenericUrl(com.google.api.client.http.GenericUrl) JsonHttpContent(com.google.api.client.http.json.JsonHttpContent) IOException(java.io.IOException) Insert(com.google.api.services.storage.Storage.Objects.Insert) BaseEncoding(com.google.common.io.BaseEncoding) HashFunction(com.google.common.hash.HashFunction) StorageObject(com.google.api.services.storage.model.StorageObject) GoogleJsonError(com.google.api.client.googleapis.json.GoogleJsonError)

Example 2 with HttpRequestFactory

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;
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) NetHttpTransport(com.google.api.client.http.javanet.NetHttpTransport) HttpTransport(com.google.api.client.http.HttpTransport) SocketTimeoutException(java.net.SocketTimeoutException) JSONObject(org.json.simple.JSONObject) HttpRequestFactory(com.google.api.client.http.HttpRequestFactory) NetHttpTransport(com.google.api.client.http.javanet.NetHttpTransport) HttpResponse(com.google.api.client.http.HttpResponse) JSONParser(org.json.simple.parser.JSONParser) HttpResponseException(com.google.api.client.http.HttpResponseException) GenericUrl(com.google.api.client.http.GenericUrl)

Example 3 with HttpRequestFactory

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;
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) NetHttpTransport(com.google.api.client.http.javanet.NetHttpTransport) HttpTransport(com.google.api.client.http.HttpTransport) JSONObject(org.json.simple.JSONObject) HttpRequestFactory(com.google.api.client.http.HttpRequestFactory) NetHttpTransport(com.google.api.client.http.javanet.NetHttpTransport) HttpResponse(com.google.api.client.http.HttpResponse) JSONParser(org.json.simple.parser.JSONParser) GenericUrl(com.google.api.client.http.GenericUrl)

Example 4 with HttpRequestFactory

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;
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) Credential(com.google.api.client.auth.oauth2.Credential) StoredCredential(com.google.api.client.auth.oauth2.StoredCredential) HashMap(java.util.HashMap) HttpRequestFactory(com.google.api.client.http.HttpRequestFactory) StoredCredential(com.google.api.client.auth.oauth2.StoredCredential) UrlEncodedContent(com.google.api.client.http.UrlEncodedContent) GenericUrl(com.google.api.client.http.GenericUrl) IOException(java.io.IOException) FileDataStoreFactory(com.google.api.client.util.store.FileDataStoreFactory) JsonObjectParser(com.google.api.client.json.JsonObjectParser) HttpRequestInitializer(com.google.api.client.http.HttpRequestInitializer) File(java.io.File)

Example 5 with HttpRequestFactory

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);
    }
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) HttpRequestFactory(com.google.api.client.http.HttpRequestFactory) HttpResponse(com.google.api.client.http.HttpResponse) GenericUrl(com.google.api.client.http.GenericUrl) ServletException(javax.servlet.ServletException) IOException(java.io.IOException)

Aggregations

GenericUrl (com.google.api.client.http.GenericUrl)8 HttpRequest (com.google.api.client.http.HttpRequest)8 HttpRequestFactory (com.google.api.client.http.HttpRequestFactory)8 HttpResponse (com.google.api.client.http.HttpResponse)7 IOException (java.io.IOException)6 HttpTransport (com.google.api.client.http.HttpTransport)4 NetHttpTransport (com.google.api.client.http.javanet.NetHttpTransport)4 HttpRequestInitializer (com.google.api.client.http.HttpRequestInitializer)3 JsonHttpContent (com.google.api.client.http.json.JsonHttpContent)2 JsonFactory (com.google.api.client.json.JsonFactory)2 PluginTestVerifier (com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifier)2 Method (java.lang.reflect.Method)2 JSONObject (org.json.simple.JSONObject)2 JSONParser (org.json.simple.parser.JSONParser)2 Test (org.junit.Test)2 Credential (com.google.api.client.auth.oauth2.Credential)1 StoredCredential (com.google.api.client.auth.oauth2.StoredCredential)1 GoogleJsonError (com.google.api.client.googleapis.json.GoogleJsonError)1 HttpHeaders (com.google.api.client.http.HttpHeaders)1 HttpResponseException (com.google.api.client.http.HttpResponseException)1