List of usage examples for com.google.api.client.googleapis.auth.oauth2 GoogleAuthorizationCodeTokenRequest GoogleAuthorizationCodeTokenRequest
public GoogleAuthorizationCodeTokenRequest(HttpTransport transport, JsonFactory jsonFactory,
String tokenServerEncodedUrl, String clientId, String clientSecret, String code, String redirectUri)
From source file:bean.GoogleOpenIdHelper.java
public String getToken(final String authCode) throws IOException { String url = "https://www.googleapis.com/oauth2/v4/token?" + "code=" + authCode + "&" + "client_id=" + CLIENT_ID + "&" + "client_secret=" + CLIENT_SECRET + "&" + "redirect_uri=" + OPEN_CALLBACK_URI + "&" + "grant_type=authorization_code"; GoogleTokenResponse tokenResponse = new GoogleAuthorizationCodeTokenRequest(new NetHttpTransport(), JacksonFactory.getDefaultInstance(), "https://www.googleapis.com/oauth2/v4/token", CLIENT_ID, CLIENT_SECRET, authCode, CALLBACK_URI).execute(); String token = tokenResponse.getIdToken(); return token; /*GoogleIdToken idToken = tokenResponse.parseIdToken(); GoogleIdToken.Payload payload = idToken.getPayload(); String userId = payload.getSubject(); // Use this value as a key to identify a user. String email = payload.getEmail();//from w w w . j a v a 2 s .c o m boolean emailVerified = Boolean.valueOf(payload.getEmailVerified()); String name = (String) payload.get("name"); String pictureUrl = (String) payload.get("picture"); String locale = (String) payload.get("locale"); String familyName = (String) payload.get("family_name"); String givenName = (String) payload.get("given_name"); return userId +"- "+ email+"-"+name+"-"+pictureUrl+"-"+locale+"-"+familyName+"-"+givenName ;*/ }
From source file:calendarevent.CalendarEvent.java
/** * @param args the command line arguments *///from w ww .j a v a 2s .co m 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:com.google.sample.games.PlayerServlet.java
License:Apache License
/** * Exchanges the authcode for an access token credential. The credential * is the associated with the given player. * * @param authCode - the non-null authcode passed from the client. * @param player - the player object which the given authcode is * associated with.//from w w w. j a v a 2 s. c om * @return the HTTP response code indicating the outcome of the exchange. */ private int exchangeAuthCode(String authCode, Player player) { try { // The client_secret.json file is downloaded from the Google API // console. This is used to identify your web application. The // contents of this file should not be shared. // // For the sample, this file is expected to be in the root of the // sample (at the same level as the top level build.gradle file). File secretFile = new File("client_secret.json"); // If we don't have the file, we can't access any APIs, so return // an error. if (!secretFile.exists()) { log("Secret file : " + secretFile.getAbsolutePath() + " does not exist!"); return HttpServletResponse.SC_FORBIDDEN; } GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JacksonFactory.getDefaultInstance(), new FileReader(secretFile)); // For the sample server, make sure that the client secret file // has been updated with actual values. if (clientSecrets.getDetails().getClientId().equals("ReplaceMe")) { String message = "client_secret.json is not configured " + "correctly! Download your app's information and place " + "it in client_secret.json"; log("ERROR: " + message); throw new IllegalStateException(message); } // small hack here to extract the application id of the game from // the client id. String applicationId = extractApplicationId(clientSecrets.getDetails().getClientId()); GoogleTokenResponse tokenResponse = new GoogleAuthorizationCodeTokenRequest(HTTPTransport, JacksonFactory.getDefaultInstance(), "https://www.googleapis.com/oauth2/v4/token", clientSecrets.getDetails().getClientId(), clientSecrets.getDetails().getClientSecret(), authCode, "").execute(); log("hasRefresh == " + (tokenResponse.getRefreshToken() != null)); log("Exchanging authCode: " + authCode + " for token"); Credential credential = new Credential.Builder(BearerToken.authorizationHeaderAccessMethod()) .setJsonFactory(JacksonFactory.getDefaultInstance()).setTransport(HTTPTransport) .setTokenServerEncodedUrl("https://www.googleapis" + ".com/oauth2/v4/token") .setClientAuthentication(new HttpExecuteInterceptor() { @Override public void intercept(HttpRequest request) throws IOException { } }).build().setFromTokenResponse(tokenResponse); player.setCredential(credential); // Now that we have a credential, we can access the Games API. PlayGamesAPI api = new PlayGamesAPI(player, applicationId, HTTPTransport, JacksonFactory.getDefaultInstance()); // Call the verify method, which checks that the access token has // access to the Games API, and that the player id used by the // client matches the playerId associated with the accessToken. boolean ok = api.verifyPlayer(); // This does not add much that is not available on the client, but // is used to demonstrate calling a Games API on the server. if (ok) { ok = api.updatePlayerInfo(); if (ok) { // persist the player. savePlayer(api.getPlayer()); } } return ok ? HttpServletResponse.SC_OK : HttpServletResponse.SC_INTERNAL_SERVER_ERROR; } catch (IOException e) { e.printStackTrace(); } return HttpServletResponse.SC_INTERNAL_SERVER_ERROR; }
From source file:org.wso2.carbon.dataservices.google.tokengen.servlet.TokenEndpoint.java
License:Open Source License
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) { AuthCode authCode = CodeHolder.getInstance().getAuthCodeForSession(request.getSession().getId()); String responseMsg = ""; JSONObject resJson = new JSONObject(); int responseStatus; if (authCode != null) { if (log.isDebugEnabled()) { log.debug("Request received for retrieve access token from session - " + request.getSession().getId()); }/*from w ww.j ava 2s . c o m*/ StringBuffer jb = new StringBuffer(); JSONObject jsonObject; String line = null; try { BufferedReader reader = request.getReader(); while ((line = reader.readLine()) != null) { jb.append(line); } jsonObject = new JSONObject(new JSONTokener(jb.toString())); String clientId = jsonObject.getString(DBConstants.GSpread.CLIENT_ID); String clientSecret = jsonObject.getString(DBConstants.GSpread.CLIENT_SECRET); String redirectURIs = jsonObject.getString(DBConstants.GSpread.REDIRECT_URIS); if (clientId == null || clientId.isEmpty()) { responseStatus = HttpStatus.SC_BAD_REQUEST; responseMsg = "ClientID is null or empty"; } else if (clientSecret == null || clientSecret.isEmpty()) { responseStatus = HttpStatus.SC_BAD_REQUEST; responseMsg = "Client Secret is null or empty"; } else if (redirectURIs == null || redirectURIs.isEmpty()) { responseStatus = HttpStatus.SC_BAD_REQUEST; responseMsg = "Redirect URIs is null or empty"; } else { HttpTransport httpTransport = new NetHttpTransport(); JacksonFactory jsonFactory = new JacksonFactory(); // Step 2: Exchange auth code for tokens GoogleTokenResponse googleTokenResponse = new GoogleAuthorizationCodeTokenRequest(httpTransport, jsonFactory, "https://www.googleapis.com/oauth2/v3/token", clientId, clientSecret, authCode.getAuthCode(), redirectURIs).execute(); resJson.append(DBConstants.GSpread.ACCESS_TOKEN, googleTokenResponse.getAccessToken()); resJson.append(DBConstants.GSpread.REFRESH_TOKEN, googleTokenResponse.getRefreshToken()); responseMsg = resJson.toString(); responseStatus = HttpStatus.SC_OK; if (log.isDebugEnabled()) { log.debug("Access token request successfully served for client id " + clientId); } } } catch (JSONException e) { responseStatus = HttpStatus.SC_INTERNAL_SERVER_ERROR; responseMsg = "Error in Processing accessTokenRequest Error - " + e.getMessage(); log.error(responseMsg, e); } catch (IOException e) { responseStatus = HttpStatus.SC_INTERNAL_SERVER_ERROR; responseMsg = "Error in Processing accessTokenRequest Error - " + e.getMessage(); log.error(responseMsg, e); } catch (Exception e) { responseStatus = HttpStatus.SC_INTERNAL_SERVER_ERROR; responseMsg = "Error in Processing accessTokenRequest Error - " + e.getMessage(); log.error(responseMsg, e); } } else { responseStatus = HttpStatus.SC_ACCEPTED; responseMsg = resJson.toString(); } try { PrintWriter out = response.getWriter(); out.println(responseMsg); response.setStatus(responseStatus); } catch (IOException e) { log.error("Error Getting print writer to write http response Error - " + e.getMessage(), e); response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); } }