Esempio n. 1
0
    public Object construct() {
      HttpClientSupport.SoapUIHttpClient httpClient = HttpClientSupport.getHttpClient();
      try {
        Settings soapuiSettings = SoapUI.getSettings();

        HttpClientSupport.applyHttpSettings(getMethod, soapuiSettings);

        httpResponse = httpClient.execute(getMethod, state);
      } catch (Exception e) {
        return e;
      } finally {
        finished = true;
      }

      return null;
    }
  public void filterRequest(SubmitContext context, WsdlRequest wsdlRequest) {
    TimeablePostMethod postMethod =
        (TimeablePostMethod) context.getProperty(BaseHttpRequestTransport.POST_METHOD);

    //	 set maxsize
    Settings settings = wsdlRequest.getSettings();

    // close connections?
    if (settings.getBoolean(HttpSettings.CLOSE_CONNECTIONS))
      postMethod.setRequestHeader("Connection", "close");

    // max size..
    postMethod.setMaxSize(settings.getLong(HttpSettings.MAX_RESPONSE_SIZE, 0));

    // apply global settings
    HttpClientSupport.applyHttpSettings(postMethod, settings);
  }
Esempio n. 3
0
  public synchronized InputStream load(String url) throws Exception {
    if (!PathUtils.isHttpPath(url)) {
      try {
        File file = new File(url.replace('/', File.separatorChar));
        if (file.exists()) url = file.toURI().toURL().toString();
      } catch (Exception e) {
      }
    }

    if (urlCache.containsKey(url)) {
      setNewBaseURI(url);
      return new ByteArrayInputStream(urlCache.get(url));
    }

    if (url.startsWith("file:")) {
      return handleFile(url);
    }

    log.debug("Getting wsdl component from [" + url + "]");

    createGetMethod(url);

    if (aborted) return null;

    LoaderWorker worker = new LoaderWorker();
    if (useWorker) worker.start();
    else worker.construct();

    while (!aborted && !finished) {
      Thread.sleep(200);
    }

    // wait for method to catch up - required in unit tests..
    // limited looping to 10 loops because of eclipse plugin which entered
    // endless loop without it
    int counter = 0;
    byte[] content = null;

    if (httpResponse != null && httpResponse.getEntity() != null) {
      content = EntityUtils.toByteArray(new BufferedHttpEntity(httpResponse.getEntity()));
    }

    while (!aborted && content == null && counter < 10) {
      Thread.sleep(200);
      counter++;
    }

    if (aborted) {
      throw new Exception("Load of url [" + url + "] was aborted");
    } else {
      if (content != null) {
        String compressionAlg = HttpClientSupport.getResponseCompressionType(httpResponse);
        if (compressionAlg != null)
          content = CompressionSupport.decompress(compressionAlg, content);

        urlCache.put(url, content);
        String newUrl = getMethod.getURI().toString();
        if (!url.equals(newUrl)) log.info("BaseURI was redirected to [" + newUrl + "]");
        setNewBaseURI(newUrl);
        urlCache.put(newUrl, content);
        return new ByteArrayInputStream(content);
      } else {
        throw new Exception(
            "Failed to load url; "
                + url
                + ", "
                + (httpResponse != null ? httpResponse.getStatusLine().getStatusCode() : 0)
                + " - "
                + (httpResponse != null ? httpResponse.getStatusLine().getReasonPhrase() : ""));
      }
    }
  }
Esempio n. 4
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);
      }
    }
  }
