private StringToStringMap clearNullValues(StringToStringMap parameters) {
   StringToStringMap params = new StringToStringMap();
   for (String key : parameters.keySet()) {
     if (parameters.get(key) != null) params.put(key, parameters.get(key));
   }
   return params;
 }
  protected void generate(StringToStringMap values, ToolHost toolHost, WsdlProject project)
      throws Exception {
    String wstoolsDir =
        SoapUI.getSettings().getString(ToolsSettings.JBOSSWS_WSTOOLS_LOCATION, null);
    if (Tools.isEmpty(wstoolsDir)) {
      UISupport.showErrorMessage("wstools directory must be set in global preferences");
      return;
    }

    String wsToolsExtension = UISupport.isWindows() ? ".bat" : ".sh";

    File wstoolsFile = new File(wstoolsDir + File.separatorChar + "wstools" + wsToolsExtension);
    if (!wstoolsFile.exists()) {
      UISupport.showErrorMessage("Could not find wstools script at [" + wstoolsFile + "]");
      return;
    }

    ProcessBuilder builder = new ProcessBuilder();
    ArgumentBuilder args = buildArgs(values, UISupport.isWindows());
    builder.command(args.getArgs());
    builder.directory(new File(wstoolsDir));

    toolHost.run(
        new ToolRunner(builder, new File(values.get(OUTPUT)), values.get(SERVICE_NAME), project));
  }
  private ArgumentBuilder buildArgs(boolean isWindows, Interface modelItem) throws IOException {
    StringToStringMap values = dialog.getValues();
    values.put(OUTPUT, Tools.ensureDir(values.get(OUTPUT), ""));
    values.put(SOURCE_OUTPUT, Tools.ensureDir(values.get(SOURCE_OUTPUT), values.get(OUTPUT)));

    ArgumentBuilder builder = new ArgumentBuilder(values);
    builder.startScript("wsconsume");

    builder.addString(OUTPUT, "-o");
    builder.addString(CATALOG, "-c");
    builder.addString(PACKAGE, "-p");
    builder.addString(SOURCE_OUTPUT, "-s");
    builder.addString(WSDLLOCATION, "-w");
    builder.addBoolean(KEEP, "-k");
    builder.addBoolean(STACKTRACE, "-t");

    String[] bindingFiles = values.get(BINDING_FILES).split(",");
    for (String file : bindingFiles) {
      if (file.trim().length() > 0) builder.addArgs("-b", file.trim());
    }

    addToolArgs(values, builder);
    builder.addArgs(getWsdlUrl(values, modelItem));

    return builder;
  }
  @Override
  protected void execute(
      SecurityTestRunner securityTestRunner, TestStep testStep, SecurityTestRunContext context) {
    scriptEngine.setScript(groovyscc.getExecuteScript().getStringValue());
    scriptEngine.setVariable("context", context);
    scriptEngine.setVariable("testStep", testStep);
    scriptEngine.setVariable("securityScan", this);
    scriptEngine.setVariable("parameters", parameters);
    scriptEngine.setVariable("log", SoapUI.ensureGroovyLog());

    try {
      scriptResult = scriptEngine.run();
      hasNext = castResultToBoolean(scriptResult);
      XmlObjectTreeModel model = null;
      for (SecurityCheckedParameter scp : getParameterHolder().getParameterList()) {
        if (parameters.containsKey(scp.getLabel()) && parameters.get(scp.getLabel()) != null) {
          if (scp.isChecked() && scp.getXpath().trim().length() > 0) {
            model = SecurityScanUtil.getXmlObjectTreeModel(testStep, scp);
            XmlTreeNode[] treeNodes = null;
            treeNodes = model.selectTreeNodes(context.expand(scp.getXpath()));
            if (treeNodes.length > 0) {
              XmlTreeNode mynode = treeNodes[0];
              mynode.setValue(1, parameters.get(scp.getLabel()));
            }
            updateRequestProperty(testStep, scp.getName(), model.getXmlObject().toString());

          } else {
            updateRequestProperty(testStep, scp.getName(), parameters.get(scp.getLabel()));
          }
        } else if (parameters.containsKey(scp.getLabel())
            && parameters.get(scp.getLabel()) == null) { // clears null values form parameters
          parameters.remove(scp.getLabel());
        }
      }

      MessageExchange message =
          (MessageExchange) testStep.run((TestCaseRunner) securityTestRunner, context);
      createMessageExchange(clearNullValues(parameters), message, context);

    } catch (Exception e) {
      SoapUI.logError(e);
      hasNext = false;
    } finally {
      // if( scriptResult != null )
      // {
      // getTestStep().getProperty( "Request" ).setValue( ( String
      // )scriptResult );
      //
      // getTestStep().run( ( TestCaseRunner )securityTestRunner,
      // ( TestCaseRunContext )securityTestRunner.getRunContext() );
      // }

    }
  }
    public void actionPerformed(ActionEvent e) {
      try {
        MockResult mockResult = mockResponse.getMockResult();
        mockResponse.evaluateScript(mockResult == null ? null : mockResult.getMockRequest());

        StringToStringMap values = null;
        if (mockResponse.getMockResult() != null) {
          values = mockResponse.getMockResult().getMockRequest().getContext().toStringToStringMap();
        }

        if (values == null || values.isEmpty()) {
          UISupport.showInfoMessage("No values were returned");
        } else {
          String msg = "<html><body>Returned values:<br>";

          for (String name : values.keySet()) {
            msg += XmlUtils.entitize(name) + " : " + XmlUtils.entitize(values.get(name)) + "<br>";
          }

          msg += "</body></html>";

          UISupport.showExtendedInfo(
              "Result", "Result of MockResponse Script", msg, new Dimension(500, 400));
        }
      } catch (Throwable e1) {
        responseScriptEditor.selectError(e1.getMessage());
        UISupport.showErrorMessage(e1.toString());
      }
    }
