/**
  * Gets the login url.
  *
  * @return the login url
  */
 public static String getLoginUrl() {
   OAuthService service = getService();
   Token token = service.getRequestToken();
   Logger.info("Request Token - " + token.getToken() + " with secret " + token.getSecret());
   Cache.add(token.getToken(), token.getSecret());
   return service.getAuthorizationUrl(token);
 }
 @Test
 public void shouldExtractTokenFromOAuthStandardResponse() {
   String response = "oauth_token=hh5s93j4hdidpola&oauth_token_secret=hdhd0244k9j7ao03";
   Token extracted = extractor.extract(response);
   assertEquals("hh5s93j4hdidpola", extracted.getToken());
   assertEquals("hdhd0244k9j7ao03", extracted.getSecret());
 }
    @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());
  }
 @Test
 public void shouldExtractTokenFromResponseWithCallbackConfirmed() {
   String response =
       "oauth_token=hh5s93j4hdidpola&oauth_token_secret=hdhd0244k9j7ao03&callback_confirmed=true";
   Token extracted = extractor.extract(response);
   assertEquals("hh5s93j4hdidpola", extracted.getToken());
   assertEquals("hdhd0244k9j7ao03", extracted.getSecret());
 }
  /*
   * (non-Javadoc)
   *
   * @see
   * javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest
   * , javax.servlet.http.HttpServletResponse)
   */
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    log.info("GET got parameters: " + req.getParameterMap());
    log.info("HTTP Session: " + req.getSession().getAttributeNames());

    HttpSession httpsession = req.getSession();

    try {

      OAuth2Provider provider =
          OAuth2Provider.valueOf((String) httpsession.getAttribute("oauth.service"));
      log.info("Got provider: " + provider);

      String oauthVerifier = "";
      Token requestToken = null;
      Token accessToken = new Token("", provider.getSecret());
      OAuthService service = provider.getOAuthService();

      if (provider.getApi() instanceof DefaultApi20) {
        oauthVerifier = req.getParameter("code");
        log.info("got OAuth 2.0 authorization code: " + oauthVerifier);

      } else if (provider.getApi() instanceof DefaultApi10a) {
        oauthVerifier = req.getParameter("oauth_verifier");
        log.info("got OAuth 1.0a verifier: " + oauthVerifier);
        requestToken =
            req.getParameter("oauth_token") != null
                ? new Token((String) req.getParameter("oauth_token"), provider.getSecret())
                : (Token) httpsession.getAttribute("oauth.requestToken");
      }

      Verifier verifier = new Verifier(oauthVerifier);
      accessToken = service.getAccessToken(requestToken, verifier);
      log.info(
          "Got a OAuth access token: " + accessToken.getToken() + ", " + accessToken.getSecret());

      Cookie accessTokenCookie = new Cookie("oauth.accessToken", accessToken.getToken());
      accessTokenCookie.setMaxAge(14 * 24 * 60 * 60);
      accessTokenCookie.setPath("/");
      resp.addCookie(accessTokenCookie);
      Cookie serviceCookie = new Cookie("oauth.service", provider.toString());
      serviceCookie.setPath("/");
      serviceCookie.setMaxAge(14 * 24 * 60 * 60);
      resp.addCookie(serviceCookie);
      Cookie secretCookie = new Cookie("oauth.secret", accessToken.getSecret());
      secretCookie.setPath("/");
      secretCookie.setMaxAge(14 * 24 * 60 * 60);
      resp.addCookie(secretCookie);

      resp.sendRedirect((String) req.getSession().getAttribute("http.referer"));

    } catch (Exception e) {
      log.log(Level.WARNING, e.getLocalizedMessage(), e);
    }
  }
Esempio n. 7
0
 public OAuthToken getRequestToken(String clientId, String clientSecret) {
   OAuthService service =
       new ServiceBuilder()
           .provider(LinkedInApi.class)
           .apiKey(clientId)
           .apiSecret(clientSecret)
           .build();
   Token requestToken = service.getRequestToken();
   OAuthToken result = new OAuthToken();
   result.setToken(requestToken.getToken());
   result.setTokenSecret(requestToken.getSecret());
   return result;
 }
