public static String getTinyUrl(String fullUrl) {
    HttpClient httpclient = new HttpClient();
    httpclient.setConnectionTimeout(TIMEOUT);
    httpclient.setTimeout(TIMEOUT);
    HttpMethod method = new GetMethod("http://tinyurl.com/api-create.php");
    method.setQueryString(new NameValuePair[] {new NameValuePair("url", fullUrl)});
    String tinyUrl = fullUrl;

    try {
      httpclient.executeMethod(method);
      tinyUrl = method.getResponseBodyAsString();
      method.releaseConnection();
    } catch (HttpException e) {
      method.releaseConnection();
      // implement Liferay logging service
    } catch (IOException e) {
      method.releaseConnection();
      // implement Liferay logging service
    } catch (Exception e) {
      method.releaseConnection();
      // implement Liferay logging service
    }

    return tinyUrl;
  }
예제 #2
0
  /**
   * Creates the HttpMethod to use to call the remote server, either its GET or POST.
   *
   * @param exchange the exchange
   * @return the created method as either GET or POST
   * @throws CamelExchangeException is thrown if error creating RequestEntity
   */
  @SuppressWarnings("deprecation")
  protected HttpMethod createMethod(Exchange exchange) throws Exception {
    // creating the url to use takes 2-steps
    String url = HttpHelper.createURL(exchange, getEndpoint());
    URI uri = HttpHelper.createURI(exchange, url, getEndpoint());
    // get the url and query string from the uri
    url = uri.toASCIIString();
    String queryString = uri.getRawQuery();

    // execute any custom url rewrite
    String rewriteUrl = HttpHelper.urlRewrite(exchange, url, getEndpoint(), this);
    if (rewriteUrl != null) {
      // update url and query string from the rewritten url
      url = rewriteUrl;
      uri = new URI(url);
      // use raw query to have uri decimal encoded which http client requires
      queryString = uri.getRawQuery();
    }

    // remove query string as http client does not accept that
    if (url.indexOf('?') != -1) {
      url = url.substring(0, url.indexOf('?'));
    }

    // create http holder objects for the request
    RequestEntity requestEntity = createRequestEntity(exchange);
    HttpMethods methodToUse =
        HttpHelper.createMethod(exchange, getEndpoint(), requestEntity != null);
    HttpMethod method = methodToUse.createMethod(url);
    if (queryString != null) {
      // need to encode query string
      queryString = UnsafeUriCharactersEncoder.encode(queryString);
      method.setQueryString(queryString);
    }

    LOG.trace("Using URL: {} with method: {}", url, method);

    if (methodToUse.isEntityEnclosing()) {
      ((EntityEnclosingMethod) method).setRequestEntity(requestEntity);
      if (requestEntity != null && requestEntity.getContentType() == null) {
        LOG.debug("No Content-Type provided for URL: {} with exchange: {}", url, exchange);
      }
    }

    // there must be a host on the method
    if (method.getHostConfiguration().getHost() == null) {
      throw new IllegalArgumentException(
          "Invalid uri: "
              + url
              + ". If you are forwarding/bridging http endpoints, then enable the bridgeEndpoint option on the endpoint: "
              + getEndpoint());
    }

    return method;
  }
예제 #3
0
  private static String getTinyUrl(String fullUrl) throws HttpException, IOException {
    HttpClient httpclient = new HttpClient();

    // Prepare a request object
    HttpMethod method = new GetMethod("http://tinyurl.com/api-create.php");
    method.setQueryString(new NameValuePair[] {new NameValuePair("url", fullUrl)});
    httpclient.executeMethod(method);
    String tinyUrl = method.getResponseBodyAsString();
    method.releaseConnection();
    return tinyUrl;
  }
 public HttpMethod generateRequestFor(List<String> recipients, String message) {
   HttpMethod httpMethod;
   if (HttpMethodType.POST.equals(outgoing.getRequest().getType())) {
     httpMethod = new PostMethod(outgoing.getRequest().getUrlPath());
     httpMethod.setRequestHeader("Content-Type", PostMethod.FORM_URL_ENCODED_CONTENT_TYPE);
     addBodyParameters((PostMethod) httpMethod, recipients, message);
   } else {
     httpMethod = new GetMethod(outgoing.getRequest().getUrlPath());
   }
   httpMethod.setQueryString(addQueryParameters(recipients, message));
   return httpMethod;
 }
