Java Code Examples for com.google.api.client.http.HttpRequestFactory#buildGetRequest()

The following examples show how to use com.google.api.client.http.HttpRequestFactory#buildGetRequest() . 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: RequestFactoryModuleTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Test
public void test_provideHttpRequestFactory_localhost() throws Exception {
  // Make sure that localhost creates a request factory with an initializer.
  boolean origIsLocal = RegistryConfig.CONFIG_SETTINGS.get().appEngine.isLocal;
  RegistryConfig.CONFIG_SETTINGS.get().appEngine.isLocal = true;
  try {
    HttpRequestFactory factory =
        RequestFactoryModule.provideHttpRequestFactory(credentialsBundle);
    HttpRequestInitializer initializer = factory.getInitializer();
    assertThat(initializer).isNotNull();
    HttpRequest request = factory.buildGetRequest(new GenericUrl("http://localhost"));
    initializer.initialize(request);
    verifyZeroInteractions(httpRequestInitializer);
  } finally {
    RegistryConfig.CONFIG_SETTINGS.get().appEngine.isLocal = origIsLocal;
  }
}
 
Example 2
Source File: ApiClientUtilsTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthorizedHttpClient() throws IOException {
  FirebaseApp app = FirebaseApp.initializeApp(TEST_OPTIONS);

  HttpRequestFactory requestFactory = ApiClientUtils.newAuthorizedRequestFactory(app);

  assertTrue(requestFactory.getInitializer() instanceof FirebaseRequestInitializer);
  HttpRequest request = requestFactory.buildGetRequest(TEST_URL);
  assertEquals("Bearer test-token", request.getHeaders().getAuthorization());
  HttpUnsuccessfulResponseHandler retryHandler = request.getUnsuccessfulResponseHandler();
  assertTrue(retryHandler instanceof RetryHandlerDecorator);
  RetryConfig retryConfig = ((RetryHandlerDecorator) retryHandler).getRetryHandler()
      .getRetryConfig();
  assertEquals(4, retryConfig.getMaxRetries());
  assertEquals(60 * 1000, retryConfig.getMaxIntervalMillis());
  assertFalse(retryConfig.isRetryOnIOExceptions());
  assertEquals(retryConfig.getRetryStatusCodes(), ImmutableList.of(500, 503));
}
 
Example 3
Source File: TestApiClientUtils.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
/**
 * Checks whther the given HttpRequestFactory has been configured for authorization and
 * automatic retries.
 *
 * @param requestFactory The HttpRequestFactory to check.
 */
public static void assertAuthAndRetrySupport(HttpRequestFactory requestFactory) {
  assertTrue(requestFactory.getInitializer() instanceof FirebaseRequestInitializer);
  HttpRequest request;
  try {
    request = requestFactory.buildGetRequest(TEST_URL);
  } catch (IOException e) {
    throw new RuntimeException("Failed to initialize request", e);
  }

  // Verify authorization
  assertTrue(request.getHeaders().getAuthorization().startsWith("Bearer "));

  // Verify retry support
  HttpUnsuccessfulResponseHandler retryHandler = request.getUnsuccessfulResponseHandler();
  assertTrue(retryHandler instanceof RetryHandlerDecorator);
  RetryConfig retryConfig = ((RetryHandlerDecorator) retryHandler).getRetryHandler()
      .getRetryConfig();
  assertEquals(DEFAULT_RETRY_CONFIG.getMaxRetries(), retryConfig.getMaxRetries());
  assertEquals(DEFAULT_RETRY_CONFIG.getMaxIntervalMillis(), retryConfig.getMaxIntervalMillis());
  assertFalse(retryConfig.isRetryOnIOExceptions());
  assertEquals(DEFAULT_RETRY_CONFIG.getRetryStatusCodes(), retryConfig.getRetryStatusCodes());
}
 
