Example usage for com.google.api.client.googleapis.auth.oauth2 GoogleAuthorizationCodeRequestUrl GoogleAuthorizationCodeRequestUrl

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

Introduction

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

Prototype

public GoogleAuthorizationCodeRequestUrl(GoogleClientSecrets clientSecrets, String redirectUri,
        Collection<String> scopes) 

Source Link

Usage

From source file:calendarevent.CalendarEvent.java

/**
 * @param args the command line arguments
 *//* www  .  j ava2 s  .  c  om*/
public static void main(String[] args) {
    // TODO code application logic here

    /*       
                
        This has to be replaced with the json data coming from the getJsonData() method
        Expecting the Json will be in the format from the above methid.
                
    */
    String jsonString = "{\n" + " \"kind\": \"calendar#events\",\n"
            + " \"etag\": \"\\\"2DaeHpkENZGECFHdcr5l8tYxjD4/QElT1PHkP9d3G5VSndpdEMlSzKE\\\"\",\n"
            + " \"summary\": \"PushEvents\",\n" + " \"description\": \"Hackathon\",\n"
            + " \"updated\": \"2014-03-29T22:35:18.495Z\",\n" + " \"timeZone\": \"Asia/Calcutta\",\n"
            + " \"accessRole\": \"reader\",\n" + " \"items\": [\n" + "  {\n"
            + "   \"kind\": \"calendar#event\",\n"
            + "   \"etag\": \"\\\"2DaeHpkENZGECFHdcr5l8tYxjD4/MTM5NjEyNTQwNzcxMTAwMA\\\"\",\n"
            + "   \"id\": \"q28lprjb8ad3m17955lf1p9d48\",\n" + "   \"status\": \"confirmed\",\n"
            + "   \"htmlLink\": \"https://www.google.com/calendar/event?eid=cTI4bHByamI4YWQzbTE3OTU1bGYxcDlkNDggM3RvcjdvamZxaWhlamNqNjduOWw0dDhnMmNAZw\",\n"
            + "   \"created\": \"2014-03-29T20:36:47.000Z\",\n"
            + "   \"updated\": \"2014-03-29T20:36:47.711Z\",\n" + "   \"summary\": \"Test API\",\n"
            + "   \"creator\": {\n" + "    \"email\": \"vrohitrao@gmail.com\",\n"
            + "    \"displayName\": \"Rohith Vallu\"\n" + "   },\n" + "   \"organizer\": {\n"
            + "    \"email\": \"3tor7ojfqihejcj67n9l4t8g2c@group.calendar.google.com\",\n"
            + "    \"displayName\": \"PushEvents\",\n" + "    \"self\": true\n" + "   },\n"
            + "   \"start\": {\n" + "    \"dateTime\": \"2014-03-30T02:30:00+05:30\"\n" + "   },\n"
            + "   \"end\": {\n" + "    \"dateTime\": \"2014-03-30T03:30:00+05:30\"\n" + "   },\n"
            + "   \"iCalUID\": \"q28lprjb8ad3m17955lf1p9d48@google.com\",\n" + "   \"sequence\": 0\n" + "  },\n"
            + "  {\n" + "   \"kind\": \"calendar#event\",\n"
            + "   \"etag\": \"\\\"2DaeHpkENZGECFHdcr5l8tYxjD4/MTM5NjEzMjUzMjQxNzAwMA\\\"\",\n"
            + "   \"id\": \"jgpue3stuo3js5qlsodob84voo\",\n" + "   \"status\": \"confirmed\",\n"
            + "   \"htmlLink\": \"https://www.google.com/calendar/event?eid=amdwdWUzc3R1bzNqczVxbHNvZG9iODR2b28gM3RvcjdvamZxaWhlamNqNjduOWw0dDhnMmNAZw\",\n"
            + "   \"created\": \"2014-03-29T22:35:32.000Z\",\n"
            + "   \"updated\": \"2014-03-29T22:35:32.417Z\",\n" + "   \"summary\": \"Test Events\",\n"
            + "   \"description\": \"Hack!!\",\n"
            + "   \"location\": \"Northeastern University, Huntington Avenue, Boston, MA, United States\",\n"
            + "   \"creator\": {\n" + "    \"email\": \"vrohitrao@gmail.com\",\n"
            + "    \"displayName\": \"Rohith Vallu\"\n" + "   },\n" + "   \"organizer\": {\n"
            + "    \"email\": \"3tor7ojfqihejcj67n9l4t8g2c@group.calendar.google.com\",\n"
            + "    \"displayName\": \"PushEvents\",\n" + "    \"self\": true\n" + "   },\n"
            + "   \"start\": {\n" + "    \"dateTime\": \"2014-03-30T04:30:00+05:30\"\n" + "   },\n"
            + "   \"end\": {\n" + "    \"dateTime\": \"2014-03-30T19:30:00+05:30\"\n" + "   },\n"
            + "   \"visibility\": \"public\",\n"
            + "   \"iCalUID\": \"jgpue3stuo3js5qlsodob84voo@google.com\",\n" + "   \"sequence\": 0\n" + "  }\n"
            + " ]\n" + "}";

    Gson gson = new Gson();
    try {
        JSONObject jsonData = new JSONObject(jsonString);
        JSONArray jsonArray = jsonData.getJSONArray("items");
        JSONObject eventData;
        Event event = new Event();
        for (int i = 0; i < jsonArray.length(); i++) {

            System.out.println(jsonArray.get(i).toString());
            Items item = gson.fromJson(jsonArray.get(i).toString(), Items.class);

            event.setSummary(item.getSummary());
            event.setLocation(item.getLocation());

            /* Will be adding the attendees here
             ArrayList<EventAttendee> attendees = new ArrayList<EventAttendee>();
             attendees.add(new EventAttendee().setEmail("attendeeEmail"));
             // ...
             event.setAttendees(attendees);
             */
            Date startDate = new Date();
            Date endDate = new Date(startDate.getTime() + 3600000);
            DateTime start = new DateTime(startDate, TimeZone.getDefault().getDefault().getTimeZone("UTC"));
            event.setStart(new EventDateTime().setDateTime(start));
            DateTime end = new DateTime(endDate, TimeZone.getTimeZone("UTC"));
            event.setEnd(new EventDateTime().setDateTime(end));
            HttpTransport transport = new NetHttpTransport();
            JsonFactory jsonFactory = new JacksonFactory();
            Calendar.Builder builder = new Calendar.Builder(transport, jsonFactory, null);
            String clientID = "937140966210.apps.googleusercontent.com";
            String redirectURL = "urn:ietf:wg:oauth:2.0:oob";
            String clientSecret = "qMFSb_cadYDG7uh3IDXWiMQY";
            ArrayList<String> scope = new ArrayList<String>();
            scope.add("https://www.googleapis.com/auth/calendar");

            String url = new GoogleAuthorizationCodeRequestUrl(clientID, redirectURL, scope).build();

            System.out.println("Go to the following link in your browser:");
            System.out.println(url);

            // Read the authorization code from the standard input stream.
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("What is the authorization code?");
            String code = in.readLine();

            GoogleTokenResponse response = new GoogleAuthorizationCodeTokenRequest(transport, jsonFactory,
                    clientID, clientSecret, redirectURL, code, redirectURL).execute();

            GoogleCredential credential = new GoogleCredential().setFromTokenResponse(response);

            Calendar service = new Calendar.Builder(transport, jsonFactory, credential).build();

            Event createdEvent = service.events().insert(item.getSummary(), event).execute();

            System.out.println(createdEvent.getId());

        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:ch.chnoch.appengine.bunddownloader.CredentialMediator.java

License:Apache License

/**
 * Retrieve the authorization URL to authorize the user with the given
 * email address.//from  w  w  w .  j a v  a2s  . c  om
 *
 * @param emailAddress User's e-mail address.
 * @return Authorization URL to redirect the user to.
 */
private String getAuthorizationUrl(String emailAddress) {
    // Generate an authorization URL based on our client settings,
    // the user's email address, and the state parameter, if present.
    GoogleAuthorizationCodeRequestUrl urlBuilder = new GoogleAuthorizationCodeRequestUrl(
            secrets.getWeb().getClientId(), secrets.getWeb().getRedirectUris().get(0), scopes)
                    .setAccessType("offline").setApprovalPrompt("force");
    // Propagate through the current state parameter, so that when the
    // user gets redirected back to our app, they see the file(s) they
    // were originally supposed to see before we realized we weren't
    // authorized.
    //    if (request.getParameter("state") != null) {
    //      urlBuilder.set("state", request.getParameter("state"));
    //    }
    if (emailAddress != null) {
        urlBuilder.set("user_id", emailAddress);
    }
    System.out.println(urlBuilder.build());
    return urlBuilder.build();
}

From source file:com.cloudsearch.oauth.CredentialMediator.java

License:Apache License

/**
 * Retrieve the authorization URL to authorize the user with the given
 * email address./*from  w w w.  j a va2  s. com*/
 *
 * @param emailAddress User's e-mail address.
 * @return Authorization URL to redirect the user to.
 */
private String getAuthorizationUrl(String emailAddress) {
    // Generate an authorization URL based on our client settings,
    // the user's email address, and the state parameter, if present.
    GoogleAuthorizationCodeRequestUrl urlBuilder = new GoogleAuthorizationCodeRequestUrl(
            secrets.getWeb().getClientId(), secrets.getWeb().getRedirectUris().get(0), scopes)
                    .setAccessType("offline").setApprovalPrompt("force");
    // Propagate through the current state parameter, so that when the
    // user gets redirected back to our app, they see the file(s) they
    // were originally supposed to see before we realized we weren't
    // authorized.
    if (request.getState() != null) {
        urlBuilder.set("state", request.getState());
    }
    if (emailAddress != null) {
        urlBuilder.set("user_id", emailAddress);
    }
    return urlBuilder.build();
}

From source file:com.dhara.googlecalendartrial.MainActivity.java

private void setUp(final String userAccount) {
    try {//w ww  .  j a v a2s .c o  m
        String clientId = "424045474279-tdm2pud0f32vovicoajj3hul5ot349r7.apps.googleusercontent.com";
        String clientSecret = "pjCbZO9lwGudNtk9CMKQ7GGx";

        // Or your redirect URL for web based applications.
        String redirectUrl = "https://localhost/oauth2callback"; //"urn:ietf:wg:oauth:2.0:oob";
        String scope = "https://www.googleapis.com/auth/calendar";
        java.util.List<String> listOfScope = new ArrayList<String>();
        listOfScope.add(scope);

        Collection<String> scopes = listOfScope;

        HttpTransport httpTransport = AndroidHttp.newCompatibleTransport();

        // Step 1: Authorize -->
        String authorizationUrl = new GoogleAuthorizationCodeRequestUrl(clientId, redirectUrl, scopes).build();

        // Point or redirect your user to the authorizationUrl.
        System.out.println("Go to the following link in your browser:");
        System.out.println(authorizationUrl);

        // Read the authorization code from the standard input stream.
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("What is the authorization code?");
        String code = in.readLine();

        // End of Step 1 <--

        // Step 2: Exchange -->
        final GoogleTokenResponse response = new GoogleAuthorizationCodeTokenRequest(httpTransport, jsonFactory,
                clientId, clientSecret, code, redirectUrl).execute();
        // End of Step 2 <--

        /*GoogleAccessProtectedResource accessProtectedResource = new Google(
            response.getAccessToken(), httpTransport, jsonFactory, clientId, clientSecret,
            response.getRefreshToken());*/

        credential = new GoogleCredential().setAccessToken(response.getAccessToken());
        Calendar service = new Calendar.Builder(httpTransport, jsonFactory, credential)
                .setApplicationName("GoogleCalendarTrial").setHttpRequestInitializer(credential)
                .setCalendarRequestInitializer(new CalendarRequestInitializer() {
                    @Override
                    protected void initializeCalendarRequest(CalendarRequest<?> calendarRequest)
                            throws IOException {
                        super.initializeCalendarRequest(calendarRequest);
                        ArrayMap<String, Object> customKeys = new ArrayMap<String, Object>();
                        customKeys.put("xoauth_requestor_id", userAccount);
                        calendarRequest.setUnknownKeys(customKeys);
                        calendarRequest.setOauthToken(response.getAccessToken());
                        calendarRequest.setKey(apiKey);
                    }
                }).build();

        List find = service.events().list("primary");
        Events events = find.execute();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.dnalog.fmrp.google.GoogleClientCredentials.java

License:Apache License

public static Credential authorize(GoogleClientSecrets clientSecrets, List scopes) throws Exception {

    String authorizationCode = "";
    String authorizeUrl = new GoogleAuthorizationCodeRequestUrl(clientSecrets,
            (clientSecrets.getDetails().getRedirectUris().get(0)), scopes).setState("").build();

    System.out.println("Paste this URL into a web browser to authorize BigQuery Access:\n" + authorizeUrl);

    System.out.println("... and type the code you received here: ");
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

    authorizationCode = in.readLine();//ww  w .  j  a  v a  2s  . c o m

    GoogleAuthorizationCodeFlow flow = getFlow(clientSecrets, scopes);

    GoogleTokenResponse response = flow.newTokenRequest(authorizationCode)
            .setRedirectUri(clientSecrets.getDetails().getRedirectUris().get(0)).execute();

    System.out.println("Token response: " + response);

    return flow.createAndStoreCredential(response, null);
}

From source file:com.google.cloud.bigquery.samples.BigQueryJavaGettingStarted.java

License:Apache License

/**
 * Creates an authorized BigQuery client service using the OAuth 2.0 protocol
 *
 * This method first creates a BigQuery authorization URL, then prompts the
 * user to visit this URL in a web browser to authorize access. The
 * application will wait for the user to paste the resulting authorization
 * code at the command line prompt.//from w w w.  j  av a2s.  c o m
 *
 * @return an authorized BigQuery client
 * @throws IOException
 */
public static Bigquery createAuthorizedClient() throws IOException {

    String authorizeUrl = new GoogleAuthorizationCodeRequestUrl(clientSecrets, REDIRECT_URI, SCOPES)
            .setState("").build();

    System.out.println("Paste this URL into a web browser to authorize BigQuery Access:\n" + authorizeUrl);

    System.out.println("... and type the code you received here: ");
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    String authorizationCode = in.readLine();

    // Exchange the auth code for an access token and refresh token
    Credential credential = exchangeCode(authorizationCode);

    return new Bigquery(TRANSPORT, JSON_FACTORY, credential);
}

From source file:com.google.cloud.tools.eclipse.appengine.login.GoogleLoginService.java

License:Apache License

/**
 * Returns a URL through which users can login.
 *
 * @param redirectUrl URL to which the login result is directed. For example, a local web
 *     server listening on the URL can receive an authorization code from it.
 *//* ww w  . j ava 2s.c  o  m*/
public static String getGoogleLoginUrl(String redirectUrl) {
    return new GoogleAuthorizationCodeRequestUrl(Constants.getOAuthClientId(), redirectUrl,
            GoogleLoginService.OAUTH_SCOPES).toString();
}

From source file:com.google.drive.samples.dredit.CredentialMediator.java

License:Apache License

/**
 * Retrieve the authorization URL to authorize the user with the given
 * email address.//from w  w  w.  j  a  v a2s  . c om
 *
 * @param emailAddress User's e-mail address.
 * @return Authorization URL to redirect the user to.
 */
private String getAuthorizationUrl(String emailAddress) {
    // Generate an authorization URL based on our client settings,
    // the user's email address, and the state parameter, if present.
    GoogleAuthorizationCodeRequestUrl urlBuilder = new GoogleAuthorizationCodeRequestUrl(
            secrets.getWeb().getClientId(), secrets.getWeb().getRedirectUris().get(0), scopes)
                    .setAccessType("offline").setApprovalPrompt("force");
    // Propagate through the current state parameter, so that when the
    // user gets redirected back to our app, they see the file(s) they
    // were originally supposed to see before we realized we weren't
    // authorized.
    if (request.getParameter("state") != null) {
        urlBuilder.set("state", request.getParameter("state"));
    }
    if (emailAddress != null) {
        urlBuilder.set("user_id", emailAddress);
    }
    return urlBuilder.build();
}

From source file:com.google.refine.extension.gdata.GDataExtension.java

License:Open Source License

static public String getAuthorizationUrl(ButterflyModule module, HttpServletRequest request)
        throws MalformedURLException {
    String authorizedUrl = makeRedirectUrl(module, request);

    // New Oauth2
    GoogleAuthorizationCodeRequestUrl url = new GoogleAuthorizationCodeRequestUrl(CLIENT_ID, authorizedUrl, // execution continues at authorized on redirect
            Arrays.asList("https://www.googleapis.com/auth/fusiontables",
                    "https://www.googleapis.com/auth/drive", // create new spreadsheets
                    "https://spreadsheets.google.com/feeds"));

    return url.toString();

}

From source file:com.google.sites.liberation.util.Auth.java

License:Apache License

/**
 * Method generates google api authorization url
 *///  w  w  w.j ava  2s  .c om
public String generateAuthUrl() {
    LOGGER.debug("Google API App Authorization URL was generated!");
    return new GoogleAuthorizationCodeRequestUrl(CLIENT_ID, REDIRECT_URI, SCOPES).setAccessType("offline")
            .setApprovalPrompt("force").build();
}