Package org.apache.shindig.gadgets.http

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


      if (gadgetUrl != null) {
        gadgetUri = Uri.parse(gadgetUrl);
      }
    }

    HttpRequest req = new HttpRequest(url).setMethod(getParameter(request, METHOD_PARAM, "GET"))
            .setContainer(container).setGadget(gadgetUri);

    if ("POST".equals(req.getMethod()) || "PUT".equals(req.getMethod())) {
      setPostData(container, request, req);
    }

    String headerData = getParameter(request, HEADERS_PARAM, "");
    if (headerData.length() > 0) {
      String[] headerList = StringUtils.split(headerData, '&');
      for (String header : headerList) {
        String[] parts = StringUtils.splitPreserveAllTokens(header, '=');
        if (parts.length != 2) {
          throw new GadgetException(GadgetException.Code.INVALID_PARAMETER,
                  "Malformed header param specified:" + header, HttpResponse.SC_BAD_REQUEST);
        }
        String headerName = Utf8UrlCoder.decode(parts[0]);
        if (!HttpRequestHandler.BAD_HEADERS.contains(headerName.toUpperCase())) {
          req.addHeader(headerName, Utf8UrlCoder.decode(parts[1]));
        }
      }
    }

    // Set the default content type for post requests when a content type is not specified
    if ("POST".equals(req.getMethod()) && req.getHeader("Content-Type") == null) {
      req.addHeader("Content-Type", "application/x-www-form-urlencoded");
    } else if ("1".equals(getParameter(request, MULTI_PART_FORM_POST, null))) {
      // We need the entire header from the original request because it comes with a boundary value
      // we need to reuse.
      req.addHeader("Content-Type", request.getHeader("Content-Type"));
    }

    req.setIgnoreCache("1".equals(getParameter(request, Param.NO_CACHE.getKey(), null)));



    // 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.
    String refresh = getParameter(request, Param.REFRESH.getKey(), null);
    if (refresh != null) {
      try {
        req.setCacheTtl(Integer.parseInt(refresh));
      } catch (NumberFormatException ignore) {}
    }
    // 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.setRewriteMimeType(getParameter(request, Param.REWRITE_MIME_TYPE.getKey(), null));

    // Figure out whether authentication is required
    AuthType auth = AuthType.parse(getParameter(request, AUTHZ_PARAM, null));
    req.setAuthType(auth);
    if (auth != AuthType.NONE) {
      if (auth == AuthType.OAUTH2) {
        req.setSecurityToken(extractAndValidateToken(request));
        req.setOAuth2Arguments(new OAuth2Arguments(request));
      } else {
        req.setSecurityToken(extractAndValidateToken(request));
        req.setOAuthArguments(new OAuthArguments(auth, request));
      }
    }

    ServletUtil.setXForwardedForHeader(request, req);
    return req;