Exemple #6
0
    public Object getValueAt(int rowIndex, int columnIndex) {
      StringToStringMap part = parts.get(rowIndex);

      switch (columnIndex) {
        case 0:
          return part.get("id");
        case 1:
          return part.get("name");
        case 2:
          return part.get("namespace");
        case 3:
          return part.get("enc");
      }

      return null;
    }
  protected String getWsdlUrl(StringToStringMap values, T modelItem) {
    String wsdl = values.get(WSDL);
    boolean useCached = values.getBoolean(CACHED_WSDL);

    if (modelItem instanceof AbstractInterface) {
      AbstractInterface<?> iface = (AbstractInterface<?>) modelItem;

      boolean hasDefinition = StringUtils.hasContent(iface.getDefinition());
      if (wsdl == null && !useCached && hasDefinition) {
        return PathUtils.expandPath(iface.getDefinition(), iface);
      }

      if (!hasDefinition || (useCached && iface.getDefinitionContext().isCached())) {
        try {
          File tempFile = File.createTempFile("tempdir", null);
          String path = tempFile.getAbsolutePath();
          tempFile.delete();
          wsdl = iface.getDefinitionContext().export(path);

          // CachedWsdlLoader loader = (CachedWsdlLoader)
          // iface.createWsdlLoader();
          // wsdl = loader.saveDefinition(path);
        } catch (Exception e) {
          SoapUI.logError(e);
        }
      }
    }

    return wsdl;
  }
  public String getAssertionNameForType(String type) {
    for (String assertion : assertionLabels.keySet()) {
      if (assertionLabels.get(assertion).equals(type)) {
        return assertion;
      }
    }

    return null;
  }
  private ConfigurationDocument createConfigFile(StringToStringMap values, Interface modelItem) {
    ConfigurationDocument configDocument = ConfigurationDocument.Factory.newInstance();
    ConfigurationType config = configDocument.addNewConfiguration();

    try {
      StringToStringMap nsMappings = StringToStringMap.fromXml(values.get(NAMESPACE_MAPPING));
      if (!nsMappings.isEmpty()) {
        GlobalType global = config.addNewGlobal();

        for (String namespace : nsMappings.keySet()) {
          PkgNSType entry = global.addNewPackageNamespace();
          entry.setNamespace(namespace);
          entry.setPackage(nsMappings.get(namespace));
        }
      }
    } catch (Exception e) {
      SoapUI.logError(e);
    }

    WsdlToJavaType wsdl2Java = config.addNewWsdlJava();

    String wsdlUrl = getWsdlUrl(values, modelItem);
    try {
      new URL(wsdlUrl);
      wsdl2Java.setLocation(wsdlUrl);
    } catch (MalformedURLException e) {
      ((Element) wsdl2Java.getDomNode()).setAttribute("file", wsdlUrl);
    }

    if (values.getBoolean(UNWRAP)) wsdl2Java.setParameterStyle(ParameterStyle.BARE);
    else wsdl2Java.setParameterStyle(ParameterStyle.WRAPPED);

    if (values.get(EJB_LINK) != null && values.get(EJB_LINK).length() > 0) {
      WsxmlType webservices = wsdl2Java.addNewWebservices();
      webservices.setEjbLink(values.get(EJB_LINK));
      webservices.setAppend(values.getBoolean(APPEND));
    } else if (values.get(SERVLET_LINK) != null && values.get(SERVLET_LINK).length() > 0) {
      WsxmlType webservices = wsdl2Java.addNewWebservices();
      webservices.setServletLink(values.get(SERVLET_LINK));
      webservices.setAppend(values.getBoolean(APPEND));
    }

    String mappingFile = values.get(MAPPING).toString().trim();
    if (mappingFile.length() > 0) {
      wsdl2Java.addNewMapping().setFile(mappingFile);
    }
    return configDocument;
  }