Esempio n. 8
0
 public boolean createTumblrUser(String oauth_token, String oauth_verifier)
     throws RemoteException, SQLException {
   Verifier verifier = new Verifier(oauth_verifier);
   Token accessToken = RMIServer.service.getAccessToken(RMIServer.request_token, verifier);
   String user_token = accessToken.getToken();
   String user_secret = accessToken.getSecret();
   Token newToken = new Token(user_token, user_secret);
   OAuthRequest request = new OAuthRequest(Verb.GET, "https://api.tumblr.com/v2/user/info");
   request.addHeader("Accept", "application/json");
   RMIServer.service.signRequest(newToken, request);
   System.out.println(request.getHeaders().keySet());
   org.scribe.model.Response response = request.send();
   JSONObject jsonresponse = new JSONObject(response.getBody());
   String name = jsonresponse.getJSONObject("response").getJSONObject("user").getString("name");
   ResultSet resultSet =
       connection
           .createStatement()
           .executeQuery("select * from users where username = \"" + name + "\"");
   if (resultSet.next()) {
     connection
         .createStatement()
         .execute(
             "update users set userToken = \""
                 + user_token
                 + "\" , userSecret = \""
                 + user_secret
                 + "\" where username = \""
                 + name
                 + "\"");
   } else {
     connection
         .createStatement()
         .execute(
             "insert into users (username,password, balance , userToken, userSecret) values (\""
                 + name
                 + "\","
                 + "\"tumblr\","
                 + 100
                 + ", "
                 + "\""
                 + user_token
                 + "\", "
                 + "\""
                 + user_secret
                 + "\")");
   }
   return true;
 }
Esempio n. 9
0
 public void testOAuthCredential() {
   OAuthCredential credential = new OAuthCredential(REQUEST_TOKEN, TOKEN, VERIFIER, TYPE);
   assertEquals(TOKEN, credential.getToken());
   assertEquals(VERIFIER, credential.getVerifier());
   assertEquals(TYPE, credential.getProviderType());
   Token requestToken = credential.getRequestToken();
   assertEquals(TOKEN, requestToken.getToken());
   assertEquals(SECRET, requestToken.getSecret());
   // test serialization
   byte[] bytes = CommonHelper.serialize(credential);
   OAuthCredential credential2 = (OAuthCredential) CommonHelper.unserialize(bytes);
   assertEquals(credential.getRequestToken().toString(), credential2.getRequestToken().toString());
   assertEquals(credential.getToken(), credential2.getToken());
   assertEquals(credential.getVerifier(), credential2.getVerifier());
   assertEquals(credential.getProviderType(), credential2.getProviderType());
 }
Esempio n. 10
0
 /**
  * Retrieve an OAuth 1.0 access token from the myExperiment response.
  *
  * @param pageParameters page params
  * @param service myExperiment OAuth service instance
  * @return the access token
  */
 private Token retrieveMyExpAccessToken(PageParameters pageParameters, OAuthService service) {
   Token accessToken = null;
   if (!pageParameters.get(MyExpApi.OAUTH_VERIFIER).isEmpty()) {
     Verifier verifier = new Verifier(pageParameters.get(MyExpApi.OAUTH_VERIFIER).toString());
     Token requestToken = MySession.get().getRequestToken();
     LOG.debug(
         "Request token: "
             + requestToken.toString()
             + " verifier: "
             + verifier.getValue()
             + " service: "
             + service.getAuthorizationUrl(requestToken));
     accessToken = service.getAccessToken(requestToken, verifier);
   }
   return accessToken;
 }
Esempio n. 11
0
  /*
   * (non-Javadoc)
   *
   * @see org.slc.sli.api.client.impl.IRESTClient#connect(java.lang.String, java.lang.String)
   */
  @Override
  public Response connect(final String authorizationCode)
      throws OAuthException, MalformedURLException, URISyntaxException {
    OAuthService service =
        new ServiceBuilder()
            .provider(SliApi.class)
            .apiKey(config.getApiKey())
            .apiSecret(config.getApiSecret())
            .callback(config.getCallback())
            .build();
    Verifier verifier = new Verifier(authorizationCode);
    Token t = null;
    SliApi.TokenResponse r =
        ((SliApi.SLIOauth20ServiceImpl) service)
            .getAccessToken(new Token(config.getApiSecret(), authorizationCode), verifier, t);

    if (r != null && r.getToken() != null) {
      accessToken = r.getToken();
      sessionToken = accessToken.getToken();
    }

    ResponseBuilder builder = Response.status(r.getOauthResponse().getCode());
    for (Map.Entry<String, String> entry : r.getOauthResponse().getHeaders().entrySet()) {
      if (entry.getKey() == null) {
        builder.header("Status", entry.getValue());
      } else {
        builder.header(entry.getKey(), entry.getValue());
      }
    }
    builder.entity(r.getOauthResponse().getBody());

    return builder.build();
  }
Esempio n. 12
0
  @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");
  }
Esempio n. 13
0
  @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");
  }
  private String getSignature(OAuthRequest request, Token token) {
    config.log("generating signature...");
    String baseString = api.getBaseStringExtractor().extract(request);
    String signature =
        api.getSignatureService()
            .getSignature(baseString, config.getApiSecret(), token.getSecret());

    config.log("base string is: " + baseString);
    config.log("signature is: " + signature);
    return signature;
  }