View Full Code Here


  /**
   * Retrieves a spec from the network, parses, and adds it to the cache.
   */
  protected T fetchFromNetwork(Query query) throws SpecRetrievalFailedException, GadgetException {
    HttpRequest request = new HttpRequest(query.specUri)
        .setIgnoreCache(query.ignoreCache)
        .setGadget(query.gadgetUri)
        .setContainer(query.container);

    // Since we don't allow any variance in cache time, we should just force the cache time
    // globally. This ensures propagation to shared caches when this is set.
    request.setCacheTtl((int) (refresh / 1000));

    HttpResponse response = pipeline.execute(request);
    if (response.getHttpStatusCode() != HttpResponse.SC_OK) {
      int retcode = response.getHttpStatusCode();
      if (retcode == HttpResponse.SC_INTERNAL_SERVER_ERROR) {
View Full Code Here

    if ((completeAuthorizationUrl == null) || (completeAuthorizationUrl.length() == 0)) {
      throw new OAuth2RequestException(ClientCredentialsGrantTypeHandler.ERROR,
              "completeAuthorizationUrl is null", null);
    }

    final HttpRequest request = new HttpRequest(Uri.parse(completeAuthorizationUrl));
    request.setMethod("GET");
    request.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");

    if (accessor == null) {
      throw new OAuth2RequestException(ClientCredentialsGrantTypeHandler.ERROR, "accessor is null",
              null);
    }

    if (!accessor.isValid() || accessor.isErrorResponse() || accessor.isRedirecting()) {
      throw new OAuth2RequestException(ClientCredentialsGrantTypeHandler.ERROR,
              "accessor is invalid", null);
    }

    if (!accessor.getGrantType().equalsIgnoreCase(OAuth2Message.CLIENT_CREDENTIALS)) {
      throw new OAuth2RequestException(ClientCredentialsGrantTypeHandler.ERROR,
              "grant type is not client_credentials", null);
    }

    for (final ClientAuthenticationHandler clientAuthenticationHandler : this.clientAuthenticationHandlers) {
      if (clientAuthenticationHandler.geClientAuthenticationType().equalsIgnoreCase(
              accessor.getClientAuthenticationType())) {
        final OAuth2HandlerError error = clientAuthenticationHandler.addOAuth2Authentication(
                request, accessor);
        if (error != null) {
          throw new OAuth2RequestException(error.getError(), error.getContextMessage(),
                  error.getCause());
        }
      }
    }

    try {
      request.setPostBody(this.getAuthorizationBody(accessor).getBytes("UTF-8"));
    } catch (final UnsupportedEncodingException e) {
      throw new OAuth2RequestException(OAuth2Error.CLIENT_CREDENTIALS_PROBLEM,
              "ClientCredentialsGrantTypeHandler - exception setting post body", e);
    }
View Full Code Here

    OAuth2HandlerError ret = null;

    final String tokenUrl = CodeAuthorizationResponseHandler.getCompleteTokenUrl(accessor
        .getTokenUrl());

    final HttpRequest request = new HttpRequest(Uri.parse(tokenUrl));
    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())) {
        final OAuth2HandlerError error = clientAuthenticationHandler.addOAuth2Authentication(
            request, accessor);
        if (error != null) {
          ret = error;
        }
      }
    }

    if (ret == null) {
      try {
        final byte[] body = CodeAuthorizationResponseHandler.getAuthorizationBody(accessor,
            authorizationCode).getBytes("UTF-8");
        request.setPostBody(body);
      } catch (final UnsupportedEncodingException e) {
        if (CodeAuthorizationResponseHandler.LOG.isLoggable()) {
          CodeAuthorizationResponseHandler.LOG.log(
              "UnsupportedEncodingException getting authorization body", e);
        }
View Full Code Here

        if (LOG.isLoggable(Level.INFO)) {
          LOG.logp(Level.INFO, CLASS_NAME, "makeFetcher", MessageKeys.RETRIEVE_REFERENCE,
              new Object[] {ref.toString()});
        }
        Uri resourceUri = gadgetUri.resolve(Uri.fromJavaUri(ref.getUri()));
        HttpRequest request =
            new HttpRequest(resourceUri).setContainer(container).setGadget(gadgetUri);
        try {
          HttpResponse response = requestPipeline.execute(request);
          byte[] responseBytes = IOUtils.toByteArray(response.getResponse());
          return FetchedData.fromBytes(responseBytes, mimeType, response.getEncoding(),
              new InputSource(ref.getUri()));
View Full Code Here

    HttpResponseBuilder builder = null;
    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

           .create();
      } else {
        Uri uri = getSocialUri(context, token);

        String socialRequestsJson = JsonSerializer.serialize(socialRequests);
        HttpRequest request = new HttpRequest(uri)
            .setIgnoreCache(context.getIgnoreCache())
            .setSecurityToken(context.getToken())
            .setMethod("POST")
            .setAuthType(AuthType.NONE)
            .setPostBody(CharsetUtil.getUtf8Bytes(socialRequestsJson))
View Full Code Here

      this.preload = preload;
      this.key = key;
    }

    public PreloadedData call() throws Exception {
      HttpRequest request = HttpPreloader.newHttpRequest(context, preload);
      String refreshIntervalStr = preload.getAttributes().get("refreshInterval");
      if (refreshIntervalStr != null) {
        try {
          int refreshInterval = Integer.parseInt(refreshIntervalStr);
          request.setCacheTtl(refreshInterval);
        } catch (NumberFormatException nfe) {
          // Ignore, and use the HTTP response interval
        }
      }

      String method = preload.getAttributes().get("method");
      if (method != null) {
        request.setMethod(method);
      }

      // TODO: params EL implementation is not yet properly escaped per spec
      String params = preload.getAttributes().get("params");
      if ((params != null) && !"".equals(params)) {
        if ("POST".equalsIgnoreCase(request.getMethod())) {
          request.setPostBody(params.getBytes("UTF-8"));
          request.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
        } else {
          UriBuilder uriBuilder = new UriBuilder(request.getUri());
          String query = uriBuilder.getQuery();
          query = query == null ? params : query + '&' + params;
          uriBuilder.setQuery(query);
          request.setUri(uriBuilder.toUri());
        }
      }

      return new Data(requestPipeline.execute(request));
    }
View Full Code Here

  /**
   * Send an OAuth GET request to the given URL.
   */
  public HttpResponse sendGet(String target) throws Exception {
    HttpRequest request = new HttpRequest(Uri.parse(target));
    request.setOAuthArguments(recallState());
    OAuthRequest dest = createRequest();
    request.setIgnoreCache(ignoreCache);
    request.setSecurityToken(securityToken);
    HttpResponse response = dest.fetch(request);
    saveState(response);
    return response;
  }
View Full Code Here

    return response;
  }

  // Yes, this is really allowed by the HTTP spec and supported by real servers.
  public HttpResponse sendGetWithBody(String target, String type, byte[] body) {
    HttpRequest request = new HttpRequest(Uri.parse(target));
    request.setOAuthArguments(recallState());
    OAuthRequest dest = createRequest();
    if (type != null) {
      request.setHeader("Content-Type", type);
    }
    request.setPostBody(body);
    request.setSecurityToken(securityToken);
    HttpResponse response = dest.fetch(request);
    saveState(response);
    return response;
  }
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.