Exemple #10
0
 private String initXPathNamespaces(String xpath) {
   if (declaredNamespaces != null && !declaredNamespaces.isEmpty()) {
     for (String prefix : declaredNamespaces.keySet()) {
       xpath =
           "declare namespace " + prefix + "='" + declaredNamespaces.get(prefix) + "';\n" + xpath;
     }
   } else if (!xpath.trim().startsWith("declare namespace")) {
     xpath = XmlUtils.declareXPathNamespaces(xmlObject) + xpath;
   }
   return xpath;
 }
Exemple #11
0
  protected Vector<WSEncryptionPart> createWSParts(List<StringToStringMap> parts) {
    Vector<WSEncryptionPart> result = new Vector<WSEncryptionPart>();

    for (StringToStringMap map : parts) {
      if (map.hasValue("id")) {
        result.add(new WSEncryptionPart(map.get("id"), map.get("enc")));
      } else {
        String ns = map.get("namespace");
        if (ns == null) {
          ns = "";
        }

        String name = map.get("name");
        if (StringUtils.hasContent(name)) {
          result.add(new WSEncryptionPart(name, ns, map.get("enc")));
        }
      }
    }

    return result;
  }
  private ArgumentBuilder buildArgs(
      StringToStringMap values, boolean isWindows, Interface modelItem) throws IOException {
    values.put(OUTPUT, Tools.ensureDir(values.get(OUTPUT), ""));

    ArgumentBuilder builder = new ArgumentBuilder(values);
    builder.startScript("wstools");

    builder.addArgs("-config", buildConfigFile(values, modelItem));
    builder.addString(OUTPUT, "-dest");
    addToolArgs(values, builder);
    return builder;
  }
  @Override
  protected StringToStringMap initValues(Interface modelItem, Object param) {
    StringToStringMap values = super.initValues(modelItem, param);

    boolean hasEjbLink = values.get(EJB_LINK, "").length() > 0;
    boolean hasServletLink = values.get(SERVLET_LINK, "").length() > 0;

    if (!hasEjbLink && !hasServletLink) {
      ejbLinkField.setEnabled(true);
      servletLinkField.setEnabled(true);
    } else {
      ejbLinkField.setEnabled(hasEjbLink && !hasServletLink);
      servletLinkField.setEnabled(hasServletLink && !hasEjbLink);

      if (hasEjbLink && hasServletLink) values.put(SERVLET_LINK, "");
    }

    appendField.setEnabled(hasEjbLink || hasServletLink);

    return values;
  }
  public void perform(SecurityTest securityTest, Object param) {
    if (dialog == null) {
      XFormDialogBuilder builder = XFormFactory.createDialogBuilder("SecurityTest Options");
      form = builder.createForm("Basic");
      form.addCheckBox(FAIL_ON_ERROR, "Fail on error")
          .addFormFieldListener(
              new XFormFieldListener() {

                public void valueChanged(XFormField sourceField, String newValue, String oldValue) {
                  form.getFormField(FAIL_SECURITYTEST_ON_ERROR)
                      .setEnabled(!Boolean.parseBoolean(newValue));
                }
              });
      form.addCheckBox(FAIL_SECURITYTEST_ON_ERROR, "Fail SecurityTest if it has failed TestSteps");

      dialog =
          builder.buildDialog(
              builder.buildOkCancelHelpActions(HelpUrls.SECURITYTESTEDITOR_HELP_URL),
              "Specify general options for this SecurityTest",
              UISupport.OPTIONS_ICON);
    }

    StringToStringMap values = new StringToStringMap();

    values.put(FAIL_ON_ERROR, String.valueOf(securityTest.getFailOnError()));
    values.put(
        FAIL_SECURITYTEST_ON_ERROR, String.valueOf(securityTest.getFailSecurityTestOnScanErrors()));
    values = dialog.show(values);

    if (dialog.getReturnValue() == XFormDialog.OK_OPTION) {
      try {
        securityTest.setFailOnError(Boolean.parseBoolean(values.get(FAIL_ON_ERROR)));
        securityTest.setFailSecurityTestOnScanErrors(
            Boolean.parseBoolean(values.get(FAIL_SECURITYTEST_ON_ERROR)));

      } catch (Exception e1) {
        UISupport.showErrorMessage(e1.getMessage());
      }
    }
  }
  public String createScriptAssertionForExists(XPathData xpathData) {
    String script =
        "import com.eviware.soapui.support.XmlHolder\n\n"
            + "def holder = new XmlHolder( messageExchange.responseContentAsXml )\n";

    StringToStringMap nsMap = xpathData.getNamespaceMap();
    for (String ns : nsMap.keySet()) {
      script += "holder.namespaces[\"" + nsMap.get(ns) + "\"] = \"" + ns + "\"\n";
    }

    script += "def node = holder.getDomNode( \"" + xpathData.getPath() + "\" )\n";
    script += "\nassert node != null\n";

    return script;
  }
  private ArgumentBuilder buildArgs(StringToStringMap values, Interface modelItem)
      throws IOException {
    values.put(OUTPUT, Tools.ensureDir(values.get(OUTPUT), ""));

    ArgumentBuilder builder = new ArgumentBuilder(values);
    builder.addArgs("java", "-jar", "wsa.jar", "-genProxy");
    addJavaArgs(values, builder);

    builder.addArgs("-wsdl", getWsdlUrl(values, modelItem));
    builder.addString(OUTPUT, "-output");
    builder.addString(PACKAGE, "-packageName");

    addToolArgs(values, builder);
    return builder;
  }
  public void setValueAt(Object arg0, int arg1, int arg2) {
    String oldKey = keyList.get(arg1);

    if (arg2 == 0) {
      String value = data.get(oldKey);

      data.remove(oldKey);
      data.put(arg0.toString(), value);

      keyList.set(arg1, arg0.toString());
    } else {
      data.put(oldKey, arg0.toString());
    }

    fireTableCellUpdated(arg1, arg2);
  }
  protected void createTransfer(StringToStringMap values) {
    String propertyTransfer = values.get(TRANSFER_STEP);

    WsdlTestCase testCase = (WsdlTestCase) request.getTestCase();
    TransferResponseValuesTestStep transferStep =
        (TransferResponseValuesTestStep) testCase.getTestStepByName(propertyTransfer);

    if (transferStep == null) {
      int index = testCase.getIndexOfTestStep(request.getRequestStep());
      transferStep =
          (TransferResponseValuesTestStep)
              testCase.insertTestStep(
                  TransferValuesStepFactory.TRANSFER_TYPE, propertyTransfer, index);
    }

    if (transferStep == null) {
      UISupport.showErrorMessage("Missing transfer step [" + propertyTransfer + "]");
      return;
    }

    PropertyTransfer transfer = transferStep.getTransferByName(values.get(TRANSFER_NAME));
    if (transfer == null) transfer = transferStep.addTransfer(values.get(TRANSFER_NAME));

    transfer.setTargetStepName(request.getRequestStep().getName());
    transfer.setTargetPropertyName("Request");
    transfer.setTargetPath(values.get(TARGET_XPATH));

    String sourceStepName = values.get(SOURCE_STEP);
    transfer.setSourceStepName(sourceStepName);

    TestStep sourceStep = testCase.getTestStepByName(sourceStepName);
    if (sourceStep == null) {
      sourceStep =
          (WsdlPropertiesTestStep)
              testCase.insertTestStep(PropertiesStepFactory.PROPERTIES_TYPE, sourceStepName, 0);
    }

    String sourcePropertyName = values.get(SOURCE_PROPERTY);

    if (sourceStep.getProperty(sourcePropertyName) == null
        && sourceStep instanceof WsdlPropertiesTestStep) {
      ((WsdlPropertiesTestStep) sourceStep).addProperty(sourcePropertyName);
    }

    transfer.setSourcePropertyName(sourcePropertyName);

    if (values.getBoolean(OPEN_EDITOR)) {
      TransferResponseValuesDesktopPanel panel =
          (TransferResponseValuesDesktopPanel) UISupport.showDesktopPanel(transferStep);

      panel.selectTransfer(transfer);
    }
  }
  public boolean configure() {
    if (dialog == null) buildDialog();

    StringToStringMap values = new StringToStringMap();
    values.put(CONTENT, token);
    values.put(IGNORE_CASE, ignoreCase);
    values.put(USE_REGEX, useRegEx);

    values = dialog.show(values);
    if (dialog.getReturnValue() == XFormDialog.OK_OPTION) {
      token = values.get(CONTENT);
      ignoreCase = values.getBoolean(IGNORE_CASE);
      useRegEx = values.getBoolean(USE_REGEX);
    }

    setConfiguration(createConfiguration());
    return true;
  }
