Package org.apache.shindig.gadgets.http

Examples of org.apache.shindig.gadgets.http.HttpRequest


    }
  }

  private void fetchRequestToken() throws OAuthRequestException, OAuthProtocolException {
    OAuthAccessor accessor = accessorInfo.getAccessor();
    HttpRequest request = createRequestTokenRequest(accessor);

    List<Parameter> requestTokenParams = Lists.newArrayList();

    addCallback(requestTokenParams);

    HttpRequest signed = sanitizeAndSign(request, requestTokenParams, true);

    OAuthMessage reply = sendOAuthMessage(signed);

    accessor.requestToken = OAuthUtil.getParameter(reply, OAuth.OAUTH_TOKEN);
    accessor.tokenSecret = OAuthUtil.getParameter(reply, OAuth.OAUTH_TOKEN_SECRET);
View Full Code Here


  private HttpRequest createRequestTokenRequest(OAuthAccessor accessor)
      throws OAuthRequestException {
    if (accessor.consumer.serviceProvider.requestTokenURL == null) {
      throw new OAuthRequestException(OAuthError.BAD_OAUTH_TOKEN_URL, "request token");
    }
    HttpRequest request = new HttpRequest(
        Uri.parse(accessor.consumer.serviceProvider.requestTokenURL));
    request.setMethod(accessorInfo.getHttpMethod().toString());
    if (accessorInfo.getHttpMethod() == HttpMethod.POST) {
      request.setHeader("Content-Type", OAuth.FORM_ENCODED);
    }
    return request;
  }
View Full Code Here

    params.addAll(authParams);

    try {
      OAuthMessage signed = OAuthUtil.newRequestMessage(accessorInfo.getAccessor(),
          base.getMethod(), target.toString(), params);
      HttpRequest oauthHttpRequest = createHttpRequest(base, selectOAuthParams(signed));
      // Following 302s on OAuth responses is unlikely to be productive.
      oauthHttpRequest.setFollowRedirects(false);
      return oauthHttpRequest;
    } catch (OAuthException e) {
      throw new OAuthRequestException(OAuthError.UNKNOWN_PROBLEM,
          "Error signing message", e);
    }
View Full Code Here

    OAuthParamLocation paramLocation = accessorInfo.getParamLocation();

    // 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 == OAuthParamLocation.POST_BODY &&
        !result.getMethod().equals("POST")) {
      paramLocation = OAuthParamLocation.AUTH_HEADER;
    }

    switch (paramLocation) {
      case AUTH_HEADER:
        result.addHeader("Authorization", getAuthorizationHeader(oauthParams));
        break;

      case POST_BODY:
        String contentType = result.getHeader("Content-Type");
        if (!OAuth.isFormEncoded(contentType)) {
          throw new OAuthRequestException(OAuthError.INVALID_REQUEST,
              "OAuth param location can only be post_body if it is of " +
              "type x-www-form-urlencoded");
        }
        String oauthData = OAuthUtil.formEncode(oauthParams);
        if (result.getPostBodyLength() == 0) {
          result.setPostBody(CharsetUtil.getUtf8Bytes(oauthData));
        } else {
          StringBuilder postBody = new StringBuilder();
          postBody.append(result.getPostBodyAsString());

          if (!result.getPostBodyAsString().endsWith("&")) {
            postBody.append('&');
          }

          postBody.append(oauthData);
          result.setPostBody(postBody.toString().getBytes());
        }
        break;

      case URI_QUERY:
        result.setUri(Uri.parse(OAuthUtil.addParameters(result.getUri().toString(), oauthParams)));
        break;
    }

    return result;
  }
