Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Licensed to the Apache Software Foundation (ASF) under one or more
   * contributor license agreements. See the NOTICE file distributed with this
   * work for additional information regarding copyright ownership. The ASF
   * licenses this file to you under the Apache License, Version 2.0 (the
   * "License"); you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  * License for the specific language governing permissions and limitations under
  * the License.
  */
 package org.apache.shindig.gadgets.oauth;
 
 import  org.apache.commons.codec.binary.Base64;
 import  org.apache.commons.codec.digest.DigestUtils;
 import  org.apache.commons.io.IOUtils;
 
 
 import  com.google.common.collect.Lists;
 import  com.google.common.collect.Maps;
 
 import  net.oauth.OAuth;
 import  net.oauth.OAuthAccessor;
 import  net.oauth.OAuthException;
 import  net.oauth.OAuthMessage;
 import  net.oauth.OAuthProblemException;
 import  net.oauth.OAuth.Parameter;
 
 import  org.json.JSONObject;
 
 import java.util.List;
 import java.util.Map;
Implements both signed fetch and full OAuth for gadgets, as well as a combination of the two that is necessary to build OAuth enabled gadgets for social sites. Signed fetch sticks identity information in the query string, signed either with the container's private key, or else with a secret shared between the container and the gadget. Full OAuth redirects the user to the OAuth service provider site to obtain the user's permission to access their data. Read the example in the appendix to the OAuth spec for a summary of how this works (The spec is at http://oauth.net/core/1.0/). The combination protocol works by sending identity information in all requests, and allows the OAuth dance to happen as well when owner == viewer. This lets OAuth service providers build up an identity mapping from ids on social network sites to their own local ids.
 
 public class OAuthRequest {
 
   // Maximum number of attempts at the protocol before giving up.
   private static final int MAX_ATTEMPTS = 2;
 
   // names of additional OAuth parameters we include in outgoing requests
   // TODO(beaton): can we do away with this bit in favor of the opensocial param?
   public static final String XOAUTH_APP_URL = "xoauth_app_url";
 
   protected static final String OPENSOCIAL_OWNERID = "opensocial_owner_id";
 
   protected static final String OPENSOCIAL_VIEWERID = "opensocial_viewer_id";
 
   protected static final String OPENSOCIAL_APPID = "opensocial_app_id";
 
   // TODO(beaton): figure out if this is the name in the 0.8 spec.
   protected static final String OPENSOCIAL_APPURL = "opensocial_app_url";
 
   protected static final String OPENSOCIAL_PROXIED_CONTENT = "opensocial_proxied_content";
 
   protected static final String XOAUTH_PUBLIC_KEY = "xoauth_signature_publickey";
 
   protected static final Pattern ALLOWED_PARAM_NAME = Pattern.compile("[-:\\w~!@$*()_\\[\\]:,./]+");
 
   private static final long ACCESS_TOKEN_EXPIRE_UNKNOWN = 0;
   private static final long ACCESS_TOKEN_FORCE_EXPIRE = -1;


  
Configuration options for the fetcher.
  protected final OAuthFetcherConfig fetcherConfig;

  
Next fetcher to use in chain.
  private final HttpFetcher fetcher;

  
Additional trusted parameters to be included in the OAuth request.
  private final List<Parameter> trustedParams;

  
State information from client
  protected OAuthClientState clientState;

  
OAuth specific stuff to include in the response.
The accessor we use for signing messages. This also holds metadata about the service provider, such as their URLs and the keys we use to access those URLs.
  private AccessorInfo accessorInfo;

  
The request the client really wants to make.
  private HttpRequest realRequest;

  
Data returned along with OAuth access token, null if this is not an access token request
  private Map<StringStringaccessTokenData;

  

Parameters:
fetcherConfig configuration options for the fetcher
fetcher fetcher to use for actually making requests
  public OAuthRequest(OAuthFetcherConfig fetcherConfigHttpFetcher fetcher) {
    this(fetcherConfigfetchernull);
  }

  

Parameters:
fetcherConfig configuration options for the fetcher
fetcher fetcher to use for actually making requests
trustedParams additional parameters to include in all outgoing OAuth requests, useful for client data that can't be pulled from the security token but is still trustworthy.
  public OAuthRequest(OAuthFetcherConfig fetcherConfigHttpFetcher fetcher,
      List<Parameter> trustedParams) {
    this. = fetcherConfig;
    this. = fetcher;
    this. = trustedParams;
  }

  
OAuth authenticated fetch.
  public HttpResponse fetch(HttpRequest request) {
     = request;
        request.getOAuthArguments().getOrigClientState());
     = new OAuthResponseParams(request.getSecurityToken(), request,
        .getStateCrypter());
    try {
      return fetchNoThrow();
    } catch (RuntimeException e) {
      // We log here to record the request/response pairs that created the failure.
      .logDetailedWarning("OAuth fetch unexpected fatal error"e);
      throw e;
    }
  }

  
Fetch data and build a response to return to the client. We try to always return something reasonable to the calling app no matter what kind of madness happens along the way. If an unchecked exception occurs, well, then the client is out of luck.
  private HttpResponse fetchNoThrow() {
    HttpResponseBuilder response = null;
    try {
          );
      response = fetchWithRetry();
    } catch (OAuthRequestException e) {
      // No data for us.
        .logDetailedInfo("Unauthenticated OAuth fetch"e);
      } else {
        .logDetailedWarning("OAuth fetch fatal error"e);
      }
      response = new HttpResponseBuilder()
          .setStrictNoCache();
      .addToResponse(response);
      return response.create();
    }
    // OK, got some data back, annotate it as necessary.
    if (response.getHttpStatusCode() >= 400) {
      .logDetailedWarning("OAuth fetch fatal error");
    } else if (.getAznUrl() != null && .sawErrorResponse()) {
      .logDetailedWarning("OAuth fetch error, reprompting for user approval");
    }
    .addToResponse(response);
    return response.create();
  }

  