예제 #5
0
  public String getTinyUrl(String fullUrl) throws HttpException, IOException {
    HttpClient httpclient = new HttpClient();
    HttpMethod method = new GetMethod("http://tinyurl.com/api-create.php");
    method.setQueryString(new NameValuePair[] {new NameValuePair("url", fullUrl)});
    httpclient.executeMethod(method);

    InputStream is = method.getResponseBodyAsStream();
    StringBuilder sb = new StringBuilder();
    for (int i = is.read(); i != -1; i = is.read()) {
      sb.append((char) i);
    }
    String tinyUrl = sb.toString();
    method.releaseConnection();

    log.info("Successfully shortened URL " + fullUrl + " via tinyurl to " + tinyUrl + ".");
    return tinyUrl;
  }
  /**
   * 执行Http请求
   *
   * @param request 请求数据
   * @param strParaFileName 文件类型的参数名
   * @param strFilePath 文件路径
   * @return
   * @throws HttpException, IOException
   */
  public HttpResponse execute(HttpRequest request, String strParaFileName, String strFilePath)
      throws HttpException, IOException {
    HttpClient httpclient = new HttpClient(connectionManager);

    // 设置连接超时
    int connectionTimeout = defaultConnectionTimeout;
    if (request.getConnectionTimeout() > 0) {
      connectionTimeout = request.getConnectionTimeout();
    }
    httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout);

    // 设置回应超时
    int soTimeout = defaultSoTimeout;
    if (request.getTimeout() > 0) {
      soTimeout = request.getTimeout();
    }
    httpclient.getHttpConnectionManager().getParams().setSoTimeout(soTimeout);

    // 设置等待ConnectionManager释放connection的时间
    httpclient.getParams().setConnectionManagerTimeout(defaultHttpConnectionManagerTimeout);

    String charset = request.getCharset();
    charset = charset == null ? DEFAULT_CHARSET : charset;
    HttpMethod method = null;

    // get模式且不带上传文件
    if (request.getMethod().equals(HttpRequest.METHOD_GET)) {
      method = new GetMethod(request.getUrl());
      method.getParams().setCredentialCharset(charset);

      // parseNotifyConfig会保证使用GET方法时,request一定使用QueryString
      method.setQueryString(request.getQueryString());
    } else if (strParaFileName.equals("") && strFilePath.equals("")) {
      // post模式且不带上传文件
      method = new PostMethod(request.getUrl());
      ((PostMethod) method).addParameters(request.getParameters());
      method.addRequestHeader(
          "Content-Type", "application/x-www-form-urlencoded; text/html; charset=" + charset);
    } else {
      // post模式且带上传文件
      method = new PostMethod(request.getUrl());
      List<Part> parts = new ArrayList<Part>();
      for (int i = 0; i < request.getParameters().length; i++) {
        parts.add(
            new StringPart(
                request.getParameters()[i].getName(),
                request.getParameters()[i].getValue(),
                charset));
      }
      // 增加文件参数,strParaFileName是参数名,使用本地文件
      parts.add(new FilePart(strParaFileName, new FilePartSource(new File(strFilePath))));

      // 设置请求体
      ((PostMethod) method)
          .setRequestEntity(
              new MultipartRequestEntity(parts.toArray(new Part[0]), new HttpMethodParams()));
    }

    // 设置Http Header中的User-Agent属性
    method.addRequestHeader("User-Agent", "Mozilla/4.0");
    HttpResponse response = new HttpResponse();

    try {
      httpclient.executeMethod(method);
      if (request.getResultType().equals(HttpResultType.STRING)) {
        response.setStringResult(method.getResponseBodyAsString());
      } else if (request.getResultType().equals(HttpResultType.BYTES)) {
        response.setByteResult(method.getResponseBody());
      }
      response.setResponseHeaders(method.getResponseHeaders());
    } catch (UnknownHostException ex) {

      return null;
    } catch (IOException ex) {

      return null;
    } catch (Exception ex) {

      return null;
    } finally {
      method.releaseConnection();
    }
    return response;
  }
