Search in sources :

Example 6 with HttpHeaders

use of com.google.api.client.http.HttpHeaders in project java-docs-samples by GoogleCloudPlatform.

the class CustomerSuppliedEncryptionKeysSamples method uploadObject.

/**
 * Uploads an object to GCS, to be stored with a customer-supplied key (CSEK). The upload may
 * continue in the background after this method returns. The caller of this method is responsible
 * for closing the input stream.
 *
 * @param storage A Storage object, ready for use
 * @param bucketName The name of the destination bucket
 * @param objectName The name of the destination object
 * @param data An InputStream containing the contents of the object to upload
 * @param base64CseKey An AES256 key, encoded as a base64 string.
 * @param base64CseKeyHash The SHA-256 hash of the above key, also encoded as a base64 string.
 * @throws IOException if there was some error uploading to GCS.
 */
public static void uploadObject(Storage storage, String bucketName, String objectName, InputStream data, String base64CseKey, String base64CseKeyHash) throws IOException {
    InputStreamContent mediaContent = new InputStreamContent("text/plain", data);
    Storage.Objects.Insert insertObject = storage.objects().insert(bucketName, null, mediaContent).setName(objectName);
    // The client library's default gzip setting may cause objects to be stored with gzip encoding,
    // which can be desirable in some circumstances but has some disadvantages as well, such as
    // making it difficult to read only a certain range of the original object.
    insertObject.getMediaHttpUploader().setDisableGZipContent(true);
    // Now set the CSEK headers
    final HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.set("x-goog-encryption-algorithm", "AES256");
    httpHeaders.set("x-goog-encryption-key", base64CseKey);
    httpHeaders.set("x-goog-encryption-key-sha256", base64CseKeyHash);
    insertObject.setRequestHeaders(httpHeaders);
    try {
        insertObject.execute();
    } catch (GoogleJsonResponseException e) {
        System.out.println("Error uploading: " + e.getContent());
        System.exit(1);
    }
}
Also used : HttpHeaders(com.google.api.client.http.HttpHeaders) GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) InputStreamContent(com.google.api.client.http.InputStreamContent)

Example 7 with HttpHeaders

use of com.google.api.client.http.HttpHeaders in project java-docs-samples by GoogleCloudPlatform.

the class CustomerSuppliedEncryptionKeysSamples method downloadObject.

/**
 * Downloads a CSEK-protected object from GCS. The download may continue in the background after
 * this method returns. The caller of this method is responsible for closing the input stream.
 *
 * @param storage A Storage object, ready for use
 * @param bucketName The name of the destination bucket
 * @param objectName The name of the destination object
 * @param base64CseKey An AES256 key, encoded as a base64 string.
 * @param base64CseKeyHash The SHA-256 hash of the above key, also encoded as a base64 string.
 *
 * @return An InputStream that contains the decrypted contents of the object.
 *
 * @throws IOException if there was some error download from GCS.
 */
public static InputStream downloadObject(Storage storage, String bucketName, String objectName, String base64CseKey, String base64CseKeyHash) throws Exception {
    // Set the CSEK headers
    final HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.set("x-goog-encryption-algorithm", "AES256");
    httpHeaders.set("x-goog-encryption-key", base64CseKey);
    httpHeaders.set("x-goog-encryption-key-sha256", base64CseKeyHash);
    Storage.Objects.Get getObject = storage.objects().get(bucketName, objectName);
    // If you're using AppEngine, turn off setDirectDownloadEnabled:
    // getObject.getMediaHttpDownloader().setDirectDownloadEnabled(false);
    getObject.setRequestHeaders(httpHeaders);
    try {
        return getObject.executeMediaAsInputStream();
    } catch (GoogleJsonResponseException e) {
        System.out.println("Error downloading: " + e.getContent());
        System.exit(1);
        return null;
    }
}
Also used : HttpHeaders(com.google.api.client.http.HttpHeaders) GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException)

Example 8 with HttpHeaders

use of com.google.api.client.http.HttpHeaders in project java-docs-samples by GoogleCloudPlatform.

the class HttpExample method getConfig.

// [END iot_http_jwt]
// [START iot_http_getconfig]
/**
 * Publish an event or state message using Cloud IoT Core via the HTTP API.
 */
public static void getConfig(String urlPath, String token, String projectId, String cloudRegion, String registryId, String deviceId, String version) throws UnsupportedEncodingException, IOException, JSONException, ProtocolException {
    // Build the resource path of the device that is going to be authenticated.
    String devicePath = String.format("projects/%s/locations/%s/registries/%s/devices/%s", projectId, cloudRegion, registryId, deviceId);
    urlPath = urlPath + devicePath + "/config?local_version=" + version;
    HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() {

        @Override
        public void initialize(HttpRequest request) {
            request.setParser(new JsonObjectParser(JSON_FACTORY));
        }
    });
    final HttpRequest req = requestFactory.buildGetRequest(new GenericUrl(urlPath));
    HttpHeaders heads = new HttpHeaders();
    heads.setAuthorization(String.format("Bearer %s", token));
    heads.setContentType("application/json; charset=UTF-8");
    heads.setCacheControl("no-cache");
    req.setHeaders(heads);
    ExponentialBackOff backoff = new ExponentialBackOff.Builder().setInitialIntervalMillis(500).setMaxElapsedTimeMillis(900000).setMaxIntervalMillis(6000).setMultiplier(1.5).setRandomizationFactor(0.5).build();
    req.setUnsuccessfulResponseHandler(new HttpBackOffUnsuccessfulResponseHandler(backoff));
    HttpResponse res = req.execute();
    System.out.println(res.getStatusCode());
    System.out.println(res.getStatusMessage());
    InputStream in = res.getContent();
    System.out.println(CharStreams.toString(new InputStreamReader(in, Charsets.UTF_8)));
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) HttpHeaders(com.google.api.client.http.HttpHeaders) HttpBackOffUnsuccessfulResponseHandler(com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler) InputStreamReader(java.io.InputStreamReader) HttpRequestFactory(com.google.api.client.http.HttpRequestFactory) InputStream(java.io.InputStream) JwtBuilder(io.jsonwebtoken.JwtBuilder) HttpResponse(com.google.api.client.http.HttpResponse) GenericUrl(com.google.api.client.http.GenericUrl) ExponentialBackOff(com.google.api.client.util.ExponentialBackOff) JsonObjectParser(com.google.api.client.json.JsonObjectParser) HttpRequestInitializer(com.google.api.client.http.HttpRequestInitializer)