Fetch data, retrying in the event that that the service provider returns an error and we think we can recover by restarting the protocol flow.
    int attempts = 0;
    boolean retry;
    HttpResponseBuilder response = null;
    do {
      retry = false;
      ++attempts;
      try {
        response = attemptFetch();
      } catch (OAuthProtocolException pe) {
        retry = handleProtocolException(peattempts);
        if (!retry) {
          if (pe.getProblemCode() != null) {
            throw .oauthRequestException(pe.getProblemCode(),
                "Service provider rejected request"pe);
          } else {
                "Service provider rejected request"pe);
          }
        }
      }
    } while (retry);
    return response;
  }
  private boolean handleProtocolException(OAuthProtocolException peint attempts)
      throws OAuthRequestException {
    if (pe.canExtend()) {
    } else if (pe.startFromScratch()) {
      .getAccessor().accessToken = null;
      .getAccessor().requestToken = null;
      .getAccessor().tokenSecret = null;
    }
    return (attempts <  && pe.canRetry());
  }

  
Does one of the following: 1) Sends a request token request, and returns an approval URL to the calling app. 2) Sends an access token request to swap a request token for an access token, and then asks for data from the service provider. 3) Asks for data from the service provider.
    if (needApproval()) {
      // This is section 6.1 of the OAuth spec.
      checkCanApprove();
      fetchRequestToken();
      // This is section 6.2 of the OAuth spec.
      buildAznUrl();
      // break out of the content fetching chain, we need permission from
      // the user to do this
      return new HttpResponseBuilder()
         .setStrictNoCache();
    } else if (needAccessToken()) {
      // This is section 6.3 of the OAuth spec
      checkCanApprove();
      saveAccessToken();
    }
    return fetchData();
  }

  
Do we need to get the user's approval to access the data?
  private boolean needApproval() {
            && .getAccessor().requestToken == null
            && .getAccessor().accessToken == null);
  }

  