Esempio n. 15
0
  public OAuthToken getAccessToken(
      String clientId, String clientSecret, String authorizationCode, OAuthToken requestToken) {
    OAuthToken token = null;

    try {
      OAuthService service =
          new ServiceBuilder()
              .provider(LinkedInApi.class)
              .apiKey(clientId)
              .apiSecret(clientSecret)
              .build();
      Verifier verifier = new Verifier(authorizationCode);
      Token reqToken = new Token(requestToken.getToken(), requestToken.getTokenSecret());
      Token accessToken = service.getAccessToken(reqToken, verifier);
      token = new OAuthToken();
      token.setToken(accessToken.getToken());
      token.setTokenSecret(accessToken.getSecret());
    } catch (Exception e) {
      log.error("Error getting AccessToken", e);
    }

    return token;
  }
Esempio n. 16
0
 /**
  * The code in this method is based on this blog post:
  * https://www.sammyk.me/the-single-most-important-way-to-make-your-facebook-app-more-secure and
  * this answer:
  * https://stackoverflow.com/questions/7124735/hmac-sha256-algorithm-for-signature-calculation
  *
  * @param url the URL to which we're adding the proof
  * @param token the application token we pass back and forth
  * @return URL with the appsecret_proof parameter added
  */
 protected String computeAppSecretProof(String url, Token token) {
   try {
     Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
     SecretKeySpec secret_key = new SecretKeySpec(this.secret.getBytes("UTF-8"), "HmacSHA256");
     sha256_HMAC.init(secret_key);
     String proof =
         org.apache.commons.codec.binary.Hex.encodeHexString(
             sha256_HMAC.doFinal(token.getToken().getBytes("UTF-8")));
     url = CommonHelper.addParameter(url, APPSECRET_PARAMETER, proof);
     return url;
   } catch (Exception e) {
     throw new TechnicalException("Unable to compute appsecret_proof", e);
   }
 }
  @Betamax(tape = "EtsyAPILibraryTape")
  @Test
  public void testRetrieveAccessToken() {
    authenticate();

    Token accessTokenBefore = requestManager.getAccessToken();
    assertEquals(true, requestManager.retrieveAccessToken());
    Token accessTokenAfter = requestManager.getAccessToken();

    assertEquals(accessTokenBefore.getToken(), accessTokenAfter.getToken());
    assertEquals(accessTokenBefore.getSecret(), accessTokenAfter.getSecret());
  }
  /** {@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);
    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();
    System.out.println("Got the Refresh Token!");
    System.out.println("(if your curious here's the response: " + response.getBody() + " )");
    return api.getAccessTokenExtractor().extract(response.getBody());
  }
  public static void authenticateEvernote(
      RenderRequest renderRequest, PortletSession portletSession, ThemeDisplay themeDisplay)
      throws OAuthException {

    HttpServletRequest request = PortalUtil.getHttpServletRequest(renderRequest);
    String authorizationUrl = StringPool.BLANK;

    try {

      OAuthService service = getOAuthService(request, themeDisplay);

      if (PortalUtil.getOriginalServletRequest(request).getParameter(OAUTH_VERIFIER) == null) {
        // Send an OAuth message to the Provider asking for a new Request
        // Token because we don't have access to the current user's account.
        Token scribeRequestToken = service.getRequestToken();

        portletSession.setAttribute(REQUEST_TOKEN, scribeRequestToken.getToken());
        portletSession.setAttribute(REQUEST_TOKEN_SECRET, scribeRequestToken.getSecret());

        authorizationUrl = EVERNOTE_SERVICE.getAuthorizationUrl(scribeRequestToken.getToken());

      } else {
        // Send an OAuth message to the Provider asking to exchange the
        // existing Request Token for an Access Token
        Token scribeRequestToken =
            new Token(
                portletSession.getAttribute(REQUEST_TOKEN).toString(),
                portletSession.getAttribute(REQUEST_TOKEN_SECRET).toString());

        Verifier scribeVerifier =
            new Verifier(
                PortalUtil.getOriginalServletRequest(request).getParameter(OAUTH_VERIFIER));

        Token scribeAccessToken = service.getAccessToken(scribeRequestToken, scribeVerifier);

        EvernoteAuth evernoteAuth =
            EvernoteAuth.parseOAuthResponse(EVERNOTE_SERVICE, scribeAccessToken.getRawResponse());

        portletSession.setAttribute(ACCESS_TOKEN, evernoteAuth.getToken());
      }

    } catch (Exception e) {
      throw new OAuthException(e);
    }

    renderRequest.setAttribute(AUTHORIZATION_URL, authorizationUrl);
  }
 private String getAuthorizationUrl(Token token) {
   return TEST_AUTHORIZATION_URL + "?authToken=" + token.getToken();
 }
 /**
  * {@inheritDoc}
  *
  * <p>LinkedIn uses the query parameter 'oauth2_access_token' rather than 'access_token'.
  */
 @Override
 public void signRequest(Token accessToken, OAuthRequest request) {
   request.addQuerystringParameter("oauth2_access_token", accessToken.getToken());
 }
