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);
}
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);
}
}
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());
}
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();
}
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();
}
}
}
Aggregations