Make sure the user is authorized to approve access tokens. At the moment we restrict this to page owner's viewing their own pages.
  private void checkCanApprove() throws OAuthRequestException {
    String pageOwner = .getSecurityToken().getOwnerId();
    String pageViewer = .getSecurityToken().getViewerId();
    String stateOwner = .getOwner();
    if (pageOwner == null) {
      throw .oauthRequestException(."Unauthenticated");
    }
    if (!pageOwner.equals(pageViewer)) {
          "Only page owners can grant OAuth approval");
    }
    if (stateOwner != null && !stateOwner.equals(pageOwner)) {
          "Client state belongs to a different person " +
          "(state owner=" + stateOwner + ", pageOwner=" + pageOwner + ')');
    }
  }
    OAuthAccessor accessor = .getAccessor();
    HttpRequest request = createRequestTokenRequest(accessor);
    
    List<Parameter> requestTokenParams = Lists.newArrayList();
    
    addCallback(requestTokenParams);
    
    HttpRequest signed = sanitizeAndSign(requestrequestTokenParamstrue);
    OAuthMessage reply = sendOAuthMessage(signed);
    accessor.requestToken = OAuthUtil.getParameter(reply, OAuth.OAUTH_TOKEN);
    accessor.tokenSecret = OAuthUtil.getParameter(reply, OAuth.OAUTH_TOKEN_SECRET);
  }
  private HttpRequest createRequestTokenRequest(OAuthAccessor accessor)
      throws OAuthRequestException {
    if (accessor.consumer.serviceProvider.requestTokenURL == null) {
          "No request token URL specified");
    }
    HttpRequest request = new HttpRequest(
        Uri.parse(accessor.consumer.serviceProvider.requestTokenURL));
      request.setHeader("Content-Type", OAuth.FORM_ENCODED);
    }
    return request;
  }
  private void addCallback(List<Parameter> requestTokenParamsthrows OAuthRequestException {
    // This will be either the consumer key callback URL or the global callback URL.
    String baseCallback = StringUtils.trimToNull(.getConsumer().getCallbackUrl());
    if (baseCallback != null) {
          baseCallback);
      if (callbackUrl != null) {
        requestTokenParams.add(new Parameter(OAuth.OAUTH_CALLBACK, callbackUrl));
      }
    }
  }

  
Strip out any owner or viewer identity information passed by the client.
  private List<Parameter> sanitize(List<Parameter> paramsthrows OAuthRequestException {
    ArrayList<Parameter> list = Lists.newArrayList();
    for (Parameter p : params) {
      String name = p.getKey();
      if (allowParam(name)) {
        list.add(p);
      } else {
            "invalid parameter name " + name +
            ", applications may not override opensocial or oauth parameters");
      }
    }
    return list;
  }
  private boolean allowParam(String paramName) {
    String canonParamName = paramName.toLowerCase();
    return (!(canonParamName.startsWith("oauth") ||
        canonParamName.startsWith("xoauth") ||
        canonParamName.startsWith("opensocial")) &&
        .matcher(canonParamName).matches());
  }

  
Add identity information, such as owner/viewer/gadget.
  private void addIdentityParams(List<Parameter> params) {
    // If no owner or viewer information is required, don't add any identity params.  This lets
    // us be compatible with strict OAuth service providers that reject extra parameters on
    // requests.
      return;
    }
    if (owner != null && .getOAuthArguments().getSignOwner()) {
      params.add(new Parameter(owner));
    }
    if (viewer != null && .getOAuthArguments().getSignViewer()) {
      params.add(new Parameter(viewer));
    }
    if (app != null) {
      params.add(new Parameter(app));
    }
    if (appUrl != null) {
      params.add(new Parameter(appUrl));
    }
    if ( != null) {
      params.addAll();
    }
    
      params.add(new Parameter("1"));
    }
  }

  
Add signature type to the message.
  private void addSignatureParams(List<Parameter> params) {
    if (.getConsumer().getConsumer().consumerKey == null) {
      params.add(
          new Parameter(OAuth.OAUTH_CONSUMER_KEY, .getSecurityToken().getDomain()));
    }
    if (.getConsumer().getKeyName() != null) {
      params.add(new Parameter(.getConsumer().getKeyName()));
    }
    params.add(new Parameter(OAuth.OAUTH_VERSION, OAuth.VERSION_1_0));
    params.add(new Parameter(OAuth.OAUTH_TIMESTAMP,
        Long.toString(.getClock().currentTimeMillis() / 1000)));
  }
  static String getAuthorizationHeader(List<Map.Entry<StringString>> oauthParams) {
    StringBuilder result = new StringBuilder("OAuth ");
    boolean first = true;
    for (Map.Entry<StringStringparameter : oauthParams) {
      if (!first) {
        result.append(", ");
      } else {
        first = false;
      }
      result.append(OAuth.percentEncode(parameter.getKey()))
            .append("=\"")
            .append(OAuth.percentEncode(parameter.getValue()))
            .append('"');
    }
    return result.toString();
  }


  
