Search in sources :

Example 21 with ByteArrayContent

use of com.google.api.client.http.ByteArrayContent in project data-transfer-project by google.

the class GooglePhotosInterface method uploadPhotoContent.

String uploadPhotoContent(InputStream inputStream) throws IOException, InvalidTokenException, PermissionDeniedException {
    // TODO: add filename
    InputStreamContent content = new InputStreamContent(null, inputStream);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    content.writeTo(outputStream);
    byte[] contentBytes = outputStream.toByteArray();
    if (contentBytes.length == 0) {
        // Google Photos cannot add an empty photo so gracefully ignore
        return "EMPTY_PHOTO";
    }
    HttpContent httpContent = new ByteArrayContent(null, contentBytes);
    return makePostRequest(BASE_URL + "uploads/", Optional.of(PHOTO_UPLOAD_PARAMS), httpContent, String.class);
}
Also used : InputStreamContent(com.google.api.client.http.InputStreamContent) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ByteArrayContent(com.google.api.client.http.ByteArrayContent) HttpContent(com.google.api.client.http.HttpContent) JsonHttpContent(com.google.api.client.http.json.JsonHttpContent)

Example 22 with ByteArrayContent

use of com.google.api.client.http.ByteArrayContent in project google-cloud-java by GoogleCloudPlatform.

the class HttpStorageRpc method write.

@Override
public void write(String uploadId, byte[] toWrite, int toWriteOffset, long destOffset, int length, boolean last) {
    try {
        if (length == 0 && !last) {
            return;
        }
        GenericUrl url = new GenericUrl(uploadId);
        HttpRequest httpRequest = storage.getRequestFactory().buildPutRequest(url, new ByteArrayContent(null, toWrite, toWriteOffset, length));
        long limit = destOffset + length;
        StringBuilder range = new StringBuilder("bytes ");
        if (length == 0) {
            range.append('*');
        } else {
            range.append(destOffset).append('-').append(limit - 1);
        }
        range.append('/');
        if (last) {
            range.append(limit);
        } else {
            range.append('*');
        }
        httpRequest.getHeaders().setContentRange(range.toString());
        int code;
        String message;
        IOException exception = null;
        try {
            HttpResponse response = httpRequest.execute();
            code = response.getStatusCode();
            message = response.getStatusMessage();
        } catch (HttpResponseException ex) {
            exception = ex;
            code = ex.getStatusCode();
            message = ex.getStatusMessage();
        }
        if (!last && code != 308 || last && !(code == 200 || code == 201)) {
            if (exception != null) {
                throw exception;
            }
            GoogleJsonError error = new GoogleJsonError();
            error.setCode(code);
            error.setMessage(message);
            throw translate(error);
        }
    } catch (IOException ex) {
        throw translate(ex);
    }
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) HttpResponse(com.google.api.client.http.HttpResponse) LowLevelHttpResponse(com.google.api.client.http.LowLevelHttpResponse) HttpResponseException(com.google.api.client.http.HttpResponseException) GoogleJsonError(com.google.api.client.googleapis.json.GoogleJsonError) GenericUrl(com.google.api.client.http.GenericUrl) IOException(java.io.IOException) ByteArrayContent(com.google.api.client.http.ByteArrayContent)

Example 23 with ByteArrayContent

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

the class HttpExample method publishMessage.

// [END iot_http_getconfig]
// [START iot_http_publish]
/**
 * Publish an event or state message using Cloud IoT Core via the HTTP API.
 */
public static void publishMessage(String payload, String urlPath, String messageType, String token, String projectId, String cloudRegion, String registryId, String deviceId) 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);
    String urlSuffix = messageType.equals("event") ? "publishEvent" : "setState";
    // Data sent through the wire has to be base64 encoded.
    Base64.Encoder encoder = Base64.getEncoder();
    String encPayload = encoder.encodeToString(payload.getBytes("UTF-8"));
    urlPath = urlPath + devicePath + ":" + urlSuffix;
    final HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() {

        @Override
        public void initialize(HttpRequest request) {
            request.setParser(new JsonObjectParser(JSON_FACTORY));
        }
    });
    HttpHeaders heads = new HttpHeaders();
    heads.setAuthorization(String.format("Bearer %s", token));
    heads.setContentType("application/json; charset=UTF-8");
    heads.setCacheControl("no-cache");
    // Add post data. The data sent depends on whether we're updating state or publishing events.
    JSONObject data = new JSONObject();
    if (messageType.equals("event")) {
        data.put("binary_data", encPayload);
    } else {
        JSONObject state = new JSONObject();
        state.put("binary_data", encPayload);
        data.put("state", state);
    }
    ByteArrayContent content = new ByteArrayContent("application/json", data.toString().getBytes("UTF-8"));
    final HttpRequest req = requestFactory.buildGetRequest(new GenericUrl(urlPath));
    req.setHeaders(heads);
    req.setContent(content);
    req.setRequestMethod("POST");
    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());
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) HttpHeaders(com.google.api.client.http.HttpHeaders) Base64(java.util.Base64) HttpBackOffUnsuccessfulResponseHandler(com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler) HttpRequestFactory(com.google.api.client.http.HttpRequestFactory) 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) JSONObject(org.json.JSONObject) JsonObjectParser(com.google.api.client.json.JsonObjectParser) HttpRequestInitializer(com.google.api.client.http.HttpRequestInitializer) ByteArrayContent(com.google.api.client.http.ByteArrayContent)