Example 4
Source File: RememberTheMilkAuthDataGenerator.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
private String getToken(String frob) throws IOException {
  URL signedUrl =
      signatureGenerator.getSignature(
          GET_TOKEN_URL, ImmutableMap.of("frob", frob, "method", GET_TOKEN_METHOD));

  HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory();
  HttpRequest getRequest = requestFactory.buildGetRequest(new GenericUrl(signedUrl));
  HttpResponse response = getRequest.execute();
  int statusCode = response.getStatusCode();
  if (statusCode != 200) {
    throw new IOException(
        "Bad status code: " + statusCode + " error: " + response.getStatusMessage());
  }

  AuthElement authElement = xmlMapper.readValue(response.getContent(), AuthElement.class);

  Preconditions.checkState(authElement.stat.equals("ok"), "state must be ok: %s", authElement);
  Preconditions.checkState(
      !Strings.isNullOrEmpty(authElement.auth.token), "token must not be empty", authElement);
  return authElement.auth.token;
}
 
Example 5
Source File: InstagramPhotoExporter.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
private <T> T makeRequest(String url, Class<T> clazz, TokensAndUrlAuthData authData)
    throws IOException {
  HttpRequestFactory requestFactory = httpTransport.createRequestFactory();
  HttpRequest getRequest =
      requestFactory.buildGetRequest(
          new GenericUrl(url + "?access_token=" + authData.getAccessToken()));
  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);
}
 
Example 6
Source File: DailyMotionSample.java    From google-oauth-java-client with Apache License 2.0 6 votes vote down vote up
private static void run(HttpRequestFactory requestFactory) throws IOException {
  DailyMotionUrl url = new DailyMotionUrl("https://api.dailymotion.com/videos/favorites");
  url.setFields("id,tags,title,url");

  HttpRequest request = requestFactory.buildGetRequest(url);
  VideoFeed videoFeed = request.execute().parseAs(VideoFeed.class);
  if (videoFeed.list.isEmpty()) {
    System.out.println("No favorite videos found.");
  } else {
    if (videoFeed.hasMore) {
      System.out.print("First ");
    }
    System.out.println(videoFeed.list.size() + " favorite videos found:");
    for (Video video : videoFeed.list) {
      System.out.println();
      System.out.println("-----------------------------------------------");
      System.out.println("ID: " + video.id);
      System.out.println("Title: " + video.title);
      System.out.println("Tags: " + video.tags);
      System.out.println("URL: " + video.url);
    }
  }
}
 
Example 7
Source File: GooglePhotosInterface.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
private <T> T makeGetRequest(String url, Optional<Map<String, String>> parameters, Class<T> clazz)
        throws IOException, InvalidTokenException, PermissionDeniedException {
  HttpRequestFactory requestFactory = httpTransport.createRequestFactory();
  HttpRequest getRequest =
      requestFactory.buildGetRequest(
          new GenericUrl(url + "?" + generateParamsString(parameters)));

  HttpResponse response;
  try {
    response = getRequest.execute();
  } catch (HttpResponseException e) {
    response =
        handleHttpResponseException(
            () ->
                requestFactory.buildGetRequest(
                    new GenericUrl(url + "?" + generateParamsString(parameters))),
            e);
  }

  Preconditions.checkState(response.getStatusCode() == 200);
  String result =
      CharStreams.toString(new InputStreamReader(response.getContent(), Charsets.UTF_8));
  return objectMapper.readValue(result, clazz);
}
 
Example 8
Source File: RememberTheMilkService.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
private <T extends RememberTheMilkResponse> T makeRequest(
    Map<String, String> parameters, Class<T> dataClass) throws IOException {

  URL signedUrl = signatureGenerator.getSignature(BASE_URL, parameters);

  HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory();
  HttpRequest getRequest = requestFactory.buildGetRequest(new GenericUrl(signedUrl));
  HttpResponse response = getRequest.execute();
  int statusCode = response.getStatusCode();
  if (statusCode != 200) {
    throw new IOException(
        "Bad status code: " + statusCode + " error: " + response.getStatusMessage());
  }

  T parsedResponse = xmlMapper.readValue(response.getContent(), dataClass);

  if (parsedResponse.error != null) {
    throw new IOException(
        "Error making call to " + signedUrl + " error: " + parsedResponse.error);
  }

  return parsedResponse;
}
 
