Package org.apache.shindig.gadgets.http

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


  /**
   * Send an OAuth POST request to the given URL.
   */
  public HttpResponse sendFormPost(String target, String body) throws Exception {
    HttpRequest request = new HttpRequest(Uri.parse(target));
    request.setOAuthArguments(recallState());
    OAuthRequest dest = createRequest();
    request.setMethod("POST");
    request.setPostBody(CharsetUtil.getUtf8Bytes(body));
    request.setHeader("content-type", "application/x-www-form-urlencoded");
    request.setSecurityToken(securityToken);
    HttpResponse response = dest.fetch(request);
    saveState(response);
    return response;
  }
View Full Code Here


  /**
   * Send an OAuth POST with binary data in the binary.
   */
  public HttpResponse sendRawPost(String target, String type, byte[] body) throws Exception {
    HttpRequest request = new HttpRequest(Uri.parse(target));
    request.setOAuthArguments(recallState());
    OAuthRequest dest = createRequest();
    request.setMethod("POST");
    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

  }

  protected MessageBundle fetchBundle(LocaleSpec locale, boolean ignoreCache)
      throws GadgetException {
    Uri url = locale.getMessages();
    HttpRequest request = new HttpRequest(url).setIgnoreCache(ignoreCache);
    // 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) {
      throw new GadgetException(GadgetException.Code.FAILED_TO_RETRIEVE_CONTENT,
          "Unable to retrieve message bundle xml. HTTP error " +
View Full Code Here

    }
  }
 
  public TemplateLibrary loadTemplateLibrary(GadgetContext context, Uri uri) throws GadgetException,
      TemplateParserException {
    HttpRequest request = new HttpRequest(uri);
    // 5 minute TTL.
    request.setCacheTtl(300);
    HttpResponse response = pipeline.execute(request);
    if (response.getHttpStatusCode() != HttpResponse.SC_OK) {
      throw new GadgetException(GadgetException.Code.FAILED_TO_RETRIEVE_CONTENT,
          "Unable to retrieve template library xml. HTTP error " +
          response.getHttpStatusCode());     
View Full Code Here

    return ImmutableList.of();
  }

  private Set<String> retrieveServices(String endpoint) {
    Uri url = Uri.parse(endpoint + "?method=" + SYSTEM_LIST_METHODS_METHOD);
    HttpRequest request = new HttpRequest(url);
    try {
      HttpResponse response = fetcher.fetch(request);
      if (response.getHttpStatusCode() == HttpResponse.SC_OK) {
        return getServicesFromJsonResponse(response.getResponseAsString());
      } else {
View Full Code Here

   * Executes a request, returning the response as JSON to be handled by makeRequest.
   */
  @Override
  protected void doFetch(HttpServletRequest request, HttpServletResponse response)
      throws GadgetException, IOException {
    HttpRequest rcr = buildHttpRequest(request);

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

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

    // 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);
View Full Code Here

      encoding = "UTF-8";
    }

    Uri url = validateUrl(request.getParameter(URL_PARAM));

    HttpRequest req = new HttpRequest(url)
        .setMethod(getParameter(request, METHOD_PARAM, "GET"))
        .setPostBody(getParameter(request, POST_DATA_PARAM, "").getBytes())
        .setContainer(getContainer(request));

    String headerData = getParameter(request, HEADERS_PARAM, "");
    if (headerData.length() > 0) {
      String[] headerList = headerData.split("&");
      for (String header : headerList) {
        String[] parts = header.split("=");
        if (parts.length != 2) {
          throw new GadgetException(GadgetException.Code.INTERNAL_SERVER_ERROR,
              "Malformed header specified,");
        }
        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");
    }

    req.setIgnoreCache("1".equals(request.getParameter(NOCACHE_PARAM)));

    if (request.getParameter(GADGET_PARAM) != null) {
      req.setGadget(Uri.parse(request.getParameter(GADGET_PARAM)));
    }

    // 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 (request.getParameter(REFRESH_PARAM) != null) {
      try {
        req.setCacheTtl(Integer.parseInt(request.getParameter(REFRESH_PARAM)));
      } catch (NumberFormatException nfe) {
        // 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(request.getParameter(REWRITE_MIME_TYPE_PARAM));

    // Figure out whether authentication is required
    AuthType auth = AuthType.parse(getParameter(request, AUTHZ_PARAM, null));
    req.setAuthType(auth);
    if (auth != AuthType.NONE) {
      req.setSecurityToken(extractAndValidateToken(request));
      req.setOAuthArguments(new OAuthArguments(auth, request));
    }
    return req;
  }
View Full Code Here

    String postBody = params.get("--postBody");
    String postFile = params.get("--postFile");
    String paramLocation = params.get("--paramLocation");
    String bodySigning = params.get("--bodySigning");

    HttpRequest request = new HttpRequest(Uri.parse(url));
    if (contentType != null) {
      request.setHeader("Content-Type", contentType);
    } else {
      request.setHeader("Content-Type", OAuth.FORM_ENCODED);
    }
    if (postBody != null) {
      request.setPostBody(postBody.getBytes());
    }
    if (postFile != null) {
      request.setPostBody(IOUtils.toByteArray(new FileInputStream(postFile)));
    }

    OAuthParamLocation paramLocationEnum = OAuthParamLocation.URI_QUERY;
    if (paramLocation != null) {
      paramLocationEnum = OAuthParamLocation.valueOf(paramLocation);
    }

    BodySigning bodySigningEnum = BodySigning.none;
    if (bodySigning != null) {
      bodySigningEnum = BodySigning.valueOf(bodySigning);
    }

    List<OAuth.Parameter> oauthParams = Lists.newArrayList();
    UriBuilder target = new UriBuilder(Uri.parse(url));
    String query = target.getQuery();
    target.setQuery(null);
    oauthParams.addAll(OAuth.decodeForm(query));
    if (OAuth.isFormEncoded(contentType) && request.getPostBodyAsString() != null) {
      oauthParams.addAll(OAuth.decodeForm(request.getPostBodyAsString()));
    } else if (bodySigningEnum == BodySigning.legacy) {
      oauthParams.add(new OAuth.Parameter(request.getPostBodyAsString(), ""));
    } else if (bodySigningEnum == BodySigning.hash) {
      oauthParams.add(
            new OAuth.Parameter(OAuthConstants.OAUTH_BODY_HASH,
                new String(Base64.encodeBase64(DigestUtils.sha(postBody.getBytes())), "UTF-8")));
    }

    if (consumerKey != null) {
      oauthParams.add(new OAuth.Parameter(OAuth.OAUTH_CONSUMER_KEY, consumerKey));
    }
    if (xOauthRequestor != null) {
      oauthParams.add(new OAuth.Parameter("xoauth_requestor_id", xOauthRequestor));
    }

    OAuthConsumer consumer = new OAuthConsumer(null, consumerKey, consumerSecret, null);
    OAuthAccessor accessor = new OAuthAccessor(consumer);
    accessor.accessToken = accessToken;
    OAuthMessage message = accessor.newRequestMessage(method, target.toString(), oauthParams);

    List<Map.Entry<String, String>> entryList = OAuthRequest.selectOAuthParams(message);

    switch (paramLocationEnum) {
      case AUTH_HEADER:
        request.addHeader("Authorization", OAuthRequest.getAuthorizationHeader(entryList));
        break;

      case POST_BODY:
        if (!OAuth.isFormEncoded(contentType)) {
          throw new RuntimeException(
              "OAuth param location can only be post_body if post body if of " +
                  "type x-www-form-urlencoded");
        }
        String oauthData = OAuthUtil.formEncode(message.getParameters());
        request.setPostBody(CharsetUtil.getUtf8Bytes(oauthData));
        break;

      case URI_QUERY:
        request.setUri(Uri.parse(OAuthUtil.addParameters(request.getUri().toString(),
            entryList)));
        break;
    }
    request.setMethod(method);

    HttpFetcher fetcher = new BasicHttpFetcher();
    HttpResponse response = fetcher.fetch(request);

    System.out.println("Request ------------------------------");
    System.out.println(request.toString());
    System.out.println("Response -----------------------------");
    System.out.println(response.toString());
  }
View Full Code Here

    }
  }

  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

      throws OAuthRequestException {
    if (accessor.consumer.serviceProvider.requestTokenURL == null) {
      throw responseParams.oauthRequestException(OAuthError.BAD_OAUTH_CONFIGURATION,
          "No request token URL specified");
    }
    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

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.