示例#1
0
 /**
  * @param out
  * @param start First byte to write
  * @param count Bytes to write or -1 for all of them.
  */
 public void writeTo(OutputStream out, long start, long count) throws IOException {
   InputStream in = getInputStream();
   try {
     in.skip(start);
     if (count < 0) IO.copy(in, out);
     else IO.copy(in, out, (int) count);
   } finally {
     in.close();
   }
 }
  public void testCanInstantiateWebContainerContextAndServletInstance()
      throws InterruptedException, IOException {

    server = new PicoJettyServer("localhost", 8080, new EmptyPicoContainer());
    PicoContextHandler barContext = server.createContext("/bar", false);

    DependencyInjectionTestServlet servlet0 = new DependencyInjectionTestServlet("Fred");
    DependencyInjectionTestServlet servlet1 =
        (DependencyInjectionTestServlet) barContext.addServletWithMapping(servlet0, "/foo");
    servlet1.setFoo("bar");

    server.start();

    Thread.sleep(2 * 1000);

    URL url = new URL("http://localhost:8080/bar/foo");
    assertEquals("hello Fred bar", IO.toString(url.openStream()));
  }
  public void testCanInstantiateWebContainerContextAndServlet()
      throws InterruptedException, IOException {

    final DefaultPicoContainer parentContainer = new DefaultPicoContainer();
    parentContainer.registerComponentInstance(String.class, "Fred");

    server = new PicoJettyServer("localhost", 8080, parentContainer);
    PicoContextHandler barContext = server.createContext("/bar", false);
    Class servletClass = DependencyInjectionTestServlet.class;
    PicoServletHolder holder = barContext.addServletWithMapping(servletClass, "/foo");
    holder.setInitParameter("foo", "bar");

    server.start();

    Thread.sleep(2 * 1000);

    URL url = new URL("http://localhost:8080/bar/foo");
    assertEquals("hello Fred bar", IO.toString(url.openStream()));
  }
示例#4
0
  /* ------------------------------------------------------------ */
  public static void extract(Resource resource, File directory, boolean deleteOnExit)
      throws IOException {
    if (Log.isDebugEnabled()) Log.debug("Extract " + resource + " to " + directory);

    String urlString = resource.getURL().toExternalForm().trim();
    int endOfJarUrl = urlString.indexOf("!/");
    int startOfJarUrl = (endOfJarUrl >= 0 ? 4 : 0);

    if (endOfJarUrl < 0) throw new IOException("Not a valid jar url: " + urlString);

    URL jarFileURL = new URL(urlString.substring(startOfJarUrl, endOfJarUrl));
    String subEntryName =
        (endOfJarUrl + 2 < urlString.length() ? urlString.substring(endOfJarUrl + 2) : null);
    boolean subEntryIsDir = (subEntryName != null && subEntryName.endsWith("/") ? true : false);

    if (Log.isDebugEnabled())
      Log.debug("Extracting entry = " + subEntryName + " from jar " + jarFileURL);

    InputStream is = jarFileURL.openConnection().getInputStream();
    JarInputStream jin = new JarInputStream(is);
    JarEntry entry = null;
    boolean shouldExtract = true;
    while ((entry = jin.getNextJarEntry()) != null) {
      String entryName = entry.getName();

      if ((subEntryName != null) && (entryName.startsWith(subEntryName))) {
        // if there is a particular subEntry that we are looking for, only
        // extract it.
        if (subEntryIsDir) {
          // if it is a subdirectory we are looking for, then we
          // are looking to extract its contents into the target
          // directory. Remove the name of the subdirectory so
          // that we don't wind up creating it too.
          entryName = entryName.substring(subEntryName.length());
          if (!entryName.equals("")) {
            // the entry is
            shouldExtract = true;
          } else shouldExtract = false;
        } else shouldExtract = true;
      } else if ((subEntryName != null) && (!entryName.startsWith(subEntryName))) {
        // there is a particular entry we are looking for, and this one
        // isn't it
        shouldExtract = false;
      } else {
        // we are extracting everything
        shouldExtract = true;
      }

      if (!shouldExtract) {
        if (Log.isDebugEnabled()) Log.debug("Skipping entry: " + entryName);
        continue;
      }

      File file = new File(directory, entryName);
      if (entry.isDirectory()) {
        // Make directory
        if (!file.exists()) file.mkdirs();
      } else {
        // make directory (some jars don't list dirs)
        File dir = new File(file.getParent());
        if (!dir.exists()) dir.mkdirs();

        // Make file
        FileOutputStream fout = null;
        try {
          fout = new FileOutputStream(file);
          IO.copy(jin, fout);
        } finally {
          IO.close(fout);
        }

        // touch the file.
        if (entry.getTime() >= 0) file.setLastModified(entry.getTime());
      }
      if (deleteOnExit) file.deleteOnExit();
    }
  }
示例#5
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);
      }
    }
  }