Esempio n. 22
0
 @Override
 public String getAuthorizationUrl(Token requestToken) {
   return String.format(YINXIANG_URL + "/OAuth.action?oauth_token=%s", requestToken.getToken());
 }
Esempio n. 23
0
 /**
  * Adds the token to the URL in question. If we require appsecret_proof, then this method will
  * also add the appsecret_proof parameter to the URL, as Facebook expects.
  *
  * @param url the URL to modify
  * @param accessToken the token we're passing back and forth
  * @return url with additional parameter(s)
  */
 protected String addExchangeToken(String url, Token accessToken) {
   if (this.useAppsecretProof) {
     url = computeAppSecretProof(url, accessToken);
   }
   return CommonHelper.addParameter(url, EXCHANGE_TOKEN_PARAMETER, accessToken.getToken());
 }
 /** {@inheritDoc} */
 public void signRequest(final Token accessToken, final OAuthRequest request) {
   request.addQuerystringParameter(OAuthConstants.ACCESS_TOKEN, accessToken.getToken());
 }
 @Test
 public void shouldParseResponse() {
   Token token = extractor.extract(response);
   assertEquals(token.getToken(), "I0122HHJKLEM21F3WLPYHDKGKZULAUO4SGMV3ABKFTDT3T3X");
 }
  /** 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());
  }
Esempio n. 27
0
  @Test
  public void test() throws Exception {
    // Create an appropriately sized blocking queue
    BlockingQueue<String> queue = Queues.newLinkedBlockingQueue();

    // Define our endpoint: By default, delimited=length is set (we need this for our processor)
    // and stall warnings are on.
    UserstreamEndpoint endpoint = new UserstreamEndpoint();
    endpoint.stallWarnings(false);

    final Token appToken =
        new Token(
            "NtGAPn05Q74N0sQrAnjvJrU7z", "7sjmEWkQ68yATYjd9GI2oJ4kebTqp0vfi9J0WHIOfFH3XaOfhV");
    final Token accessToken =
        new Token(
            "4235420180-wR8ylQuJh22hh02XJVgHeGdJxWpQIan8SOiVa7s",
            "yVeJHBYwKMB4DzQ997rG8lRZh1kymvf0F0hAoEsdJbh6X");
    Authentication auth =
        new OAuth1(
            appToken.getToken(),
            appToken.getSecret(),
            accessToken.getToken(),
            accessToken.getSecret());
    // Authentication auth = new com.twitter.hbc.httpclient.auth.BasicAuth(username, password);

    final BlockingQueue<Event> events = Queues.newLinkedBlockingQueue();
    // Create a new BasicClient. By default gzip is enabled.
    BasicClient client =
        new ClientBuilder()
            .name("sampleExampleClient")
            .hosts(Constants.USERSTREAM_HOST)
            .endpoint(endpoint)
            .authentication(auth)
            .processor(new StringDelimitedProcessor(queue))
            .eventMessageQueue(events)
            .build();

    // Establish a connection
    client.connect();

    // Do whatever needs to be done with messages
    for (int msgRead = 0; msgRead < 5; msgRead++) {
      if (client.isDone()) {
        System.out.println(
            "Client connection closed unexpectedly: " + client.getExitEvent().getMessage());
        break;
      }

      String msg = queue.poll(5, TimeUnit.SECONDS);
      if (msg == null) {
        System.out.println("Did not receive a message in 5 seconds");
      } else if (msgRead != 0) {
        final ObjectMapper mapper = new ObjectMapper();
        final TwitterData twitterData = mapper.readValue(msg, TwitterData.class);
        System.out.println(msg);
      }
    }

    client.stop();

    // Print some stats
    System.out.printf("The client read %d messages!\n", client.getStatsTracker().getNumMessages());
  }
Esempio n. 28
0
 /**
  * Use this when the user has a code from the browser. This browser-code can be exchanged for a
  * accessToken. The accessToken is used to use further API-calls.
  *
  * @param code the code from the browser
  * @return accessToken
  */
 public String loginWithBrowserCode(String code) {
   Verifier v = new Verifier(code);
   Token accessToken = service.getAccessToken(null, v);
   accessTokenString = accessToken.getToken();
   return accessTokenString;
 }
  /** @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");
    }
  }
Esempio n. 30
0
 @Override
 public String getAuthorizationUrl(Token requestToken) {
   return String.format(AUTHENTICATE_URL, requestToken.getToken());
 }