Exemple #20
0
  private ArgumentBuilder buildArgs(StringToStringMap values, Interface modelItem) {
    ArgumentBuilder builder = new ArgumentBuilder(values);

    values.put(XSBTARGET, Tools.ensureDir(values.get(XSBTARGET), ""));
    values.put(SRCTARGET, Tools.ensureDir(values.get(SRCTARGET), ""));

    builder.startScript("scomp", ".cmd", "");

    builder.addString(XSBTARGET, "-d");
    builder.addString(SRCTARGET, "-src");
    builder.addString(JARFILE, "-out");

    builder.addBoolean(SRCONLY, "-srconly");
    builder.addBoolean(DOWNLOADS, "-dl");
    builder.addBoolean(NOUPA, "-noupa");
    builder.addBoolean(NOPVR, "-nopvr");
    builder.addBoolean(NOANN, "-noann");
    builder.addBoolean(NOVDOC, "-novdoc");
    builder.addBoolean(DEBUG, "-debug");

    builder.addString(JAVASOURCE, "-javasource");
    builder.addString(ALLOWMDEF, "-allowmdef");
    builder.addString(CATALOG, "-catalog");
    builder.addBoolean(VERBOSE, "-verbose");

    String javac = ToolsSupport.getToolLocator().getJavacLocation(false);

    if (StringUtils.hasContent(javac)) {
      builder.addArgs("-compiler", javac + File.separatorChar + "javac");
    }
    addToolArgs(values, builder);

    builder.addString(XSDCONFIG, null);
    builder.addArgs(getWsdlUrl(values, modelItem));

    return builder;
  }
  public boolean configure() {
    if (dialog == null) {
      buildDialog();
    }

    StringToStringMap values = new StringToStringMap();

    values.put(NAME_FIELD, getName());
    values.put(MINIMUM_REQUESTS_FIELD, String.valueOf(minRequests));
    values.put(MAX_AVERAGE_FIELD, String.valueOf(maxAverage));
    values.put(TEST_STEP_FIELD, getTargetStep());
    values.put(MAX_ERRORS_FIELD, String.valueOf(maxErrors));
    values.put(SAMPLE_INTERVAL_FIELD, String.valueOf(sampleInterval));

    dialog.setOptions(TEST_STEP_FIELD, getTargetStepOptions(true));
    values = dialog.show(values);

    if (dialog.getReturnValue() == XFormDialog.OK_OPTION) {
      try {
        minRequests = Integer.parseInt(values.get(MINIMUM_REQUESTS_FIELD));
        maxAverage = Integer.parseInt(values.get(MAX_AVERAGE_FIELD));
        maxErrors = Integer.parseInt(values.get(MAX_ERRORS_FIELD));
        sampleInterval = Integer.parseInt(values.get(SAMPLE_INTERVAL_FIELD));
        setName(values.get(NAME_FIELD));
        setTargetStep(values.get(TEST_STEP_FIELD));
      } catch (Exception e) {
        UISupport.showErrorMessage(e.getMessage());
      }

      updateConfiguration();

      return true;
    }

    return false;
  }