Example 9
Source File: StorageSample.java    From cloud-storage-docs-xml-api-examples with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {

  try {
    AppIdentityCredential credential = new AppIdentityCredential(Arrays.asList(STORAGE_SCOPE));

    // Set up and execute Google Cloud Storage request.
    String bucketName = req.getRequestURI();
    if (bucketName.equals("/")) {
      resp.sendError(404, "No bucket specified - append /bucket-name to the URL and retry.");
      return;
    }
    // Remove any trailing slashes, if found.
    //[START snippet]
    String cleanBucketName = bucketName.replaceAll("/$", "");
    String URI = GCS_URI + cleanBucketName;
    HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(credential);
    GenericUrl url = new GenericUrl(URI);
    HttpRequest request = requestFactory.buildGetRequest(url);
    HttpResponse response = request.execute();
    String content = response.parseAsString();
    //[END snippet]

    // Display the output XML.
    resp.setContentType("text/xml");
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(resp.getOutputStream()));
    String formattedContent = content.replaceAll("(<ListBucketResult)", XSL + "$1");
    writer.append(formattedContent);
    writer.flush();
    resp.setStatus(200);
  } catch (Throwable e) {
    resp.sendError(404, e.getMessage());
  }
}
 
Example 10
Source File: GoogleHttpClientEdgeGridInterceptorIntegrationTest.java    From AkamaiOPEN-edgegrid-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testInterceptor() throws URISyntaxException, IOException, RequestSigningException {

    wireMockServer.stubFor(get(urlPathEqualTo("/billing-usage/v1/reportSources"))
            .withHeader("Authorization", matching(".*"))
            .withHeader("Host", equalTo(SERVICE_MOCK))
            .willReturn(aResponse()
                    .withStatus(302)
                    .withHeader("Location", "/billing-usage/v1/reportSources/alternative")));

    wireMockServer.stubFor(get(urlPathEqualTo("/billing-usage/v1/reportSources/alternative"))
            .withHeader("Authorization", matching(".*"))
            .withHeader("Host", equalTo(SERVICE_MOCK))
            .willReturn(aResponse()
                    .withStatus(200)
                    .withHeader("Content-Type", "text/xml")
                    .withBody("<response>Some content</response>")));

    HttpRequestFactory requestFactory = createSigningRequestFactory();

    URI uri = URI.create("https://endpoint.net/billing-usage/v1/reportSources");
    HttpRequest request = requestFactory.buildGetRequest(new GenericUrl(uri));
    // Mimic what the library does to process the interceptor.
    request.setFollowRedirects(true).execute();

    List<LoggedRequest> loggedRequests = wireMockServer.findRequestsMatching(RequestPattern
            .everything()).getRequests();
    MatcherAssert.assertThat(loggedRequests.get(0).getHeader("Authorization"),
            Matchers.not(CoreMatchers.equalTo(loggedRequests.get(1).getHeader("Authorization"))));

}
 
Example 11
Source File: GoogleHttpClientTest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Test
public void failedRequest(final MockTracer tracer) throws IOException {
  final HttpRequestFactory requestFactory = new NetHttpTransport().createRequestFactory();
  final HttpRequest request = requestFactory.buildGetRequest(new GenericUrl("http://localhost:12345"));
  try {
    final int statusCode = request.execute().getStatusCode();
    assertEquals(200, statusCode);
  }
  catch (final ConnectException ignore) {
  }

  final List<MockSpan> spans = tracer.finishedSpans();
  assertEquals(1, spans.size());
  assertEquals(GoogleHttpClientAgentIntercept.COMPONENT_NAME, spans.get(0).tags().get(Tags.COMPONENT.getKey()));
}
 
