Java Code Examples for com.google.api.client.http.HttpResponse#disconnect()
The following examples show how to use
com.google.api.client.http.HttpResponse#disconnect() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MediaHttpUploader.java From google-api-java-client with Apache License 2.0 | 6 votes |
/** * This method sends a POST request with empty content to get the unique upload URL. * * @param initiationRequestUrl The request URL where the initiation request will be sent */ private HttpResponse executeUploadInitiation(GenericUrl initiationRequestUrl) throws IOException { updateStateAndNotifyListener(UploadState.INITIATION_STARTED); initiationRequestUrl.put("uploadType", "resumable"); HttpContent content = metadata == null ? new EmptyContent() : metadata; HttpRequest request = requestFactory.buildRequest(initiationRequestMethod, initiationRequestUrl, content); initiationHeaders.set(CONTENT_TYPE_HEADER, mediaContent.getType()); if (isMediaLengthKnown()) { initiationHeaders.set(CONTENT_LENGTH_HEADER, getMediaContentLength()); } request.getHeaders().putAll(initiationHeaders); HttpResponse response = executeCurrentRequest(request); boolean notificationCompleted = false; try { updateStateAndNotifyListener(UploadState.INITIATION_COMPLETE); notificationCompleted = true; } finally { if (!notificationCompleted) { response.disconnect(); } } return response; }
Example 2
Source File: CryptoSigners.java From firebase-admin-java with Apache License 2.0 | 6 votes |
@Override public byte[] sign(byte[] payload) throws IOException { String encodedUrl = String.format(IAM_SIGN_BLOB_URL, serviceAccount); HttpResponse response = null; String encodedPayload = BaseEncoding.base64().encode(payload); Map<String, String> content = ImmutableMap.of("bytesToSign", encodedPayload); try { HttpRequest request = requestFactory.buildPostRequest(new GenericUrl(encodedUrl), new JsonHttpContent(jsonFactory, content)); request.setParser(new JsonObjectParser(jsonFactory)); request.setResponseInterceptor(interceptor); response = request.execute(); SignBlobResponse parsed = response.parseAs(SignBlobResponse.class); return BaseEncoding.base64().decode(parsed.signature); } finally { if (response != null) { try { response.disconnect(); } catch (IOException ignored) { // Ignored } } } }
Example 3
Source File: FirebaseAuthIT.java From firebase-admin-java with Apache License 2.0 | 6 votes |
private String signInWithCustomToken(String customToken) throws IOException { GenericUrl url = new GenericUrl(VERIFY_CUSTOM_TOKEN_URL + "?key=" + IntegrationTestUtils.getApiKey()); Map<String, Object> content = ImmutableMap.<String, Object>of( "token", customToken, "returnSecureToken", true); HttpRequest request = transport.createRequestFactory().buildPostRequest(url, new JsonHttpContent(jsonFactory, content)); request.setParser(new JsonObjectParser(jsonFactory)); HttpResponse response = request.execute(); try { GenericJson json = response.parseAs(GenericJson.class); return json.get("idToken").toString(); } finally { response.disconnect(); } }
Example 4
Source File: FirebaseAuthIT.java From firebase-admin-java with Apache License 2.0 | 6 votes |
private String signInWithPassword(String email, String password) throws IOException { GenericUrl url = new GenericUrl(VERIFY_PASSWORD_URL + "?key=" + IntegrationTestUtils.getApiKey()); Map<String, Object> content = ImmutableMap.<String, Object>of( "email", email, "password", password, "returnSecureToken", true); HttpRequest request = transport.createRequestFactory().buildPostRequest(url, new JsonHttpContent(jsonFactory, content)); request.setParser(new JsonObjectParser(jsonFactory)); HttpResponse response = request.execute(); try { GenericJson json = response.parseAs(GenericJson.class); return json.get("idToken").toString(); } finally { response.disconnect(); } }
Example 5
Source File: FirebaseAuthIT.java From firebase-admin-java with Apache License 2.0 | 6 votes |
private String resetPassword( String email, String oldPassword, String newPassword, String oobCode) throws IOException { GenericUrl url = new GenericUrl(RESET_PASSWORD_URL + "?key=" + IntegrationTestUtils.getApiKey()); Map<String, Object> content = ImmutableMap.<String, Object>of( "email", email, "oldPassword", oldPassword, "newPassword", newPassword, "oobCode", oobCode); HttpRequest request = transport.createRequestFactory().buildPostRequest(url, new JsonHttpContent(jsonFactory, content)); request.setParser(new JsonObjectParser(jsonFactory)); HttpResponse response = request.execute(); try { GenericJson json = response.parseAs(GenericJson.class); return json.get("email").toString(); } finally { response.disconnect(); } }
Example 6
Source File: FirebaseAuthIT.java From firebase-admin-java with Apache License 2.0 | 6 votes |
private String signInWithEmailLink( String email, String oobCode) throws IOException { GenericUrl url = new GenericUrl(EMAIL_LINK_SIGN_IN_URL + "?key=" + IntegrationTestUtils.getApiKey()); Map<String, Object> content = ImmutableMap.<String, Object>of( "email", email, "oobCode", oobCode); HttpRequest request = transport.createRequestFactory().buildPostRequest(url, new JsonHttpContent(jsonFactory, content)); request.setParser(new JsonObjectParser(jsonFactory)); HttpResponse response = request.execute(); try { GenericJson json = response.parseAs(GenericJson.class); return json.get("idToken").toString(); } finally { response.disconnect(); } }
Example 7
Source File: HttpHelper.java From firebase-admin-java with Apache License 2.0 | 5 votes |
private static void disconnectQuietly(HttpResponse response) { if (response != null) { try { response.disconnect(); } catch (IOException ignored) { // Ignored. } } }
Example 8
Source File: MediaHttpUploader.java From google-api-java-client with Apache License 2.0 | 5 votes |
/** * Direct Uploads the media. * * @param initiationRequestUrl The request URL where the initiation request will be sent * @return HTTP response */ private HttpResponse directUpload(GenericUrl initiationRequestUrl) throws IOException { updateStateAndNotifyListener(UploadState.MEDIA_IN_PROGRESS); HttpContent content = mediaContent; if (metadata != null) { content = new MultipartContent().setContentParts(Arrays.asList(metadata, mediaContent)); initiationRequestUrl.put("uploadType", "multipart"); } else { initiationRequestUrl.put("uploadType", "media"); } HttpRequest request = requestFactory.buildRequest(initiationRequestMethod, initiationRequestUrl, content); request.getHeaders().putAll(initiationHeaders); // We do not have to do anything special here if media content length is unspecified because // direct media upload works even when the media content length == -1. HttpResponse response = executeCurrentRequest(request); boolean responseProcessed = false; try { if (isMediaLengthKnown()) { totalBytesServerReceived = getMediaContentLength(); } updateStateAndNotifyListener(UploadState.MEDIA_COMPLETE); responseProcessed = true; } finally { if (!responseProcessed) { response.disconnect(); } } return response; }
Example 9
Source File: OAuth2Utils.java From google-api-java-client with Apache License 2.0 | 5 votes |
static boolean runningOnComputeEngine(HttpTransport transport, SystemEnvironmentProvider environment) { // If the environment has requested that we do no GCE checks, return immediately. if (Boolean.parseBoolean(environment.getEnv("NO_GCE_CHECK"))) { return false; } GenericUrl tokenUrl = new GenericUrl(getMetadataServerUrl(environment)); for (int i = 1; i <= MAX_COMPUTE_PING_TRIES; ++i) { try { HttpRequest request = transport.createRequestFactory().buildGetRequest(tokenUrl); request.setConnectTimeout(COMPUTE_PING_CONNECTION_TIMEOUT_MS); request.getHeaders().set("Metadata-Flavor", "Google"); HttpResponse response = request.execute(); try { HttpHeaders headers = response.getHeaders(); return headersContainValue(headers, "Metadata-Flavor", "Google"); } finally { response.disconnect(); } } catch (SocketTimeoutException expected) { // Ignore logging timeouts which is the expected failure mode in non GCE environments. } catch (IOException e) { LOGGER.log( Level.WARNING, "Failed to detect whether we are running on Google Compute Engine.", e); } } return false; }
Example 10
Source File: FirebaseChannel.java From java-docs-samples with Apache License 2.0 | 5 votes |
/** * sendFirebaseMessage. * * @param channelKey . * @param game . * @throws IOException . */ public void sendFirebaseMessage(String channelKey, Game game) throws IOException { // Make requests auth'ed using Application Default Credentials HttpRequestFactory requestFactory = httpTransport.createRequestFactory(new HttpCredentialsAdapter(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(); } } }
Example 11
Source File: IntegrationTestUtils.java From firebase-admin-java with Apache License 2.0 | 5 votes |
public ResponseInfo put(String path, String json) throws IOException { String url = options.getDatabaseUrl() + path + "?access_token=" + getToken(); HttpRequest request = requestFactory.buildPutRequest(new GenericUrl(url), ByteArrayContent.fromString("application/json", json)); HttpResponse response = null; try { response = request.execute(); return new ResponseInfo(response); } finally { if (response != null) { response.disconnect(); } } }
Example 12
Source File: FirebaseInstanceId.java From firebase-admin-java with Apache License 2.0 | 5 votes |
private static void disconnectQuietly(HttpResponse response) { if (response != null) { try { response.disconnect(); } catch (IOException ignored) { // ignored } } }
Example 13
Source File: ApiClientUtils.java From firebase-admin-java with Apache License 2.0 | 5 votes |
public static void disconnectQuietly(HttpResponse response) { if (response != null) { try { response.disconnect(); } catch (IOException ignored) { // ignored } } }
Example 14
Source File: CryptoSigners.java From firebase-admin-java with Apache License 2.0 | 5 votes |
/** * Initializes a {@link CryptoSigner} instance for the given Firebase app. Follows the protocol * documented at go/firebase-admin-sign. */ public static CryptoSigner getCryptoSigner(FirebaseApp firebaseApp) throws IOException { GoogleCredentials credentials = ImplFirebaseTrampolines.getCredentials(firebaseApp); // If the SDK was initialized with a service account, use it to sign bytes. if (credentials instanceof ServiceAccountCredentials) { return new ServiceAccountCryptoSigner((ServiceAccountCredentials) credentials); } FirebaseOptions options = firebaseApp.getOptions(); HttpRequestFactory requestFactory = options.getHttpTransport().createRequestFactory( new FirebaseRequestInitializer(firebaseApp)); JsonFactory jsonFactory = options.getJsonFactory(); // If the SDK was initialized with a service account email, use it with the IAM service // to sign bytes. String serviceAccountId = options.getServiceAccountId(); if (!Strings.isNullOrEmpty(serviceAccountId)) { return new IAMCryptoSigner(requestFactory, jsonFactory, serviceAccountId); } // If the SDK was initialized with some other credential type that supports signing // (e.g. GAE credentials), use it to sign bytes. if (credentials instanceof ServiceAccountSigner) { return new ServiceAccountCryptoSigner((ServiceAccountSigner) credentials); } // Attempt to discover a service account email from the local Metadata service. Use it // with the IAM service to sign bytes. HttpRequest request = requestFactory.buildGetRequest(new GenericUrl(METADATA_SERVICE_URL)); request.getHeaders().set("Metadata-Flavor", "Google"); HttpResponse response = request.execute(); try { byte[] output = ByteStreams.toByteArray(response.getContent()); serviceAccountId = StringUtils.newStringUtf8(output).trim(); return new IAMCryptoSigner(requestFactory, jsonFactory, serviceAccountId); } finally { response.disconnect(); } }
Example 15
Source File: SplunkEventWriter.java From beam with Apache License 2.0 | 4 votes |
/** * Flushes a batch of requests via {@link HttpEventPublisher}. * * @param receiver Receiver to write {@link SplunkWriteError}s to */ private void flush( OutputReceiver<SplunkWriteError> receiver, BagState<SplunkEvent> bufferState, ValueState<Long> countState) throws IOException { if (!bufferState.isEmpty().read()) { HttpResponse response = null; List<SplunkEvent> events = Lists.newArrayList(bufferState.read()); try { // Important to close this response to avoid connection leak. response = publisher.execute(events); if (!response.isSuccessStatusCode()) { flushWriteFailures( events, response.getStatusMessage(), response.getStatusCode(), receiver); logWriteFailures(countState); } else { LOG.info("Successfully wrote {} events", countState.read()); SUCCESS_WRITES.inc(countState.read()); } } catch (HttpResponseException e) { LOG.error( "Error writing to Splunk. StatusCode: {}, content: {}, StatusMessage: {}", e.getStatusCode(), e.getContent(), e.getStatusMessage()); logWriteFailures(countState); flushWriteFailures(events, e.getStatusMessage(), e.getStatusCode(), receiver); } catch (IOException ioe) { LOG.error("Error writing to Splunk: {}", ioe.getMessage()); logWriteFailures(countState); flushWriteFailures(events, ioe.getMessage(), null, receiver); } finally { // States are cleared regardless of write success or failure since we // write failed events to an output PCollection. bufferState.clear(); countState.clear(); if (response != null) { response.disconnect(); } } } }
Example 16
Source File: IcannHttpReporter.java From nomulus with Apache License 2.0 | 4 votes |
/** Uploads {@code reportBytes} to ICANN, returning whether or not it succeeded. */ public boolean send(byte[] reportBytes, String reportFilename) throws XmlException, IOException { validateReportFilename(reportFilename); GenericUrl uploadUrl = new GenericUrl(makeUrl(reportFilename)); HttpRequest request = httpTransport .createRequestFactory() .buildPutRequest(uploadUrl, new ByteArrayContent(CSV_UTF_8.toString(), reportBytes)); HttpHeaders headers = request.getHeaders(); headers.setBasicAuthentication(getTld(reportFilename) + "_ry", password); headers.setContentType(CSV_UTF_8.toString()); request.setHeaders(headers); request.setFollowRedirects(false); HttpResponse response = null; logger.atInfo().log( "Sending report to %s with content length %d", uploadUrl, request.getContent().getLength()); boolean success = true; try { response = request.execute(); byte[] content; try { content = ByteStreams.toByteArray(response.getContent()); } finally { response.getContent().close(); } logger.atInfo().log( "Received response code %d with content %s", response.getStatusCode(), new String(content, UTF_8)); XjcIirdeaResult result = parseResult(content); if (result.getCode().getValue() != 1000) { success = false; logger.atWarning().log( "PUT rejected, status code %s:\n%s\n%s", result.getCode(), result.getMsg(), result.getDescription()); } } finally { if (response != null) { response.disconnect(); } else { success = false; logger.atWarning().log("Received null response from ICANN server at %s", uploadUrl); } } return success; }
Example 17
Source File: SplunkEventWriter.java From DataflowTemplates with Apache License 2.0 | 4 votes |
/** * Utility method to flush a batch of requests via {@link HttpEventPublisher}. * * @param receiver Receiver to write {@link SplunkWriteError}s to */ private void flush( OutputReceiver<SplunkWriteError> receiver, @StateId(BUFFER_STATE_NAME) BagState<SplunkEvent> bufferState, @StateId(COUNT_STATE_NAME) ValueState<Long> countState) throws IOException { if (!bufferState.isEmpty().read()) { HttpResponse response = null; List<SplunkEvent> events = Lists.newArrayList(bufferState.read()); try { // Important to close this response to avoid connection leak. response = publisher.execute(events); if (!response.isSuccessStatusCode()) { flushWriteFailures( events, response.getStatusMessage(), response.getStatusCode(), receiver); logWriteFailures(countState); } else { LOG.info("Successfully wrote {} events", countState.read()); SUCCESS_WRITES.inc(countState.read()); } } catch (HttpResponseException e) { LOG.error( "Error writing to Splunk. StatusCode: {}, content: {}, StatusMessage: {}", e.getStatusCode(), e.getContent(), e.getStatusMessage()); logWriteFailures(countState); flushWriteFailures(events, e.getStatusMessage(), e.getStatusCode(), receiver); } catch (IOException ioe) { LOG.error("Error writing to Splunk: {}", ioe.getMessage()); logWriteFailures(countState); flushWriteFailures(events, ioe.getMessage(), null, receiver); } finally { // States are cleared regardless of write success or failure since we // write failed events to an output PCollection. bufferState.clear(); countState.clear(); if (response != null) { response.disconnect(); } } } }
Example 18
Source File: HttpRequestIT.java From pinpoint with Apache License 2.0 | 4 votes |
public void close(HttpResponse response) throws IOException { if (response != null) { response.disconnect(); } }
Example 19
Source File: BatchRequest.java From google-api-java-client with Apache License 2.0 | 4 votes |
/** * Executes all queued HTTP requests in a single call, parses the responses and invokes callbacks. * * <p> * Calling {@link #execute()} executes and clears the queued requests. This means that the * {@link BatchRequest} object can be reused to {@link #queue} and {@link #execute()} requests * again. * </p> */ public void execute() throws IOException { boolean retryAllowed; Preconditions.checkState(!requestInfos.isEmpty()); // Log a warning if the user is using the global batch endpoint. In the future, we can turn this // into a preconditions check. if (GLOBAL_BATCH_ENDPOINT.equals(this.batchUrl.toString())) { LOGGER.log(Level.WARNING, GLOBAL_BATCH_ENDPOINT_WARNING); } HttpRequest batchRequest = requestFactory.buildPostRequest(this.batchUrl, null); // NOTE: batch does not support gzip encoding HttpExecuteInterceptor originalInterceptor = batchRequest.getInterceptor(); batchRequest.setInterceptor(new BatchInterceptor(originalInterceptor)); int retriesRemaining = batchRequest.getNumberOfRetries(); do { retryAllowed = retriesRemaining > 0; MultipartContent batchContent = new MultipartContent(); batchContent.getMediaType().setSubType("mixed"); int contentId = 1; for (RequestInfo<?, ?> requestInfo : requestInfos) { batchContent.addPart(new MultipartContent.Part( new HttpHeaders().setAcceptEncoding(null).set("Content-ID", contentId++), new HttpRequestContent(requestInfo.request))); } batchRequest.setContent(batchContent); HttpResponse response = batchRequest.execute(); BatchUnparsedResponse batchResponse; try { // Find the boundary from the Content-Type header. String boundary = "--" + response.getMediaType().getParameter("boundary"); // Parse the content stream. InputStream contentStream = response.getContent(); batchResponse = new BatchUnparsedResponse(contentStream, boundary, requestInfos, retryAllowed); while (batchResponse.hasNext) { batchResponse.parseNextResponse(); } } finally { response.disconnect(); } List<RequestInfo<?, ?>> unsuccessfulRequestInfos = batchResponse.unsuccessfulRequestInfos; if (!unsuccessfulRequestInfos.isEmpty()) { requestInfos = unsuccessfulRequestInfos; } else { break; } retriesRemaining--; } while (retryAllowed); requestInfos.clear(); }
Example 20
Source File: HttpRequestJDK7IT.java From pinpoint with Apache License 2.0 | 4 votes |
public void close(HttpResponse response) throws IOException { if (response != null) { response.disconnect(); } }