Example 24 with ByteArrayContent

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

the class FirebaseChannel method firebasePatch.

public HttpResponse firebasePatch(String path, Object object) throws IOException {
    // Make requests auth'ed using Application Default Credentials
    Credential credential = GoogleCredential.getApplicationDefault().createScoped(FIREBASE_SCOPES);
    HttpRequestFactory requestFactory = httpTransport.createRequestFactory(credential);
    String json = new Gson().toJson(object);
    GenericUrl url = new GenericUrl(path);
    return requestFactory.buildPatchRequest(url, new ByteArrayContent("application/json", json.getBytes())).execute();
}
Also used : GoogleCredential(com.google.api.client.googleapis.auth.oauth2.GoogleCredential) Credential(com.google.api.client.auth.oauth2.Credential) HttpRequestFactory(com.google.api.client.http.HttpRequestFactory) Gson(com.google.gson.Gson) GenericUrl(com.google.api.client.http.GenericUrl) ByteArrayContent(com.google.api.client.http.ByteArrayContent)

Example 25 with ByteArrayContent

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

the class FirebaseChannel method sendFirebaseMessage.

public void sendFirebaseMessage(String channelKey, Game game) throws IOException {
    // Make requests auth'ed using Application Default Credentials
    HttpRequestFactory requestFactory = httpTransport.createRequestFactory(credential);
    GenericUrl url = new GenericUrl(String.format("%s/channels/%s.json", firebaseDbUrl, channelKey));
    HttpResponse response = null;
    try {
        if (null == game) {
            response = requestFactory.buildDeleteRequest(url).execute();
        } else {
            String gameJson = new Gson().toJson(game);
            response = requestFactory.buildPatchRequest(url, new ByteArrayContent("application/json", gameJson.getBytes())).execute();
        }
        if (response.getStatusCode() != 200) {
            throw new RuntimeException("Error code while updating Firebase: " + response.getStatusCode());
        }
    } finally {
        if (null != response) {
            response.disconnect();
        }
    }
}
Also used : HttpRequestFactory(com.google.api.client.http.HttpRequestFactory) HttpResponse(com.google.api.client.http.HttpResponse) Gson(com.google.gson.Gson) GenericUrl(com.google.api.client.http.GenericUrl) ByteArrayContent(com.google.api.client.http.ByteArrayContent)

Aggregations

ByteArrayContent (com.google.api.client.http.ByteArrayContent)43 GenericUrl (com.google.api.client.http.GenericUrl)24 HttpRequest (com.google.api.client.http.HttpRequest)17 IOException (java.io.IOException)12 Test (org.junit.Test)12 HttpResponse (com.google.api.client.http.HttpResponse)10 HttpRequestFactory (com.google.api.client.http.HttpRequestFactory)7 HttpContent (com.google.api.client.http.HttpContent)6 HttpHeaders (com.google.api.client.http.HttpHeaders)6 Gson (com.google.gson.Gson)6 MockResponse (com.google.api.ads.common.lib.testing.MockResponse)4 MockHttpTransport (com.google.api.client.testing.http.MockHttpTransport)4 MockLowLevelHttpRequest (com.google.api.client.testing.http.MockLowLevelHttpRequest)4 File (com.google.api.services.drive.model.File)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 Credential (com.google.api.client.auth.oauth2.Credential)3 GoogleCredential (com.google.api.client.googleapis.auth.oauth2.GoogleCredential)3 HttpResponseException (com.google.api.client.http.HttpResponseException)3 InputStreamContent (com.google.api.client.http.InputStreamContent)3 AbstractInputStreamContent (com.google.api.client.http.AbstractInputStreamContent)2