public AccessToken authUser( String consumerKey, String username, String password, String consumerSecret) throws N0ticeException { log.info( "Attempting to auth user: "******", " + username + ", " + password + ", " + consumerSecret); OAuthRequest request = createOauthRequest(Verb.POST, apiUrl + "/user/auth"); addBodyParameter(request, "consumerkey", consumerKey); addBodyParameter(request, "username", username); addBodyParameter(request, "password", password); // Manually sign this request using the consumer secret rather than the access key/access // secret. addBodyParameter(request, "oauth_signature_method", "HMAC-SHA1"); addBodyParameter(request, "oauth_version", "1.0"); addBodyParameter(request, "oauth_timestamp", Long.toString(DateTimeUtils.currentTimeMillis())); final String effectiveUrl = request.getCompleteUrl() + "?" + request.getBodyContents(); addBodyParameter(request, "oauth_signature", sign(effectiveUrl, consumerSecret)); final Response response = request.send(); final String responseBody = response.getBody(); if (response.getCode() == 200) { return new UserParser().parseAuthUserResponse(responseBody); } handleExceptions(response); throw new N0ticeException(response.getBody()); }
/** {@inheritDoc} */ public Token getAccessToken(Token requestToken, Verifier verifier) { OAuthRequest request = new OAuthRequest(api.getAccessTokenVerb(), api.getAccessTokenEndpoint()); switch (api.getAccessTokenVerb()) { case POST: request.addBodyParameter(OAuthConstants.CLIENT_ID, config.getApiKey()); request.addBodyParameter(OAuthConstants.CLIENT_SECRET, config.getApiSecret()); request.addBodyParameter(OAuthConstants.CODE, verifier.getValue()); request.addBodyParameter(OAuthConstants.REDIRECT_URI, config.getCallback()); if (config.hasScope()) { request.addBodyParameter(OAuthConstants.SCOPE, config.getScope()); } if (config.hasGrantType()) { request.addBodyParameter(OAuthConstants.GRANT_TYPE, config.getGrantType()); } break; case GET: default: request.addQuerystringParameter(OAuthConstants.CLIENT_ID, config.getApiKey()); request.addQuerystringParameter(OAuthConstants.CLIENT_SECRET, config.getApiSecret()); request.addQuerystringParameter(OAuthConstants.CODE, verifier.getValue()); request.addQuerystringParameter(OAuthConstants.REDIRECT_URI, config.getCallback()); if (config.hasScope()) { request.addQuerystringParameter(OAuthConstants.SCOPE, config.getScope()); } if (config.hasGrantType()) { request.addQuerystringParameter(OAuthConstants.GRANT_TYPE, config.getGrantType()); } } Response response = request.send(); return api.getAccessTokenExtractor().extract(response.getBody()); }
protected void remoteProcessAction(ActionRequest actionRequest, ActionResponse actionResponse) throws Exception { ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY); OAuthRequest oAuthRequest = new OAuthRequest(Verb.POST, getServerPortletURL()); setRequestParameters(actionRequest, actionResponse, oAuthRequest); addOAuthParameter(oAuthRequest, "p_p_lifecycle", "1"); addOAuthParameter(oAuthRequest, "p_p_state", WindowState.NORMAL.toString()); Response response = getResponse(themeDisplay.getUser(), oAuthRequest); if (response.getCode() == HttpServletResponse.SC_FOUND) { String redirectLocation = response.getHeader(HttpHeaders.LOCATION); actionResponse.sendRedirect(redirectLocation); } else { HttpServletResponse httpServletResponse = PortalUtil.getHttpServletResponse(actionResponse); httpServletResponse.setContentType(response.getHeader(HttpHeaders.CONTENT_TYPE)); ServletResponseUtil.write(httpServletResponse, response.getStream()); } }
public static void main(String[] args) throws Exception { OAuthService service = new ServiceBuilder().provider(TwitterApi.class).apiKey(apiKey).apiSecret(apiSecret).build(); OAuthRequest request = new OAuthRequest(Verb.POST, URL); request.addBodyParameter("track", "wsop"); Token t = new Token(token, tokenSecret); service.signRequest(t, request); Response response = request.send(); JSONTokener jsonTokener = new JSONTokener(new InputStreamReader(response.getStream(), "UTF-8")); int i = 0; StringBuilder sb = new StringBuilder(); while (i++ < 2) { try { JSONObject jsonObject = new JSONObject(jsonTokener); sb.append(new Tweet(jsonObject).getHTML() + "\n"); } catch (JSONException ex) { throw new IOException("Got JSONException: " + ex.getMessage()); } } System.out.println(HTMLCreator.createHTML(sb)); }
final <T extends ServerResponse> T doPost(CommandArguments args, Class<T> clazz, String url) throws FlickrException { try { OAuthRequest request = new OAuthRequest(Verb.POST, url); // check for proxy, use if available if (proxy != null) { request.setProxy(proxy); } for (Map.Entry<String, Object> param : args.getParameters().entrySet()) { if (param.getValue() instanceof String) { request.addQuerystringParameter(param.getKey(), (String) param.getValue()); } } oauth.signRequest(request); MultipartEntity multipart = args.getBody(request.getOauthParameters()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); multipart.writeTo(baos); request.addPayload(baos.toByteArray()); request.addHeader("Content-type", multipart.getContentType().getValue()); Response response = request.send(); String body = response.getBody(); return parseBody(args, clazz, body); } catch (IOException ex) { throw new UnsupportedOperationException("Error preparing multipart request", ex); } }
protected void downloadApp( PortletRequest portletRequest, PortletResponse portletResponse, long appPackageId, boolean unlicensed, File file) throws Exception { ThemeDisplay themeDisplay = (ThemeDisplay) portletRequest.getAttribute(WebKeys.THEME_DISPLAY); OAuthRequest oAuthRequest = new OAuthRequest(Verb.GET, getServerPortletURL()); setBaseRequestParameters(portletRequest, portletResponse, oAuthRequest); String serverNamespace = getServerNamespace(); addOAuthParameter( oAuthRequest, serverNamespace.concat("appPackageId"), String.valueOf(appPackageId)); addOAuthParameter(oAuthRequest, "p_p_lifecycle", "2"); if (unlicensed) { addOAuthParameter(oAuthRequest, "p_p_resource_id", "serveUnlicensedApp"); } else { addOAuthParameter(oAuthRequest, "p_p_resource_id", "serveApp"); } Response response = getResponse(themeDisplay.getUser(), oAuthRequest); FileUtil.write(file, response.getStream()); }
@Override protected FacebookProfile retrieveUserProfileFromToken(final Token accessToken) { String body = sendRequestForData(accessToken, getProfileUrl(accessToken)); if (body == null) { throw new HttpCommunicationException("Not data found for accessToken : " + accessToken); } final FacebookProfile profile = extractUserProfile(body); addAccessTokenToProfile(profile, accessToken); if (profile != null && this.requiresExtendedToken) { String url = CommonHelper.addParameter(EXCHANGE_TOKEN_URL, OAuthConstants.CLIENT_ID, this.key); url = CommonHelper.addParameter(url, OAuthConstants.CLIENT_SECRET, this.secret); url = addExchangeToken(url, accessToken); final ProxyOAuthRequest request = createProxyRequest(url); final long t0 = System.currentTimeMillis(); final Response response = request.send(); final int code = response.getCode(); body = response.getBody(); final long t1 = System.currentTimeMillis(); logger.debug("Request took : " + (t1 - t0) + " ms for : " + url); logger.debug("response code : {} / response body : {}", code, body); if (code == 200) { logger.debug("Retrieve extended token from : {}", body); final Token extendedAccessToken = this.api20.getAccessTokenExtractor().extract(body); logger.debug("Extended token : {}", extendedAccessToken); addAccessTokenToProfile(profile, extendedAccessToken); } else { logger.error("Cannot get extended token : {} / {}", code, body); } } return profile; }
public String getUserFollowers() { OAuthRequest request = new OAuthRequest(Verb.GET, GET_FOLLOWERS_URL); this.service.signRequest(twToken.getAccessToken(), request); Response response = request.send(); JSONObject res = null; JSONObject followers = new JSONObject(); JSONArray followersList = new JSONArray(); try { res = new JSONObject(response.getBody()); JSONArray followersIDList = res.getJSONArray("ids"); JSONObject other = null; for (int i = 0; i < followersIDList.length(); i++) { // System.out.println(friendsIDList.get(i).toString()); other = getOtherProfileJson(followersIDList.get(i).toString()); // System.out.println(other); if (!other.toString().contains("No user matches for specified terms")) followersList.put(other); followers.put("friends", followersList); } } catch (JSONException e) { response.getBody(); } if (res != null) // return res.toJSONString(); return followers.toString(); else return null; }
@Override protected Void doInBackground(String... verifier) { Verifier v = new Verifier(verifier[0]); // save this token for practical use. Token accessToken = service.getAccessToken(requestToken, v); OAuthRequest request = new OAuthRequest(Verb.GET, "http://api.openstreetmap.org/api/capabilities"); service.signRequest(accessToken, request); Response response = request.send(); Log.i("TakeABreak", response.getBody()); SharedPreferences.Editor editor = settings.edit(); editor.putString("accessToken", accessToken.getToken()); editor.putString("accessSecret", accessToken.getSecret()); // The requestToken is saved for use later on to verify the OAuth request. // See onResume() below editor.putString("requestToken", requestToken.getToken()); editor.putString("requestSecret", requestToken.getSecret()); editor.commit(); mCallback.onSuccess(); return null; }
/** {@inheritDoc} */ public Token refreshAccessToken(Token accessToken) { String accessTokenEndpoint = api.getAccessTokenEndpoint(); if (accessTokenEndpoint.contains("?grant_type=")) { // handle the ugly case where the grant_type parameter is already hardcoded in the constant // url accessTokenEndpoint = accessTokenEndpoint.substring(0, accessTokenEndpoint.indexOf("?")); } OAuthRequest request = new OAuthRequest(api.getAccessTokenVerb(), accessTokenEndpoint); switch (api.getAccessTokenVerb()) { case POST: request.addBodyParameter(OAuthConstants.CLIENT_ID, config.getApiKey()); request.addBodyParameter(OAuthConstants.CLIENT_SECRET, config.getApiSecret()); // request.addBodyParameter(OAuthConstants.REDIRECT_URI, config.getCallback()); request.addBodyParameter(OAuthConstants.GRANT_TYPE, api.getRefreshTokenParameterName()); request.addBodyParameter(api.getRefreshTokenParameterName(), accessToken.getToken()); break; case GET: default: request.addQuerystringParameter(OAuthConstants.CLIENT_ID, config.getApiKey()); request.addQuerystringParameter(OAuthConstants.CLIENT_SECRET, config.getApiSecret()); request.addQuerystringParameter(OAuthConstants.REDIRECT_URI, config.getCallback()); request.addQuerystringParameter( OAuthConstants.GRANT_TYPE, api.getRefreshTokenParameterName()); request.addQuerystringParameter(api.getRefreshTokenParameterName(), accessToken.getToken()); } Response response = request.send(); return api.getAccessTokenExtractor().extract(response.getBody()); }
public User updateUserDetails(String username, String displayName, String bio, MediaFile image) throws N0ticeException { OAuthRequest request = createOauthRequest(Verb.POST, apiUrl + "/user/" + username); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); if (displayName != null) { addStringPart(entity, "displayName", displayName); } if (bio != null) { addStringPart(entity, "bio", bio); } if (image != null) { entity.addPart("image", new ByteArrayBody(image.getData(), image.getFilename())); } request.addHeader("Content-Type", entity.getContentType().getValue()); addMultipartEntity(request, entity); oauthSignRequest(request); Response response = request.send(); final String repsonseBody = response.getBody(); if (response.getCode() == 200) { return new UserParser().parseUserProfile(repsonseBody); } handleExceptions(response); throw new N0ticeException(response.getBody()); }
public Noticeboard editNoticeboard( String domain, String name, String description, Boolean moderated, Boolean featured, MediaFile cover) throws N0ticeException { OAuthRequest request = createOauthRequest(Verb.POST, urlBuilder.noticeBoard(domain)); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); addEntityPartParameter(entity, "name", name); addEntityPartParameter(entity, "description", description); addEntityPartParameter( entity, "moderated", moderated != null ? Boolean.toString(moderated) : null); addEntityPartParameter( entity, "featured", featured != null ? Boolean.toString(featured) : null); if (cover != null) { entity.addPart("cover", new ByteArrayBody(cover.getData(), cover.getFilename())); } // TODO implement /* if (endDate != null) { addEntityPartParameter(entity, "endDate", ISODateTimeFormat.dateTimeNoMillis().print(new DateTime(endDate))); } if (cover != null) { entity.addPart("cover", new ByteArrayBody(cover.getData(), cover.getFilename())); } StringBuilder supportedMediaTypesValue = new StringBuilder(); Iterator<MediaType> supportedMediaTypesIterator = supportedMediaTypes.iterator(); while(supportedMediaTypesIterator.hasNext()) { supportedMediaTypesValue.append(supportedMediaTypesIterator.next()); if (supportedMediaTypesIterator.hasNext()) { supportedMediaTypesValue.append(COMMA); } } addEntityPartParameter(entity, "supportedMediaTypes", supportedMediaTypesValue.toString()); if (group != null) { addEntityPartParameter(entity, "group", group); } */ request.addHeader("Content-Type", entity.getContentType().getValue()); addMultipartEntity(request, entity); oauthSignRequest(request); Response response = request.send(); final String responseBody = response.getBody(); if (response.getCode() == 200) { return noticeboardParser.parseNoticeboardResult(responseBody); } handleExceptions(response); throw new N0ticeException(response.getBody()); }
/** * Search with term and location. * * @param term Search term * @param latitude Latitude * @param longitude Longitude * @return JSON string response */ public String search(String term, double latitude, double longitude) { OAuthRequest request = new OAuthRequest(Verb.GET, "http://api.yelp.com/v2/search"); request.addQuerystringParameter("term", term); request.addQuerystringParameter("ll", latitude + "," + longitude); this.service.signRequest(this.accessToken, request); Response response = request.send(); return response.getBody(); }
private boolean testAuth() { // Now let's go and ask for a protected resource! System.out.println("Testing authentication..."); Response response = sendRequest(new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL)); System.out.println(response.isSuccessful() ? "Success" : "Failure"); return response.isSuccessful(); }
/** * Search with term and location. * * @param term Search term * @param latitude Latitude * @param longitude Longitude * @return JSON string response */ public String search(String term, String location) { OAuthRequest request = new OAuthRequest(Verb.GET, "http://api.yelp.com/v2/search"); request.addQuerystringParameter("term", term); request.addQuerystringParameter("location", location); this.service.signRequest(this.accessToken, request); Response response = request.send(); return response.getBody(); }
@Override public OAuthUser getUser(OAuthService service, Token accessToken) { OAuthRequest oauthRequest = new OAuthRequest(Verb.GET, "https://api.twitter.com/1.1/account/verify_credentials.json"); service.signRequest(accessToken, oauthRequest); Response oauthResponse = oauthRequest.send(); String body = oauthResponse.getBody(); return parseInfos(body); }
/** * Retrieve an OAuth 2.0 access token from the RODL response. * * @param pageParameters page params * @param service RODL OAuth service instance * @return the access token * @throws URISyntaxException the response details contain invalid URIs */ @SuppressWarnings("unused") private Token retrieveDlibraAccessToken(PageParameters pageParameters, OAuthService service) throws URISyntaxException { Token accessToken = null; // TODO in the OAuth 2.0 implicit grant flow the access token is sent // in URL fragment - how to retrieve it in Wicket? if (!pageParameters.get("access_token").isEmpty() && !pageParameters.get("token_type").isEmpty()) { if (pageParameters.get("token_type").equals("bearer")) { accessToken = new Token(pageParameters.get("access_token").toString(), null); } else { error("Unsupported token type: " + pageParameters.get("token_type").toString()); } } else if (!pageParameters.get("code").isEmpty()) { URI uri = new URI( new DlibraApi().getAccessTokenEndpoint() + "?grant_type=authorization_code&code=" + pageParameters.get("code").toString()); ObjectMapper mapper = new ObjectMapper(); String body = null; try { Response response; try { response = OAuthHelpService.sendRequest(service, Verb.GET, uri); body = response.getBody(); @SuppressWarnings("unchecked") Map<String, String> responseData = mapper.readValue(body, Map.class); if (responseData.containsKey("access_token") && responseData.containsKey("token_type")) { if (responseData.get("token_type").equalsIgnoreCase("bearer")) { accessToken = new Token(responseData.get("access_token"), null); } else { error("Unsupported access token type: " + responseData.get("token_type")); } } else { error("Missing keys from access token endpoint response"); } } catch (OAuthException e) { body = e.getResponse().getBody(); @SuppressWarnings("unchecked") Map<String, String> responseData = mapper.readValue(body, Map.class); error( String.format( "Access token endpoint returned error %s (%s)", responseData.get("error"), responseData.get("error_description"))); } } catch (JsonParseException e) { error("Error in parsing access token endpoint response: " + body); } catch (JsonMappingException e) { error("Error in parsing access token endpoint response: " + body); } catch (IOException e) { error("Error in parsing access token endpoint response: " + body); } } return accessToken; }
/** * Call api endpoint * * @param verb http-method to use, like: GET, POST, PUT, DELETE, PATCH * @param url the api-url to call * @return the output of the api-call, can be a JSON-string */ private String call(Verb verb, String url) { String urlEnd = url; if (!url.startsWith("/")) { urlEnd = "/" + url; } OAuthRequest request = new OAuthRequest(verb, "https://graph.facebook.com/v2.2" + urlEnd); request.addHeader("Authorization", "Bearer " + accessTokenString); Response response = request.send(); return response.getBody(); }
public String search(String location) { OAuthRequest request = new OAuthRequest(Verb.GET, "http://api.yelp.com/business_review_search"); request.addQuerystringParameter("location", location); request.addQuerystringParameter("term", "food"); request.addQuerystringParameter("ywsid", "VM6cprFxivTjEhfQsoxKhQ"); this.service.signRequest(this.accessToken, request); Response response = request.send(); return response.getBody(); }
@Override public BookmarkShort loadDataFromNetwork() throws Exception { final OAuthRequest request = new OAuthRequest( Verb.DELETE, application.getString(R.string.ravelry_url) + String.format( "/people/%s/favorites/%s.json", prefs.username().get(), favoriteId)); Response response = executeRequest(request); return new Gson().fromJson(response.getBody(), BookmarkShort.class); }
/** * Check: https://developer.linkedin.com/docs/fields/basic-profile * * @param accessToken * @return */ public String getBasicProfile(String accessToken) { OAuthRequest oauthRequest = new OAuthRequest( Verb.GET, "https://api.linkedin.com/v1/people/~:(picture-url,email-address)?format=json"); Token token = new Token(accessToken, apiSecret); oAuthService.signRequest(token, oauthRequest); Response oauthResponse = oauthRequest.send(); String responseBody = oauthResponse.getBody(); return responseBody; }
/** {@inheritDoc} */ public Token getAccessToken(Token requestToken, Verifier verifier) { OAuthRequest request = new OAuthRequest(api.getAccessTokenVerb(), api.getAccessTokenEndpoint()); request.addQuerystringParameter(OAuthConstants.GRANT_TYPE, OAuthConstants.AUTHORIZATION_CODE); request.addQuerystringParameter(OAuthConstants.CLIENT_ID, config.getApiKey()); request.addQuerystringParameter(OAuthConstants.CLIENT_SECRET, config.getApiSecret()); request.addQuerystringParameter(OAuthConstants.CODE, verifier.getValue()); request.addQuerystringParameter(OAuthConstants.REDIRECT_URI, config.getCallback()); if (config.hasScope()) request.addQuerystringParameter(OAuthConstants.SCOPE, config.getScope()); Response response = request.send(); return api.getAccessTokenExtractor().extract(response.getBody()); }
@Override public OAuthUser getUser(OAuthService service, Token accessToken) { OAuthRequest oauthRequest = new OAuthRequest( Verb.GET, "http://api.linkedin.com/v1/people/~:(id,first-name,last-name,email-address)"); service.signRequest(accessToken, oauthRequest); Response oauthResponse = oauthRequest.send(); String body = oauthResponse.getBody(); return parseInfos(body); }
public void run() { try { System.out.println("Starting Twitter public stream consumer thread."); // Enter your consumer key and secret below OAuthService service = new ServiceBuilder() .provider(TwitterApi.class) .apiKey("qFiiPwXFjaiRsFAq5OSYHFT0f") .apiSecret("V9t7qXkbjglS76TKy6Xw9U2fukb1Nh1xmtKKR30kXR6noap9Qe") .build(); // Set your access token Token accessToken = new Token( "66266917-XNT9WqkdFO8TQz6VQeCQtYEZIBdgpp82tUxCrIcIW", "2v4EMHESOz4yeajmjj8788mkGa2UOLAeUR1nrJ27tlSek"); // Let's generate the request System.out.println("Connecting to Twitter Public Stream"); OAuthRequest request = new OAuthRequest(Verb.POST, STREAM_URI); request.addHeader("version", "HTTP/1.1"); request.addHeader("host", "stream.twitter.com"); request.setConnectionKeepAlive(true); request.addHeader("user-agent", "Twitter Stream Reader"); request.addBodyParameter( "track", "Bank of America, bofa, bofa_news, bofa_help, ROLB, BMB, Pingit, Ping-it, BarclaysMobileBanking, Barclays Live, Feature Store, Barclays, Barclaycard, BCS, BarclaysWealth, john mcfarlane, @Barclays, @Barclaysuk, hsbc, hsbc_press, citi, Citigroup Inc, RBS, Royal Bank Of Scotland, LLyods Bank, STAN, @StanChart, Santander, NatWest, Halifax, Tesco Bank"); // Set keywords you'd like to track here service.signRequest(accessToken, request); Response response = request.send(); // Create a reader to read Twitter's stream BufferedReader reader = new BufferedReader(new InputStreamReader(response.getStream())); // Create a new file for raw tweets File file = new File("C:\\Users\\Striker\\Desktop\\Tweet Data\\raw_tweet.txt"); FileWriter fw = new FileWriter(file.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); String line; while ((line = reader.readLine()) != null) { latestTweet = line; bw.write(line); bw.newLine(); tweetCount++; System.out.println(line); } bw.close(); } catch (IOException ioe) { ioe.printStackTrace(); } }
public List<ModerationComplaint> getModerationComplaints(String id) throws N0ticeException { final OAuthRequest request = createOauthRequest(Verb.GET, urlBuilder.get(id) + "/flags"); oauthSignRequest(request); final Response response = request.send(); if (response.getCode() == 200) { return moderationComplaintParser.parse(response.getBody()); } handleExceptions(response); throw new N0ticeException(response.getBody()); }
public Content authedGet(String id) throws N0ticeException { final OAuthRequest request = createOauthRequest(Verb.GET, urlBuilder.get(id)); oauthSignRequest(request); final Response response = request.send(); if (response.getCode() == 200) { return searchParser.parseReport(response.getBody()); } handleExceptions(response); throw new N0ticeException(response.getBody()); }
public void closeNoticeboard(String domain) throws N0ticeException { OAuthRequest request = createOauthRequest(Verb.POST, urlBuilder.closeNoticeboard(domain)); oauthSignRequest(request); final Response response = request.send(); if (response.getCode() == 200) { return; } handleExceptions(response); throw new N0ticeException(response.getBody()); }
public boolean voteInteresting(String id) throws N0ticeException { OAuthRequest request = createOauthRequest(Verb.POST, apiUrl + "/" + id + "/vote/interesting"); oauthSignRequest(request); final Response response = request.send(); if (response.getCode() == 200) { return true; } handleExceptions(response); throw new N0ticeException(response.getBody()); }
public int interestingVotes(String id) throws N0ticeException { OAuthRequest request = createOauthRequest(Verb.GET, apiUrl + "/" + id + "/votes/interesting"); final Response response = request.send(); if (response.getCode() == 200) { return searchParser.parseVotes(response.getBody()); } handleExceptions(response); throw new N0ticeException(response.getBody()); }
public boolean deleteReport(String id) throws N0ticeException { OAuthRequest request = createOauthRequest(Verb.DELETE, apiUrl + "/" + id); oauthSignRequest(request); final Response response = request.send(); if (response.getCode() == 200) { return true; } handleExceptions(response); throw new N0ticeException(response.getBody()); }