Start with an HttpRequest. Throw if there are any attacks in the query. Throw if there are any attacks in the post body. Build up OAuth parameter list. Sign it. Add OAuth parameters to new request. Send it.
  public HttpRequest sanitizeAndSign(HttpRequest baseList<Parameter> params,
      boolean tokenEndpointthrows OAuthRequestException {
    if (params == null) {
      params = Lists.newArrayList();
    }
    UriBuilder target = new UriBuilder(base.getUri());
    String query = target.getQuery();
    target.setQuery(null);
    params.addAll(sanitize(OAuth.decodeForm(query)));
    switch(OAuthUtil.getSignatureType(tokenEndpointbase.getHeader("Content-Type"))) {
      case :
        break;
      case :
        params.addAll(sanitize(OAuth.decodeForm(base.getPostBodyAsString())));
        break;
      case :
        try {
          byte[] body = IOUtils.toByteArray(base.getPostBody());
          byte[] hash = DigestUtils.sha(body);
          String b64 = new String(Base64.encodeBase64(hash), ..name());
          params.add(new Parameter(.b64));
        } catch (IOException e) {
              "Error taking body hash"e);
        }
        break;
    }
    addIdentityParams(params);
    addSignatureParams(params);
    try {
      OAuthMessage signed = OAuthUtil.newRequestMessage(.getAccessor(),
          base.getMethod(), target.toString(), params);
      HttpRequest oauthHttpRequest = createHttpRequest(baseselectOAuthParams(signed));
      // Following 302s on OAuth responses is unlikely to be productive.
      oauthHttpRequest.setFollowRedirects(false);
      return oauthHttpRequest;
    } catch (OAuthException e) {
          "Error signing message"e);
    }
  }
      List<Map.Entry<StringString>> oauthParamsthrows OAuthRequestException {
    // paramLocation could be overriden by a run-time parameter to fetchRequest
    HttpRequest result = new HttpRequest(base);
    // If someone specifies that OAuth parameters go in the body, but then sends a request for
    // data using GET, we've got a choice.  We can throw some type of error, since a GET request
    // can't have a body, or we can stick the parameters somewhere else, like, say, the header.
    // We opt to put them in the header, since that stands some chance of working with some
    // OAuth service providers.
    if (paramLocation == . &&
        !result.getMethod().equals("POST")) {
      paramLocation = .;
    }
    switch (paramLocation) {
      case :
        result.addHeader("Authorization"getAuthorizationHeader(oauthParams));
        break;
      case :
        String contentType = result.getHeader("Content-Type");
        if (!OAuth.isFormEncoded(contentType)) {
              "OAuth param location can only be post_body if post body if of " +
              "type x-www-form-urlencoded");
        }
        String oauthData = OAuthUtil.formEncode(oauthParams);
        if (result.getPostBodyLength() == 0) {
          result.setPostBody(CharsetUtil.getUtf8Bytes(oauthData));
        } else {
          result.setPostBody((result.getPostBodyAsString() + '&' + oauthData).getBytes());
        }
        break;
      case :
        result.setUri(Uri.parse(OAuthUtil.addParameters(result.getUri().toString(), oauthParams)));
        break;
    }
    return result;
  }

  
Sends OAuth request token and access token messages.
  private OAuthMessage sendOAuthMessage(HttpRequest request)
    HttpResponse response = fetchFromServer(request);
    checkForProtocolProblem(response);
    OAuthMessage reply = new OAuthMessage(nullnullnull);
    reply.addParameters(OAuth.decodeForm(response.getResponseAsString()));
    reply = parseAuthHeader(replyresponse);
    if (OAuthUtil.getParameter(reply, OAuth.OAUTH_TOKEN) == null) {
          "No oauth_token returned from service provider");
    }
    if (OAuthUtil.getParameter(reply, OAuth.OAUTH_TOKEN_SECRET) == null) {
          "No oauth_token_secret returned from service provider");
    }
    return reply;
  }

  
Parse OAuth WWW-Authenticate header and either add them to an existing message or create a new message.

Parameters:
msg
resp
Returns:
the updated message.
  private OAuthMessage parseAuthHeader(OAuthMessage msgHttpResponse resp) {
    if (msg == null) {
      msg = new OAuthMessage(nullnullnull);
    }
    for (String auth : resp.getHeaders("WWW-Authenticate")) {
      msg.addParameters(OAuthMessage.decodeAuthorization(auth));
    }
    return msg;
  }

  
