Esempio n. 1
0
  /**
   * Constructs the appropriate node object based on the type of the expression.
   *
   * @return
   * @throws Exception
   */
  private ExpNode<T, V> factorTree() throws Exception {

    if (!tokens.hasNext()) return null;
    Token token = tokens.next();
    // System.out.println("factor tree token => " + token.getToken());
    if (token == null) return null;

    if (token.getTokentype() == Types.J_EXPRESSION
        || token.getTokentype() == Types.OGNL_EXPRESSION) {
      // The factor is a number. Return a ConstNode.
      return new ConstNode<T, V>(token);
    } else if (token.getTokentype() == Types.DELIMITER && token.getToken().equals("(")) {
      // The factor is an expression in parentheses.
      ExpNode<T, V> exp = expressionTree();

      if (!(token = tokens.next()).getToken().equals(")"))
        throw new ParseError("Missing right parenthesis.");
      return exp;
    } else if (token == null)
      throw new ParseError("End-of-line encountered in the middle of an expression.");
    else if (token.getToken().equals(")")) throw new ParseError("Extra right parenthesis.");
    else if (token.getToken().equals("&") || token.getToken().equals("|"))
      throw new ParseError("Misplaced operator.");
    else throw new ParseError("Unexpected character \"" + token.getToken() + "\" encountered.");
  } // end factorTree()
  /** {@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());
  }
Esempio n. 3
0
 /**
  * Authorizes a request token for given principal and roles and returns verifier.
  *
  * @param token Request token to authorize.
  * @param userPrincipal User principal to authorize the token for.
  * @param roles Set of roles to authorize the token for.
  * @return OAuth verifier value for exchanging this token for an access token.
  */
 public String authorizeToken(
     final Token token, final Principal userPrincipal, final Set<String> roles) {
   final Token authorized = token.authorize(userPrincipal, roles);
   requestTokenByTokenString.put(token.getToken(), authorized);
   final String verifier = newUUIDString();
   verifierByTokenString.put(token.getToken(), verifier);
   return verifier;
 }
 @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());
 }
Esempio n. 5
0
 public boolean isSessionValid() {
   if (mAccessToken != null) {
     return (!TextUtils.isEmpty(mAccessToken.getToken())
         && (mAccessToken.getExpiresIn() == 0
             || (System.currentTimeMillis() < mAccessToken.getExpiresIn())));
   }
   return false;
 }
 @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());
 }
Esempio n. 7
0
 @Override
 public OAuth1Token newRequestToken(
     final String consumerKey,
     final String callbackUrl,
     final Map<String, List<String>> attributes) {
   final Token rt =
       new Token(newUUIDString(), newUUIDString(), consumerKey, callbackUrl, attributes);
   requestTokenByTokenString.put(rt.getToken(), rt);
   return rt;
 }
Esempio n. 8
0
  /**
   * Method to build the expression tree using recursive descent parser technique. Handles the OR
   * condition.
   *
   * @return
   * @throws Exception
   */
  private ExpNode<T, V> expressionTree() throws Exception {

    ExpNode<T, V> exp; // The expression tree for the expression.
    exp = termTree(); // Start with the first term.

    if (!tokens.hasNext()) return exp;

    Token token = tokens.next();
    // System.out.println("expression tree token => " + token.getToken());
    if (token != null && token.getToken().equals("|")) {
      // Read the next term and combine it with the
      // previous terms into a bigger expression tree.
      while (token != null && token.getToken().equals("|")) {
        ExpNode<T, V> nextTerm = termTree();
        exp = new BinOpNode<T, V>(token, exp, nextTerm);
        token = tokens.hasNext() ? tokens.next() : null;
      }
    }

    if (token != null) tokens.goBack(1);
    return exp;
  } // end expressionTree()
