Example usage for com.google.api.client.googleapis.auth.oauth2 GoogleAuthorizationCodeFlow newAuthorizationUrl

List of usage examples for com.google.api.client.googleapis.auth.oauth2 GoogleAuthorizationCodeFlow newAuthorizationUrl

Introduction

In this page you can find the example usage for com.google.api.client.googleapis.auth.oauth2 GoogleAuthorizationCodeFlow newAuthorizationUrl.

Prototype

@Override
    public GoogleAuthorizationCodeRequestUrl newAuthorizationUrl() 

Source Link

Usage

From source file:com.github.lbroudoux.elasticsearch.river.drive.rest.DriveOAuthAction.java

License:Apache License

@Override
public void handleRequest(RestRequest request, RestChannel channel, Client client) throws Exception {
    if (logger.isDebugEnabled()) {
        logger.debug("REST DriveOAuthAction called");
    }/*from  w  ww  . j av a  2  s. com*/

    String clientId = request.param("client_id");
    String clientSecret = request.param("client_secret");
    String authCode = request.param("auth_code");
    String authCode1 = request.param("auth_code_1");

    if (clientId == null || clientSecret == null) {
        onFailure(request, channel, new IOException("client_id and client_secret can not be null."));
    }

    try {
        XContentBuilder builder = jsonBuilder();
        // We'll use some transport and json factory for sure.
        HttpTransport httpTransport = new NetHttpTransport();
        JsonFactory jsonFactory = new JacksonFactory();

        if (authCode == null) {
            // It's the first call, we've got to build the authorization url.
            GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport,
                    jsonFactory, clientId, clientSecret, Arrays.asList(DriveScopes.DRIVE_READONLY))
                            .setAccessType("offline").setApprovalPrompt("force").build();

            builder.startObject()
                    .field(new XContentBuilderString("url"),
                            flow.newAuthorizationUrl().setRedirectUri("urn:ietf:wg:oauth:2.0:oob").build())
                    .endObject();

        } else {
            // We've got auth code from Google and should request an access token and a refresh token.
            GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport,
                    jsonFactory, clientId, clientSecret, Arrays.asList(DriveScopes.DRIVE_READONLY))
                            .setAccessType("offline").setApprovalPrompt("force").build();

            // authCode main contain a "/"; recreate it if splitted.
            if (authCode1 != null) {
                authCode = authCode + "/" + authCode1;
            }

            GoogleTokenResponse response = flow.newTokenRequest(authCode)
                    .setRedirectUri("urn:ietf:wg:oauth:2.0:oob").execute();

            builder.startObject().field(new XContentBuilderString("accessToken"), response.getAccessToken())
                    .field(new XContentBuilderString("refreshToken"), response.getRefreshToken()).endObject();
        }
        channel.sendResponse(new BytesRestResponse(RestStatus.OK, builder));
    } catch (IOException ioe) {
        onFailure(request, channel, ioe);
    }
}

From source file:com.letscode.rsync.Main.java

public static void main(String[] args) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    if (args.length <= 0) {
        System.out.println("Please input your upload file path : ");
        filePath = br.readLine();/* w w w.j a  v  a 2s.co  m*/
        if ("".equals(filePath)) {
            System.exit(0);
        }
    } else {
        filePath = args[0];
    }

    HttpTransport httpTransport = new NetHttpTransport();
    JsonFactory jsonFactory = new JacksonFactory();

    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory,
            CLIENT_ID, CLIENT_SECRET, Arrays.asList(new String[] { "https://www.googleapis.com/auth/drive" }))
                    .setAccessType("online").setApprovalPrompt("auto").build();

    String url = flow.newAuthorizationUrl().setRedirectUri("urn:ietf:wg:oauth:2.0:oob").build();
    System.out.println("****Please open the following URL in your browser then type the authorization code");
    System.out.println("[COPY] " + url);
    System.out.print("[PASTE] Authen code : ");
    String code = br.readLine();

    GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(REDIRECT_URI).execute();
    GoogleCredential credential = new GoogleCredential().setFromTokenResponse(response);

    drive = new Drive.Builder(httpTransport, jsonFactory, credential).setApplicationName(APPLICATION_NAME)
            .build();

    uploadFolder(false, filePath);
}

From source file:com.liferay.google.GoogleOAuth.java

License:Open Source License

