Java Code Examples for com.google.api.client.http.HttpResponse#parseAs()
The following examples show how to use
com.google.api.client.http.HttpResponse#parseAs() .
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: GoogleAuth.java From endpoints-java with Apache License 2.0 | 7 votes |
@VisibleForTesting static TokenInfo parseTokenInfo(HttpRequest request) throws IOException, ServiceUnavailableException { HttpResponse response = request.execute(); int statusCode = response.getStatusCode(); TokenInfo info = response.parseAs(TokenInfo.class); if (statusCode != 200) { String errorDescription = "Unknown error"; if (info != null && info.errorDescription != null) { errorDescription = info.errorDescription; } errorDescription += " (" + statusCode + ")"; if (statusCode >= 500) { logger.atSevere().log("Error validating access token: %s", errorDescription); throw new ServiceUnavailableException("Failed to validate access token"); } logger.atInfo().log("Invalid access token: %s", errorDescription); return null; } if (info == null || Strings.isEmptyOrWhitespace(info.email)) { logger.atWarning().log("Access token does not contain email scope"); return null; } return info; }
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: KickflipApiClient.java From kickflip-android-sdk with Apache License 2.0 | 6 votes |
/** * Parse the HttpResponse as the appropriate Response subclass * * @param response * @param responseClass * @param cb * @throws IOException */ private void handleKickflipResponse(HttpResponse response, Class<? extends Response> responseClass, KickflipCallback cb) throws IOException { if (cb == null) return; HashMap responseMap = null; Response kickFlipResponse = response.parseAs(responseClass); if (VERBOSE) Log.i(TAG, String.format("RESPONSE: %s body: %s", shortenUrlString(response.getRequest().getUrl().toString()), new GsonBuilder().setPrettyPrinting().create().toJson(kickFlipResponse))); // if (Stream.class.isAssignableFrom(responseClass)) { // if( ((String) responseMap.get("stream_type")).compareTo("HLS") == 0){ // kickFlipResponse = response.parseAs(HlsStream.class); // } else if( ((String) responseMap.get("stream_type")).compareTo("RTMP") == 0){ // // TODO: // } // } else if(User.class.isAssignableFrom(responseClass)){ // kickFlipResponse = response.parseAs(User.class); // } if (kickFlipResponse == null) { postExceptionToCallback(cb, UNKNOWN_ERROR_CODE); } else if (!kickFlipResponse.isSuccessful()) { postExceptionToCallback(cb, UNKNOWN_ERROR_CODE); } else { postResponseToCallback(cb, kickFlipResponse); } }
Example 4
Source File: YouTubeSample.java From google-http-java-client with Apache License 2.0 | 6 votes |
public static ListResponse parseJson(HttpResponse httpResponse) throws IOException { ListResponse listResponse = httpResponse.parseAs(ListResponse.class); if (listResponse.getSearchResults().isEmpty()) { System.out.println("No results found."); } else { for (SearchResult searchResult : listResponse.getSearchResults()) { System.out.println(); System.out.println("-----------------------------------------------"); System.out.println("Kind: " + searchResult.getKind()); System.out.println("Video ID: " + searchResult.getId().getVideoId()); System.out.println("Title: " + searchResult.getSnippet().getTitle()); System.out.println("Description: " + searchResult.getSnippet().getDescription()); } } return listResponse; }
Example 5
Source File: VaultEndpoint.java From datacollector with Apache License 2.0 | 6 votes |
protected Secret getSecret(String path, String method, HttpContent content) throws VaultException { try { HttpRequest request = getRequestFactory().buildRequest( method, new GenericUrl(getConf().getAddress() + path), content ); HttpResponse response = request.execute(); if (!response.isSuccessStatusCode()) { LOG.error("Request failed status: {} message: {}", response.getStatusCode(), response.getStatusMessage()); } return response.parseAs(Secret.class); } catch (IOException e) { LOG.error(e.toString(), e); throw new VaultException("Failed to authenticate: " + e.toString(), e); } }
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: 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 8
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 9
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 10
Source File: GerritApiTransportImpl.java From copybara with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") public static <T> T execute(Type responseType, HttpRequest httpRequest) throws IOException, GerritApiException { HttpResponse response; try { response = httpRequest.execute(); } catch (HttpResponseException e) { throw new GerritApiException(e.getStatusCode(), e.getContent(), e.getContent()); } return (T) response.parseAs(responseType); }
Example 11
Source File: RestClient.java From apigee-deploy-maven-plugin with Apache License 2.0 | 5 votes |
/** * Retrieve the last revision of a given apiproxy or sharedflow. * * @param bundle the application bundle to check * * @return the highest revision number of the deployed bundle regardless of environment * * @throws IOException exception if something went wrong communicating with the rest endpoint */ public Long getLatestRevision(Bundle bundle) throws IOException { // trying to construct the URL like // https://api.enterprise.apigee.com/v1/organizations/apigee-cs/apis/taskservice/ // response is like // { // "name" : "taskservice1", // "revision" : [ "1" ] // } GenericUrl url = new GenericUrl( format("%s/%s/organizations/%s/%s/%s/", profile.getHostUrl(), profile.getApi_version(), profile.getOrg(), bundle.getType().getPathName(), bundle.getName())); HttpRequest restRequest = requestFactory.buildGetRequest(url); restRequest.setReadTimeout(0); HttpHeaders headers = new HttpHeaders(); headers.setAccept("application/json"); restRequest.setHeaders(headers); Long revision = null; try { HttpResponse response = executeAPI(profile, restRequest); AppRevision apprev = response.parseAs(AppRevision.class); Collections.sort(apprev.revision, new StringToIntComparator()); revision = Long.parseLong(apprev.revision.get(0)); log.info(PrintUtil.formatResponse(response, gson.toJson(apprev))); } catch (HttpResponseException e) { log.error(e.getMessage()); } return revision; }
Example 12
Source File: RestClient.java From apigee-deploy-maven-plugin with Apache License 2.0 | 5 votes |
public Long deleteBundle(Bundle bundle) throws IOException { Long deployedRevision = getDeployedRevision(bundle); if (deployedRevision == bundle.getRevision()) { // the same version is the active bundle deactivate first deactivateBundle(bundle); } GenericUrl url = new GenericUrl(format("%s/%s/organizations/%s/%s/%s/revisions/%d", profile.getHostUrl(), profile.getApi_version(), profile.getOrg(), bundle.getType().getPathName(), bundle.getName(), bundle.getRevision())); HttpHeaders headers = new HttpHeaders(); headers.setAccept("application/json"); headers.setContentType("application/octet-stream"); HttpRequest deleteRestRequest = requestFactory.buildDeleteRequest(url); deleteRestRequest.setReadTimeout(0); deleteRestRequest.setHeaders(headers); HttpResponse response = null; response = executeAPI(profile, deleteRestRequest); // String deleteResponse = response.parseAsString(); AppConfig deleteResponse = response.parseAs(AppConfig.class); if (log.isInfoEnabled()) log.info(PrintUtil.formatResponse(response, gson.toJson(deleteResponse).toString())); applyDelay(); return deleteResponse.getRevision(); }
Example 13
Source File: Authorizer.java From gcp-token-broker with Apache License 2.0 | 5 votes |
private static UserInfo getUserInfo(Credential credential) throws IOException { HttpRequest request = HTTP_TRANSPORT .createRequestFactory(credential) .buildGetRequest(new GenericUrl(USER_INFO_URI)); request.getHeaders().setContentType("application/json"); request.setParser(new JsonObjectParser(JSON_FACTORY)); HttpResponse response = request.execute(); return response.parseAs(UserInfo.class); }
Example 14
Source File: SplunkHttpSinkTask.java From kafka-connect-splunk with Apache License 2.0 | 4 votes |
@Override public void put(Collection<SinkRecord> collection) { if (collection.isEmpty()) { log.trace("No records in collection."); return; } try { log.trace("Posting {} message(s) to {}", collection.size(), this.eventCollectorUrl); SinkRecordContent sinkRecordContent = new SinkRecordContent(collection); if (log.isTraceEnabled()) { try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { sinkRecordContent.writeTo(outputStream); outputStream.flush(); byte[] buffer = outputStream.toByteArray(); log.trace("Posting\n{}", new String(buffer, "UTF-8")); } catch (IOException ex) { if (log.isTraceEnabled()) { log.trace("exception thrown while previewing post", ex); } } } HttpRequest httpRequest = this.httpRequestFactory.buildPostRequest(this.eventCollectorUrl, sinkRecordContent); HttpResponse httpResponse = httpRequest.execute(); if (httpResponse.getStatusCode() == 403) { throw new ConnectException("Authentication was not successful. Please check the token with Splunk."); } if (httpResponse.getStatusCode() == 417) { log.warn("This exception happens when too much content is pushed to splunk per call. Look at this blog post " + "http://blogs.splunk.com/2016/08/12/handling-http-event-collector-hec-content-length-too-large-errors-without-pulling-your-hair-out/" + " Setting consumer.max.poll.records to a lower value will decrease the number of message posted to Splunk " + "at once."); throw new ConnectException("Status 417: Content-Length of XXXXX too large (maximum is 1000000). Verify Splunk config or " + " lower the value in consumer.max.poll.records."); } if (JSON_MEDIA_TYPE.equalsIgnoreParameters(httpResponse.getMediaType())) { SplunkStatusMessage statusMessage = httpResponse.parseAs(SplunkStatusMessage.class); if (!statusMessage.isSuccessful()) { throw new RetriableException(statusMessage.toString()); } } else { throw new RetriableException("Media type of " + Json.MEDIA_TYPE + " was not returned."); } } catch (IOException e) { throw new RetriableException( String.format("Exception while posting data to %s.", this.eventCollectorUrl), e ); } }
Example 15
Source File: LabelsSample.java From java-docs-samples with Apache License 2.0 | 4 votes |
/** * Add or modify a label on a dataset. * * See <a href="https://cloud.google.com/bigquery/docs/labeling-datasets">the BigQuery * documentation</a>. */ public static void labelDataset( String projectId, String datasetId, String labelKey, String labelValue) throws IOException { // Authenticate requests using Google Application Default credentials. GoogleCredentials credential = GoogleCredentials.getApplicationDefault(); credential = credential.createScoped(Arrays.asList("https://www.googleapis.com/auth/bigquery")); // Get a new access token. // Note that access tokens have an expiration. You can reuse a token rather than requesting a // new one if it is not yet expired. AccessToken accessToken = credential.refreshAccessToken(); // Set the content of the request. Dataset dataset = new Dataset(); dataset.addLabel(labelKey, labelValue); HttpContent content = new JsonHttpContent(JSON_FACTORY, dataset); // Send the request to the BigQuery API. String urlFormat = "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.getTokenValue())); HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(); HttpRequest request = requestFactory.buildPostRequest(url, content); request.setParser(JSON_FACTORY.createJsonObjectParser()); // Workaround for transports which do not support PATCH requests. // See: http://stackoverflow.com/a/32503192/101923 request.setHeaders(new HttpHeaders().set("X-HTTP-Method-Override", "PATCH")); HttpResponse response = request.execute(); // Check for errors. 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", labelKey, responseDataset.getLabels().get(labelKey)); }
Example 16
Source File: LabelsSample.java From java-docs-samples with Apache License 2.0 | 4 votes |
/** * Add or modify a label on a table. * * See <a href="https://cloud.google.com/bigquery/docs/labeling-datasets">the BigQuery * documentation</a>. */ public static void labelTable( String projectId, String datasetId, String tableId, String labelKey, String labelValue) throws IOException { // Authenticate requests using Google Application Default credentials. GoogleCredentials credential = GoogleCredentials.getApplicationDefault(); credential = credential.createScoped(Arrays.asList("https://www.googleapis.com/auth/bigquery")); // Get a new access token. // Note that access tokens have an expiration. You can reuse a token rather than requesting a // new one if it is not yet expired. AccessToken accessToken = credential.refreshAccessToken(); // Set the content of the request. Table table = new Table(); table.addLabel(labelKey, labelValue); HttpContent content = new JsonHttpContent(JSON_FACTORY, table); // Send the request to the BigQuery API. String urlFormat = "https://www.googleapis.com/bigquery/v2/projects/%s/datasets/%s/tables/%s" + "?fields=labels&access_token=%s"; GenericUrl url = new GenericUrl( String.format(urlFormat, projectId, datasetId, tableId, accessToken.getTokenValue())); HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(); HttpRequest request = requestFactory.buildPostRequest(url, content); request.setParser(JSON_FACTORY.createJsonObjectParser()); // Workaround for transports which do not support PATCH requests. // See: http://stackoverflow.com/a/32503192/101923 request.setHeaders(new HttpHeaders().set("X-HTTP-Method-Override", "PATCH")); HttpResponse response = request.execute(); // Check for errors. if (response.getStatusCode() != 200) { throw new RuntimeException(response.getStatusMessage()); } Table responseTable = response.parseAs(Table.class); System.out.printf( "Updated label \"%s\" with value \"%s\"\n", labelKey, responseTable.getLabels().get(labelKey)); }
Example 17
Source File: RestClient.java From apigee-deploy-maven-plugin with Apache License 2.0 | 4 votes |
/** * Import a bundle into the Apigee gateway. * * @param bundleFile reference to the local bundle file * @param bundle the bundle descriptor to use * * @return the revision of the uploaded bundle * * @throws IOException exception if something went wrong communicating with the rest endpoint */ public Long uploadBundle(String bundleFile, Bundle bundle) throws IOException { FileContent fContent = new FileContent("application/octet-stream", new File(bundleFile)); //testing log.debug("URL parameters API Version {}", (profile.getApi_version())); log.debug("URL parameters URL {}", (profile.getHostUrl())); log.debug("URL parameters Org {}", (profile.getOrg())); log.debug("URL parameters App {}", bundle.getName()); StringBuilder url = new StringBuilder(); url.append(format("%s/%s/organizations/%s/%s?action=import&name=%s", profile.getHostUrl(), profile.getApi_version(), profile.getOrg(), bundle.getType().getPathName(), bundle.getName())); if (getProfile().isValidate()) { url.append("&validate=true"); } HttpRequest restRequest = requestFactory.buildPostRequest(new GenericUrl(url.toString()), fContent); restRequest.setReadTimeout(0); HttpHeaders headers = new HttpHeaders(); headers.setAccept("application/json"); restRequest.setHeaders(headers); Long result; try { HttpResponse response = executeAPI(profile, restRequest); AppConfig apiResult = response.parseAs(AppConfig.class); result = apiResult.getRevision(); if (log.isInfoEnabled()) log.info(PrintUtil.formatResponse(response, gson.toJson(apiResult))); applyDelay(); } catch (HttpResponseException e) { log.error(e.getMessage(), e); throw new IOException(e.getMessage(), e); } return result; }
Example 18
Source File: RestClient.java From apigee-deploy-maven-plugin with Apache License 2.0 | 4 votes |
/** * Update a revsion of a bunlde with the supplied content. * * @param bundleFile reference to the local bundle file * @param bundle the bundle descriptor to use * * @return the revision of the uploaded bundle * * @throws IOException exception if something went wrong communicating with the rest endpoint */ public Long updateBundle(String bundleFile, Bundle bundle) throws IOException { FileContent fContent = new FileContent("application/octet-stream", new File(bundleFile)); //System.out.println("\n\n\nFile path: "+ new File(bundleFile).getCanonicalPath().toString()); log.debug("URL parameters API Version {}", profile.getApi_version()); log.debug("URL parameters URL {}", profile.getHostUrl()); log.debug("URL parameters Org {}", profile.getOrg()); log.debug("URL parameters App {}", bundle.getName()); StringBuilder url = new StringBuilder(); url.append(format("%s/%s/organizations/%s/%s/%s/revisions/%d", profile.getHostUrl(), profile.getApi_version(), profile.getOrg(), bundle.getType().getPathName(), bundle.getName(), bundle.getRevision())); if (getProfile().isValidate()) { url.append("?validate=true"); } HttpRequest restRequest = requestFactory.buildPostRequest(new GenericUrl(url.toString()), fContent); restRequest.setReadTimeout(0); HttpHeaders headers = new HttpHeaders(); headers.setAccept("application/json"); restRequest.setHeaders(headers); Long result; try { HttpResponse response = executeAPI(profile, restRequest); AppConfig appconf = response.parseAs(AppConfig.class); result = appconf.getRevision(); if (log.isInfoEnabled()) log.info(PrintUtil.formatResponse(response, gson.toJson(appconf))); applyDelay(); } catch (HttpResponseException e) { log.error(e.getMessage()); throw new IOException(e.getMessage()); } return result; }
Example 19
Source File: RestClient.java From apigee-deploy-maven-plugin with Apache License 2.0 | 4 votes |
public String activateBundleRevision(Bundle bundle) throws IOException { BundleActivationConfig deployment2 = new BundleActivationConfig(); try { HttpHeaders headers = new HttpHeaders(); headers.setAccept("application/json"); GenericUrl url = new GenericUrl(format("%s/%s/organizations/%s/environments/%s/%s/%s/revisions/%d/deployments", profile.getHostUrl(), profile.getApi_version(), profile.getOrg(), profile.getEnvironment(), bundle.getType().getPathName(), bundle.getName(), bundle.getRevision())); GenericData data = new GenericData(); data.set("override", Boolean.valueOf(getProfile().isOverride()).toString()); //Fix for https://github.com/apigee/apigee-deploy-maven-plugin/issues/18 if (profile.getDelayOverride() != 0) { data.set("delay", profile.getDelayOverride()); } HttpRequest deployRestRequest = requestFactory.buildPostRequest(url, new UrlEncodedContent(data)); deployRestRequest.setReadTimeout(0); deployRestRequest.setHeaders(headers); HttpResponse response = null; response = executeAPI(profile, deployRestRequest); if (getProfile().isOverride()) { SeamLessDeploymentStatus deployment3 = response.parseAs(SeamLessDeploymentStatus.class); Iterator<BundleActivationConfig> iter = deployment3.environment.iterator(); while (iter.hasNext()) { BundleActivationConfig config = iter.next(); if (config.environment.equalsIgnoreCase(profile.getEnvironment())) { if (!config.state.equalsIgnoreCase("deployed")) { log.info("Waiting to assert bundle activation....."); Thread.sleep(10); Long deployedRevision = getDeployedRevision(bundle); if (bundle.getRevision() != null && bundle.getRevision().equals(deployedRevision)) { log.info("Deployed revision is: " + bundle.getRevision()); return "deployed"; } else log.error("Deployment failed to activate"); throw new MojoExecutionException("Deployment failed: Bundle did not activate within expected time. Please check deployment status manually before trying again"); } else { log.info(PrintUtil.formatResponse(response, gson.toJson(deployment3))); } } } } deployment2 = response.parseAs(BundleActivationConfig.class); if (log.isInfoEnabled()) { log.info(PrintUtil.formatResponse(response, gson.toJson(deployment2))); log.info("Deployed revision is:{}", deployment2.revision); } applyDelay(); } catch (Exception e) { log.error(e.getMessage()); throw new IOException(e); } return deployment2.state; }