Example 12
Source File: GoogleHttpClientITest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
public static void main(final String[] args) throws Exception {
  final HttpRequestFactory requestFactory = new NetHttpTransport().createRequestFactory();
  final HttpRequest request = requestFactory.buildGetRequest(new GenericUrl("https://www.google.com"));
  final int statusCode = request.execute().getStatusCode();
  if (200 != statusCode)
    throw new AssertionError("ERROR: response: " + statusCode);

  TestUtil.checkSpan(new ComponentSpanCount("google-http-client", 1));
}
 
Example 13
Source File: ApiClientUtilsTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testAuthorizedHttpClientWithoutRetry() throws IOException {
  FirebaseApp app = FirebaseApp.initializeApp(TEST_OPTIONS);

  HttpRequestFactory requestFactory = ApiClientUtils.newAuthorizedRequestFactory(app, null);

  assertTrue(requestFactory.getInitializer() instanceof FirebaseRequestInitializer);
  HttpRequest request = requestFactory.buildGetRequest(TEST_URL);
  assertEquals("Bearer test-token", request.getHeaders().getAuthorization());
  HttpUnsuccessfulResponseHandler retryHandler = request.getUnsuccessfulResponseHandler();
  assertFalse(retryHandler instanceof RetryHandlerDecorator);
}
 
Example 14
Source File: MockHttpTransportTest.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
public void testBuildGetRequest_preservesLoLevelHttpRequest() throws Exception {
  MockHttpTransport httpTransport = new MockHttpTransport();
  GenericUrl url = new GenericUrl("http://example.org");
  HttpRequestFactory requestFactory = httpTransport.createRequestFactory();
  HttpRequest request = requestFactory.buildGetRequest(url);
  request.getHeaders().set("foo", "bar");
  Object unusedOnlyInspectingSideEffects = request.execute();
  MockLowLevelHttpRequest actualRequest = httpTransport.getLowLevelHttpRequest();
  assertThat(actualRequest.getHeaders()).containsKey("foo");
  assertThat(actualRequest.getHeaders().get("foo")).containsExactly("bar");
}
 
Example 15
Source File: GoogleCallback.java    From liberty-bikes with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Method that performs introspection on an AUTH string, and returns data as
 * a String->String hashmap.
 *
 * @param auth
 *            the authstring to query, as built by an auth impl.
 * @return the data from the introspect, in a map.
 */
private Map<String, String> introspectAuth(GoogleAuthorizationCodeFlow flow, GoogleTokenResponse gResponse) throws IOException {
    Map<String, String> results = new HashMap<String, String>();

    Credential credential = flow.createAndStoreCredential(gResponse, null);

    try {
        // ask google to verify the response from the auth string
        // if invalid, it'll throw an exception
        HttpRequestFactory requestFactory = new NetHttpTransport().createRequestFactory(credential);
        GenericUrl url = new GenericUrl("https://www.googleapis.com/oauth2/v3/userinfo");
        HttpRequest infoRequest = requestFactory.buildGetRequest(url);

        infoRequest.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        String jsonIdentity = infoRequest.execute().parseAsString();
        GoogleUser user = jsonb.fromJson(jsonIdentity, GoogleUser.class);
        System.out.println("User logged in: " + jsonb.toJson(user));
        Objects.requireNonNull(user.name, "User name was null");
        Objects.requireNonNull(user.email, "User email was null");

        results.put("valid", "true");
        results.put("id", "GOOGLE:" + user.email);
        results.put("upn", user.email);
        results.put("name", user.name);
        results.put("email", user.email);
    } catch (Exception e) {
        System.out.println(e.toString());
        e.printStackTrace();
        results.put("valid", "false");
    }

    return results;
}
 