View Full Code Here

    if (accessor.consumer.serviceProvider.accessTokenURL == null) {
      throw new OAuthRequestException(OAuthError.BAD_OAUTH_TOKEN_URL, "access token");
    }
    Uri accessTokenUri = Uri.parse(accessor.consumer.serviceProvider.accessTokenURL);
    HttpRequest request = new HttpRequest(accessTokenUri);
    request.setMethod(accessorInfo.getHttpMethod().toString());
    if (accessorInfo.getHttpMethod() == HttpMethod.POST) {
      request.setHeader("Content-Type", OAuth.FORM_ENCODED);
    }

    List<Parameter> msgParams = Lists.newArrayList();
    msgParams.add(new Parameter(OAuth.OAUTH_TOKEN, accessor.requestToken));
    if (accessorInfo.getSessionHandle() != null) {
      msgParams.add(new Parameter(OAuthConstants.OAUTH_SESSION_HANDLE,
          accessorInfo.getSessionHandle()));
    }
    String receivedCallback = realRequest.getOAuthArguments().getReceivedCallbackUrl();
    if (!StringUtils.isBlank(receivedCallback)) {
      try {
        Uri parsed = Uri.parse(receivedCallback);
        String verifier = parsed.getQueryParameter(OAuth.OAUTH_VERIFIER);
        if (verifier != null) {
          msgParams.add(new Parameter(OAuth.OAUTH_VERIFIER, verifier));
        }
      } catch (IllegalArgumentException e) {
        throw new OAuthRequestException(OAuthError.INVALID_REQUEST,
            "Invalid received callback URL: " + receivedCallback, e);
      }
    }

    HttpRequest signed = sanitizeAndSign(request, msgParams, true);

    OAuthMessage reply = sendOAuthMessage(signed);

    accessor.accessToken = OAuthUtil.getParameter(reply, OAuth.OAUTH_TOKEN);
    accessor.tokenSecret = OAuthUtil.getParameter(reply, OAuth.OAUTH_TOKEN_SECRET);
