private static void addBodyIfPostOrPut(HttpRequest httpRequest, ResponseDefinition response)
     throws UnsupportedEncodingException {
   Request originalRequest = response.getOriginalRequest();
   if (originalRequest.getMethod().isOneOf(PUT, POST)) {
     HttpEntityEnclosingRequest requestWithEntity = (HttpEntityEnclosingRequest) httpRequest;
     requestWithEntity.setEntity(buildEntityFrom(originalRequest));
   }
 }
Example #2
0
 static void enhanceEntity(final HttpEntityEnclosingRequest request) {
   final HttpEntity entity = request.getEntity();
   if (entity != null && !entity.isRepeatable() && !isEnhanced(entity)) {
     final HttpEntity proxy =
         (HttpEntity)
             Proxy.newProxyInstance(
                 HttpEntity.class.getClassLoader(),
                 new Class<?>[] {HttpEntity.class},
                 new RequestEntityExecHandler(entity));
     request.setEntity(proxy);
   }
 }
Example #3
0
  @Override
  public org.zalando.logbook.HttpRequest withBody() throws IOException {
    if (request instanceof HttpEntityEnclosingRequest) {
      final HttpEntityEnclosingRequest request = (HttpEntityEnclosingRequest) this.request;
      this.body = toByteArray(request.getEntity());
      request.setEntity(new ByteArrayEntity(body));
    } else {
      this.body = new byte[0];
    }

    return this;
  }
  @Override
  protected ClientHttpResponse executeInternal(HttpHeaders headers, byte[] bufferedOutput)
      throws IOException {
    addHeaders(this.httpRequest, headers);

    if (this.httpRequest instanceof HttpEntityEnclosingRequest) {
      HttpEntityEnclosingRequest entityEnclosingRequest =
          (HttpEntityEnclosingRequest) this.httpRequest;
      HttpEntity requestEntity = new ByteArrayEntity(bufferedOutput);
      entityEnclosingRequest.setEntity(requestEntity);
    }
    HttpResponse httpResponse = this.httpClient.execute(this.httpRequest, this.httpContext);
    return new HttpComponentsClientHttpResponse(httpResponse);
  }
Example #5
0
 public String renderRequestText(HttpRequest request) {
   StringBuilder sb = new StringBuilder();
   sb.append(renderRequestStartLine(request));
   sb.append(renderHeaders(request.getAllHeaders()));
   if (request instanceof HttpEntityEnclosingRequest) {
     final HttpEntityEnclosingRequest requestEntity = (HttpEntityEnclosingRequest) request;
     final String body = renderEntityIfAscii(requestEntity.getEntity());
     if (body != null) {
       sb.append("\n");
       sb.append(body);
     }
   }
   return sb.toString();
 }
  /** Generates a cURL command equivalent to the given request. */
  private static String toCurl(HttpUriRequest request) throws IOException {
    StringBuilder builder = new StringBuilder();

    builder.append("curl ");

    for (Header header : request.getAllHeaders()) {
      builder.append("--header \"");
      builder.append(header.toString().trim());
      builder.append("\" ");
    }

    URI uri = request.getURI();

    // If this is a wrapped request, use the URI from the original
    // request instead. getURI() on the wrapper seems to return a
    // relative URI. We want an absolute URI.
    if (request instanceof RequestWrapper) {
      HttpRequest original = ((RequestWrapper) request).getOriginal();
      if (original instanceof HttpUriRequest) {
        uri = ((HttpUriRequest) original).getURI();
      }
    }

    builder.append("\"");
    builder.append(uri);
    builder.append("\"");

    if (request instanceof HttpEntityEnclosingRequest) {
      HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request;
      HttpEntity entity = entityRequest.getEntity();
      if (entity != null && entity.isRepeatable()) {
        if (entity.getContentLength() < 1024) {
          ByteArrayOutputStream stream = new ByteArrayOutputStream();
          entity.writeTo(stream);
          String entityString = stream.toString();

          // TODO: Check the content type, too.
          builder.append(" --data-ascii \"").append(entityString).append("\"");
        } else {
          builder.append(" [TOO MUCH DATA TO INCLUDE]");
        }
      }
    }

    return builder.toString();
  }
  @Test
  public void shouldProxyTheRequestMethodUriBodyAndContentType()
      throws ServletException, IOException, URISyntaxException {
    CloseableHttpClient mockHttpClient =
        mock(CloseableHttpClient.class, Mockito.RETURNS_DEEP_STUBS);

    AbstractLightblueProxyServlet servlet =
        getTestServlet(mockHttpClient, null, "http://myservice.com", null);

    HttpServletRequest stubRequest =
        new StubHttpServletRequest(
            "http://my.site.com/app/get/the/thing?foo=bar",
            "GET",
            "{test:0}",
            "application/json",
            "/get/*");

    HttpServletResponse mockResponse = mock(HttpServletResponse.class);
    ServletOutputStream outputStream = new FakeServletOutputStream(new ByteArrayOutputStream());
    when(mockResponse.getOutputStream()).thenReturn(outputStream);

    servlet.service(stubRequest, mockResponse);

    ArgumentCaptor<HttpUriRequest> requestCaptor = ArgumentCaptor.forClass(HttpUriRequest.class);

    verify(mockHttpClient).execute(requestCaptor.capture());

    HttpUriRequest request = requestCaptor.getValue();

    assertEquals("GET", request.getMethod());
    assertEquals(new URI("http://myservice.com/the/thing?foo=bar"), request.getURI());
    assertThat(request, instanceOf(HttpEntityEnclosingRequest.class));
    assertEquals(1, request.getHeaders("content-type").length);
    assertEquals("application/json", request.getHeaders("content-type")[0].getValue());

    HttpEntityEnclosingRequest entityEnclosingRequest = (HttpEntityEnclosingRequest) request;
    ByteArrayOutputStream entityOutStream = new ByteArrayOutputStream();
    entityEnclosingRequest.getEntity().writeTo(entityOutStream);

    byte[] expectedEntityBytes = new byte[stubRequest.getContentLength()];
    stubRequest.getInputStream().read(expectedEntityBytes, 0, stubRequest.getContentLength());

    assertEquals(new String(expectedEntityBytes), entityOutStream.toString());
  }