Esempio n. 9
0
  /**
   * Method to build the expression tree using recursive descent parser technique. Handles the AND
   * condition.
   *
   * @return
   * @throws Exception
   */
  private ExpNode<T, V> termTree() throws Exception {

    ExpNode<T, V> term; // The expression tree representing the term.
    term = factorTree();

    if (!tokens.hasNext()) return term;
    Token token = tokens.next();
    // System.out.println("term tree token => " + token.getToken());
    if (token != null && token.getToken().equals("&")) {
      // Read the next factor, and combine it with the
      // previous factors into a bigger expression tree.
      while (token != null && token.getToken().equals("&")) {
        ExpNode<T, V> nextFactor = factorTree();
        term = new BinOpNode<T, V>(token, term, nextFactor);
        token = tokens.hasNext() ? tokens.next() : null;
      }
    }

    if (token != null) tokens.goBack(1);

    return term;
  } // end termValue()
Esempio n. 10
0
  public void addAccessToken(
      final String token,
      final String secret,
      final String consumerKey,
      final String callbackUrl,
      final Principal principal,
      final Set<String> roles,
      final MultivaluedMap<String, String> attributes) {
    final Token accessToken =
        new Token(token, secret, consumerKey, callbackUrl, principal, roles, attributes);

    accessTokenByTokenString.put(accessToken.getToken(), accessToken);
  }
Esempio n. 11
0
 @Override
 public OAuth1Token newAccessToken(final OAuth1Token requestToken, final String verifier) {
   if (verifier == null
       || requestToken == null
       || !verifier.equals(verifierByTokenString.remove(requestToken.getToken()))) {
     return null;
   }
   final Token token = requestTokenByTokenString.remove(requestToken.getToken());
   if (token == null) {
     return null;
   }
   final Token at = new Token(newUUIDString(), newUUIDString(), token);
   accessTokenByTokenString.put(at.getToken(), at);
   return at;
 }
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
  public void dialog(
      Context context, WeiboParameters parameters, final WeiboDialogListener listener) {
    parameters.add("client_id", APP_KEY);
    parameters.add("response_type", "token");
    parameters.add("redirect_uri", mRedirectUrl);
    parameters.add("display", "mobile");

    if (isSessionValid()) {
      parameters.add(TOKEN, mAccessToken.getToken());
    }
    String url = URL_OAUTH2_ACCESS_AUTHORIZE + "?" + Utility.encodeUrl(parameters);
    if (context.checkCallingOrSelfPermission(Manifest.permission.INTERNET)
        != PackageManager.PERMISSION_GRANTED) {
      Utility.showAlert(context, "Error", "Application requires permission to access the Internet");
    } else {
      new WeiboDialog(this, context, url, listener).show();
    }
  }
  /** {@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());
  }
Esempio n. 15
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;
 }
Esempio n. 16
0
 /**
  * 获取登录凭证.
  *
  * @param appid 应用程序id
  * @param secret 应用程序密钥
  * @return 如果应用程序id或密钥失败,或网络错误则返回null
  */
 public String getToken(String appid, String secret) {
   return Token.getToken(appid, secret);
 }