Esempio n. 5
0
  protected Settings initSettings(String fileName) {
    // TODO Why try to load settings from current directory before using root?
    // This caused a bug in Eclipse:
    // https://sourceforge.net/tracker/?func=detail&atid=737763&aid=2620284&group_id=136013
    File settingsFile = new File(fileName).exists() ? new File(fileName) : null;

    try {
      if (settingsFile == null) {
        settingsFile = new File(new File(getRoot()), DEFAULT_SETTINGS_FILE);
        if (!settingsFile.exists()) {
          settingsFile =
              new File(new File(System.getProperty("user.home", ".")), DEFAULT_SETTINGS_FILE);
          lastSettingsLoad = 0;
        }
      } else {
        settingsFile = new File(fileName);
        if (!settingsFile.getAbsolutePath().equals(this.settingsFile)) {
          lastSettingsLoad = 0;
        }
      }

      if (!settingsFile.exists()) {
        if (settingsDocument == null) {
          log.info("Creating new settings at [" + settingsFile.getAbsolutePath() + "]");
          settingsDocument = SoapuiSettingsDocumentConfig.Factory.newInstance();
          setInitialImport(true);
        }

        lastSettingsLoad = System.currentTimeMillis();
      } else if (settingsFile.lastModified() > lastSettingsLoad) {
        settingsDocument = SoapuiSettingsDocumentConfig.Factory.parse(settingsFile);

        byte[] encryptedContent = settingsDocument.getSoapuiSettings().getEncryptedContent();
        if (encryptedContent != null) {
          char[] password = null;
          if (this.password == null) {
            // swing element -!! uh!
            JPasswordField passwordField = new JPasswordField();
            JLabel qLabel = new JLabel("Password");
            JOptionPane.showConfirmDialog(
                null,
                new Object[] {qLabel, passwordField},
                "Global Settings",
                JOptionPane.OK_CANCEL_OPTION);
            password = passwordField.getPassword();
          } else {
            password = this.password.toCharArray();
          }

          String encryptionAlgorithm =
              settingsDocument.getSoapuiSettings().getEncryptedContentAlgorithm();
          byte[] data =
              OpenSSL.decrypt(
                  StringUtils.isNullOrEmpty(encryptionAlgorithm) ? "des3" : encryptionAlgorithm,
                  password,
                  encryptedContent);
          try {
            settingsDocument =
                SoapuiSettingsDocumentConfig.Factory.parse(new String(data, "UTF-8"));
          } catch (Exception e) {
            log.warn("Wrong password.");
            JOptionPane.showMessageDialog(
                null,
                "Wrong password, creating backup settings file [ "
                    + settingsFile.getAbsolutePath()
                    + ".bak.xml. ]\nSwitch to default settings.",
                "Error - Wrong Password",
                JOptionPane.ERROR_MESSAGE);
            settingsDocument.save(new File(settingsFile.getAbsolutePath() + ".bak.xml"));
            throw e;
          }
        }

        log.info("initialized soapui-settings from [" + settingsFile.getAbsolutePath() + "]");
        lastSettingsLoad = settingsFile.lastModified();

        if (settingsWatcher == null) {
          settingsWatcher = new SettingsWatcher();
          SoapUI.getSoapUITimer().scheduleAtFixedRate(settingsWatcher, 10000, 10000);
        }
      }
    } catch (Exception e) {
      log.warn("Failed to load settings from [" + e.getMessage() + "], creating new");
      settingsDocument = SoapuiSettingsDocumentConfig.Factory.newInstance();
      lastSettingsLoad = 0;
    }

    if (settingsDocument.getSoapuiSettings() == null) {
      settingsDocument.addNewSoapuiSettings();
      settings = new XmlBeansSettingsImpl(null, null, settingsDocument.getSoapuiSettings());

      initDefaultSettings(settings);
    } else {
      settings = new XmlBeansSettingsImpl(null, null, settingsDocument.getSoapuiSettings());
    }

    this.settingsFile = settingsFile.getAbsolutePath();

    if (!settings.isSet(WsdlSettings.EXCLUDED_TYPES)) {
      StringList list = new StringList();
      list.add("schema@http://www.w3.org/2001/XMLSchema");
      settings.setString(WsdlSettings.EXCLUDED_TYPES, list.toXml());
    }

    if (settings
        .getString(HttpSettings.HTTP_VERSION, HttpSettings.HTTP_VERSION_1_1)
        .equals(HttpSettings.HTTP_VERSION_0_9)) {
      settings.setString(HttpSettings.HTTP_VERSION, HttpSettings.HTTP_VERSION_1_1);
    }

    setIfNotSet(WsdlSettings.NAME_WITH_BINDING, true);
    setIfNotSet(WsdlSettings.NAME_WITH_BINDING, 500);
    setIfNotSet(HttpSettings.HTTP_VERSION, HttpSettings.HTTP_VERSION_1_1);
    setIfNotSet(HttpSettings.MAX_TOTAL_CONNECTIONS, 2000);
    setIfNotSet(HttpSettings.RESPONSE_COMPRESSION, true);
    setIfNotSet(HttpSettings.LEAVE_MOCKENGINE, true);
    setIfNotSet(UISettings.AUTO_SAVE_PROJECTS_ON_EXIT, true);
    setIfNotSet(UISettings.SHOW_DESCRIPTIONS, true);
    setIfNotSet(WsdlSettings.XML_GENERATION_ALWAYS_INCLUDE_OPTIONAL_ELEMENTS, true);
    setIfNotSet(WsaSettings.USE_DEFAULT_RELATES_TO, true);
    setIfNotSet(WsaSettings.USE_DEFAULT_RELATIONSHIP_TYPE, true);
    setIfNotSet(UISettings.SHOW_STARTUP_PAGE, true);
    setIfNotSet(UISettings.GC_INTERVAL, "60");
    setIfNotSet(WsdlSettings.CACHE_WSDLS, true);
    setIfNotSet(WsdlSettings.PRETTY_PRINT_RESPONSE_MESSAGES, true);
    setIfNotSet(HttpSettings.RESPONSE_COMPRESSION, true);
    setIfNotSet(HttpSettings.INCLUDE_REQUEST_IN_TIME_TAKEN, true);
    setIfNotSet(HttpSettings.INCLUDE_RESPONSE_IN_TIME_TAKEN, true);
    setIfNotSet(HttpSettings.LEAVE_MOCKENGINE, true);
    setIfNotSet(HttpSettings.START_MOCK_SERVICE, true);
    setIfNotSet(UISettings.AUTO_SAVE_INTERVAL, "0");
    setIfNotSet(UISettings.GC_INTERVAL, "60");
    setIfNotSet(UISettings.SHOW_STARTUP_PAGE, true);
    setIfNotSet(WsaSettings.SOAP_ACTION_OVERRIDES_WSA_ACTION, false);
    setIfNotSet(WsaSettings.USE_DEFAULT_RELATIONSHIP_TYPE, true);
    setIfNotSet(WsaSettings.USE_DEFAULT_RELATES_TO, true);
    setIfNotSet(WsaSettings.OVERRIDE_EXISTING_HEADERS, false);
    setIfNotSet(WsaSettings.ENABLE_FOR_OPTIONAL, false);
    setIfNotSet(VersionUpdateSettings.AUTO_CHECK_VERSION_UPDATE, true);
    if (!settings.isSet(ProxySettings.AUTO_PROXY) && !settings.isSet(ProxySettings.ENABLE_PROXY)) {
      settings.setBoolean(ProxySettings.AUTO_PROXY, true);
      settings.setBoolean(ProxySettings.ENABLE_PROXY, true);
    }

    boolean setWsiDir = false;
    String wsiLocationString = settings.getString(WSISettings.WSI_LOCATION, null);
    if (StringUtils.isNullOrEmpty(wsiLocationString)) {
      setWsiDir = true;
    } else {
      File wsiFile = new File(wsiLocationString);
      if (!wsiFile.exists()) {
        setWsiDir = true;
      }
    }
    if (setWsiDir) {
      String wsiDir = System.getProperty("wsi.dir", new File(".").getAbsolutePath());
      settings.setString(WSISettings.WSI_LOCATION, wsiDir);
    }
    HttpClientSupport.addSSLListener(settings);

    return settings;
  }
  public Response sendRequest(SubmitContext submitContext, Request request) throws Exception {
    AbstractHttpRequestInterface<?> httpRequest = (AbstractHttpRequestInterface<?>) request;

    HttpClient httpClient = HttpClientSupport.getHttpClient();
    ExtendedHttpMethod httpMethod = createHttpMethod(httpRequest);
    boolean createdState = false;

    HttpState httpState = (HttpState) submitContext.getProperty(SubmitContext.HTTP_STATE_PROPERTY);
    if (httpState == null) {
      httpState = new HttpState();
      submitContext.setProperty(SubmitContext.HTTP_STATE_PROPERTY, httpState);
      createdState = true;
    }

    HostConfiguration hostConfiguration = new HostConfiguration();

    String localAddress = System.getProperty("soapui.bind.address", httpRequest.getBindAddress());
    if (localAddress == null || localAddress.trim().length() == 0)
      localAddress = SoapUI.getSettings().getString(HttpSettings.BIND_ADDRESS, null);

    if (localAddress != null && localAddress.trim().length() > 0) {
      try {
        hostConfiguration.setLocalAddress(InetAddress.getByName(localAddress));
      } catch (Exception e) {
        SoapUI.logError(e);
      }
    }

    submitContext.removeProperty(RESPONSE);
    submitContext.setProperty(HTTP_METHOD, httpMethod);
    submitContext.setProperty(POST_METHOD, httpMethod);
    submitContext.setProperty(HTTP_CLIENT, httpClient);
    submitContext.setProperty(REQUEST_CONTENT, httpRequest.getRequestContent());
    submitContext.setProperty(HOST_CONFIGURATION, hostConfiguration);
    submitContext.setProperty(WSDL_REQUEST, httpRequest);
    submitContext.setProperty(RESPONSE_PROPERTIES, new StringToStringMap());

    for (RequestFilter filter : filters) {
      filter.filterRequest(submitContext, httpRequest);
    }

    try {
      Settings settings = httpRequest.getSettings();

      // custom http headers last so they can be overridden
      StringToStringMap headers = httpRequest.getRequestHeaders();
      for (String header : headers.keySet()) {
        String headerValue = headers.get(header);
        headerValue = PropertyExpander.expandProperties(submitContext, headerValue);
        httpMethod.setRequestHeader(header, headerValue);
      }

      // do request
      WsdlProject project = (WsdlProject) ModelSupport.getModelItemProject(httpRequest);
      WssCrypto crypto = null;
      if (project != null) {
        crypto =
            project
                .getWssContainer()
                .getCryptoByName(
                    PropertyExpander.expandProperties(submitContext, httpRequest.getSslKeystore()));
      }

      if (crypto != null && WssCrypto.STATUS_OK.equals(crypto.getStatus())) {
        hostConfiguration
            .getParams()
            .setParameter(
                SoapUIHostConfiguration.SOAPUI_SSL_CONFIG,
                crypto.getSource() + " " + crypto.getPassword());
      }

      // dump file?
      httpMethod.setDumpFile(
          PathUtils.expandPath(
              httpRequest.getDumpFile(), (AbstractWsdlModelItem<?>) httpRequest, submitContext));

      // include request time?
      if (settings.getBoolean(HttpSettings.INCLUDE_REQUEST_IN_TIME_TAKEN))
        httpMethod.initStartTime();

      // submit!
      httpClient.executeMethod(hostConfiguration, httpMethod, httpState);
      httpMethod.getTimeTaken();
    } catch (Throwable t) {
      httpMethod.setFailed(t);

      if (t instanceof Exception) throw (Exception) t;

      SoapUI.logError(t);
      throw new Exception(t);
    } finally {
      for (int c = filters.size() - 1; c >= 0; c--) {
        filters.get(c).afterRequest(submitContext, httpRequest);
      }

      if (!submitContext.hasProperty(RESPONSE)) {
        createDefaultResponse(submitContext, httpRequest, httpMethod);
      }

      Response response = (Response) submitContext.getProperty(BaseHttpRequestTransport.RESPONSE);
      StringToStringMap responseProperties =
          (StringToStringMap)
              submitContext.getProperty(BaseHttpRequestTransport.RESPONSE_PROPERTIES);

      for (String key : responseProperties.keySet()) {
        response.setProperty(key, responseProperties.get(key));
      }

      if (httpMethod != null) {
        httpMethod.releaseConnection();
      } else log.error("PostMethod is null");

      if (createdState) {
        submitContext.setProperty(SubmitContext.HTTP_STATE_PROPERTY, null);
      }
    }

    return (Response) submitContext.getProperty(BaseHttpRequestTransport.RESPONSE);
  }