Example #8
0
  private void execute() throws IOException, ClientProtocolException {
    if (resp != null) {
      return;
    }

    if (entity == null) {
      resp = getClient().execute(req);
      return;
    }

    try {
      if (req instanceof HttpEntityEnclosingRequest) {
        HttpEntityEnclosingRequest eReq = (HttpEntityEnclosingRequest) req;
        eReq.setEntity(entity);
      }
      resp = getClient().execute(req);
    } finally {
      entity.close();
      entity = null;
    }
  }
Example #9
0
  private void handleURLEncodedData(UrlEncodedFormEntity form) {
    AbstractHttpEntity entity = null;
    if (data != null) {
      try {
        entity = new StringEntity(data, "UTF-8");
      } catch (Exception ex) {
        // FIXME
        Log.e(LCAT, "Exception, implement recovery: ", ex);
      }
    } else {
      entity = form;
    }

    Header header = request.getFirstHeader("Content-Type");
    if (header == null) {
      entity.setContentType("application/x-www-form-urlencoded");
    } else {
      entity.setContentType(header.getValue());
    }

    HttpEntityEnclosingRequest e = (HttpEntityEnclosingRequest) request;
    e.setEntity(entity);
  }
 /** {@inheritDoc} */
 public HttpResponse fetch(HttpRequest request) {
   if (!whitelist.allows(request.getUri().toJavaUri())) {
     log.warn(
         "A request to "
             + request.getUri()
             + " has been denied.  To allow requests to this URL add the application URL to your whitelist (http://confluence.atlassian.com/x/KQfCDQ ).");
     return new HttpResponseBuilder()
         .setHttpStatusCode(HttpResponse.SC_FORBIDDEN)
         .setHeader("Content-Type", "text/plain")
         .setResponseString(
             "Requests to "
                 + request.getUri()
                 + " are not allowed.  See your administrator about configuring a whitelist entry for this destination (http://confluence.atlassian.com/x/KQfCDQ ).")
         .create();
   }
   HttpCacheKey cacheKey = new HttpCacheKey(request);
   HttpResponse response = cache.getResponse(cacheKey, request);
   if (response != null) {
     return response;
   }
   try {
     HttpUriRequest hcRequest = newHcRequest(request);
     if (request.getPostBodyLength() > 0) {
       ((HttpEntityEnclosingRequest) hcRequest)
           .setEntity(new InputStreamEntity(request.getPostBody(), request.getPostBodyLength()));
     }
     org.apache.http.HttpResponse hcResponse;
     try {
       // first try with TLS, the most common SSL protocol
       hcResponse = newHttpClient("TLSv1", request).execute(hcRequest);
     } catch (SSLException e) {
       log.debug(
           "SSL Exception establishing connection with TLSv1 protocol. Falling back to SSLv3.", e);
       // if TLS failed, try with SSLv3
       hcResponse = newHttpClient("SSLv3", request).execute(hcRequest);
     }
     response = makeResponse(hcResponse);
     return cache.addResponse(cacheKey, request, response);
   } catch (IOException e) {
     if (e instanceof java.net.SocketTimeoutException || e instanceof java.net.SocketException) {
       return HttpResponse.timeout();
     } else {
       log.error("Unable to retrieve response", e);
     }
     return HttpResponse.error();
   }
 }
  @Override
  public void filterAbstractHttpRequest(SubmitContext context, AbstractHttpRequest<?> httpRequest) {
    Settings settings = httpRequest.getSettings();
    String compressionAlg = settings.getString(HttpSettings.REQUEST_COMPRESSION, "None");
    if (!"None".equals(compressionAlg)) {
      try {
        ExtendedHttpMethod method =
            (ExtendedHttpMethod) context.getProperty(BaseHttpRequestTransport.HTTP_METHOD);
        if (method instanceof HttpEntityEnclosingRequest) {
          HttpEntity requestEntity = ((HttpEntityEnclosingRequest) method).getEntity();
          if (requestEntity != null) {
            ByteArrayOutputStream tempOut = new ByteArrayOutputStream();
            requestEntity.writeTo(tempOut);

            byte[] compressedData =
                CompressionSupport.compress(compressionAlg, tempOut.toByteArray());
            ((HttpEntityEnclosingRequest) method).setEntity(new ByteArrayEntity(compressedData));
          }
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
Example #12
0
    private void zza(HttpEntityEnclosingRequest httpentityenclosingrequest)
    {
        StringBuffer stringbuffer;
        stringbuffer = new StringBuffer();
        org.apache.http.Header aheader[] = httpentityenclosingrequest.getAllHeaders();
        int k = aheader.length;
        for (int i = 0; i < k; i++)
        {
            stringbuffer.append(aheader[i].toString()).append("\n");
        }

        stringbuffer.append(httpentityenclosingrequest.getRequestLine().toString()).append("\n");
        if (httpentityenclosingrequest.getEntity() == null)
        {
            break MISSING_BLOCK_LABEL_147;
        }
        httpentityenclosingrequest = httpentityenclosingrequest.getEntity().getContent();
        if (httpentityenclosingrequest == null)
        {
            break MISSING_BLOCK_LABEL_147;
        }
        int j = httpentityenclosingrequest.available();
        if (j > 0)
        {
            try
            {
                byte abyte0[] = new byte[j];
                httpentityenclosingrequest.read(abyte0);
                stringbuffer.append("POST:\n");
                stringbuffer.append(new String(abyte0)).append("\n");
            }
            // Misplaced declaration of an exception variable
            catch (HttpEntityEnclosingRequest httpentityenclosingrequest)
            {
                zzae.zzac("Error Writing hit to log...");
            }
        }
        zzae.zzaa(stringbuffer.toString());
        return;
    }
  public void handle(HttpRequest request, HttpResponse response, HttpContext argument)
      throws HttpException, IOException {
    if (BasicAuthHelper.isAuthenticated(request) == false) {
      BasicAuthHelper.unauthedResponse(response);

      return;
    }

    response.setStatusCode(HttpStatus.SC_OK);

    if (request instanceof HttpEntityEnclosingRequest) {
      HttpEntityEnclosingRequest enclosingRequest = (HttpEntityEnclosingRequest) request;

      HttpEntity entity = enclosingRequest.getEntity();

      String entityString = EntityUtils.toString(entity);

      Uri u = Uri.parse("http://localhost/?" + entityString);

      JSONObject arguments = null;

      try {
        arguments = new JSONObject(URLDecoder.decode(u.getQueryParameter("json"), "UTF-8"));
      } catch (JSONException e) {
        LogManager.getInstance(this._context).logException(e);

        response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);

        StringEntity body = new StringEntity(e.toString());
        body.setContentType("text/plain");

        response.setEntity(body);

        return;
      }

      if (arguments != null) {
        try {
          JavaScriptEngine engine = new JavaScriptEngine(this._context);

          String action = arguments.getString("action");

          if ("fetch".equals(action)) {
            if (arguments.has("keys")) {
              JSONObject result = new JSONObject();
              result.put("status", "success");

              JSONArray keys = arguments.getJSONArray("keys");

              JSONObject values = new JSONObject();

              for (int i = 0; i < keys.length(); i++) {
                String key = keys.getString(i);

                String value = engine.fetchString(key);

                values.put(key, value);
              }

              result.put("values", values);

              StringEntity body = new StringEntity(result.toString(2));
              body.setContentType("application/json");

              response.setEntity(body);

              return;
            }
          } else if ("put".equals(action)) {
            JSONArray names = arguments.names();

            for (int i = 0; i < names.length(); i++) {
              String name = names.getString(i);

              if ("action".equals(name) == false) {
                String value = arguments.getString(name);

                if (value != null) engine.persistString(name, value);
              }
            }

            JSONObject result = new JSONObject();
            result.put("status", "success");

            StringEntity body = new StringEntity(result.toString(2));
            body.setContentType("application/json");

            response.setEntity(body);

            return;
          }
        } catch (JSONException e) {
          LogManager.getInstance(this._context).logException(e);

          response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);

          StringEntity body = new StringEntity(e.toString());
          body.setContentType("text/plain");

          response.setEntity(body);

          return;
        }
      }
    }

    response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);

    StringEntity body = new StringEntity(this._context.getString(R.string.error_malformed_request));
    body.setContentType("text/plain");

    response.setEntity(body);
  }
Example #14
0
  @SuppressWarnings("deprecation")
  @Override
  public void filterHttpRequest(SubmitContext context, HttpRequestInterface<?> request) {
    HttpRequestBase httpMethod =
        (HttpRequestBase) context.getProperty(BaseHttpRequestTransport.HTTP_METHOD);

    String path = PropertyExpander.expandProperties(context, request.getPath());
    StringBuffer query = new StringBuffer();
    String encoding =
        System.getProperty("soapui.request.encoding", StringUtils.unquote(request.getEncoding()));

    StringToStringMap responseProperties =
        (StringToStringMap) context.getProperty(BaseHttpRequestTransport.RESPONSE_PROPERTIES);

    MimeMultipart formMp =
        "multipart/form-data".equals(request.getMediaType())
                && httpMethod instanceof HttpEntityEnclosingRequestBase
            ? new MimeMultipart()
            : null;

    RestParamsPropertyHolder params = request.getParams();

    for (int c = 0; c < params.getPropertyCount(); c++) {
      RestParamProperty param = params.getPropertyAt(c);

      String value = PropertyExpander.expandProperties(context, param.getValue());
      responseProperties.put(param.getName(), value);

      List<String> valueParts =
          sendEmptyParameters(request) || (!StringUtils.hasContent(value) && param.getRequired())
              ? RestUtils.splitMultipleParametersEmptyIncluded(
                  value, request.getMultiValueDelimiter())
              : RestUtils.splitMultipleParameters(value, request.getMultiValueDelimiter());

      // skip HEADER and TEMPLATE parameter encoding (TEMPLATE is encoded by
      // the URI handling further down)
      if (value != null
          && param.getStyle() != ParameterStyle.HEADER
          && param.getStyle() != ParameterStyle.TEMPLATE
          && !param.isDisableUrlEncoding()) {
        try {
          if (StringUtils.hasContent(encoding)) {
            value = URLEncoder.encode(value, encoding);
            for (int i = 0; i < valueParts.size(); i++)
              valueParts.set(i, URLEncoder.encode(valueParts.get(i), encoding));
          } else {
            value = URLEncoder.encode(value);
            for (int i = 0; i < valueParts.size(); i++)
              valueParts.set(i, URLEncoder.encode(valueParts.get(i)));
          }
        } catch (UnsupportedEncodingException e1) {
          SoapUI.logError(e1);
          value = URLEncoder.encode(value);
          for (int i = 0; i < valueParts.size(); i++)
            valueParts.set(i, URLEncoder.encode(valueParts.get(i)));
        }
        // URLEncoder replaces space with "+", but we want "%20".
        value = value.replaceAll("\\+", "%20");
        for (int i = 0; i < valueParts.size(); i++)
          valueParts.set(i, valueParts.get(i).replaceAll("\\+", "%20"));
      }

      if (param.getStyle() == ParameterStyle.QUERY && !sendEmptyParameters(request)) {
        if (!StringUtils.hasContent(value) && !param.getRequired()) continue;
      }

      switch (param.getStyle()) {
        case HEADER:
          for (String valuePart : valueParts) httpMethod.addHeader(param.getName(), valuePart);
          break;
        case QUERY:
          if (formMp == null || !request.isPostQueryString()) {
            for (String valuePart : valueParts) {
              if (query.length() > 0) query.append('&');

              query.append(URLEncoder.encode(param.getName()));
              query.append('=');
              if (StringUtils.hasContent(valuePart)) query.append(valuePart);
            }
          } else {
            try {
              addFormMultipart(
                  request, formMp, param.getName(), responseProperties.get(param.getName()));
            } catch (MessagingException e) {
              SoapUI.logError(e);
            }
          }

          break;
        case TEMPLATE:
          try {
            value =
                getEncodedValue(
                    value,
                    encoding,
                    param.isDisableUrlEncoding(),
                    request.getSettings().getBoolean(HttpSettings.ENCODED_URLS));
            path = path.replaceAll("\\{" + param.getName() + "\\}", value == null ? "" : value);
          } catch (UnsupportedEncodingException e) {
            SoapUI.logError(e);
          }
          break;
        case MATRIX:
          try {
            value =
                getEncodedValue(
                    value,
                    encoding,
                    param.isDisableUrlEncoding(),
                    request.getSettings().getBoolean(HttpSettings.ENCODED_URLS));
          } catch (UnsupportedEncodingException e) {
            SoapUI.logError(e);
          }

          if (param.getType().equals(XmlBoolean.type.getName())) {
            if (value.toUpperCase().equals("TRUE") || value.equals("1")) {
              path += ";" + param.getName();
            }
          } else {
            path += ";" + param.getName();
            if (StringUtils.hasContent(value)) {
              path += "=" + value;
            }
          }
          break;
        case PLAIN:
          break;
      }
    }

    if (request.getSettings().getBoolean(HttpSettings.FORWARD_SLASHES))
      path = PathUtils.fixForwardSlashesInPath(path);

    if (PathUtils.isHttpPath(path)) {
      try {
        // URI(String) automatically URLencodes the input, so we need to
        // decode it first...
        URI uri = new URI(path, request.getSettings().getBoolean(HttpSettings.ENCODED_URLS));
        context.setProperty(BaseHttpRequestTransport.REQUEST_URI, uri);
        java.net.URI oldUri = httpMethod.getURI();
        httpMethod.setURI(
            HttpUtils.createUri(
                oldUri.getScheme(),
                oldUri.getRawUserInfo(),
                oldUri.getHost(),
                oldUri.getPort(),
                oldUri.getRawPath(),
                uri.getEscapedQuery(),
                oldUri.getRawFragment()));
      } catch (Exception e) {
        SoapUI.logError(e);
      }
    } else if (StringUtils.hasContent(path)) {
      try {
        java.net.URI oldUri = httpMethod.getURI();
        String pathToSet =
            StringUtils.hasContent(oldUri.getRawPath()) && !"/".equals(oldUri.getRawPath())
                ? oldUri.getRawPath() + path
                : path;
        java.net.URI newUri =
            URIUtils.createURI(
                oldUri.getScheme(),
                oldUri.getHost(),
                oldUri.getPort(),
                pathToSet,
                oldUri.getQuery(),
                oldUri.getFragment());
        httpMethod.setURI(newUri);
        context.setProperty(
            BaseHttpRequestTransport.REQUEST_URI,
            new URI(
                newUri.toString(), request.getSettings().getBoolean(HttpSettings.ENCODED_URLS)));
      } catch (Exception e) {
        SoapUI.logError(e);
      }
    }

    if (query.length() > 0 && !request.isPostQueryString()) {
      try {
        java.net.URI oldUri = httpMethod.getURI();
        httpMethod.setURI(
            URIUtils.createURI(
                oldUri.getScheme(),
                oldUri.getHost(),
                oldUri.getPort(),
                oldUri.getRawPath(),
                query.toString(),
                oldUri.getFragment()));
      } catch (Exception e) {
        SoapUI.logError(e);
      }
    }

    if (request instanceof RestRequest) {
      String acceptEncoding = ((RestRequest) request).getAccept();
      if (StringUtils.hasContent(acceptEncoding)) {
        httpMethod.setHeader("Accept", acceptEncoding);
      }
    }

    if (formMp != null) {
      // create request message
      try {
        if (request.hasRequestBody() && httpMethod instanceof HttpEntityEnclosingRequest) {
          String requestContent =
              PropertyExpander.expandProperties(
                  context, request.getRequestContent(), request.isEntitizeProperties());
          if (StringUtils.hasContent(requestContent)) {
            initRootPart(request, requestContent, formMp);
          }
        }

        for (Attachment attachment : request.getAttachments()) {
          MimeBodyPart part = new PreencodedMimeBodyPart("binary");

          if (attachment instanceof FileAttachment<?>) {
            String name = attachment.getName();
            if (StringUtils.hasContent(attachment.getContentID())
                && !name.equals(attachment.getContentID())) name = attachment.getContentID();

            part.setDisposition(
                "form-data; name=\"" + name + "\"; filename=\"" + attachment.getName() + "\"");
          } else part.setDisposition("form-data; name=\"" + attachment.getName() + "\"");

          part.setDataHandler(new DataHandler(new AttachmentDataSource(attachment)));

          formMp.addBodyPart(part);
        }

        MimeMessage message = new MimeMessage(AttachmentUtils.JAVAMAIL_SESSION);
        message.setContent(formMp);
        message.saveChanges();
        RestRequestMimeMessageRequestEntity mimeMessageRequestEntity =
            new RestRequestMimeMessageRequestEntity(message, request);
        ((HttpEntityEnclosingRequest) httpMethod).setEntity(mimeMessageRequestEntity);
        httpMethod.setHeader("Content-Type", mimeMessageRequestEntity.getContentType().getValue());
        httpMethod.setHeader("MIME-Version", "1.0");
      } catch (Throwable e) {
        SoapUI.logError(e);
      }
    } else if (request.hasRequestBody() && httpMethod instanceof HttpEntityEnclosingRequest) {
      if (StringUtils.hasContent(request.getMediaType()))
        httpMethod.setHeader(
            "Content-Type", getContentTypeHeader(request.getMediaType(), encoding));

      if (request.isPostQueryString()) {
        try {
          ((HttpEntityEnclosingRequest) httpMethod).setEntity(new StringEntity(query.toString()));
        } catch (UnsupportedEncodingException e) {
          SoapUI.logError(e);
        }
      } else {
        String requestContent =
            PropertyExpander.expandProperties(
                context, request.getRequestContent(), request.isEntitizeProperties());
        List<Attachment> attachments = new ArrayList<Attachment>();

        for (Attachment attachment : request.getAttachments()) {
          if (attachment.getContentType().equals(request.getMediaType())) {
            attachments.add(attachment);
          }
        }

        if (StringUtils.hasContent(requestContent) && attachments.isEmpty()) {
          try {
            byte[] content =
                encoding == null ? requestContent.getBytes() : requestContent.getBytes(encoding);
            ((HttpEntityEnclosingRequest) httpMethod).setEntity(new ByteArrayEntity(content));
          } catch (UnsupportedEncodingException e) {
            ((HttpEntityEnclosingRequest) httpMethod)
                .setEntity(new ByteArrayEntity(requestContent.getBytes()));
          }
        } else if (attachments.size() > 0) {
          try {
            MimeMultipart mp = null;

            if (StringUtils.hasContent(requestContent)) {
              mp = new MimeMultipart();
              initRootPart(request, requestContent, mp);
            } else if (attachments.size() == 1) {
              ((HttpEntityEnclosingRequest) httpMethod)
                  .setEntity(new InputStreamEntity(attachments.get(0).getInputStream(), -1));

              httpMethod.setHeader(
                  "Content-Type", getContentTypeHeader(request.getMediaType(), encoding));
            }

            if (((HttpEntityEnclosingRequest) httpMethod).getEntity() == null) {
              if (mp == null) mp = new MimeMultipart();

              // init mimeparts
              AttachmentUtils.addMimeParts(request, attachments, mp, new StringToStringMap());

              // create request message
              MimeMessage message = new MimeMessage(AttachmentUtils.JAVAMAIL_SESSION);
              message.setContent(mp);
              message.saveChanges();
              RestRequestMimeMessageRequestEntity mimeMessageRequestEntity =
                  new RestRequestMimeMessageRequestEntity(message, request);
              ((HttpEntityEnclosingRequest) httpMethod).setEntity(mimeMessageRequestEntity);
              httpMethod.setHeader(
                  "Content-Type",
                  getContentTypeHeader(
                      mimeMessageRequestEntity.getContentType().getValue(), encoding));
              httpMethod.setHeader("MIME-Version", "1.0");
            }
          } catch (Exception e) {
            SoapUI.logError(e);
          }
        }
      }
    }
  }
Example #15
0
    public void run() {
      try {
        Thread.sleep(10);
        if (DBG) {
          Log.d(LCAT, "send()");
        }
        /*
        Header[] h = request.getAllHeaders();
        for(int i=0; i < h.length; i++) {
        	Header hdr = h[i];
        	//Log.e(LCAT, "HEADER: " + hdr.toString());
        }
         */
        handler = new LocalResponseHandler(TiHTTPClient.this);
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        SocketFactory sslFactory;
        if (validatesSecureCertificate()) {
          sslFactory = SSLSocketFactory.getSocketFactory();
        } else {
          sslFactory = new NonValidatingSSLSocketFactory();
        }
        registry.register(new Scheme("https", sslFactory, 443));
        HttpParams params = new BasicHttpParams();

        if (timeout != -1) {
          HttpConnectionParams.setConnectionTimeout(params, timeout);
        }

        ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(params, registry);
        client = new DefaultHttpClient(manager, params);

        if (credentials != null) {
          client.getCredentialsProvider().setCredentials(new AuthScope(null, -1), credentials);
          credentials = null;
        }
        HttpProtocolParams.setUseExpectContinue(client.getParams(), false);
        HttpProtocolParams.setVersion(client.getParams(), HttpVersion.HTTP_1_1);

        if (request instanceof BasicHttpEntityEnclosingRequest) {

          UrlEncodedFormEntity form = null;
          MultipartEntity mpe = null;

          if (nvPairs.size() > 0) {
            try {
              form = new UrlEncodedFormEntity(nvPairs, "UTF-8");
            } catch (UnsupportedEncodingException e) {
              Log.e(LCAT, "Unsupported encoding: ", e);
            }
          }

          if (parts.size() > 0 && needMultipart) {
            mpe = new MultipartEntity();
            for (String name : parts.keySet()) {
              Log.d(
                  LCAT,
                  "adding part "
                      + name
                      + ", part type: "
                      + parts.get(name).getMimeType()
                      + ", len: "
                      + parts.get(name).getContentLength());
              mpe.addPart(name, parts.get(name));
            }
            if (form != null) {
              try {
                ByteArrayOutputStream bos =
                    new ByteArrayOutputStream((int) form.getContentLength());
                form.writeTo(bos);
                mpe.addPart(
                    "form",
                    new StringBody(
                        bos.toString(),
                        "application/x-www-form-urlencoded",
                        Charset.forName("UTF-8")));
              } catch (UnsupportedEncodingException e) {
                Log.e(LCAT, "Unsupported encoding: ", e);
              } catch (IOException e) {
                Log.e(LCAT, "Error converting form to string: ", e);
              }
            }

            HttpEntityEnclosingRequest e = (HttpEntityEnclosingRequest) request;
            Log.d(LCAT, "totalLength=" + totalLength);

            /*ProgressEntity progressEntity = new ProgressEntity(mpe, new ProgressListener() {
            	public void progress(int progress) {
            		KrollCallback cb = getCallback(ON_SEND_STREAM);
            		if (cb != null) {
            			TiDict data = new TiDict();
            			data.put("progress", ((double)progress)/fTotalLength);
            			data.put("source", proxy);
            			cb.callWithProperties(data);
            		}
            	}
            });*/
            // e.setEntity(progressEntity);

            e.setEntity(mpe);
            e.addHeader("Length", totalLength + "");
          } else {
            handleURLEncodedData(form);
          }
        }
        if (DBG) {
          Log.d(LCAT, "Preparing to execute request");
        }
        String result = client.execute(host, request, handler);
        if (result != null) {
          Log.d(LCAT, "Have result back from request len=" + result.length());
        }
        connected = false;
        setResponseText(result);
        setReadyState(READY_STATE_DONE);
      } catch (Exception e) {
        Log.e(LCAT, "HTTP Error: " + e.getMessage(), e);
        sendError(e.getMessage());
      }
    }
Example #16
0
  public void service(ServletRequest request, ServletResponse response)
      throws ServletException, IOException {
    listenerCallBack.fireOnRequest(project, request, response);
    if (response.isCommitted()) {
      return;
    }

    ExtendedHttpMethod method;
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    if (httpRequest.getMethod().equals("GET")) {
      method = new ExtendedGetMethod();
    } else if (httpRequest.getMethod().equals("POST")) {
      method = new ExtendedPostMethod();
    } else if (httpRequest.getMethod().equals("PUT")) {
      method = new ExtendedPutMethod();
    } else if (httpRequest.getMethod().equals("HEAD")) {
      method = new ExtendedHeadMethod();
    } else if (httpRequest.getMethod().equals("OPTIONS")) {
      method = new ExtendedOptionsMethod();
    } else if (httpRequest.getMethod().equals("TRACE")) {
      method = new ExtendedTraceMethod();
    } else if (httpRequest.getMethod().equals("PATCH")) {
      method = new ExtendedPatchMethod();
    } else {
      method = new ExtendedGenericMethod(httpRequest.getMethod());
    }

    method.setDecompress(false);

    ByteArrayOutputStream requestBody = null;
    if (method instanceof HttpEntityEnclosingRequest) {
      requestBody = Tools.readAll(request.getInputStream(), 0);
      ByteArrayEntity entity = new ByteArrayEntity(requestBody.toByteArray());
      entity.setContentType(request.getContentType());
      ((HttpEntityEnclosingRequest) method).setEntity(entity);
    }

    // for this create ui server and port, properties.
    JProxyServletWsdlMonitorMessageExchange capturedData =
        new JProxyServletWsdlMonitorMessageExchange(project);
    capturedData.setRequestHost(httpRequest.getServerName());
    capturedData.setRequestMethod(httpRequest.getMethod());
    capturedData.setRequestHeader(httpRequest);
    capturedData.setHttpRequestParameters(httpRequest);
    capturedData.setQueryParameters(httpRequest.getQueryString());
    capturedData.setTargetURL(httpRequest.getRequestURL().toString());

    //		CaptureInputStream capture = new CaptureInputStream( httpRequest.getInputStream() );

    // check connection header
    String connectionHeader = httpRequest.getHeader("Connection");
    if (connectionHeader != null) {
      connectionHeader = connectionHeader.toLowerCase();
      if (!connectionHeader.contains("keep-alive") && !connectionHeader.contains("close")) {
        connectionHeader = null;
      }
    }

    // copy headers
    boolean xForwardedFor = false;
    @SuppressWarnings("unused")
    Enumeration<?> headerNames = httpRequest.getHeaderNames();
    while (headerNames.hasMoreElements()) {
      String hdr = (String) headerNames.nextElement();
      String lhdr = hdr.toLowerCase();

      if (dontProxyHeaders.contains(lhdr)) {
        continue;
      }
      if (connectionHeader != null && connectionHeader.contains(lhdr)) {
        continue;
      }

      Enumeration<?> vals = httpRequest.getHeaders(hdr);
      while (vals.hasMoreElements()) {
        String val = (String) vals.nextElement();
        if (val != null) {
          method.setHeader(lhdr, val);
          xForwardedFor |= "X-Forwarded-For".equalsIgnoreCase(hdr);
        }
      }
    }

    // Proxy headers
    method.setHeader("Via", "SoapUI Monitor");
    if (!xForwardedFor) {
      method.addHeader("X-Forwarded-For", request.getRemoteAddr());
    }

    StringBuffer url = new StringBuffer("http://");
    url.append(httpRequest.getServerName());
    if (httpRequest.getServerPort() != 80) {
      url.append(":" + httpRequest.getServerPort());
    }

    if (httpRequest.getServletPath() != null) {
      url.append(httpRequest.getServletPath());
      try {
        method.setURI(new java.net.URI(url.toString().replaceAll(" ", "%20")));
      } catch (URISyntaxException e) {
        SoapUI.logError(e);
      }

      if (httpRequest.getQueryString() != null) {
        url.append("?" + httpRequest.getQueryString());
        try {
          method.setURI(new java.net.URI(url.toString()));
        } catch (URISyntaxException e) {
          SoapUI.logError(e);
        }
      }
    }

    method.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, false);
    setProtocolversion(method, request.getProtocol());
    ProxyUtils.setForceDirectConnection(method.getParams());
    listenerCallBack.fireBeforeProxy(project, request, response, method);

    if (settings.getBoolean(LaunchForm.SSLTUNNEL_REUSESTATE)) {
      if (httpState == null) {
        httpState = new BasicHttpContext();
      }
      HttpClientSupport.execute(method, httpState);
    } else {
      HttpClientSupport.execute(method);
    }

    // wait for transaction to end and store it.
    capturedData.stopCapture();

    capturedData.setRequest(requestBody == null ? null : requestBody.toByteArray());
    capturedData.setRawResponseBody(method.getResponseBody());
    capturedData.setResponseHeader(method.getHttpResponse());
    capturedData.setRawRequestData(getRequestToBytes(request.toString(), requestBody));
    capturedData.setRawResponseData(getResponseToBytes(method, capturedData.getRawResponseBody()));
    byte[] decompressedResponseBody = method.getDecompressedResponseBody();
    capturedData.setResponseContent(
        decompressedResponseBody != null ? new String(decompressedResponseBody) : "");
    capturedData.setResponseStatusCode(
        method.hasHttpResponse() ? method.getHttpResponse().getStatusLine().getStatusCode() : null);
    capturedData.setResponseStatusLine(
        method.hasHttpResponse() ? method.getHttpResponse().getStatusLine().toString() : null);

    listenerCallBack.fireAfterProxy(project, request, response, method, capturedData);

    ((HttpServletResponse) response)
        .setStatus(
            method.hasHttpResponse()
                ? method.getHttpResponse().getStatusLine().getStatusCode()
                : null);

    if (!response.isCommitted()) {
      StringToStringsMap responseHeaders = capturedData.getResponseHeaders();
      // capturedData = null;

      // copy headers to response
      HttpServletResponse httpServletResponse = (HttpServletResponse) response;
      for (Map.Entry<String, List<String>> headerEntry : responseHeaders.entrySet()) {
        for (String header : headerEntry.getValue()) {
          httpServletResponse.addHeader(headerEntry.getKey(), header);
        }
      }

      if (capturedData.getRawResponseBody() != null) {
        IO.copy(
            new ByteArrayInputStream(capturedData.getRawResponseBody()),
            httpServletResponse.getOutputStream());
      }
    }

    synchronized (this) {
      if (contentTypeMatches(method)) {
        listenerCallBack.fireAddMessageExchange(capturedData);
      }
    }
  }