예제 #7
0
  /**
   * Report to deliver engines that a portlet has been uploaded
   *
   * @param contentId contentId of portlet
   */
  private void updateDeliverEngines(Integer digitalAssetId) {
    List allUrls = CmsPropertyHandler.getInternalDeliveryUrls();
    allUrls.addAll(CmsPropertyHandler.getPublicDeliveryUrls());

    Iterator urlIterator = allUrls.iterator();
    while (urlIterator.hasNext()) {
      String url = (String) urlIterator.next() + "/DeployPortlet.action";

      try {
        HttpClient client = new HttpClient();

        // establish a connection within 5 seconds
        client.setConnectionTimeout(5000);

        // set the default credentials
        HttpMethod method = new GetMethod(url);
        method.setQueryString("digitalAssetId=" + digitalAssetId);
        method.setFollowRedirects(true);

        // execute the method
        client.executeMethod(method);
        StatusLine status = method.getStatusLine();
        if (status != null && status.getStatusCode() == 200) {
          log.info("Successfully deployed portlet at " + url);
        } else {
          log.warn("Failed to deploy portlet at " + url + ": " + status);
        }

        // clean up the connection resources
        method.releaseConnection();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }

    /*
    Properties props = CmsPropertyHandler.getProperties();
    for (Enumeration keys = props.keys(); keys.hasMoreElements();) {
        String key = (String) keys.nextElement();
        if (key.startsWith(PORTLET_DEPLOY_PREFIX)) {
            String url = props.getProperty(key);
            try {
                HttpClient client = new HttpClient();

                //establish a connection within 5 seconds
                client.setConnectionTimeout(5000);

                //set the default credentials
                HttpMethod method = new GetMethod(url);
                method.setQueryString("digitalAssetId=" + digitalAssetId);
                method.setFollowRedirects(true);

                //execute the method
                client.executeMethod(method);
                StatusLine status = method.getStatusLine();
                if (status != null && status.getStatusCode() == 200) {
                    log.info("Successfully deployed portlet at " + url);
                } else {
                    log.warn("Failed to deploy portlet at " + url + ": " + status);
                }

                //clean up the connection resources
                method.releaseConnection();
            } catch (Throwable e) {
                log.error(e.getMessage(), e);
            }
        }
    }
    */

  }
예제 #8
0
 public int executeMethod(
     HostConfiguration hostconfig, final HttpMethod httpMethod, final HttpState state)
     throws IOException, HttpException {
   httpMethod.setQueryString(appendParams(httpMethod.getQueryString()));
   return super.executeMethod(hostconfig, httpMethod, state);
 }
예제 #9
0
  protected byte[] doPreemptiveAuthentication(
      HttpClient client, HttpMethod method, RenderRequest request, RenderResponse response) {
    byte[] result = super.doPreemptiveAuthentication(client, method, request, response);
    if (result != null) {
      // already handled
      return result;
    }

    // System.out.println("SSOWebContentPortlet.doPreemptiveAuthentication...");

    PortletPreferences prefs = request.getPreferences();
    String type = getSingleSignOnAuthType(prefs);

    if (type.equalsIgnoreCase(SSO_TYPE_BASIC_PREEMPTIVE)) {
      // Preemptive, basic authentication
      String userName = (String) request.getAttribute(SSO_REQUEST_ATTRIBUTE_USERNAME);
      if (userName == null) userName = "";
      String password = (String) request.getAttribute(SSO_REQUEST_ATTRIBUTE_PASSWORD);
      if (password == null) password = "";

      // System.out.println("...performing preemptive basic authentication with userName:
      // "+userName+", and password: "******"");
        if (formAction == null || formAction.length() == 0) {
          log.warn(
              "sso.type specified as 'form', but no: "
                  + SSO_TYPE_FORM_ACTION_URL
                  + ", action was specified - unable to preemptively authenticate by form.");
          return null;
        }
        String userNameField = prefs.getValue(SSO_TYPE_FORM_USERNAME_FIELD, "");
        if (userNameField == null || userNameField.length() == 0) {
          log.warn(
              "sso.type specified as 'form', but no: "
                  + SSO_TYPE_FORM_USERNAME_FIELD
                  + ", username field was specified - unable to preemptively authenticate by form.");
          return null;
        }
        String passwordField = prefs.getValue(SSO_TYPE_FORM_PASSWORD_FIELD, "password");
        if (passwordField == null || passwordField.length() == 0) {
          log.warn(
              "sso.type specified as 'form', but no: "
                  + SSO_TYPE_FORM_PASSWORD_FIELD
                  + ", password field was specified - unable to preemptively authenticate by form.");
          return null;
        }

        String userName = (String) request.getAttribute(SSO_REQUEST_ATTRIBUTE_USERNAME);
        if (userName == null) userName = "";
        String password = (String) request.getAttribute(SSO_REQUEST_ATTRIBUTE_PASSWORD);
        if (password == null) password = "";

        // get submit method
        int i = type.indexOf('.');
        boolean isPost =
            i > 0
                ? type.substring(i + 1).equalsIgnoreCase("post")
                : true; // default to post, since it is a form

        // get parameter map
        HashMap formParams = new HashMap();
        formParams.put(userNameField, new String[] {userName});
        formParams.put(passwordField, new String[] {password});
        String formArgs = prefs.getValue(SSO_TYPE_FORM_ACTION_ARGS, "");
        if (formArgs != null && formArgs.length() > 0) {
          StringTokenizer iter = new StringTokenizer(formArgs, ";");
          while (iter.hasMoreTokens()) {
            String pair = iter.nextToken();
            i = pair.indexOf('=');
            if (i > 0) formParams.put(pair.substring(0, i), new String[] {pair.substring(i + 1)});
          }
        }

        // resuse client - in case new cookies get set - but create a new method (for the
        // formAction)
        String formMethod = (isPost) ? FORM_POST_METHOD : FORM_GET_METHOD;
        method =
            getHttpMethod(
                client,
                getURLSource(formAction, formParams, request, response),
                formParams,
                formMethod,
                request);
        // System.out.println("...posting credentials");
        result = doHttpWebContent(client, method, 0, request, response);
        // System.out.println("Result of attempted authorization: "+success);
        PortletMessaging.publish(request, FORM_AUTH_STATE, Boolean.valueOf(result != null));
        return result;
      } catch (Exception ex) {
        // bad
        log.error("Form-based authentication failed", ex);
      }
    } else if (type.equalsIgnoreCase(SSO_TYPE_URL) || type.equalsIgnoreCase(SSO_TYPE_URL_BASE64)) {
      // set user name and password parameters in the HttpMethod
      String userNameParam = prefs.getValue(SSO_TYPE_URL_USERNAME_PARAM, "");
      if (userNameParam == null || userNameParam.length() == 0) {
        log.warn(
            "sso.type specified as 'url', but no: "
                + SSO_TYPE_URL_USERNAME_PARAM
                + ", username parameter was specified - unable to preemptively authenticate by URL.");
        return null;
      }
      String passwordParam = prefs.getValue(SSO_TYPE_URL_PASSWORD_PARAM, "");
      if (passwordParam == null || passwordParam.length() == 0) {
        log.warn(
            "sso.type specified as 'url', but no: "
                + SSO_TYPE_URL_PASSWORD_PARAM
                + ", password parameter was specified - unable to preemptively authenticate by URL.");
        return null;
      }
      String userName = (String) request.getAttribute(SSO_REQUEST_ATTRIBUTE_USERNAME);
      if (userName == null) userName = "";
      String password = (String) request.getAttribute(SSO_REQUEST_ATTRIBUTE_PASSWORD);
      if (password == null) password = "";
      if (type.equalsIgnoreCase(SSO_TYPE_URL_BASE64)) {
        Base64 encoder = new Base64();
        userName = new String(encoder.encode(userName.getBytes()));
        password = new String(encoder.encode(password.getBytes()));
      }

      // GET and POST accept args differently
      if (method instanceof PostMethod) {
        // add POST data
        PostMethod postMethod = (PostMethod) method;
        postMethod.addParameter(userNameParam, userName);
        postMethod.addParameter(passwordParam, password);
      } else {
        // augment GET query string
        NameValuePair[] authPairs =
            new NameValuePair[] {
              new NameValuePair(userNameParam, userName), new NameValuePair(passwordParam, password)
            };
        String existingQuery = method.getQueryString();
        method.setQueryString(authPairs);
        if (existingQuery != null && existingQuery.length() > 0) {
          // augment existing query with new auth query
          existingQuery = existingQuery + '&' + method.getQueryString();
          method.setQueryString(existingQuery);
        }
      }

      return result;
    }
    // else System.out.println("...sso.type: "+type+", no pre-emptive authentication");

    // not handled
    return null;
  }
  /**
   * 执行Http请求
   *
   * @param request
   * @return
   */
  public HttpResponse execute(HttpRequest request) {
    HttpClient httpclient = new HttpClient(connectionManager);

    // 设置连接超时
    int connectionTimeout = defaultConnectionTimeout;
    if (request.getConnectionTimeout() > 0) {
      connectionTimeout = request.getConnectionTimeout();
    }
    httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout);

    // 设置回应超时
    int soTimeout = defaultSoTimeout;
    if (request.getTimeout() > 0) {
      soTimeout = request.getTimeout();
    }
    httpclient.getHttpConnectionManager().getParams().setSoTimeout(soTimeout);

    // 设置等待ConnectionManager释放connection的时间
    httpclient.getParams().setConnectionManagerTimeout(defaultHttpConnectionManagerTimeout);

    String charset = request.getCharset();
    charset = charset == null ? DEFAULT_CHARSET : charset;
    HttpMethod method = null;

    if (request.getMethod().equals(HttpRequest.METHOD_GET)) {
      method = new GetMethod(request.getUrl());
      method.getParams().setCredentialCharset(charset);

      // parseNotifyConfig会保证使用GET方法时,request一定使用QueryString
      method.setQueryString(request.getQueryString());
    } else {
      method = new PostMethod(request.getUrl());
      ((PostMethod) method).addParameters(request.getParameters());
      method.addRequestHeader(
          "Content-Type", "application/x-www-form-urlencoded; text/html; charset=" + charset);
    }

    // 设置Http Header中的User-Agent属性
    method.addRequestHeader("User-Agent", "Mozilla/4.0");
    HttpResponse response = new HttpResponse();

    try {
      httpclient.executeMethod(method);
      if (request.getResultType().equals(HttpResultType.STRING)) {
        response.setStringResult(method.getResponseBodyAsString());
      } else if (request.getResultType().equals(HttpResultType.BYTES)) {
        response.setByteResult(method.getResponseBody());
      }
      response.setResponseHeaders(method.getResponseHeaders());
    } catch (UnknownHostException ex) {

      return null;
    } catch (IOException ex) {

      return null;
    } catch (Exception ex) {

      return null;
    } finally {
      method.releaseConnection();
    }
    return response;
  }