Example 16
Source File: UpdateRegistrarRdapBaseUrlsAction.java    From nomulus with Apache License 2.0 5 votes vote down vote up
private ImmutableSetMultimap<String, String> getRdapBaseUrlsPerIanaIdWithTld(
    String tld, String id, HttpRequestFactory requestFactory) {
  String content;
  try {
    HttpRequest request =
        requestFactory.buildGetRequest(new GenericUrl(String.format(LIST_URL, tld)));
    request.getHeaders().setAcceptEncoding("identity");
    request.getHeaders().setCookie(String.format("%s=%s", COOKIE_ID, id));
    HttpResponse response = request.execute();

    try (InputStream input = response.getContent()) {
      content = new String(ByteStreams.toByteArray(input), UTF_8);
    }
  } catch (IOException e) {
    throw new UncheckedIOException(
        "Error reading RDAP list from MoSAPI server: " + e.getMessage(), e);
  } finally {
    logout(requestFactory, id, tld);
  }

  logger.atInfo().log("list reply: '%s'", content);
  JsonObject listReply = new Gson().fromJson(content, JsonObject.class);
  JsonArray services = listReply.getAsJsonArray("services");
  // The format of the response "services" is an array of "ianaIDs to baseUrls", where "ianaIDs
  // to baseUrls" is an array of size 2 where the first item is all the "iana IDs" and the
  // second item all the "baseUrls".
  ImmutableSetMultimap.Builder<String, String> builder = new ImmutableSetMultimap.Builder<>();
  for (JsonElement service : services) {
    for (JsonElement ianaId : service.getAsJsonArray().get(0).getAsJsonArray()) {
      for (JsonElement baseUrl : service.getAsJsonArray().get(1).getAsJsonArray()) {
        builder.put(ianaId.getAsString(), baseUrl.getAsString());
      }
    }
  }

  return builder.build();
}
 
Example 17
Source File: UpdateRegistrarRdapBaseUrlsAction.java    From nomulus with Apache License 2.0 5 votes vote down vote up
private void logout(HttpRequestFactory requestFactory, String id, String tld) {
  try {
    HttpRequest request =
        requestFactory.buildGetRequest(new GenericUrl(String.format(LOGOUT_URL, tld)));
    request.getHeaders().setCookie(String.format("%s=%s", COOKIE_ID, id));
    request.execute();
  } catch (IOException e) {
    logger.atWarning().withCause(e).log("Failed to log out of MoSAPI server. Continuing.");
    // No need for the whole Action to fail if only the logout failed. We can just continue with
    // the data we got.
  }
}
 
Example 18
Source File: HttpExample.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
/** Publish an event or state message using Cloud IoT Core via the HTTP API. */
protected static void publishMessage(
    String payload,
    String urlPath,
    String messageType,
    String token,
    String projectId,
    String cloudRegion,
    String registryId,
    String deviceId)
    throws IOException, JSONException {
  // 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 = "event".equals(messageType) ? "publishEvent" : "setState";

  // Data sent through the wire has to be base64 encoded.
  Base64.Encoder encoder = Base64.getEncoder();

  String encPayload = encoder.encodeToString(payload.getBytes(StandardCharsets.UTF_8.name()));

  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 ("event".equals(messageType)) {
    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(StandardCharsets.UTF_8.name()));

  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());
}
 