Builds the data we'll cache on the client while we wait for approval.
  private void buildClientApprovalState() {
    OAuthAccessor accessor = .getAccessor();
    .getNewClientState().setRequestToken(accessor.requestToken);
  }

  
Builds the URL the client needs to visit to approve access.
  private void buildAznUrl() throws OAuthRequestException {
    // We add the token, gadget is responsible for the callback URL.
    OAuthAccessor accessor = .getAccessor();
    if (accessor.consumer.serviceProvider.userAuthorizationURL == null) {
          "No authorization URL specified");
    }
    StringBuilder azn = new StringBuilder(
        accessor.consumer.serviceProvider.userAuthorizationURL);
    if (azn.indexOf("?") == -1) {
      azn.append('?');
    } else {
      azn.append('&');
    }
    azn.append(OAuth.OAUTH_TOKEN);
    azn.append('=');
    azn.append(OAuth.percentEncode(accessor.requestToken));
  }

  
Do we need to exchange a request token for an access token?
  private boolean needAccessToken() {
        && .getAccessor().requestToken != null
        && .getAccessor().accessToken == null) {
      return true;
    }
  }
  private boolean accessTokenExpired() {
  }

  
Implements section 6.3 of the OAuth spec.
    if (.getAccessor().accessToken != null) {
      // session extension per
      // http://oauth.googlecode.com/svn/spec/ext/session/1.0/drafts/1/spec.html
      .getAccessor().requestToken = .getAccessor().accessToken;
      .getAccessor().accessToken = null;
    }
    OAuthAccessor accessor = .getAccessor();
    if (accessor.consumer.serviceProvider.accessTokenURL == null) {
          "No access token URL specified.");
    }
    Uri accessTokenUri = Uri.parse(accessor.consumer.serviceProvider.accessTokenURL);
    HttpRequest request = new HttpRequest(accessTokenUri);
      request.setHeader("Content-Type", OAuth.FORM_ENCODED);
    }
    List<Parameter> msgParams = Lists.newArrayList();
    msgParams.add(new Parameter(OAuth.OAUTH_TOKEN, accessor.requestToken));
    if (.getSessionHandle() != null) {
      msgParams.add(new Parameter(.,
          .getSessionHandle()));
    }
    if (!StringUtils.isBlank(receivedCallback)) {
      try {
        Uri parsed = Uri.parse(receivedCallback);
        String verifier = parsed.getQueryParameter(.);
        if (verifier != null) {
          msgParams.add(new Parameter(.verifier));
        }
      } catch (IllegalArgumentException e) {
            "Invalid received callback URL: " + receivedCallbacke);
      }
    }
    HttpRequest signed = sanitizeAndSign(requestmsgParamstrue);
    OAuthMessage reply = sendOAuthMessage(signed);
    accessor.accessToken = OAuthUtil.getParameter(reply, OAuth.OAUTH_TOKEN);
    accessor.tokenSecret = OAuthUtil.getParameter(reply, OAuth.OAUTH_TOKEN_SECRET);
    if (OAuthUtil.getParameter(reply.) != null) {
      try {
        int expireSecs = Integer.parseInt(OAuthUtil.getParameter(reply,
            .));
        long expireMillis = .getClock().currentTimeMillis() + expireSecs * 1000;
        .setTokenExpireMillis(expireMillis);
      } catch (NumberFormatException e) {
        // Hrm.  Bogus server.  We can safely ignore this, we'll just wait for the server to
        // tell us when the access token has expired.
        .logDetailedWarning("server returned bogus expiration");
      }
    }
    // Clients may want to retrieve extra information returned with the access token.  Several
    // OAuth service providers (e.g. Yahoo, NetFlix) return a user id along with the access
    // token, and the user id is required to use their APIs.  Clients signal that they need this
    // extra data by sending a fetch request for the access token URL.
    //
    // We don't return oauth* parameters from the response, because we know how to handle those
    // ourselves and some of them (such as oauth_token_secret) aren't supposed to be sent to the
    // client.
    //
    // Note that this data is not stored server-side.  Clients need to cache these user-ids or
    // other data themselves, probably in user prefs, if they expect to need the data in the
    // future.
    if (accessTokenUri.equals(.getUri())) {
       = Maps.newHashMap();
      for (Entry<StringStringparam : OAuthUtil.getParameters(reply)) {
        if (!param.getKey().startsWith("oauth")) {
          .put(param.getKey(), param.getValue());
        }
      }
    }
  }

  