Esempio n. 17
0
  public ExpressionPart parseTokens(Vector<Token> input) throws Exception { // TODO INNY PARSER
    System.out.println("parsing tokens");

    if (input.size() == 0) {
      System.out.println("no tokens to parse!");
      return null;
    }

    for (int k = 0; k < input.size(); k++) {
      System.out.println(
          "next token: " + input.get(k).getToken() + " type: " + input.get(k).getType());
    }

    if (input.size() == 1 && input.get(0).getType() == 0) {
      System.out.println("only one number to parse");
      return new Number(Double.parseDouble(input.get(0).getToken()));
    }
    if (input.size() == 1 && input.get(0).getType() == 3) {
      System.out.println("only one variable to parse");
      return new Variable(input.get(0).getToken());
    }

    ExpressionPart returnVal = null;
    System.out.println(
        "amount of tokens: "
            + input.size()); // I'm working on new parser, i don't like the way current one is
    // functioning

    /*
    //int bracketLevel = 0;
    int tmpBracketLevel = 0;
    int i = input.size() - 1;
    boolean bracketFlag = false;
    if(input.get(0).getToken().equals("(") && input.get(i).getToken().equals(")")){
    	bracketFlag = true;
    	for(int j = 0; j < i; j++){
    		Token currToken = input.get(j);
    		if(currToken.getToken().equals("(")){
    			tmpBracketLevel ++;
    		}
    		if(currToken.getToken().equals(")")){
    			tmpBracketLevel --;
    			if(tmpBracketLevel == 0 && j < i-1){
    				bracketFlag = false;
    				break;
    			}
    		}
    	}
    }
    if(bracketFlag){
    	i = input.size() - 2;
    }
    String currentOp = input.get(0).getToken();

    int k;
    if(bracketFlag){
    	k = 2;
    }else{
    	k = 1;
    }
    Vector<Token> rightSideOfLast = new Vector<Token>();
    for(; k < i; k++){
    	Token currToken = input.get(k);
    	if(getPriority(currentOp) >= getPriority(currToken.getToken())){
    		System.out.println("token with higer priority!");
    		if(returnVal instanceof Addition){
    			Addition tmp = (Addition)returnVal;
    			tmp.addAddend(parseTokens(rightSideOfLast));
    			returnVal = tmp;
    		}else if(returnVal instanceof Substraction){
    			Substraction tmp = (Substraction)returnVal;
    			tmp.setSubtrahend(parseTokens(rightSideOfLast));
    			returnVal = tmp;
    		}else{
    			returnVal = parseTokens(rightSideOfLast);
    		}

    		currentOp = currToken.getToken();

    		if(currentOp.equals("+")){
    			System.out.println("addition");
    			if(returnVal == null){
    				Addition tmp = new Addition();
    				tmp.addAddend(returnVal);
    				returnVal = tmp;
    				System.out.println("returnVal == null");
    				System.out.println(returnVal);
    			}else if(returnVal instanceof Addition){
    				Addition tmp = (Addition)returnVal;
    				tmp.addAddend(returnVal);
    				returnVal = tmp;
    			}
    		}
    		if(currentOp.equals("-")){
    			Substraction tmp = new Substraction();
    			tmp.setMinuend(returnVal);
    			returnVal = tmp;
    		}
    		if(currentOp.equals("*")){

    		}
    		if(currentOp.equals("/")){

    		}
    		if(currentOp.equals("=")){

    		}

    		rightSideOfLast.clear();
    	}else{
    		rightSideOfLast.add(currToken);
    	}
    }
    System.out.println("end of parsing!");
    return returnVal;*/

    String currentOp = "";
    int lastOperatorPos = 0;
    for (int k = 0;
        k <= 5;
        k++) { // look only at operators at lowest priority, then ones higher priority
      Vector<Token> tokensToAdd = new Vector<Token>();
      System.out.println("searching for operators with priority: " + k);
      if (!currentOp.equals("")) {
        break;
      }
      int bracketLevel = 0;
      int tmpBracketLevel = 0;
      int i = input.size() - 1;
      boolean bracketFlag = false; // TODO system struktur, ewentualnie bez tokenow
      if (input.get(0).getToken().equals("(") && input.get(i).getToken().equals(")")) {
        bracketFlag = true;
        for (int j = 0; j < i; j++) {
          Token currToken = input.get(j);
          if (currToken
              .getToken()
              .equals("(")) { // if thera are brackets surronding expression, ignore them
            tmpBracketLevel++;
          }
          if (currToken.getToken().equals(")")) {
            tmpBracketLevel--;
            if (tmpBracketLevel == 0 && j < i - 1) {
              bracketFlag = false;
              break;
            }
          }
        }
      }
      if (bracketFlag) {
        i = input.size() - 2;
      }

      for (; i >= 0; i--) { // TODO daje odwrotna kolejnosc niz wpisane(nie mozna )
        Token currToken = input.get(i);
        tokensToAdd.add(currToken); // tokens that are between last operator and next one(useful in
        // addition/multiplications)
        if (currToken.getToken().equals(")")) {
          bracketLevel++;
        }
        if (currToken.getToken().equals("(")) {
          bracketLevel--;
        }
        if (bracketLevel > 0) {
          System.out.println("skipping token, searching for end of bracket");
          continue;
        }
        System.out.println("next token: " + currToken.getToken() + " type: " + currToken.getType());
        if (currToken.getType() == 1) {
          if (getPriority(currToken.getToken()) == k) {
            lastOperatorPos = i;
            if (currentOp.equals("")) { // to jest, zeby nie ustawial nowego operatora
              currentOp =
                  currToken
                      .getToken(); // TODO obsluga pierwiastkowania(a tym samym operacje z innym
              // zapisem niz arg op arg)
            }

            if (currentOp.equals(currToken.getToken())) {
              Vector<Token> firstPart = new Vector<Token>();
              Vector<Token> secondPart = new Vector<Token>();

              if (!bracketFlag) {
                firstPart.addAll(input.subList(0, i));
                secondPart.addAll(input.subList(i + 1, input.size()));
              } else {
                firstPart.addAll(input.subList(1, i));
                secondPart.addAll(input.subList(i + 1, input.size() - 1));
              }
              if (returnVal == null) { // parse diffrent operators
                System.out.println("first operator");
                if (currentOp.equals("\\")) {
                  Fraction returnValTmp = new Fraction();

                  System.out.println("[\\]part 1");
                  returnValTmp.setNumerator(parseTokens(firstPart));
                  System.out.println("[\\]part 2");
                  returnValTmp.setDenominator(parseTokens(secondPart));
                  returnVal = returnValTmp;
                }
                if (currentOp.equals("+")) {
                  Addition returnValTmp = new Addition();

                  System.out.println("[+]part 1");
                  returnValTmp.addAddend(parseTokens(secondPart));
                  // System.out.println("[+]part 2");
                  // returnValTmp.addAddend(parseTokens(secondPart));
                  returnVal = returnValTmp;
                  System.out.println("end of part 2");
                  tokensToAdd.clear();
                }
                if (currentOp.equals("-")) {
                  Substraction returnValTmp = new Substraction();

                  System.out.println("[-]part 1");
                  returnValTmp.setMinuend(parseTokens(firstPart));
                  System.out.println("[-]part 2");
                  returnValTmp.setSubtrahend(parseTokens(secondPart));
                  returnVal = returnValTmp;
                }
                if (currentOp.equals("*")) {
                  Multiplication returnValTmp = new Multiplication();

                  System.out.println("[*]part 1");
                  returnValTmp.addFactor(parseTokens(secondPart));
                  // System.out.println("[+]part 2");
                  // returnValTmp.addAddend(parseTokens(secondPart));
                  returnVal = returnValTmp;
                  System.out.println("end of part 2");
                  tokensToAdd.clear();
                }
                if (currentOp.equals("/")) {
                  Division returnValTmp = new Division();

                  System.out.println("[/]part 1");
                  returnValTmp.setDividend(parseTokens(firstPart));
                  System.out.println("[/]part 2");
                  returnValTmp.setDivisor(parseTokens(secondPart));
                  returnVal = returnValTmp;
                }
                if (currentOp.equals("^")) {
                  Exponentiation returnValTmp = new Exponentiation();

                  System.out.println("[^]part 1");
                  returnValTmp.setBase(parseTokens(firstPart));
                  System.out.println("[^]part 2");
                  returnValTmp.setExponent(parseTokens(secondPart));
                  returnVal = returnValTmp;
                }
                if (currentOp.equals("=")) {
                  Equation returnValTmp = new Equation();

                  System.out.println("[=]part 1");
                  returnValTmp.setSide1(parseTokens(firstPart));
                  System.out.println("[=]part 2");
                  returnValTmp.setSide2(parseTokens(secondPart));
                  returnVal = returnValTmp;
                }
              } else {
                System.out.println("next operator");

                if (currentOp.equals("+") && returnVal instanceof Addition) {
                  Addition returnValConverted = (Addition) returnVal;

                  // System.out.println("[+]part 1");
                  // returnValConverted.addAddend(parseTokens(firstPart));
                  Vector<Token> tokensInArg = new Vector<Token>();
                  tokensInArg.addAll(tokensToAdd.subList(0, tokensToAdd.size() - 1));

                  System.out.println("[+]part 2(adding only second part)");
                  returnValConverted.addAddend(parseTokens(tokensInArg));
                  tokensToAdd.clear();
                }
                if (currentOp.equals("*") && returnVal instanceof Multiplication) {
                  Multiplication returnValConverted = (Multiplication) returnVal;

                  // System.out.println("[+]part 1");
                  // returnValConverted.addAddend(parseTokens(firstPart));
                  Vector<Token> tokensInArg = new Vector<Token>();
                  tokensInArg.addAll(tokensToAdd.subList(0, tokensToAdd.size() - 1));

                  System.out.println("[+]part 2(adding only second part)");
                  returnValConverted.addFactor(parseTokens(tokensInArg));
                  tokensToAdd.clear();
                }
              }
            }
          }
        }
        if (bracketFlag && i <= 1) {
          break;
        }
      }

      Vector<Token> firstPart = new Vector<Token>();
      Vector<Token> secondPart = new Vector<Token>();

      if (!bracketFlag) {
        firstPart.addAll(input.subList(0, lastOperatorPos));
        secondPart.addAll(input.subList(lastOperatorPos + 1, input.size()));
      } else if (lastOperatorPos >= 1) {
        firstPart.addAll(input.subList(1, lastOperatorPos));
        secondPart.addAll(input.subList(lastOperatorPos + 1, input.size() - 1));
      }

      System.out.println("Adding last part");
      if (currentOp.equals("+") && returnVal instanceof Addition) {
        Addition returnValConverted = (Addition) returnVal;

        System.out.println("[+]part 1(adding only first part)");
        returnValConverted.addAddend(parseTokens(firstPart));
        tokensToAdd.clear();
      }
      if (currentOp.equals("*") && returnVal instanceof Multiplication) {
        Multiplication returnValConverted = (Multiplication) returnVal;

        System.out.println("[*]part 1(adding only first part)");
        returnValConverted.addFactor(parseTokens(firstPart));
        tokensToAdd.clear();
      }
      if (returnVal != null) {
        break;
      }
    }
    return returnVal;
  }
Esempio n. 18
0
 public void putDatas(String route, JSONObject json, final ResponseHandler handler) {
   String url = API_BASE_URL + route;
   url += "?token=" + Token.getToken();
   this.performRequest(url, Request.Method.PUT, json, handler);
 }
Esempio n. 19
0
 private void getData(String route, String id, final ResponseHandler handler) {
   String url = API_BASE_URL + route + '/' + id;
   url += "?token=" + Token.getToken();
   this.performRequest(url, Request.Method.GET, new JSONObject(), handler);
 }
 @Test
 public void shouldParseResponse() {
   Token token = extractor.extract(response);
   assertEquals(token.getToken(), "I0122HHJKLEM21F3WLPYHDKGKZULAUO4SGMV3ABKFTDT3T3X");
 }
 /** {@inheritDoc} */
 public void signRequest(Token accessToken, OAuthRequest request) {
   request.addQuerystringParameter(OAuthConstants.ACCESS_TOKEN, accessToken.getToken());
 }