public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {

    ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);

    String cmd = ParamUtil.getString(request, Constants.CMD);

    String redirectUri = PortalUtil.getPortalURL(request) + _REDIRECT_URI;

    if (cmd.equals("login")) {
        GoogleAuthorizationCodeFlow flow = getFlow(themeDisplay.getCompanyId());

        GoogleAuthorizationCodeRequestUrl googleAuthorizationCodeRequestUrl = flow.newAuthorizationUrl();

        googleAuthorizationCodeRequestUrl.setRedirectUri(redirectUri);

        String url = googleAuthorizationCodeRequestUrl.build();

        response.sendRedirect(url);/*from   w ww.  j ava2 s .c  o  m*/
    } else if (cmd.equals("token")) {
        HttpSession session = request.getSession();

        String code = ParamUtil.getString(request, "code");

        if (Validator.isNotNull(code)) {
            Credential credential = exchangeCode(themeDisplay.getCompanyId(), code, redirectUri);

            User user = setGoogleCredentials(session, themeDisplay.getCompanyId(), credential);

            if ((user != null) && (user.getStatus() == WorkflowConstants.STATUS_INCOMPLETE)) {

                redirectUpdateAccount(request, response, user);

                return null;
            }

            sendLoginRedirect(request, response);

            return null;
        }

        String error = ParamUtil.getString(request, "error");

        if (error.equals("access_denied")) {
            sendLoginRedirect(request, response);

            return null;
        }
    }

    return null;
}

From source file:com.liferay.google.login.hook.action.GoogleLoginAction.java

License:Open Source License

@Override
public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {

    ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);

    String cmd = ParamUtil.getString(request, Constants.CMD);

    if (cmd.equals("login")) {
        GoogleAuthorizationCodeFlow googleAuthorizationCodeFlow = getGoogleAuthorizationCodeFlow(
                themeDisplay.getCompanyId());

        GoogleAuthorizationCodeRequestUrl googleAuthorizationCodeRequestUrl = googleAuthorizationCodeFlow
                .newAuthorizationUrl();//from   www.j av  a 2 s. co  m

        googleAuthorizationCodeRequestUrl.setRedirectUri(getRedirectURI(request));

        response.sendRedirect(googleAuthorizationCodeRequestUrl.build());
    } else if (cmd.equals("token")) {
        HttpSession session = request.getSession();

        String code = ParamUtil.getString(request, "code");

        if (Validator.isNotNull(code)) {
            Credential credential = getCredential(themeDisplay.getCompanyId(), code, getRedirectURI(request));

            User user = setCredential(session, themeDisplay.getCompanyId(), credential);

            if ((user != null) && (user.getStatus() == WorkflowConstants.STATUS_INCOMPLETE)) {

                sendUpdateAccountRedirect(request, response, user);

                return null;
            }

            sendLoginRedirect(request, response);

            return null;
        }

        String error = ParamUtil.getString(request, "error");

        if (error.equals("access_denied")) {
            sendLoginRedirect(request, response);

            return null;
        }
    }

    return null;
}

From source file:com.liferay.portal.security.sso.google.internal.GoogleAuthorizationImpl.java

License:Open Source License

@Override
public String getLoginRedirect(long companyId, String returnRequestUri, List<String> scopes) throws Exception {

    GoogleAuthorizationCodeFlow googleAuthorizationCodeFlow = getGoogleAuthorizationCodeFlow(companyId, scopes);

    GoogleAuthorizationCodeRequestUrl googleAuthorizationCodeRequestUrl = googleAuthorizationCodeFlow
            .newAuthorizationUrl();/*from   w w  w  . j  av a  2 s .c  o  m*/

    googleAuthorizationCodeRequestUrl = googleAuthorizationCodeRequestUrl.setRedirectUri(returnRequestUri);

    return googleAuthorizationCodeRequestUrl.build();
}

From source file:com.mkyong.controller.PlusSampleServlet.java

