public static GoogleCredential getGoogleCredential() throws Exception {
    if (_googleCredential != null) {
      return _googleCredential;
    }

    GoogleCredential.Builder builder = new GoogleCredential.Builder();

    builder.setJsonFactory(new JacksonFactory());
    builder.setServiceAccountId(PortletPropsValues.GOOGLE_API_SERVICE_ACCOUNT_ID);

    File file =
        new File(
            PropsUtil.get(PropsKeys.LIFERAY_HOME)
                + PortletPropsValues.GOOGLE_API_SERVICE_ACCOUNT_PRIVATE_KEY_P12_FILE);

    builder.setServiceAccountPrivateKeyFromP12File(file);

    builder.setServiceAccountScopes(
        Arrays.asList(PortletPropsValues.GOOGLE_API_SERVICE_ACCOUNT_SCOPES));
    builder.setServiceAccountUser(PortletPropsValues.GOOGLE_API_SERVICE_ACCOUNT_USER);
    builder.setTransport(new NetHttpTransport());

    _googleCredential = builder.build();

    return _googleCredential;
  }
  protected GoogleDriveSession buildGoogleDriveSession() throws IOException, PortalException {

    long userId = PrincipalThreadLocal.getUserId();

    User user = UserLocalServiceUtil.getUser(userId);

    if (user.isDefaultUser()) {
      throw new PrincipalException("User is not authenticated");
    }

    GoogleCredential.Builder builder = new GoogleCredential.Builder();

    String googleClientId = PrefsPropsUtil.getString(user.getCompanyId(), "google-client-id");
    String googleClientSecret =
        PrefsPropsUtil.getString(user.getCompanyId(), "google-client-secret");

    builder.setClientSecrets(googleClientId, googleClientSecret);

    JacksonFactory jsonFactory = new JacksonFactory();

    builder.setJsonFactory(jsonFactory);

    HttpTransport httpTransport = new NetHttpTransport();

    builder.setTransport(httpTransport);

    GoogleCredential googleCredential = builder.build();

    ExpandoBridge expandoBridge = user.getExpandoBridge();

    String googleAccessToken =
        GetterUtil.getString(expandoBridge.getAttribute("googleAccessToken", false));

    googleCredential.setAccessToken(googleAccessToken);

    String googleRefreshToken =
        GetterUtil.getString(expandoBridge.getAttribute("googleRefreshToken", false));

    googleCredential.setRefreshToken(googleRefreshToken);

    Drive.Builder driveBuilder = new Drive.Builder(httpTransport, jsonFactory, googleCredential);

    Drive drive = driveBuilder.build();

    Drive.About driveAbout = drive.about();

    Drive.About.Get driveAboutGet = driveAbout.get();

    About about = driveAboutGet.execute();

    return new GoogleDriveSession(drive, about.getRootFolderId());
  }
 @SuppressWarnings({"oracle.jdeveloper.java.semantic-warning", "deprecation"})
 private Credential authorize() throws Exception {
   HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
   com.google.api.client.googleapis.auth.oauth2.GoogleCredential.Builder builder =
       new com.google.api.client.googleapis.auth.oauth2.GoogleCredential.Builder();
   builder.setTransport(HTTP_TRANSPORT);
   builder.setJsonFactory(JSON_FACTORY);
   builder.setServiceAccountId(getServiceAccountEmail());
   builder.setServiceAccountScopes(new String[] {"https://www.googleapis.com/auth/analytics"});
   builder.setServiceAccountPrivateKeyFromP12File(getServiceAccountPrivateKey().getFile());
   GoogleCredential credential = builder.build();
   return credential;
 }
  private Calendar getCalendar(final ApiKey apiKey) throws UpdateFailedException {
    HttpTransport httpTransport = new NetHttpTransport();
    JacksonFactory jsonFactory = new JacksonFactory();
    // Get all the attributes for this connector's oauth token from the stored attributes
    final String accessToken = guestService.getApiKeyAttribute(apiKey, "accessToken");
    final String refreshToken = guestService.getApiKeyAttribute(apiKey, "refreshToken");
    final String clientId = guestService.getApiKeyAttribute(apiKey, "google.client.id");
    final String clientSecret = guestService.getApiKeyAttribute(apiKey, "google.client.secret");
    final GoogleCredential.Builder builder = new GoogleCredential.Builder();
    builder.setTransport(httpTransport);
    builder.setJsonFactory(jsonFactory);
    builder.setClientSecrets(clientId, clientSecret);
    GoogleCredential credential = builder.build();
    final Long tokenExpires = Long.valueOf(guestService.getApiKeyAttribute(apiKey, "tokenExpires"));
    credential.setExpirationTimeMilliseconds(tokenExpires);
    credential.setAccessToken(accessToken);
    credential.setRefreshToken(refreshToken);
    try {
      if (tokenExpires < System.currentTimeMillis()) {
        boolean tokenRefreshed = false;

        // Don't worry about checking if we are running on a mirrored test instance.
        // Refreshing tokens independently on both the main server and a mirrored instance
        // seems to work just fine.

        // Try to swap the expired access token for a fresh one.
        tokenRefreshed = credential.refreshToken();

        if (tokenRefreshed) {
          Long newExpireTime = credential.getExpirationTimeMilliseconds();
          logger.info(
              "google calendar token has been refreshed, new expire time = " + newExpireTime);
          // Update stored expire time
          guestService.setApiKeyAttribute(apiKey, "accessToken", credential.getAccessToken());
          guestService.setApiKeyAttribute(apiKey, "tokenExpires", newExpireTime.toString());
        }
      }
    } catch (TokenResponseException e) {
      logger.warn(
          "module=GoogleCalendarUpdater component=background_updates action=refreshToken"
              + " connector="
              + apiKey.getConnector().getName()
              + " guestId="
              + apiKey.getGuestId()
              + " status=permanently failed");
      // Notify the user that the tokens need to be manually renewed
      notificationsService.addNamedNotification(
          apiKey.getGuestId(),
          Notification.Type.WARNING,
          connector().statusNotificationName(),
          "Heads Up. We failed in our attempt to automatically refresh your Google Calendar authentication tokens.<br>"
              + "Please head to <a href=\"javascript:App.manageConnectors()\">Manage Connectors</a>,<br>"
              + "scroll to the Google Calendar connector, and renew your tokens (look for the <i class=\"icon-resize-small icon-large\"></i> icon)");

      // Record permanent update failure since this connector is never
      // going to succeed
      guestService.setApiKeyStatus(
          apiKey.getId(), ApiKey.Status.STATUS_PERMANENT_FAILURE, Utils.stackTrace(e));
      throw new UpdateFailedException(
          "refresh token attempt permanently failed due to a bad token refresh response", e, true);
    } catch (IOException e) {
      logger.warn(
          "module=GoogleCalendarUpdater component=background_updates action=refreshToken"
              + " connector="
              + apiKey.getConnector().getName()
              + " guestId="
              + apiKey.getGuestId()
              + " status=temporarily failed");
      // Notify the user that the tokens need to be manually renewed
      throw new UpdateFailedException("refresh token attempt failed", e, true);
    }
    final Calendar.Builder calendarBuilder =
        new Calendar.Builder(httpTransport, jsonFactory, credential);
    final Calendar calendar = calendarBuilder.build();
    return calendar;
  }