Exemple #22
0
 public void setValues(StringToStringMap values) {
   for (Iterator<String> i = values.keySet().iterator(); i.hasNext(); ) {
     String key = i.next();
     setComponentValue(key, values.get(key));
   }
 }
Exemple #23
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);
          }
        }
      }
    }
  }
Exemple #24
0
    public Credentials getCredentials(final AuthScope authScope) {
      if (authScope == null) {
        throw new IllegalArgumentException("Authentication scope may not be null");
      }

      //	if( cache.containsKey( authScope ) )
      //	{
      //	return cache.get( authScope );
      //	}

      String pw = getPassword();
      if (pw == null) pw = "";

      if (AuthPolicy.NTLM.equalsIgnoreCase(authScope.getScheme())
          || AuthPolicy.SPNEGO.equalsIgnoreCase(authScope.getScheme())) {
        String workstation = "";
        try {
          workstation = InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException e) {
        }

        if (hasCredentials()) {
          log.info("Returning url credentials");
          return new NTCredentials(getUsername(), pw, workstation, null);
        }

        log.info(
            authScope.getHost() + ":" + authScope.getPort() + " requires Windows authentication");
        if (ntDialog == null) {
          buildNtDialog();
        }

        StringToStringMap values = new StringToStringMap();
        values.put(
            "Info",
            "Authentication required for ["
                + authScope.getHost()
                + ":"
                + authScope.getPort()
                + "]");
        ntDialog.setValues(values);

        if (ntDialog.show()) {
          values = ntDialog.getValues();
          NTCredentials credentials =
              new NTCredentials(
                  values.get("Username"),
                  values.get("Password"),
                  workstation,
                  values.get("Domain"));

          cache.put(authScope, credentials);
          return credentials;
        }
      } else if (AuthPolicy.BASIC.equalsIgnoreCase(authScope.getScheme())
          || AuthPolicy.DIGEST.equalsIgnoreCase(authScope.getScheme())) {
        if (hasCredentials()) {
          log.info("Returning url credentials");
          UsernamePasswordCredentials credentials =
              new UsernamePasswordCredentials(getUsername(), pw);
          cache.put(authScope, credentials);
          return credentials;
        }

        log.info(
            authScope.getHost()
                + ":"
                + authScope.getPort()
                + " requires authentication with the realm '"
                + authScope.getRealm()
                + "'");
        ShowDialog showDialog = new ShowDialog();
        showDialog.values.put(
            "Info",
            "Authentication required for ["
                + authScope.getHost()
                + ":"
                + authScope.getPort()
                + "]");

        UISupport.getUIUtils().runInUIThreadIfSWT(showDialog);
        if (showDialog.result) {
          UsernamePasswordCredentials credentials =
              new UsernamePasswordCredentials(
                  showDialog.values.get("Username"), showDialog.values.get("Password"));
          cache.put(authScope, credentials);
          return credentials;
        }
      }

      return null;
    }
 public String getAssertionTypeForName(String name) {
   return assertionLabels.get(name);
 }
  private ConfigurationDocument createConfigFile(StringToStringMap values) {
    ConfigurationDocument configDocument = ConfigurationDocument.Factory.newInstance();
    ConfigurationType config = configDocument.addNewConfiguration();

    JavaToWsdlType java2Wsdl = config.addNewJavaWsdl();
    ServiceType service = java2Wsdl.addNewService();
    service.setEndpoint(values.get(ENDPOINT));
    service.setStyle(Style.Enum.forString(values.get(STYLE)));
    service.setParameterStyle(ParameterStyle.Enum.forString(values.get(PARAMETER_STYLE)));
    service.setName(values.get(SERVICE_NAME));

    MappingType mapping = java2Wsdl.addNewMapping();
    mapping.setFile(values.get(MAPPING));

    NamespacesType namespaces = java2Wsdl.addNewNamespaces();
    namespaces.setTargetNamespace(values.get(TARGET_NAMESPACE));
    namespaces.setTypeNamespace(values.get(TYPES_NAMESPACE));

    WsxmlType webservices = java2Wsdl.addNewWebservices();
    if (values.get(EJB_LINK) != null && values.get(EJB_LINK).length() > 0)
      webservices.setEjbLink(values.get(EJB_LINK));
    if (values.get(SERVLET_LINK) != null && values.get(SERVLET_LINK).length() > 0)
      webservices.setServletLink(values.get(SERVLET_LINK));
    return configDocument;
  }
Exemple #27
0
 protected void addToolArgs(StringToStringMap values, ArgumentBuilder builder) {
   String[] toolArgs = Tools.tokenizeArgs(values.get(TOOL_ARGS));
   if (toolArgs != null) builder.addArgs(toolArgs);
 }
Exemple #28
0
 protected void addJavaArgs(StringToStringMap values, ArgumentBuilder builder) {
   String[] javaArgs = Tools.tokenizeArgs(values.get(JAVA_ARGS));
   if (javaArgs != null) builder.addArgs(javaArgs);
 }
 public Object getValueAt(int arg0, int arg1) {
   String str = keyList.get(arg0);
   return arg1 == 0 ? str : data.get(str);
 }
  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);
  }