View Full Code Here

    HttpResponseBuilder builder;
    if (accessTokenData != null) {
      // This is a request for access token data, return it.
      builder = formatAccessTokenData();
    } else {
      HttpRequest signed = sanitizeAndSign(realRequest, null, false);

      HttpResponse response = fetchFromServer(signed);

      checkForProtocolProblem(response);
      builder = new HttpResponseBuilder(response);
View Full Code Here

    }

    // Canonicalize the path
    Uri href = normalizeUrl(httpApiRequest.href);
    try {
      HttpRequest req = new HttpRequest(href);
      req.setMethod(method);
      if (httpApiRequest.body != null) {
        req.setPostBody(httpApiRequest.body.getBytes());
      }

      // Copy over allowed headers
      for (Map.Entry<String, List<String>> header : httpApiRequest.headers.entrySet()) {
        if (!BAD_HEADERS.contains(header.getKey().trim().toUpperCase())) {
          for (String value : header.getValue()) {
            req.addHeader(header.getKey(), value);
          }
        }
      }

      // Extract the gadget URI from the request or the security token
      final Uri gadgetUri = getGadgetUri(requestItem.getToken(), httpApiRequest);
      if (gadgetUri == null) {
        throw new ProtocolException(HttpServletResponse.SC_BAD_REQUEST,
            "Gadget URI not specified in request");
      }
      req.setGadget(gadgetUri);

      // Detect the authz parsing
      if (httpApiRequest.authz != null) {
        req.setAuthType(AuthType.parse(httpApiRequest.authz));
      }

      final AuthType authType = req.getAuthType();
      if (authType != AuthType.NONE) {
        if (authType == AuthType.OAUTH2) {
          req.setSecurityToken(requestItem.getToken());

          Map<String, String> authSettings = getAuthSettings(requestItem);
          OAuth2Arguments oauth2Args = new OAuth2Arguments(req.getAuthType(), authSettings);

          req.setOAuth2Arguments(oauth2Args);
        } else {
          req.setSecurityToken(requestItem.getToken());

          Map<String, String> authSettings = getAuthSettings(requestItem);
          OAuthArguments oauthArgs = new OAuthArguments(req.getAuthType(), authSettings);
          oauthArgs.setSignOwner(httpApiRequest.signOwner);
          oauthArgs.setSignViewer(httpApiRequest.signViewer);

          req.setOAuthArguments(oauthArgs);
        }
      }

      // TODO: Allow the rewriter to use an externally forced mime type. This is needed
      // allows proper rewriting of <script src="x"/> where x is returned with
      // a content type like text/html which unfortunately happens all too often

      req.setIgnoreCache(httpApiRequest.noCache);
      req.setSanitizationRequested(httpApiRequest.sanitize);

      // If the proxy request specifies a refresh param then we want to force the min TTL for
      // the retrieved entry in the cache regardless of the headers on the content when it
      // is fetched from the original source.
      if (httpApiRequest.refreshInterval != null) {
        req.setCacheTtl(httpApiRequest.refreshInterval);
      }

      final HttpRequest request = req;
      HttpResponse results = requestPipeline.execute(req);
      GadgetContext context = new GadgetContext() {
        @Override
        public Uri getUrl() {
          return gadgetUri;
        }

        @Override
        public String getParameter(String key) {
          return request.getParam(key);
        }

        @Override
        public boolean getIgnoreCache() {
          return request.getIgnoreCache();
        }

        @Override
        public String getContainer() {
          return requestItem.getToken().getContainer();
View Full Code Here

              accessor, grantRequestHandler, completeAuthUrl });
    }

    OAuth2HandlerError ret = null;

    HttpRequest authorizationRequest;
    try {
      authorizationRequest = grantRequestHandler.getAuthorizationRequest(accessor, completeAuthUrl);
    } catch (final OAuth2RequestException e) {
      authorizationRequest = null;
      ret = new OAuth2HandlerError(e.getError(), e.getErrorText(), e);
View Full Code Here

      BasicOAuth2Request.LOG.log("refershTokenUrl = {0}", refershTokenUrl);
    }

    if (refershTokenUrl != null) {
      HttpResponse response = null;
      final HttpRequest request = new HttpRequest(Uri.parse(refershTokenUrl));
      request.setMethod("POST");
      request.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");

      for (final ClientAuthenticationHandler clientAuthenticationHandler : this.clientAuthenticationHandlers) {
        if (clientAuthenticationHandler.geClientAuthenticationType().equalsIgnoreCase(
                accessor.getClientAuthenticationType())) {
          clientAuthenticationHandler.addOAuth2Authentication(request, accessor);
        }
      }

      try {
        final byte[] body = BasicOAuth2Request.getRefreshBody(accessor).getBytes("UTF-8");
        request.setPostBody(body);
      } catch (final Exception e) {
        if (isLogging) {
          BasicOAuth2Request.LOG.log("refreshToken()", e);
        }
        ret = new OAuth2HandlerError(OAuth2Error.REFRESH_TOKEN_PROBLEM,
View Full Code Here

   * Executes a request, returning the response as JSON to be handled by makeRequest.
   */
  public void fetch(HttpServletRequest request, HttpServletResponse response)
          throws GadgetException, IOException {

    HttpRequest rcr = buildHttpRequest(request);
    String container = rcr.getContainer();
    final Uri gadgetUri = rcr.getGadget();
    if (gadgetUri == null) {
      throw new GadgetException(GadgetException.Code.MISSING_PARAMETER,
              "Unable to find gadget in request", HttpResponse.SC_FORBIDDEN);
    }

    Gadget gadget;
    GadgetContext context = new HttpGadgetContext(request) {
      @Override
      public Uri getUrl() {
        return gadgetUri;
      }
      @Override
      public boolean getIgnoreCache() {
        return getParameter("bypassSpecCache").equals("1");
      }
    };
    try {
      gadget = processor.process(context);
    } catch (ProcessingException e) {
      throw new GadgetException(GadgetException.Code.INTERNAL_SERVER_ERROR,
              "Error processing gadget", e, HttpResponse.SC_BAD_REQUEST);
    }

    // Validate gadget is correct for the host.
    // Ensures that the gadget has not hand crafted this request to represent itself as
    // another gadget in a locked domain environment.
    if (!lockedDomainService.isGadgetValidForHost(context.getHost(), gadget, container)) {
      throw new GadgetException(GadgetException.Code.GADGET_HOST_MISMATCH,
              "The gadget is incorrect for this request", HttpResponse.SC_FORBIDDEN);
    }

    if (!gadgetAdminStore.isWhitelisted(container, gadgetUri.toString())) {
      throw new GadgetException(GadgetException.Code.NON_WHITELISTED_GADGET,
              "The requested content is unavailable", HttpResponse.SC_FORBIDDEN);
    }

    // Serialize the response
    HttpResponse results = requestPipeline.execute(rcr);

    // Rewrite the response
    if (contentRewriterRegistry != null) {
      try {
        results = contentRewriterRegistry.rewriteHttpResponse(rcr, results, gadget);
      } catch (RewritingException e) {
        throw new GadgetException(GadgetException.Code.INTERNAL_SERVER_ERROR, e,
                e.getHttpStatusCode());
      }
    }

    // Serialize the response
    String output = convertResponseToJson(rcr.getSecurityToken(), request, results);

    // Find and set the refresh interval
    setResponseHeaders(request, response, results);
    response.setStatus(HttpServletResponse.SC_OK);
    response.setCharacterEncoding("UTF-8");
View Full Code Here

TOP

Related Classes of org.apache.shindig.gadgets.http.HttpRequest

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.