License:Apache License

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
    // Check if we have stored credentials using the Authorization Flow.
    // Note that we only check if there are stored credentials, but not if they are still valid.
    // The user may have revoked authorization, in which case we would need to go through the
    // authorization flow again, which this implementation does not handle.
    //----GoogleAuthorizationCodeFlow authFlow = Utils.initializeFlow();
    //Prafull/* ww  w . j ava  2s. c  om*/
    GoogleAuthorizationCodeFlow authFlowCalendar = Utils.initializeFlowCalendar();

    //----Credential credential = authFlow.loadCredential(Utils.getUserId(req));
    //Prafull
    Credential credential_calendar = authFlowCalendar.loadCredential(Utils.getUserId(req));
    /* ----
    if (credential == null) {
      // If we don't have a token in store, redirect to authorization screen.
      resp.sendRedirect(
          authFlow.newAuthorizationUrl().setRedirectUri(Utils.getRedirectUri(req)).build());
      return;
    }
    ----*/
    //Prafull
    if (credential_calendar == null) {
        // If we don't have a token in store, redirect to authorization screen.
        resp.sendRedirect(
                authFlowCalendar.newAuthorizationUrl().setRedirectUri(Utils.getRedirectUri(req)).build());
        return;
    }

    // If we do have stored credentials, build the Plus object using them.

    //--- Plus plus = new Plus.Builder(
    //=---Utils.HTTP_TRANSPORT, Utils.JSON_FACTORY, credential).setApplicationName("API Demo").build();

    com.google.api.services.calendar.Calendar service = new com.google.api.services.calendar.Calendar.Builder(
            Utils.HTTP_TRANSPORT_CAL, Utils.JSON_FACTORY_CAL, credential_calendar)
                    .setApplicationName("API Demo").build();

    // Make the API call

    //Person profile = plus.people().get("me").execute();
    // Send the results as the response

    // create a response writer to print on the JSP page
    PrintWriter respWriter = resp.getWriter();
    resp.setStatus(200);
    resp.setContentType("text/html");
    respWriter.println("<h1>HELLO WORLD </h1>");

    //respWriter.println("<img src='" + profile.getImage().getUrl() + "'>");
    //respWriter.println("<a href='" + profile.getUrl() + "'>" + profile.getDisplayName() + "</a>");

    DateTime now = new DateTime(System.currentTimeMillis());
    respWriter.println("<h2>" + service.getApplicationName() + "</h2>");

    CalendarList feed = service.calendarList().list().execute();
    Events even = service.events().list("primary").setMaxResults(10).setTimeMin(now).setOrderBy("startTime")
            .setSingleEvents(true).execute();

    com.google.api.services.calendar.model.Events events = service.events().list("primary").setMaxResults(10)
            .setTimeMin(now).setOrderBy("startTime").setSingleEvents(true).execute();

    List<Event> items = events.getItems();
    if (items.size() == 0) {
        respWriter.println("No upcoming events found.");
    } else {
        respWriter.println("Upcoming events");
        for (Event event : items) {
            DateTime start = event.getStart().getDateTime();
            if (start == null) {
                start = event.getStart().getDate();
            }
            respWriter.printf("%s (%s)\n", event.getSummary(), start);
        }
    }

    //respWriter.println("<a href='" + profile.getUrl() + "'>" + profile.getDisplayName() + "</a>");

}

From source file:com.niroshpg.android.gmail.CronHandlerServlet.java

License:Apache License

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
    // Check if we have stored credentials using the Authorization Flow.
    // Note that we only check if there are stored credentials, but not if they are still valid.
    // The user may have revoked authorization, in which case we would need to go through the
    // authorization flow again, which this implementation does not handle.
    GoogleAuthorizationCodeFlow authFlow = GmailUtils.newFlow();

    Credential credential = null;/*from  w  w  w. j  a  va2  s.c  om*/
    String userId = Datastore.getUserId();
    credential = authFlow.loadCredential(userId);

    if (credential == null) {
        //
        // If we don't have a token in store, redirect to authorization screen.
        logger.warning("auth flow started ...");
        resp.sendRedirect(
                authFlow.newAuthorizationUrl().setRedirectUri(GmailUtils.getRedirectUri(req)).build());
        return;
    }
    // Create a new authorized Gmail API client
    Gmail service = new Gmail.Builder(GmailUtils.HTTP_TRANSPORT, GmailUtils.JSON_FACTORY, credential)
            .setApplicationName(APP_NAME).build();

    List<Label> lableList = listLabels(service, "me");

    List<Message> messegeList = listMessagesWithLabels(service, "me",
            Arrays.asList(getLableIdForName(lableList, "EQM")));

    logger.warning("store messages for processing ... ");
    for (Message message : messegeList) {
        String messageBody = "";
        try {
            MimeMessage mimeMessage = getMimeMessage(service, "me", message.getId());
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            mimeMessage.writeTo(baos);
            messageBody = baos.toString();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        String extractedMsgBody = MessageUtility.extractData(messageBody);

        Datastore.addMessage(extractedMsgBody);
    }

    logger.warning("invoke send all");
    sendMessagesToAll();
    logger.warning("removing label from messages ...");
    removeUnRead(service, "me", messegeList);
}

From source file:com.niroshpg.android.gmail.PlusSampleServlet.java

