Package com.maverick.http

Examples of com.maverick.http.HttpClient


  private synchronized HttpClient getHttpClient() {
    if (client == null) {
      // #ifdef DEBUG
      log.info("Creating HttpClient instance"); //$NON-NLS-1$
      // #endif
      client = new HttpClient(aditoHostname, aditoPort, isSecure);
      client.setAuthenticationPrompt(defaultAuthenticationPrompt != null ? defaultAuthenticationPrompt : getGUI());
      if (defaultProxyHost != null && !defaultProxyHost.equals("")) { //$NON-NLS-1$
        // #ifdef DEBUG
        log.info("Configuring proxies for HttpClient instance"); //$NON-NLS-1$
        // #endif
View Full Code Here


    try {
           
      for (int i = 0; i < 3; i++) {

              HttpClient client = getHttpClient();
              if (doPreemptive) {
                  client.setCredentials(new PasswordCredentials(username,
                          ticket));
                  client.setPreferredAuthentication("Basic");
              }
              else {
                  client.setCredentials(null);
              }

        // #ifdef DEBUG
        log.info("Registering with the server"); //$NON-NLS-1$
        log.info("Server is " + (isSecure ? "https://" : "http://") + getAditoHost() //$NON-NLS-1$
            + ":" + getAditoPort()); //$NON-NLS-1$
        // #endif
        GetMethod post = new GetMethod("/agent"); //$NON-NLS-1$

              client.setPreemtiveAuthentication(doPreemptive);
        if (!doPreemptive && ticket != null) {
          post.setParameter("ticket", ticket); //$NON-NLS-1$
        }

        post.setParameter(
            "agentType", getConfiguration().getAgentType()); //$NON-NLS-1$ //$NON-NLS-2$
        post.setParameter("locale", Locale.getDefault().toString()); //$NON-NLS-1$

        response = client.execute(post);

        if (response.getStatus() == 302) {
          // Reset the client
          this.client = null;
View Full Code Here

   */
  public boolean sendProxiedRequest() throws Exception {

    byte[] content = null;
    OutputStream serverOut = null;
    HttpClient client;
    SessionClients clients = null;
    HttpSession session = requestProcessor.getSession();

    // Manage the sessions clients
    synchronized (session) {
      clients = (SessionClients) session.getAttribute(Constants.HTTP_CLIENTS);
      if (clients == null) {
        clients = new SessionClients();
        session.setAttribute(Constants.HTTP_CLIENTS, clients);
      }
    }
   
    RequestParameterMap requestParameters = requestProcessor.getRequestParameters();
    URL proxiedURL = requestParameters.getProxiedURIDetails().getProxiedURL();

    synchronized (clients) {
      String key = proxiedURL.getHost() + ":"
        + (proxiedURL.getPort() > 0 ? proxiedURL.getPort() : proxiedURL.getProtocol().equals("https") ? 443 : 80)
        + ":"
        + proxiedURL.getProtocol().equals("https")
        + ":"
        + requestProcessor.getWebForward().getResourceId()
        + Thread.currentThread().getName();
      client = (HttpClient) clients.get(key);

      if (client == null) {
        client = new HttpClient(proxiedURL.getHost(), (proxiedURL.getPort() > 0 ? proxiedURL.getPort()
          : proxiedURL.getProtocol().equals("https") ? 443 : 80), proxiedURL.getProtocol().equals("https"));

        if (!requestProcessor.getWebForward().getPreferredAuthenticationScheme().equals(HttpAuthenticatorFactory.NONE) && !requestProcessor.getWebForward()
                .getAuthenticationUsername()
                .equals("")
          && !requestProcessor.getWebForward().getAuthenticationPassword().equals("")) {
          PasswordCredentials pwd = new PasswordCredentials();
          pwd.setUsername(SessionInfoReplacer.replace(requestProcessor.getSessionInfo(), requestProcessor.getWebForward()
                  .getAuthenticationUsername()));
          pwd.setPassword(SessionInfoReplacer.replace(requestProcessor.getSessionInfo(), requestProcessor.getWebForward()
                  .getAuthenticationPassword()));
          client.setCredentials(pwd);
        }

        // Set the preferred scheme
        client.setPreferredAuthentication(requestProcessor.getWebForward().getPreferredAuthenticationScheme());

        // Do not track cookies, browser will instead
        client.setIncludeCookies(false);
       
        // If we're using basic authentication then preempt the 401
        // response
        client.setPreemtiveAuthentication(requestProcessor.getWebForward()
                .getPreferredAuthenticationScheme()
                .equalsIgnoreCase("BASIC"));
        clients.put(key, client);
      }
    }

    if (log.isDebugEnabled())
      log.debug("Connecting to [" + proxiedURL + "] ");

    ProxiedHttpMethod method;

         if (!requestProcessor.getWebForward().getFormType().equals(WebForwardTypes.FORM_SUBMIT_NONE) &&
             !requestProcessor.getWebForward().getFormType().equals("") &&
             !requestProcessor.getWebForward().getFormType().equals(WebForwardTypes.FORM_SUBMIT_JAVASCRIPT) &&
             !Boolean.TRUE.equals(launchSession.getAttribute(LAUNCH_ATTR_AUTH_POSTED))) {

            /**
             * This code will automatically submit form parameters.
             *
             * LDP - Use the full URI with parameters as we need to ensure parameters are sent as they are received.
             */
      method = new ProxiedHttpMethod(requestProcessor.getWebForward().getFormType(),
          SessionInfoReplacer.replace(requestProcessor.getSessionInfo(),
          requestProcessor.getUriEncoded()),
          requestProcessor.getWebForward().getFormType().equals(WebForwardTypes.FORM_SUBMIT_POST)? new MultiMap() : requestParameters,
          requestProcessor.getSessionInfo(),
          requestProcessor.getWebForward().getFormType().equals(WebForwardTypes.FORM_SUBMIT_POST));

      if (requestProcessor.getWebForward().getEncoding() != null && !requestProcessor.getWebForward().getEncoding().equals(WebForwardTypes.DEFAULT_ENCODING))
                method.setCharsetEncoding(requestProcessor.getWebForward().getEncoding());

            StringTokenizer tokens = new StringTokenizer(requestProcessor.getWebForward().getFormParameters(), "\n");
            int idx;
            String param;
            while (tokens.hasMoreTokens()) {
                param = SessionInfoReplacer.replace(requestProcessor.getLaunchSession().getSession(), tokens.nextToken().trim());
                idx = param.indexOf('=');
                if (idx > -1 && idx < param.length()-1) {
                    method.addParameter(param.substring(0, idx), param.substring(idx + 1));
                } else
                    method.addParameter(param, "");
            }
           
            launchSession.setAttribute(LAUNCH_ATTR_AUTH_POSTED, Boolean.TRUE);
        } else {
          /**
             * LDP - Use the full URI with parameters as we need to ensure parameters are sent as they are received.
           */
          method = new ProxiedHttpMethod(requestProcessor.getMethod(),
          SessionInfoReplacer.replace(requestProcessor.getSessionInfo(),
            requestProcessor.getUriEncoded()),
            requestParameters,
          requestProcessor.getSessionInfo(),
          requestProcessor.getRequest().getContentType()!=null &&
          requestProcessor.getRequest().getContentType().startsWith("application/x-www-form-urlencoded"));

            if (requestProcessor.getWebForward().getEncoding() != null && !requestProcessor.getWebForward().getEncoding().equals(WebForwardTypes.DEFAULT_ENCODING))
                method.setCharsetEncoding(requestProcessor.getWebForward().getEncoding());
        }

    int contentLength = 0;
    String contentType = null;
   
    for (Enumeration e = requestProcessor.getHeaderNames(); e.hasMoreElements();) {

      String hdr = (String) e.nextElement();

      if (ignoreHeaders.containsKey(hdr)) {
        if (log.isDebugEnabled())
          log.debug("Ignoring " + hdr + " = " + requestProcessor.getHeader(hdr));
        continue;
      }

      // See if there any replacements for this header
      List replacements = WebForwardDatabaseFactory.getInstance().getReplacementsForContent(launchSession.getSession().getUser().getPrincipalName(),
        Replacement.REPLACEMENT_TYPE_SENT_HEADER,
        hdr,
        proxiedURL.toExternalForm());

      Enumeration vals = requestProcessor.getHeaders(hdr);
      while (vals.hasMoreElements()) {
        String val = (String) vals.nextElement();

        // Do the replacements
        for (Iterator i = replacements.iterator(); i.hasNext();) {
          Replacement r = (Replacement) i.next();
          val = val.replaceAll(r.getMatchPattern(), r.getReplacePattern());
        }

        if (val != null) {
          if (hdr.equalsIgnoreCase(HttpConstants.HDR_HOST)) {
            if (proxiedURL.getPort() == -1) {
              val = proxiedURL.getHost();
            } else {
              val = proxiedURL.getHost() + ":" + proxiedURL.getPort();
            }
          } else if (hdr.equalsIgnoreCase(HttpConstants.HDR_COOKIE)) {
            // We shouldnt supply our local cookies
            if (log.isDebugEnabled())
              log.debug(" Splitting cookie " + val);
            String[] cookieVals = val.split("\\;");
            StringBuffer newVal = new StringBuffer();
            for (int i = 0; i < cookieVals.length; i++) {
              if (log.isDebugEnabled())
                log.debug("Cookie = " + cookieVals[i]);
              int idx = cookieVals[i].indexOf('=');
              String cn = "";
              String cv = "";
              if(idx==-1) {
                cn = Util.trimBoth(cookieVals[i]);
              } else if(idx < cookieVals[i].length()-1) {
                cn = Util.trimBoth(cookieVals[i].substring(0, idx));
                cv = Util.trimBoth(cookieVals[i].substring(idx + 1));     
              } else {
                cn = Util.trimBoth(cookieVals[i].substring(0, idx));         
              }
              if (cn.equals("webForward") || cn.equals(Constants.LOGON_TICKET)
                || cn.equals(Constants.DOMAIN_LOGON_TICKET)
                || (cn.equals(sessionIdCookieName) && cv.equals(requestProcessor.getSession().getId()))) {
                if (log.isDebugEnabled())
                  log.debug("  Omiting cookie " + cn + "=" + cv);
              } else {
                // TODO is it ok to store the cookie map in
                // memory?
                CookieItem cookie = cookieMap.getByFakeCookieName(cn);
                if (cookie == null) {
                  if (log.isDebugEnabled())
                    log.debug("  Cookie " + cn + " unmapped, ignoring");
                  // Un-mapped cookie, ignore
                } else {
                  if (log.isDebugEnabled())
                    log.debug("  Including cookie " + cn + "=" + cv);
                  if (newVal.length() > 0) {
                    newVal.append("; ");
                  }
                  newVal.append(cookie.getRealCookieName());
                  newVal.append("=");
                  newVal.append(Util.urlDecode(cv));
                }
              }
            }
            if (newVal.length() == 0) {
              if (log.isDebugEnabled())
                log.debug("Send no cookies");
              val = null;
            } else {
              val = newVal.toString();
              if (log.isDebugEnabled())
                log.debug("Using cooking val of " + val);
            }
          }
          // Change the refererer
          else if (hdr.equalsIgnoreCase(HttpConstants.HDR_REFERER)) {
            try {
              URL refUrl = new URL(val);
              refUrl.getQuery();
              if (log.isDebugEnabled())
                log.debug("Splitting refererer query string [" + val + "] " + refUrl.getQuery());
              if (refUrl.getFile() != null) {
                 
                  ProxyURIDetails uriDetails = RequestParameterMap.parseProxyPath(refUrl.getFile(), "UTF-8");
                  if(uriDetails.getProxiedURL() == null) {
                      /* If the referer is not a proxied URL then don't send a referer. This
                       * way a target server won't know its a request from Adito by
                       * examining the referer
                       */
                      val = null;
                  }
                  else {
                      val = uriDetails.getProxiedURL().toExternalForm();
                  }
              }
            } catch (MalformedURLException murle) {

            }
          } else if (hdr.equalsIgnoreCase(HttpConstants.HDR_CONTENT_LENGTH)) {
            contentLength = Integer.parseInt(val);
            continue;
          } else if(hdr.equalsIgnoreCase(HttpConstants.HDR_CONTENT_TYPE)) {
            contentType = val;
            continue;
          } else if (hdr.equalsIgnoreCase(HttpConstants.HDR_CONNECTION)) {
            // Handled by the Maverick HTTP client
            continue;
          }

          if (val != null) {
            method.getProxiedRequest().addHeaderField(hdr, val);
          }

          if (log.isDebugEnabled())
            log.debug("Adding request property " + hdr + " = " + val);
        }
      }
    }

    // Proxy headers
    method.getProxiedRequest().setHeaderField("Via", Branding.PRODUCT_NAME);
   
    if(requestParameters.isMultipart() && requestParameters.getMultipartDataLength()  > 0) {
        method.setContent(getDebugStream(requestParameters.getMultipartData()), requestParameters.getMultipartDataLength(), requestParameters.getOriginalContentType());
        }
        else if(!requestParameters.isWwwFormURLEncoded() && contentLength > 0) {
            method.setContent(getDebugStream(requestProcessor.getRequest().getInputStream()), requestParameters.getOriginalContentLength(), requestParameters.getOriginalContentType());
        }

    serverResponse = client.execute(method);

    responseCode = serverResponse.getStatus();
    responseMessage = serverResponse.getReason();

    return true;
View Full Code Here

     */

    try {
      URL target = getTarget(launchSession, request);
      setRequestEncoding(launchSession, target, request);
      HttpClient client = getClient(launchSession, target);
      ProxiedHttpMethod method = getMethod(client, launchSession, request, target);
      processPortsAndXForwarding(method, request);
      checkProcessedContent(launchSession, method, request);
      addCustomHeaders(webForward, method);
     
View Full Code Here

    String hostname = target.getHost();
    boolean isSecure = target.getProtocol().equalsIgnoreCase("https");
    int connectPort = target.getPort() == -1 ? (isSecure ? 443 : 80) : target.getPort();

    HttpClient client;

    SessionClients clients = null;
    // CookieMap cookieMap = null;
    synchronized (launchSession.getSession().getHttpSession()) {
      clients = (SessionClients) launchSession.getSession().getHttpSession().getAttribute(Constants.HTTP_CLIENTS);
      if (clients == null) {
        clients = new SessionClients();
        launchSession.getSession().getHttpSession().setAttribute(Constants.HTTP_CLIENTS, clients);
      }
    }

    synchronized (clients) {
      String key = hostname + ":"
        + connectPort
        + ":"
        + isSecure
        + ":"
        + webForward.getResourceId()
        + ":"
        + Thread.currentThread().getName()
        + ":"
        + launchSession.getSession().getId();
      client = (HttpClient) clients.get(key);

      if (client == null) {
        client = new HttpClient(hostname, connectPort, isSecure);
        client.setIncludeCookies(false);
       
        if (!webForward.getPreferredAuthenticationScheme().equals(HttpAuthenticatorFactory.NONE) && !webForward.getAuthenticationUsername()
                .equals("")
          && !webForward.getAuthenticationPassword().equals("")) {
          PasswordCredentials pwd = new PasswordCredentials();
          pwd.setUsername(SessionInfoReplacer.replace(launchSession.getSession(), webForward.getAuthenticationUsername()));
          pwd.setPassword(SessionInfoReplacer.replace(launchSession.getSession(), webForward.getAuthenticationPassword()));
          client.setCredentials(pwd);
        }

        // Set the preferred scheme
        client.setPreferredAuthentication(webForward.getPreferredAuthenticationScheme());

        // If we're using basic authentication then preempt the 401
        // response
        client.setPreemtiveAuthentication(webForward.getPreferredAuthenticationScheme().equalsIgnoreCase("BASIC"));

        clients.put(key, client);
      }
    }
View Full Code Here

    private final HttpClient client;
    private final HttpTestContainer container;
    private final HttpTestEntry entry;

    HttpTestRunner(HttpTestContainer container, HttpTestEntry entry) {
        client = new HttpClient(container.getRootUrl(), container.getPort(), false);
        this.container = container;
        this.entry = entry;
    }
View Full Code Here

      try {
       
        System.setProperty("com.maverick.ssl.allowUntrustedCertificates", "true");
        System.setProperty("com.maverick.ssl.allowInvalidCertificates", "true");
       
        HttpClient client = new HttpClient("127.0.0.1", 443, true);
        GetMethod get = new GetMethod("AGENT", "/");
        client.setCredentials(new PasswordCredentials("lee", "xxxxxxxxxx"));
        client.setPreemtiveAuthentication(true);
       
        HttpResponse response = client.execute(get);
       
        c = new MultiplexedConnection(new SocketChannelFactory());

            c.startProtocol(response.getConnection().getInputStream(), response.getConnection().getOutputStream(), false);
View Full Code Here

                }

                try {
                    int port = Integer.parseInt(proxyPort);

                    HttpClient client = new HttpClient(proxyHost, port, isSecure);
                    HttpMethod method = new ConnectMethod(url.getHost(), url.getPort() == -1 ? 443 : url.getPort(), true);

                    PasswordCredentials credentials = new PasswordCredentials();
                    credentials.setUsername(proxyUsername);
                    credentials.setPassword(proxyPassword);

                    client.setCredentials(credentials);

                    HttpResponse response = client.execute(method);
                    socket = response.getConnection().getSocket();
                } catch (HttpException ex) {
                    // #ifdef DEBUG
                    log.info(MessageFormat.format(Messages.getString("HttpsURLConnection.proxyConnectionFailed"), new Object[] { ex.getMessage(), new Integer(ex.getStatus()) })); //$NON-NLS-1$
                    // #endif
View Full Code Here

TOP

Related Classes of com.maverick.http.HttpClient

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.