Example 9 with HttpHeaders

use of com.google.api.client.http.HttpHeaders in project java-docs-samples by GoogleCloudPlatform.

the class BuildIapRequest method buildIapRequest.

/**
 * Clone request and add an IAP Bearer Authorization header with signed JWT token.
 *
 * @param request Request to add authorization header
 * @param iapClientId OAuth 2.0 client ID for IAP protected resource
 * @return Clone of request with Bearer style authorization header with signed jwt token.
 * @throws Exception exception creating signed JWT
 */
public static HttpRequest buildIapRequest(HttpRequest request, String iapClientId) throws Exception {
    // get service account credentials
    ServiceAccountCredentials credentials = getCredentials();
    // get the base url of the request URL
    String jwt = getSignedJwt(credentials, iapClientId);
    if (jwt == null) {
        throw new Exception("Unable to create a signed jwt token for : " + iapClientId + "with issuer : " + credentials.getClientEmail());
    }
    String idToken = getGoogleIdToken(jwt);
    if (idToken == null) {
        throw new Exception("Unable to retrieve open id token");
    }
    // Create an authorization header with bearer token
    HttpHeaders httpHeaders = request.getHeaders().clone().setAuthorization("Bearer " + idToken);
    // create request with jwt authorization header
    return httpTransport.createRequestFactory().buildRequest(request.getRequestMethod(), request.getUrl(), request.getContent()).setHeaders(httpHeaders);
}
Also used : HttpHeaders(com.google.api.client.http.HttpHeaders) ServiceAccountCredentials(com.google.auth.oauth2.ServiceAccountCredentials)

Example 10 with HttpHeaders

use of com.google.api.client.http.HttpHeaders in project java-docs-samples by GoogleCloudPlatform.

the class BuildAndVerifyIapRequestIT method testGenerateAndVerifyIapRequestIsSuccessful.

// Access an IAP protected url with a signed jwt authorization header, verify jwt token
@Test
public void testGenerateAndVerifyIapRequestIsSuccessful() throws Exception {
    HttpRequest request = httpTransport.createRequestFactory().buildGetRequest(new GenericUrl(IAP_PROTECTED_URL));
    HttpRequest iapRequest = BuildIapRequest.buildIapRequest(request, IAP_CLIENT_ID);
    HttpResponse response = iapRequest.execute();
    assertEquals(response.getStatusCode(), HttpStatus.SC_OK);
    String headerWithtoken = response.parseAsString();
    String[] split = headerWithtoken.split(":");
    assertNotNull(split);
    assertEquals(2, split.length);
    assertEquals("x-goog-authenticated-user-jwt", split[0].trim());
    String jwtToken = split[1].trim();
    HttpRequest verifyJwtRequest = httpTransport.createRequestFactory().buildGetRequest(new GenericUrl(IAP_PROTECTED_URL)).setHeaders(new HttpHeaders().set("x-goog-iap-jwt-assertion", jwtToken));
    boolean verified = verifyIapRequestHeader.verifyJwtForAppEngine(verifyJwtRequest, IAP_PROJECT_NUMBER, IAP_PROJECT_ID);
    assertTrue(verified);
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) HttpHeaders(com.google.api.client.http.HttpHeaders) HttpResponse(com.google.api.client.http.HttpResponse) GenericUrl(com.google.api.client.http.GenericUrl) Test(org.junit.Test)

Aggregations

HttpHeaders (com.google.api.client.http.HttpHeaders)46 HttpRequest (com.google.api.client.http.HttpRequest)22 IOException (java.io.IOException)21 GenericUrl (com.google.api.client.http.GenericUrl)13 HttpResponse (com.google.api.client.http.HttpResponse)13 HttpRequestFactory (com.google.api.client.http.HttpRequestFactory)10 GoogleJsonError (com.google.api.client.googleapis.json.GoogleJsonError)7 HttpRequestInitializer (com.google.api.client.http.HttpRequestInitializer)6 Test (org.junit.Test)6 HttpContent (com.google.api.client.http.HttpContent)5 Objects (com.google.api.services.storage.model.Objects)5 HttpResponseException (com.google.api.client.http.HttpResponseException)4 HttpTransport (com.google.api.client.http.HttpTransport)4 JsonObjectParser (com.google.api.client.json.JsonObjectParser)4 JacksonFactory (com.google.api.client.json.jackson2.JacksonFactory)4 MockHttpTransport (com.google.api.client.testing.http.MockHttpTransport)4 SocketTimeoutException (java.net.SocketTimeoutException)4 Map (java.util.Map)4 GoogleCredential (com.google.api.client.googleapis.auth.oauth2.GoogleCredential)3 GoogleJsonResponseException (com.google.api.client.googleapis.json.GoogleJsonResponseException)3