try { Insert req = storage.objects().insert(object.getBucket(), object); GenericUrl url = req.buildHttpRequest().getUrl(); String scheme = url.getScheme(); String host = url.getHost(); int port = url.getPort(); port = port > 0 ? port : url.toURL().getDefaultPort(); String path = "/upload" + url.getRawPath(); url = new GenericUrl(scheme + "://" + host + ":" + port + 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()); BaseEncoding base64 = BaseEncoding.base64(); HashFunction hashFunction = Hashing.sha256(); requestHeaders.set("x-goog-encryption-algorithm", "AES256"); requestHeaders.set("x-goog-encryption-key", key); base64.encode(hashFunction.hashBytes(base64.decode(key)).asBytes()));
private GenericUrl buildTargetUrl(String path) { GenericUrl genericUrl = new GenericUrl(translate.getBaseUrl() + "v2/" + path); if (options.getApiKey() != null) { genericUrl.put("key", options.getApiKey()); } return genericUrl; }
/** @return {@code location} with query parameter 'digest' set to the BLOB's digest */ @Override public URL getApiRoute(String apiRouteBase) { return new GenericUrl(location).set("digest", blobDigest).toURL(); }
@Nullable private T fallBackToHttp(URL url) throws IOException, RegistryException { GenericUrl httpUrl = new GenericUrl(url); httpUrl.setScheme("http"); eventDispatcher.dispatch( LogEvent.info( "Failed to connect to " + url + " over HTTPS. Attempting again with HTTP: " + httpUrl)); return call(httpUrl.toURL(), connectionFactory); }
String STORAGE_SCOPE = "https://www.googleapis.com/auth/devstorage.read_write"; JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance(); Log.d("testing", "checking if I can create a credential"); httpTransport = AndroidHttp.newCompatibleTransport(); KeyStore keystore = KeyStore.getInstance("PKCS12"); keystore.load(resources_.openRawResource(R.raw.gcs_privatekey), "password".toCharArray()); PrivateKey key = (PrivateKey) keystore.getKey("privatekey", "password".toCharArray()); GoogleCredential credential = new GoogleCredential.Builder() .setTransport(httpTransport) .setJsonFactory(JSON_FACTORY) .setServiceAccountPrivateKey(key) .setServiceAccountId(SERVICE_ACCOUNT_EMAIL) .setServiceAccountScopes(Collections.singleton(STORAGE_SCOPE)) // .setServiceAccountUser(SERVICE_ACCOUNT_EMAIL) // .setClientSecrets(CLIENT_ID, CLIENT_SECRET) .build(); credential.refreshToken(); String URI = "https://storage.googleapis.com/" + BUCKET_NAME; HttpRequestFactory requestFactory = httpTransport.createRequestFactory(credential); GenericUrl url = new GenericUrl(URI); HttpRequest request = requestFactory.buildGetRequest(url); HttpResponse response = request.execute(); String content = response.parseAsString(); Log.d("testing", "response content is: " + content); new Storage.Builder(httpTransport, JSON_FACTORY, credential) .setApplicationName("appname").build();
private <T> T makeGetRequest(String url, Optional<Map<String, String>> parameters, Class<T> clazz) throws IOException { HttpRequestFactory requestFactory = httpTransport.createRequestFactory(); HttpRequest getRequest = requestFactory .buildGetRequest(new GenericUrl(url + "?" + generateParamsString(parameters))); HttpResponse response = getRequest.execute(); int statusCode = response.getStatusCode(); if (statusCode != 200) { throw new IOException( "Bad status code: " + statusCode + " error: " + response.getStatusMessage()); } String result = CharStreams .toString(new InputStreamReader(response.getContent(), Charsets.UTF_8)); return objectMapper.readValue(result, clazz); }
@Override public String open(Job loadJob) { try { String builder = BASE_RESUMABLE_URI + options.getProjectId() + "/jobs"; GenericUrl url = new GenericUrl(builder); url.set("uploadType", "resumable"); JsonFactory jsonFactory = bigquery.getJsonFactory(); HttpRequestFactory requestFactory = bigquery.getRequestFactory(); HttpRequest httpRequest = requestFactory.buildPostRequest(url, new JsonHttpContent(jsonFactory, loadJob)); httpRequest.getHeaders().set("X-Upload-Content-Value", "application/octet-stream"); HttpResponse response = httpRequest.execute(); return response.getHeaders().getLocation(); } catch (IOException ex) { throw translate(ex); } }
"https://www.googleapis.com/bigquery/v2/projects/%s/datasets/%s" + "?fields=labels&access_token=%s"; GenericUrl url = new GenericUrl(String.format(urlFormat, projectId, datasetId, accessToken)); HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(); HttpRequest request = requestFactory.buildPostRequest(url, content); request.setParser(JSON_FACTORY.createJsonObjectParser()); request.setHeaders(new HttpHeaders().set("X-HTTP-Method-Override", "PATCH")); HttpResponse response = request.execute(); if (response.getStatusCode() != 200) { throw new RuntimeException(response.getStatusMessage()); Dataset responseDataset = response.parseAs(Dataset.class); System.out.printf( "Updated label \"%s\" with value \"%s\"\n",
@Override protected TokenResponse executeRefreshToken() throws IOException { GenericUrl tokenUrl = new GenericUrl(getTokenServerEncodedUrl()); HttpRequest request = getTransport().createRequestFactory().buildGetRequest(tokenUrl); request.setParser(new JsonObjectParser(getJsonFactory())); request.getHeaders().set("Metadata-Flavor", "Google"); return request.execute().parseAs(TokenResponse.class); }
@Nullable private static String queryProjectIdFromComputeEngine() { HttpTransport transport; try { transport = newTransport(); } catch (GeneralSecurityException | IOException e) { logger.log(Level.WARNING, "Failed to create HttpTransport.", e); return null; } try { GenericUrl projectIdUrl = new GenericUrl("http://metadata/computeMetadata/v1/project/project-id"); HttpRequest request = transport.createRequestFactory().buildGetRequest(projectIdUrl); request.getHeaders().set("Metadata-Flavor", "Google"); String result = request.execute().parseAsString(); projectIdFromComputeEngine.set(result); return result; } catch (IOException e) { logger.log(Level.INFO, "Could not determine project ID from Compute Engine.", e); return null; } }
private static String getAppEngineProjectIdFromMetadataServer() throws IOException { String metadata = "http://metadata.google.internal"; String projectIdURL = "/computeMetadata/v1/project/project-id"; GenericUrl url = new GenericUrl(metadata + projectIdURL); HttpTransport netHttpTransport = new NetHttpTransport(); HttpRequestFactory requestFactory = netHttpTransport.createRequestFactory(); HttpRequest request = requestFactory .buildGetRequest(url) .setConnectTimeout(500) .setReadTimeout(500) .setHeaders(new HttpHeaders().set("Metadata-Flavor", "Google")); HttpResponse response = request.execute(); return headerContainsMetadataFlavor(response) ? response.parseAsString() : null; }
/** * Parses the contents of a URL to produce an RDF model. */ public Model getModel(String url) throws IOException { HttpRequestFactory factory = TRANSPORT.createRequestFactory(); HttpRequest rootGetRequest = factory.buildGetRequest( new GenericUrl(url)); HttpHeaders headers = new HttpHeaders(); headers.setCookie(authCookie); headers.setAccept("text/turtle"); rootGetRequest.setHeaders(headers); HttpResponse response = rootGetRequest.execute(); if (response.getStatusCode() != 200) { throw new IOException("Unexpected return code: " + response.getStatusCode() + "\nMessage:\n" + response.getStatusMessage()); } StringWriter writer = new StringWriter(); IOUtils.copy(response.getContent(), writer, "UTF-8"); String fixedString = fixProblematicPeriods(writer.toString()); Model defaultModel = ModelFactory.createDefaultModel(); return defaultModel.read( new StringReader(fixedString), url, "TURTLE"); }
static <T> T makePostRequest(HttpTransport httpTransport, String url, HttpContent httpContent, Class<T> clazz) throws IOException { HttpRequestFactory factory = httpTransport.createRequestFactory(); HttpRequest postRequest = factory.buildPostRequest(new GenericUrl(url), httpContent); HttpResponse response = postRequest.execute(); int statusCode = response.getStatusCode(); if (statusCode != 200) { throw new IOException( "Bad status code: " + statusCode + " error: " + response.getStatusMessage()); } String result = CharStreams .toString(new InputStreamReader(response.getContent(), Charsets.UTF_8)); return new ObjectMapper().readValue(result, clazz); } }
private HttpResponse getMetadataResponse(String url) throws IOException { GenericUrl genericUrl = new GenericUrl(url); HttpRequest request = transportFactory.create().createRequestFactory().buildGetRequest(genericUrl); JsonObjectParser parser = new JsonObjectParser(OAuth2Utils.JSON_FACTORY); request.setParser(parser); request.getHeaders().set("Metadata-Flavor", "Google"); request.setThrowExceptionOnExecuteError(false); HttpResponse response; try { response = request.execute(); } catch (UnknownHostException exception) { throw new IOException("ComputeEngineCredentials cannot find the metadata server. This is" + " likely because code is not running on Google Compute Engine.", exception); } return response; }
private String makeCall(HttpTransport transport) throws IOException { HttpRequest get = transport.createRequestFactory() .buildPostRequest(new GenericUrl(INRPUT_LOGIN_SERVER), null) .setFollowRedirects(false) .setThrowExceptionOnExecuteError(false); HttpResponse response = get.execute(); if (response.getStatusCode() != 302) { throw new IOException("Unexpected return code: " + response.getStatusCode() + "\nMessage:\n" + response.getStatusMessage()); } String cookieValue = response.getHeaders().getFirstHeaderStringValue("set-cookie"); if (Strings.isNullOrEmpty(cookieValue)) { throw new IOException("Couldn't extract cookie value from headers: " + response.getHeaders()); } return cookieValue; } }
private String requestRaw(String path) throws IOException { HttpRequest getRequest = TRANSPORT.createRequestFactory().buildGetRequest( new GenericUrl(baseUrl + path)); HttpHeaders headers = new HttpHeaders(); headers.setAuthorization("Bearer " + accessToken); getRequest.setHeaders(headers); HttpResponse response = getRequest.execute(); validateResponse(getRequest, response, 200); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); IOUtils.copy(response.getContent(), byteArrayOutputStream, true); return byteArrayOutputStream.toString(); }
/** Posts a new status for the user, initially marked as private.**/ public void postStatus(String content, String idempotencyKey) throws IOException { ImmutableMap<String, String> formParams = ImmutableMap.of( "status", content, // Default everything to private to avoid a privacy incident "visibility", "private" ); UrlEncodedContent urlEncodedContent = new UrlEncodedContent(formParams); HttpRequest postRequest = TRANSPORT.createRequestFactory() .buildPostRequest( new GenericUrl(baseUrl + POST_URL), urlEncodedContent) .setThrowExceptionOnExecuteError(false); HttpHeaders headers = new HttpHeaders(); headers.setAuthorization("Bearer " + accessToken); if (!Strings.isNullOrEmpty(idempotencyKey)) { // This prevents the same post from being posted twice in the case of network errors headers.set("Idempotency-Key", idempotencyKey); } postRequest.setHeaders(headers); HttpResponse response = postRequest.execute(); validateResponse(postRequest, response, 200); }
/** Posts an RDF model to a Solid server. **/ public String postContent( String url, String slug, String type, Model model) throws IOException { StringWriter stringWriter = new StringWriter(); model.write(stringWriter, "TURTLE"); HttpContent content = new ByteArrayContent("text/turtle", stringWriter.toString().getBytes()); HttpRequest postRequest = factory.buildPostRequest( new GenericUrl(url), content); HttpHeaders headers = new HttpHeaders(); headers.setCookie(authCookie); headers.set("Link", "<" + type + ">; rel=\"type\""); headers.set("Slug", slug); postRequest.setHeaders(headers); HttpResponse response = postRequest.execute(); validateResponse(response, 201); return response.getHeaders().getLocation(); }
return null; GenericUrl url = new GenericUrl(uploadId); HttpRequest httpRequest = bigquery .getRequestFactory() .buildPutRequest(url, new ByteArrayContent(null, toWrite, toWriteOffset, length)); httpRequest.setParser(bigquery.getObjectParser()); long limit = destOffset + length; StringBuilder range = new StringBuilder("bytes "); range.append('*'); httpRequest.getHeaders().setContentRange(range.toString()); int code; String message; HttpResponse response = null; try { response = httpRequest.execute(); code = response.getStatusCode(); message = response.getStatusMessage(); } catch (HttpResponseException ex) { exception = ex; return last && response != null ? response.parseAs(Job.class) : null; } catch (IOException ex) { throw translate(ex);
new GenericUrl(UriTemplate.expand(api.getBaseUrl() + method.getPath(), param, true)); System.out.println(url); HttpRequestFactory requestFactory = httpTransport.createRequestFactory(credential); HttpRequest request = requestFactory.buildRequest(method.getHttpMethod(), url, content); String response = request.execute().parseAsString(); System.out.println(response);