Save off our new token and secret to the persistent store.
  private void saveAccessToken() throws OAuthRequestException {
    OAuthAccessor accessor = .getAccessor();
    TokenInfo tokenInfo = new TokenInfo(accessor.accessToken, accessor.tokenSecret,
  }

  
Builds the data we'll cache on the client while we make requests.
  private void buildClientAccessState() {
    OAuthAccessor accessor = .getAccessor();
    .getNewClientState().setAccessToken(accessor.accessToken);
  }

  
Get honest-to-goodness user data.

Throws:
OAuthProtocolException if the service provider returns an OAuth related error instead of user data.
    HttpResponseBuilder builder = null;
    if ( != null) {
      // This is a request for access token data, return it.
      builder = formatAccessTokenData();
    } else {
      HttpRequest signed = sanitizeAndSign(nullfalse);
      HttpResponse response = fetchFromServer(signed);
      checkForProtocolProblem(response);
      builder = new HttpResponseBuilder(response);
    }
    return builder;
  }
    HttpResponse response = null;
    try {
      response = .fetch(request);
      if (response == null) {
            "No response from server");
      }
      return response;
    } catch (GadgetException e) {
          ."No response from server"e);
    } finally {
      .addRequestTrace(requestresponse);
    }
  }

  
Access token data is returned to the gadget as json key/value pairs: { "user_id": "12345678" }
    HttpResponseBuilder builder = new HttpResponseBuilder();
    builder.addHeader("Content-Type""application/json; charset=utf-8");
    // no need to cache this, these requests should be fairly rare, and the results should be
    // cached in gadget.
    builder.setStrictNoCache();
    JSONObject json = new JSONObject();
    builder.setResponseString(json.toString());
    return builder;
  }

  
Look for an OAuth protocol problem. For cases where no access token is in play

Parameters:
response
Throws:
OAuthProtocolException
  private void checkForProtocolProblem(HttpResponse responsethrows OAuthProtocolException {
    if (isFullOAuthError(response)) {
      OAuthMessage message = parseAuthHeader(nullresponse);
      if (OAuthUtil.getParameter(message, OAuthProblemException.OAUTH_PROBLEM) != null) {
        // SP reported extended error information
        throw new OAuthProtocolException(message);
      }
      // No extended information, guess based on HTTP response code.
      throw new OAuthProtocolException(response.getHttpStatusCode());
    }
  }

  
Check if a response might be due to an OAuth protocol error. We don't want to intercept errors for signed fetch, we only care about places where we are dealing with OAuth request and/or access tokens.
  private boolean isFullOAuthError(HttpResponse response) {
    // 401 and 403 are likely to be authentication errors.
        && response.getHttpStatusCode() != .) {
      return false;
    }
    // If the client forced us to use full OAuth, this might be OAuth related.
      return true;
    }
    // If we're using an access token, this might be OAuth related.
    if (.getAccessor().accessToken != null) {
      return true;
    }
    // Not OAuth related.
    return false;
  }

  
Extracts only those parameters from an OAuthMessage that are OAuth-related. An OAuthMessage may hold a whole bunch of non-OAuth-related parameters because they were all needed for signing. But when constructing a request we need to be able to extract just the OAuth-related parameters because they, and only they, may have to be put into an Authorization: header or some such thing.

Parameters:
message the OAuthMessage object, which holds non-OAuth parameters such as foo=bar (which may have been in the original URI query part, or perhaps in the POST body), as well as OAuth-related parameters (such as oauth_timestamp or oauth_signature).
Returns:
a list that contains only the oauth_related parameters.
  static List<Map.Entry<StringString>> selectOAuthParams(OAuthMessage message) {
    List<Map.Entry<StringString>> result = Lists.newArrayList();
    for (Map.Entry<StringStringparam : OAuthUtil.getParameters(message)) {
      if (isContainerInjectedParameter(param.getKey())) {
        result.add(param);
      }
    }
    return result;
  }
  private static boolean isContainerInjectedParameter(String key) {
    key = key.toLowerCase();
    return key.startsWith("oauth") || key.startsWith("xoauth") || key.startsWith("opensocial");
  }
New to GrepCode? Check out our FAQ X