@Override protected Boolean doInBackground(HashMap<String, String>... params) { SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getActivity()); // Load the saved accessToken Token accessToken = new Token( settings.getString("accessToken", null), settings.getString("accessSecret", null)); OAuthService service = new ServiceBuilder() .provider(OpenStreetMapAPI.class) .apiKey("3rTM4by36P1CsMfiwZ1g58L1c1tZOpQWLUo591tx") .apiSecret("Cl2NKl6LFAvKqXpI7Kvccwyamdz80rHAXLruWhbG") .build(); Toast.makeText(m_a, m_a.getResources().getString(R.string.add_loading), Toast.LENGTH_LONG) .show(); /** Getting a changeset from the api */ OAuthRequest changeset_request = new OAuthRequest(Verb.PUT, "http://api.openstreetmap.org/api/0.6/changeset/create"); String changeset_payload = "<osm>\n" + "<changeset>\n" + "<tag k=\"created_by\" v=\"TakeABreak 1.5\"/>\n" + "</changeset>\n" + "</osm>"; changeset_request.addPayload(changeset_payload); changeset_request.addHeader("Content-Length", Integer.toString(changeset_payload.length())); changeset_request.addHeader("Content-Type", "text/xml"); service.signRequest(accessToken, changeset_request); // the access token from step 4 Response changeset_response = changeset_request.send(); Log.d("TakeABreak", "Changeset: " + changeset_response.getBody()); params[0].put("changeset", changeset_response.getBody()); /** PUT-ing the change proper. */ OAuthRequest request = new OAuthRequest(Verb.PUT, "http://api.openstreetmap.org/api/0.6/node/create"); String payload = generatePayload(params[0]); request.addPayload(payload); request.addHeader("Content-Length", Integer.toString(payload.length())); request.addHeader("Content-Type", "text/xml"); service.signRequest(accessToken, request); // the access token from step 4 Response response = request.send(); // Log.d("TakeABreak", response.toString()); Iterator<Entry<String, String>> it = response.getHeaders().entrySet().iterator(); Log.d("TakeABreak", response.getBody()); // System.out.println(response.getBody()); return response.isSuccessful(); // return true; }
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)); }
@Override public void apply(final RequestTemplate template) { final OAuthRequest request = buildAuthenticationRequest(template); OAuthService service = buildAuthenticationService(); service.signRequest(credentials.accessToken(), request); template.header("Authorization", extractAuthenticationHeader(request)); }
private void oauthSignRequest(OAuthRequest request) throws MissingCredentialsExeception { if (scribeAccessToken != null) { service.signRequest(scribeAccessToken, request); return; } throw new MissingCredentialsExeception(); }
@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); }
/** * 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; }
@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(); } }
/** * Invoke an HTTP GET request on a remote host. You must close the InputStream after you are done * with. * * @param path The request path * @param parameters The parameters (collection of Parameter objects) * @return The Response */ @Override public com.flickr4java.flickr.Response get( String path, Map<String, Object> parameters, String sharedSecret) { OAuthRequest request = new OAuthRequest(Verb.GET, API_HOST + path); for (Map.Entry<String, Object> entry : parameters.entrySet()) { request.addQuerystringParameter(entry.getKey(), String.valueOf(entry.getValue())); } if (proxyAuth) { request.addHeader("Proxy-Authorization", "Basic " + getProxyCredentials()); } RequestContext requestContext = RequestContext.getRequestContext(); Auth auth = requestContext.getAuth(); if (auth != null) { Token requestToken = new Token(auth.getToken(), auth.getTokenSecret()); OAuthService service = createOAuthService(parameters, sharedSecret); service.signRequest(requestToken, request); } if (Flickr.debugRequest) { logger.debug("GET: " + request.getCompleteUrl()); } setTimeouts(request); org.scribe.model.Response scribeResponse = request.send(); try { com.flickr4java.flickr.Response response = null; synchronized (mutex) { String strXml = scribeResponse.getBody(); if (Flickr.debugStream) { logger.debug(strXml); } Document document = builder.parse(new InputSource(new StringReader(strXml))); response = (com.flickr4java.flickr.Response) responseClass.newInstance(); response.parse(document); } return response; } catch (IllegalAccessException e) { throw new FlickrRuntimeException(e); } catch (InstantiationException e) { throw new FlickrRuntimeException(e); } catch (SAXException e) { throw new FlickrRuntimeException(e); } catch (IOException e) { throw new FlickrRuntimeException(e); } }
protected Response getResponse(User user, OAuthRequest oAuthRequest) throws Exception { Token token = oAuthManager.getAccessToken(user); if (token != null) { OAuthService oAuthService = oAuthManager.getOAuthService(); oAuthService.signRequest(token, oAuthRequest); } oAuthRequest.setFollowRedirects(false); return oAuthRequest.send(); }
public static void main(String[] args) { String apiKey = "your_app_id"; String apiSecret = "your_api_secret"; OAuthService service = new ServiceBuilder() // .provider(BitlyApi.class) // .apiKey(apiKey) // .apiSecret(apiSecret) // .callback("http://localhost:8080/oauth_callback") // .debug() // .build(); Scanner in = new Scanner(System.in); System.out.println("=== " + NETWORK_NAME + "'s OAuth Workflow ==="); System.out.println(); // Obtain the Authorization URL System.out.println("Fetching the Authorization URL..."); String authorizationUrl = service.getAuthorizationUrl(EMPTY_TOKEN); System.out.println("Got the Authorization URL!"); System.out.println("Now go and authorize Scribe here:"); System.out.println(authorizationUrl); System.out.println("And paste the authorization code here"); System.out.print(">>"); Verifier verifier = new Verifier(in.nextLine()); System.out.println(); // Trade the Request Token and Verfier for the Access Token System.out.println("Trading the Request Token for an Access Token..."); Token accessToken = service.getAccessToken(EMPTY_TOKEN, verifier); System.out.println("Got the Access Token!"); System.out.println("(if your curious it looks like this: " + accessToken + " )"); System.out.println(); // Now let's go and ask for a protected resource! System.out.println("Now we're going to access a protected resource..."); OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL); service.signRequest(accessToken, request); Response response = request.send(); System.out.println("Got it! Lets see what we found..."); System.out.println(); System.out.println(response.getCode()); System.out.println(response.getBody()); System.out.println(); System.out.println("Thats it man! Go and build something awesome with Scribe! :)"); }
public static void main(String[] args) { // Replace these with your client id and secret final String clientId = "your client id"; final String clientSecret = "your client secret"; final OAuthService service = new ServiceBuilder() .provider(TutByApi.class) .apiKey(clientId) .apiSecret(clientSecret) .grantType("authorization_code") .callback("http://www.example.com/oauth_callback/") .build(); final Scanner in = new Scanner(System.in, "UTF-8"); System.out.println("=== " + NETWORK_NAME + "'s OAuth Workflow ==="); System.out.println(); System.out.println("Fetching the Authorization URL..."); final String authorizationUrl = service.getAuthorizationUrl(EMPTY_TOKEN); System.out.println("Got the Authorization URL!"); System.out.println("Now go and authorize SubScribe here:"); System.out.println(authorizationUrl); System.out.println("And paste the authorization code here"); System.out.print(">>"); final Verifier verifier = new Verifier(in.nextLine()); System.out.println(); // Trade the Request Token and Verfier for the Access Token System.out.println("Trading the Request Token for an Access Token..."); final Token accessToken = service.getAccessToken(EMPTY_TOKEN, verifier); System.out.println("Got the Access Token!"); System.out.println("(if your curious it looks like this: " + accessToken + " )"); System.out.println(); // Now let's go and ask for a protected resource! System.out.println("Now we're going to access a protected resource..."); final OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL); service.signRequest(accessToken, request); final Response response = request.send(); System.out.println("Got it! Lets see what we found..."); System.out.println(); System.out.println(response.getCode()); System.out.println(response.getBody()); System.out.println(); System.out.println("Thats it man! Go and build something awesome with SubScribe! :)"); }
public static void main(String[] args) { OAuthService service = new ServiceBuilder() .provider(Layer7Api.class) .apiKey("Consumer") .apiSecret("Secret") .build(); Scanner in = new Scanner(System.in); System.out.println("=== Layer7's OAuth Toolkit 1.0 Workflow ==="); System.out.println(); // Obtain the Request Token System.out.println("Fetching the Request Token..."); Token requestToken = service.getRequestToken(); System.out.println("Got the Request Token!"); System.out.println(); System.out.println("Now go and authorize Scribe here:"); System.out.println(service.getAuthorizationUrl(requestToken)); System.out.println("And paste the verifier here"); System.out.print(">>"); Verifier verifier = new Verifier(in.nextLine()); System.out.println(); // Trade the Request Token and Verifier for the Access Token System.out.println("Trading the Request Token for an Access Token..."); Token accessToken = service.getAccessToken(requestToken, verifier); System.out.println("Got the Access Token!"); System.out.println("(if your curious it looks like this: " + accessToken + " )"); System.out.println(); // Now let's go and ask for a protected resource! System.out.println("Now we're going to access a protected resource..."); OAuthRequest request = new OAuthRequest(Verb.POST, PROTECTED_RESOURCE_URI); service.signRequest(accessToken, request); Response response = request.send(); System.out.println("Got it! Lets see what we found..."); System.out.println(); System.out.println(response.getBody()); System.out.println(); System.out.println( "Thats it man! Go and build something awesome with Scribe and Layer 7's OAuth Toolkit! :)"); }
public static void main(String[] args) { String apiKey = "357304594324208"; String apiSecret = "8eca9a549d5c3631752c4d472a5814c1"; OAuthService service = new ServiceBuilder() .provider(FacebookApi.class) .apiKey(apiKey) .apiSecret(apiSecret) .callback("https://sharp-night-6938.herokuapp.com/oauth_callback/") .build(); Scanner in = new Scanner(System.in); System.out.println("=== " + NETWORK_NAME + "'s OAuth Workflow ==="); System.out.println(); // Obtain the Authorization URL System.out.println("Fetching the Authorization URL..."); String authorizationUrl = service.getAuthorizationUrl(EMPTY_TOKEN); System.out.println("Got the Authorization URL!"); System.out.println("Now go and authorize Scribe here:"); System.out.println(authorizationUrl); System.out.println("And paste the authorization code here"); System.out.print(">>"); Verifier verifier = new Verifier(in.nextLine()); System.out.println(); // Trade the Request Token and Verfier for the Access Token System.out.println("Trading the Request Token for an Access Token..."); Token accessToken = service.getAccessToken(EMPTY_TOKEN, verifier); System.out.println("Got the Access Token!"); System.out.println("(if your curious it looks like this: " + accessToken + " )"); System.out.println(); // Now let's go and ask for a protected resource! System.out.println("Now we're going to access a protected resource..."); OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL); service.signRequest(accessToken, request); Response response = request.send(); System.out.println("Got it! Lets see what we found..."); System.out.println(); System.out.println(response.getCode()); System.out.println(response.getBody()); System.out.println(); }
@HandlesEvent("loginGoogle") public Resolution loginGoogle() { logger.info("Entrando en LoginGoogle...."); OAuthService service = googleServiceProvider.getService(); logger.debug("OAuth service----->{}", service.getVersion()); Token accessToken = (Token) getContext().getRequest().getSession().getAttribute(ATTR_OAUTH_ACCESS_TOKEN + "Google"); if (accessToken == null) { logger.debug("El access Token es nulo, se crea uno nuevo."); Token requestToken = service.getRequestToken(); getContext() .getRequest() .getSession() .setAttribute(ATTR_OAUTH_REQUEST_TOKEN + "Google", requestToken); String url = AUTHORIZE_URL.concat(requestToken.getToken()); logger.debug("Se redirecciona a la pagina de google: {}", url); return new RedirectResolution(url); } logger.debug("Forward a pagina inicial, el access token esta en sesion: {}", accessToken); // coge perfil usuario OAuthRequest oauthRequest = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL); logger.debug("Se va a conectar al servicio de google: "); service.signRequest(accessToken, oauthRequest); Response oauthResponse = oauthRequest.send(); String body = oauthResponse.getBody(); ObjectMapper mapper = new ObjectMapper(); try { respuestaJson = mapper.readValue(body, new TypeReference<Map<String, Object>>() {}); } catch (IOException e) { logger.error("El mapeado de Json fallo : {}", e.getMessage()); getContext() .getValidationErrors() .addGlobalError(new SimpleError("error.excepcion.jackson", e.getMessage())); } logger.debug("La respuesta body: {}", body); return new ForwardResolution("/WEB-INF/jsp/google.jsp"); }
/** * Makes a request to get the profile of the authenticated user for this provider. * * @param accessToken * @param profileUrl * @return */ protected String sendRequestForProfile(Token accessToken, String profileUrl) { logger.debug("accessToken : {} / profileUrl : {}", accessToken, profileUrl); OAuthRequest request = new OAuthRequest(Verb.GET, profileUrl); service.signRequest(accessToken, request); // for Google if (this instanceof GoogleProvider) { request.addHeader("GData-Version", "3.0"); } Response response = request.send(); int code = response.getCode(); String body = response.getBody(); logger.debug("response code : {} / response body : {}", code, body); if (code != 200) { logger.error("Get the user profile failed, code : " + code + " / body : " + body); return null; } return body; }
public static void main(String[] args) throws MalformedURLException { OAuthService service = new ServiceBuilder() .provider(FoursquareApi.class) .apiKey("FEGFXJUFANVVDHVSNUAMUKTTXCP1AJQD53E33XKJ44YP1S4I") .apiSecret("AYWKUL5SWPNC0CTQ202QXRUG2NLZYXMRA34ZSDW4AUYBG2RC") .build(); Scanner in = new Scanner(System.in); System.out.println("=== Foursquare's OAuth Workflow ==="); System.out.println(); // Obtain the Request Token System.out.println("Fetching the Request Token..."); Token requestToken = service.getRequestToken(); System.out.println("Got the Request Token!"); System.out.println(); System.out.println("Now go and authorize Scribe here:"); System.out.println(service.getAuthorizationUrl(requestToken)); System.out.println("And paste the verifier here"); System.out.print(">>"); Verifier verifier = new Verifier(in.nextLine()); System.out.println(); // Trade the Request Token and Verfier for the Access Token System.out.println("Trading the Request Token for an Access Token..."); Token accessToken = service.getAccessToken(requestToken, verifier); System.out.println("Got the Access Token!"); System.out.println("(if your curious it looks like this: " + accessToken + " )"); System.out.println(); // Now let's go and ask for a protected resource! System.out.println("Now we're going to access a protected resource..."); OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL); service.signRequest(accessToken, request); Response response = request.send(); System.out.println("Got it! Lets see what we found..."); System.out.println(); System.out.println(response.getBody()); System.out.println(); System.out.println("Thats it man! Go and build something awesome with Scribe! :)"); }
@HandlesEvent("callback") public Resolution callback() { logger.debug("El codigo para verificar es: {}", oauth_verifier); // coge request token OAuthService service = googleServiceProvider.getService(); Token requestToken = (Token) getContext() .getRequest() .getSession() .getAttribute(ATTR_OAUTH_REQUEST_TOKEN + "Google"); // coge access token Verifier verifier = new Verifier(oauth_verifier); Token accessToken = service.getAccessToken(requestToken, verifier); logger.debug("El access token es: {}", accessToken.getRawResponse()); // guarda access token en session getContext() .getRequest() .getSession() .setAttribute(ATTR_OAUTH_ACCESS_TOKEN + "Google", accessToken); // coge perfil usuario OAuthRequest oauthRequest = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL); logger.debug("Se va a conectar al servicio de google: "); service.signRequest(accessToken, oauthRequest); Response oauthResponse = oauthRequest.send(); String body = oauthResponse.getBody(); ObjectMapper mapper = new ObjectMapper(); try { respuestaJson = mapper.readValue(body, new TypeReference<Map<String, Object>>() {}); } catch (IOException e) { getContext() .getValidationErrors() .addGlobalError(new SimpleError("error.excepcion.jackson", e.getMessage())); } logger.debug("La respuesta body: {}", oauthResponse.getBody()); return new ForwardResolution("/WEB-INF/jsp/google.jsp"); }
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("0GglmCJSWdauygE0dPYVhRoYN") .apiSecret("aikSSCPcX1AOayVw98MKuPvalUKvPZhaESEJMawVGK9a9bfG0I") .build(); // Set your access token Token accessToken = new Token( "863517241-dba29VzM7RaYMOvwFv03KOdkki6SVluRiRLqc1Ks", "cB8WS8duMCy4I30ZawZJFuv743jLdTWKLKkniMKfZOEQi"); // 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", "java,heroku,twitter"); // Set keywords you'd like to // track here request.addBodyParameter("follow", "4884271164"); // 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())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (IOException ioe) { ioe.printStackTrace(); } }
public synchronized String _request(String end, Verb verb, MaxCDNRequest body, Token token) throws SignatureException, Exception { OAuthService service = new ServiceBuilder().provider(MaxCDNApi.class).apiKey(key).apiSecret(secret).build(); OAuthRequest request = new OAuthRequest(verb, this.MaxCDNrws_url + alias + end); request.addHeader("User-Agent", "Java MaxCDN API Client"); if (verb == Verb.PUT || verb == Verb.POST) { for (int i = 0; i < body.names().length(); i++) { String key = (String) body.names().get(i); request.addBodyParameter(key, body.getString(key)); } } service.signRequest((token == null) ? new Token("", "") : token, request); Response response = request.send(); // Console.log(response.getBody()); return response.getBody(); }
public static void main(String[] args) { // Replace these with your own api key and secret String apiKey = "your_app_id"; String apiSecret = "your_api_secret"; String callbackURL = "your_call_back"; OAuthService service = new ServiceBuilder() .provider(FacebookApi.class) .apiKey(apiKey) .apiSecret(apiSecret) .callback(callbackURL) .grantType(OAuthConstants.CLIENT_CREDENTIALS) .build(); System.out.println("=== " + NETWORK_NAME + "'s OAuth Workflow ==="); System.out.println(); System.out.println( "Getting an access Token with Client Credentials (a.k.a App Login as Facebook defines)"); Token accessToken = service.getAccessToken(EMPTY_TOKEN, null); System.out.println("Got the Access Token!"); System.out.println("(if your curious it looks like this: " + accessToken + " )"); System.out.println(); // Now let's go and ask for a protected resource! System.out.println("Now we're going to access a protected resource..."); OAuthRequest request = new OAuthRequest(Verb.GET, String.format(PROTECTED_RESOURCE_URL, apiKey)); service.signRequest(accessToken, request); Response response = request.send(); System.out.println("Got it! Lets see what we found..."); System.out.println(); System.out.println(response.getCode()); System.out.println(response.getBody()); System.out.println(); System.out.println("Thats it man! Go and build something awesome with Scribe! :)"); }
/** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (request.getParameter("oauth_problem") != null) { if (request.getParameter("oauth_problem").equals("user_refused")) response.sendRedirect("refuse.html"); } else { OAuthService service; Token requestToken, accessToken; OAuthRequest requestLink; org.scribe.model.Response responseLink; DBHandler db = new DBHandler(); service = new ServiceBuilder() .provider(LinkedInApi.class) .apiKey("754z46slfke0xm") .apiSecret("Jm46YNdPTb2toxoY") .build(); String oAuthToken = request.getParameter("oauth_token"); String oAuthVerifier = request.getParameter("oauth_verifier"); String[] data = db.getData(oAuthToken); String oAuthSecret = data[1]; String roomId = data[2]; String email = data[3]; requestToken = new Token(oAuthToken, oAuthSecret); Verifier v = new Verifier(oAuthVerifier); accessToken = service.getAccessToken(requestToken, v); System.out.println("\n\n\n\n\n" + accessToken + "\n\n\n\n\n"); db.setAccessData(email, accessToken.getToken(), accessToken.getSecret()); requestLink = new OAuthRequest(Verb.GET, "https://api.linkedin.com/v1/people/~?format=json"); service.signRequest(accessToken, requestLink); // the access token // from step 4 responseLink = requestLink.send(); if (responseLink.getCode() != 401) { JSONObject j1 = new JSONObject(responseLink.getBody()); TeamchatAPI api = WebAppTeamChatAPI.getTeamchatAPIInstance(getServletConfig()); api.perform( api.context() .byId(roomId) .post( new PrimaryChatlet() .setQuestionHtml( "Now you are authorized to send linkedin updates from teamchat" + "<br/><b>Use following keywords -</b><br/><ul>" + "<li>'profile' - Get Profile Information</li>" + "<li>'post' - Post on LinkedIn</li></ol>" + "<li>'reset' - Remove your account from teamchat</li></ul>"))); request.setAttribute("name", j1.getString("firstName") + " " + j1.getString("lastName")); RequestDispatcher rd = request.getRequestDispatcher("Auth.jsp"); rd.forward(request, response); } else response.sendRedirect("error.html"); } }
@Override public void signRequest(Token accessToken, OAuthRequest request) { oAuthService.signRequest(accessToken, request); }
public Response sendRequest(OAuthRequest r) { service.signRequest(accessToken, r); return r.send(); }
public void signRequest(Token accessToken, OAuthRequest oauthRequest) { oAuthService.signRequest(accessToken, oauthRequest); }
/** * Invoke an HTTP POST request on a remote host. * * @param path The request path * @param parameters The parameters (collection of Parameter objects) * @return The Response object */ @Override public com.flickr4java.flickr.Response post( String path, Map<String, Object> parameters, String sharedSecret, boolean multipart) { OAuthRequest request = new OAuthRequest(Verb.POST, API_HOST + path); if (multipart) { buildMultipartRequest(parameters, request); } else { buildNormalPostRequest(parameters, request); } RequestContext requestContext = RequestContext.getRequestContext(); Auth auth = requestContext.getAuth(); if (auth != null) { Token requestToken = new Token(auth.getToken(), auth.getTokenSecret()); OAuthService service = createOAuthService(parameters, sharedSecret); service.signRequest(requestToken, request); } if (multipart) { // Ensure all parameters (including oauth) are added to payload so signature matches parameters.putAll(request.getOauthParameters()); request.addPayload(buildMultipartBody(parameters, getMultipartBoundary())); } if (proxyAuth) { request.addHeader("Proxy-Authorization", "Basic " + getProxyCredentials()); } if (Flickr.debugRequest) { logger.debug("POST: " + request.getCompleteUrl()); } org.scribe.model.Response scribeResponse = request.send(); try { com.flickr4java.flickr.Response response = null; synchronized (mutex) { String strXml = scribeResponse.getBody(); if (Flickr.debugStream) { logger.debug(strXml); } if (strXml.startsWith("oauth_problem=")) { throw new FlickrRuntimeException(strXml); } Document document = builder.parse(new InputSource(new StringReader(strXml))); response = (com.flickr4java.flickr.Response) responseClass.newInstance(); response.parse(document); } return response; } catch (IllegalAccessException e) { throw new FlickrRuntimeException(e); } catch (InstantiationException e) { throw new FlickrRuntimeException(e); } catch (SAXException e) { throw new FlickrRuntimeException(e); } catch (IOException e) { throw new FlickrRuntimeException(e); } }
public static void saveAccessToken(HttpServletRequest request, OAuthService service, Token accessToken) throws Exception { OAuthRequest _request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL); service.signRequest(accessToken, _request); Response _response = _request.send(); if (_response.getCode() != 200) throw new OAuthException("Can query account information."); String contentType = _response.getHeader("Content-Type"); if (contentType == null) contentType = ""; //String charset = ""; int semicolonPos = contentType.indexOf(';'); if (semicolonPos > 0) { String _charset = contentType.substring(semicolonPos + 1).trim(); if (_charset.startsWith("charset")) { //charset = _charset.substring(_charset.indexOf('=') + 1); } contentType = contentType.substring(0, semicolonPos); } Map<String, String> responseAttributes = null; String response = _response.getBody(); if ("application/json".equals(contentType) || (response.startsWith("{") && response.endsWith("}"))) { JSONObject jsonResponse = new JSONObject(response); if (jsonResponse != null) { if (jsonResponse.has("error")) { throw new OAuthException("Error getting access token: " + System.getProperty("line.separator") + jsonResponse.toString()); } responseAttributes = parseJSONObject(jsonResponse); } } else if ("text/plain".equals(contentType) || (response.contains("=") && response.contains("&"))) { //responseAttributes = OAuthUtil.parseQueryString(response); } if (responseAttributes == null) throw new OAuthException("Get response, but no account information."); String id = responseAttributes.get("id"); String accountName = id + "@facebook.com"; Account found = OAuthRealm._.getAccount(accountName); if (found == null) { Map<SchemaType, String> metadata = new HashMap<SchemaType, String>(); metadata.put(GoogleSchemaType.ID, responseAttributes.get("id")); metadata.put(AXSchemaType.FIRSTNAME, responseAttributes.get("given_name")); metadata.put(AXSchemaType.LASTNAME, responseAttributes.get("family_name")); metadata.put(AXSchemaType.FULLNAME, responseAttributes.get("name")); metadata.put(AXSchemaType.TIMEZONE, responseAttributes.get("timezone")); found = OAuthRealm._.createAccountInDatabase(accountName, metadata); } Account principal = new SubjectAccreditedImpl((AbstractAccount) found, accessToken); HttpSession session = request.getSession(true); Subject subject = new Subject(); //TODO: hardcoded to jetty - rewrite //******************************************************* DefaultIdentityService _identityService = new DefaultIdentityService(); UserIdentity user = _identityService.newUserIdentity(subject, principal, new String[0]); Authentication cached=new HttpSessionAuthentication(session, user); session.setAttribute(HttpSessionAuthentication.__J_AUTHENTICATED, cached); //******************************************************* request.getSession().setAttribute(GOOGLE_ACCESS_TOKEN_SESSION, accessToken); }
/** Callback. */ public static void callback() { // Get Service OAuthService service = getServiceNoCallback(); // Get Query String Token and Verifier Logger.info("LinkedIn Callback - Params: " + params); String oauthToken = params.get("oauth_token"); String oauthVerifier = params.get("oauth_verifier"); Verifier verifier = new Verifier(oauthVerifier); Logger.info("Token: " + oauthToken); Logger.info("Verifier: " + oauthVerifier); // Request Access Token Token accessToken = service.getAccessToken( new Token(oauthToken, Cache.get(oauthToken, String.class)), verifier); // Log Debug Logger.info("LinkedIn Access Token: " + accessToken); // Check Response if (accessToken != null && accessToken.getToken() != null) { // Get Profile Details String url = "http://api.linkedin.com/v1/people/~:(id,first-name,last-name,industry,picture-url,headline)"; OAuthRequest request = new OAuthRequest(Verb.GET, url); service.signRequest(accessToken, request); Response response = request.send(); String responseBody = response.getBody(); Logger.info("Response Body: %s", responseBody); // Check Status if (response == null || response.getCode() != 200) { String msg = ""; if (response != null) { msg = response.getBody(); } throw new UnexpectedException(msg); } // Parse XML Response Map<String, String> data = new HashMap<String, String>(); Document doc = XML.getDocument(responseBody); Node person = doc.getElementsByTagName("person").item(0); NodeList list = person.getChildNodes(); for (int i = 0; i < list.getLength(); i++) { Node n = list.item(i); data.put(n.getNodeName(), n.getTextContent()); } // Load Data Object LinkedInProfile p = new LinkedInProfile( data.get("id"), data.get("first-name"), data.get("last-name"), data.get("industry"), data.get("picture-url"), data.get("headline"), accessToken.getToken()); // Log Debug Logger.info("Profile Data Map: %s", data); Logger.info("Profile Data Object: %s", p); // Do Callback to Calling App try { Class model = Class.forName(getModel()); Method method = model.getMethod("linkedinOAuthCallback", new Class[] {LinkedInProfile.class}); if (Modifier.isStatic(method.getModifiers())) { method.invoke(null, p); } else { throw new UnexpectedException("Method linkedinOAuthCallback method needs to be static"); } } catch (ClassNotFoundException e) { throw new UnexpectedException("Cannot find your model class " + getModel()); } catch (NoSuchMethodException e) { throw new UnexpectedException( "Model class " + getModel() + " must provide a method with this signature: [public static void linkedinOAuthCallback(play.modules.linkedin.LinkedInProfile o)]"); } catch (IllegalAccessException e) { throw new UnexpectedException( "Module linkedin does not have access to call your model's linkedinOAuthCallback(play.modules.linkedin.LinkedInProfile o)"); } catch (InvocationTargetException e) { throw new UnexpectedException( "Module linkedin encountered an error while calling your model's linkedinOAuthCallback(play.modules.linkedin.LinkedInProfile o): " + e.getMessage()); } } else { throw new UnexpectedException("Access Token Unavailable"); } // Redirect to Landing Page redirect(getLandUrl()); }