Example 19
Source File: Oauth2CallbackServlet.java    From getting-started-java with Apache License 2.0 4 votes vote down vote up
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException,
    ServletException {

  // Ensure that this is no request forgery going on, and that the user
  // sending us this connect request is the user that was supposed to.
  if (req.getSession().getAttribute("state") == null
      || !req.getParameter("state").equals((String) req.getSession().getAttribute("state"))) {
    resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    logger.log(
        Level.WARNING,
        "Invalid state parameter, expected " + (String) req.getSession().getAttribute("state")
            + " got " + req.getParameter("state"));
    resp.sendRedirect("/books");
    return;
  }

  req.getSession().removeAttribute("state");     // Remove one-time use state.

  flow = new GoogleAuthorizationCodeFlow.Builder(
      HTTP_TRANSPORT,
      JSON_FACTORY,
      getServletContext().getInitParameter("bookshelf.clientID"),
      getServletContext().getInitParameter("bookshelf.clientSecret"),
      SCOPES).build();

  final TokenResponse tokenResponse =
      flow.newTokenRequest(req.getParameter("code"))
          .setRedirectUri(getServletContext().getInitParameter("bookshelf.callback"))
          .execute();

  req.getSession().setAttribute("token", tokenResponse.toString()); // Keep track of the token.
  final Credential credential = flow.createAndStoreCredential(tokenResponse, null);
  final HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(credential);

  final GenericUrl url = new GenericUrl(USERINFO_ENDPOINT);      // Make an authenticated request.
  final HttpRequest request = requestFactory.buildGetRequest(url);
  request.getHeaders().setContentType("application/json");

  final String jsonIdentity = request.execute().parseAsString();
  @SuppressWarnings("unchecked")
  HashMap<String, String> userIdResult =
      new ObjectMapper().readValue(jsonIdentity, HashMap.class);
  // From this map, extract the relevant profile info and store it in the session.
  req.getSession().setAttribute("userEmail", userIdResult.get("email"));
  req.getSession().setAttribute("userId", userIdResult.get("sub"));
  req.getSession().setAttribute("userImageUrl", userIdResult.get("picture"));
  logger.log(Level.INFO, "Login successful, redirecting to "
      + (String) req.getSession().getAttribute("loginDestination"));
  resp.sendRedirect((String) req.getSession().getAttribute("loginDestination"));
}
 
Example 20
Source File: Oauth2CallbackServlet.java    From getting-started-java with Apache License 2.0 4 votes vote down vote up
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException,
    ServletException {

  // Ensure that this is no request forgery going on, and that the user
  // sending us this connect request is the user that was supposed to.
  if (req.getSession().getAttribute("state") == null
      || !req.getParameter("state").equals((String) req.getSession().getAttribute("state"))) {
    resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    resp.sendRedirect("/books");
    return;
  }

  req.getSession().removeAttribute("state");     // Remove one-time use state.

  flow = new GoogleAuthorizationCodeFlow.Builder(
      HTTP_TRANSPORT,
      JSON_FACTORY,
      getServletContext().getInitParameter("bookshelf.clientID"),
      getServletContext().getInitParameter("bookshelf.clientSecret"),
      SCOPES).build();

  final TokenResponse tokenResponse =
      flow.newTokenRequest(req.getParameter("code"))
          .setRedirectUri(getServletContext().getInitParameter("bookshelf.callback"))
          .execute();

  req.getSession().setAttribute("token", tokenResponse.toString()); // Keep track of the token.
  final Credential credential = flow.createAndStoreCredential(tokenResponse, null);
  final HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(credential);

  final GenericUrl url = new GenericUrl(USERINFO_ENDPOINT);      // Make an authenticated request.
  final HttpRequest request = requestFactory.buildGetRequest(url);
  request.getHeaders().setContentType("application/json");

  final String jsonIdentity = request.execute().parseAsString();
  @SuppressWarnings("unchecked")
  HashMap<String, String> userIdResult =
      new ObjectMapper().readValue(jsonIdentity, HashMap.class);
  // From this map, extract the relevant profile info and store it in the session.
  req.getSession().setAttribute("userEmail", userIdResult.get("email"));
  req.getSession().setAttribute("userId", userIdResult.get("sub"));
  req.getSession().setAttribute("userImageUrl", userIdResult.get("picture"));
  resp.sendRedirect((String) req.getSession().getAttribute("loginDestination"));
}