License:Apache License

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
    // Check if we have stored credentials using the Authorization Flow.
    // Note that we only check if there are stored credentials, but not if they are still valid.
    // The user may have revoked authorization, in which case we would need to go through the
    // authorization flow again, which this implementation does not handle.
    GoogleAuthorizationCodeFlow authFlow = GmailUtils.newFlow();

    UserService userService = UserServiceFactory.getUserService();
    Credential credential = null;//from   w w  w.  j ava2s .  com
    if (userService != null) {
        String userId = userService.getCurrentUser().getUserId();
        Datastore.saveUserId(userId);
        credential = authFlow.loadCredential(userId);

        //
        if (credential == null) {
            //
            // If we don't have a token in store, redirect to authorization screen.
            logger.warning("auth flow started ...");
            resp.sendRedirect(
                    authFlow.newAuthorizationUrl().setRedirectUri(GmailUtils.getRedirectUri(req)).build());
            return;
        }
        //     try{
        //        credential.refreshToken();
        //     }
        //     catch(TokenResponseException e){
        //         resp.sendRedirect(
        //                 authFlow.newAuthorizationUrl().setRedirectUri(GmailUtils.getRedirectUri(req)).build());
        //         return;
        //     }

        // Create a new authorized Gmail API client
        Gmail service = new Gmail.Builder(GmailUtils.HTTP_TRANSPORT, GmailUtils.JSON_FACTORY, credential)
                .setApplicationName(APP_NAME).build();
        // Make the API call
        BigInteger startHistoryId = null;

        //service.users().getProfile("me").setRequestHeaders(service.users().getProfile("me").getRequestHeaders().)

        startHistoryId = getHistoryId(service, "me", credential);
        logger.warning("hid[url]= " + startHistoryId);
        List<Label> lableList = listLabels(service, "me");

        List<Message> messegeList = listMessagesWithLabels(service, "me",
                Arrays.asList(getLableIdForName(lableList, "EQM")/*,
                                                                 getLableIdForName(lableList,"UNREAD")*/
                ));

        logger.warning("store messages for processing ... ");
        for (Message message : messegeList) {

            //Message detailMessage = getMessage(service, "me", message.getId());
            String messageBody = "";
            try {
                MimeMessage mimeMessage = getMimeMessage(service, "me", message.getId());
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                mimeMessage.writeTo(baos);
                messageBody = baos.toString();
            } catch (MessagingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            //logger.warning("working "+detailMessage.getSnippet()+" ... ");
            //logger.warning("messageBody= "+messageBody+" ... ");

            //String messageBody = StringUtils.newStringUtf8(Base64.decodeBase64(detailMessage.getRaw()));//StringUtils.newStringUtf8(detailMessage.getPayload().getBody().decodeData()/*Base64.decodeBase64(detailMessage.getPayload().getBody().decodeData())*/);
            //String messageBody = StringUtils.newStringUtf8(detailMessage.getPayload().getBody().decodeData());
            String extractedMsgBody = MessageUtility.extractData(messageBody);
            //logger.warning("adding "+extractedMsgBody+" ... ");
            Datastore.addMessage(extractedMsgBody);
        }

        logger.warning("invoke send all");
        sendMessagesToAll();
        logger.warning("removing label from messages ...");
        removeUnRead(service, "me", messegeList);

        //List<History> historyList = null;
        //if(messegeList != null && messegeList.size() > 1)
        //{ 
        //   logger.warning("messege count = " + messegeList.size());
        //   
        //   for(Message amsg : messegeList)
        //   {
        //logger.warning("id= " + amsg.getId());
        //   if(amsg.getHistoryId() != null)
        //   {
        //      startHistoryId = amsg.getHistoryId();
        //logger.warning("hid= " + amsg.getHistoryId());
        //      break;
        //   }
        //}
        //      if(startHistoryId != null)
        //      {      
        //         historyList = listHistory(service, "me", startHistoryId);
        //      }
        //      else
        //      {
        //         logger.warning("could not find start history id");
        //         
        //         //historyList = listHistory(service, "me", BigInteger.valueOf(1));
        //         
        //      }
        //   }

        resp.setContentType("text/html");
        resp.setCharacterEncoding("UTF-8");
        PrintWriter writer = resp.getWriter();
        writer.println("<!doctype html><html><head>");
        writer.println("<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">");
        writer.println("<title>" + APP_NAME + "</title>");

        writer.println("</head><body>");

        //printThreadIds(service,writer);
        if (messegeList != null && messegeList.size() > 0) {
            writer.println("<p> msg count = " + messegeList.size() + "</p>");
            //for(Message msg : messegeList){                 
            //writer.println("<p>"+msg.toPrettyString()+"</p>");
            //}
        }
        //           if(historyList != null && historyList.size() >0)
        //           {
        //              for(History history : historyList){                 
        //                 writer.println("<p>"+history.toPrettyString()+"</p>");
        //              }
        //           }
        else {
            writer.println("<p>history not found</p>");
        }

        writer.println("<div class=\"header\"><b>" + req.getUserPrincipal().getName() + "</b> | " + "<a href=\""
                + userService.createLogoutURL(req.getRequestURL().toString()) + "\">Log out</a> | "
                + "<a href=\"http://code.google.com/p/google-api-java-client/source/browse"
                + "/calendar-appengine-sample?repo=samples\">See source code for " + "this sample</a></div>");
        writer.println("<div id=\"main\"/>");
        writer.println("</body></html>");
    } else {
        PrintWriter writer = resp.getWriter();
        writer.println("<!doctype html><html><head>");
        writer.println("<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">");
        writer.println("<title>" + APP_NAME + "</title>");

        writer.println("</head><body>");
        writer.println("<h2>user service not found</h2>");
        writer.println("</body></html>");
    }

}

From source file:com.otway.picasasync.webclient.GoogleOAuth.java

License:Apache License

public PicasawebClient authenticatePicasa(Settings settings, boolean allowInteractive, SyncState state)
        throws IOException, GeneralSecurityException {
    final HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();

    log.info("Preparing to authenticate via OAuth...");
    Credential cred = null;//from  w  ww  .  j  a v  a 2  s.  co  m

    String refreshToken = settings.getRefreshToken();
    if (refreshToken != null) {
        // We have a refresh token - so get some refreshed credentials
        cred = getRefreshedCredentials(refreshToken);
    }

    if (cred == null && allowInteractive) {

        // Either there was no valid refresh token, or the credentials could not
        // be created (they may have been revoked). So run the auth flow

        log.info("No credentials - beginning OAuth flow...");

        state.setStatus("Requesting Google Authentication...");

        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(httpTransport, jsonFactory, clientId,
                clientSecret, Collections.singleton(scope));

        String authorizationUrl = flow.newAuthorizationUrl().setRedirectUri(redirectUrl)
                .setAccessType("offline").setApprovalPrompt("force").build();

        try {
            OAuthGUI authGUI = new OAuthGUI();

            // Display the interactive GUI for the user to log in via the browser
            String code = authGUI.initAndShowGUI(authorizationUrl, state);

            log.info("Token received from UI. Requesting credentials...");

            // Now we have the code from the interactive login, set up the
            // credentials request and call it.
            GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(redirectUrl).execute();

            // Retrieve the credential from the request response
            cred = new GoogleCredential.Builder().setTransport(httpTransport).setJsonFactory(jsonFactory)
                    .setClientSecrets(clientId, clientSecret).build().setFromTokenResponse(response);

            state.setStatus("Google Authentication succeeded.");

            log.info("Credentials received - storing refresh token...");

            // Squirrel this away for next time
            settings.setRefreshToken(cred.getRefreshToken());
            settings.saveSettings();
        } catch (Exception ex) {
            log.error("Failed to initialise interactive OAuth GUI", ex);
        }
    }

    if (cred != null) {

        log.info("Building PicasaWeb Client...");

        // Build a web client using the credentials we created
        return new PicasawebClient(cred);
    }

    return null;
}

From source file:com.singhanuvrat.experiment.googleapi.OAuth2Native.java

License:Apache License

/**
 * Authorizes the installed application to access user's protected data.
 * //from w  w w . j ava2  s  . com
 * @param transport HTTP transport
 * @param jsonFactory JSON factory
 * @param receiver verification code receiver
 * @param scopes OAuth 2.0 scopes
 */
public static Credential authorize(final HttpTransport transport, final JsonFactory jsonFactory,
        final VerificationCodeReceiver receiver, final Iterable<String> scopes) throws Exception {
    try {
        final String redirectUri = receiver.getRedirectUri();
        final GoogleClientSecrets clientSecrets = OAuth2Native.loadClientSecrets(jsonFactory);
        // redirect to an authorization page
        // TODO(mlinder, 1.11.0-beta): Use setAccessType("offline").setApprovalPrompt("force") with
        // FileCredentialStore.
        final GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(transport, jsonFactory,
                clientSecrets, scopes).setAccessType("offline").setApprovalPrompt("force").build();
        OAuth2Native.browse(flow.newAuthorizationUrl().setRedirectUri(redirectUri).build());
        // receive authorization code and exchange it for an access token
        final String code = receiver.waitForCode();
        final GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(redirectUri).execute();
        // store credential and return it
        return flow.createAndStoreCredential(response, null);
    } finally {
        receiver.stop();
    }
}