コード例 #1
0
ファイル: AMFSubmit.java プロジェクト: SmartBear/soapui
  private SoapUIAMFConnection getConnection(AMFRequest amfRequest) throws Exception {
    SoapUIAMFConnection amfConnection = null;
    if (isAuthorisationEnabled(amfRequest) && (context.getModelItem() instanceof WsdlTestCase)) {
      if ((amfConnection = (SoapUIAMFConnection) context.getProperty(AMF_CONNECTION)) != null) {
        return amfConnection;
      } else {
        throw new Exception("amf session connection error! ");
      }
    } else if (isAuthorisationEnabled(amfRequest)
        && (context.getModelItem() instanceof AMFRequestTestStep)) {
      String endpoint = context.expand(getTestCaseConfig(amfRequest).getAmfEndpoint());
      String username = context.expand(getTestCaseConfig(amfRequest).getAmfLogin());
      String password = context.expand(getTestCaseConfig(amfRequest).getAmfPassword());

      if (StringUtils.hasContent(endpoint) && StringUtils.hasContent(username)) {
        credentials = new AMFCredentials(endpoint, username, password, context);
        amfConnection = credentials.login();
      } else {
        amfConnection = new SoapUIAMFConnection();
        amfConnection.connect(context.expand(amfRequest.getEndpoint()));
      }

      context.setProperty(AMF_CONNECTION, amfConnection);
      return amfConnection;
    } else {
      amfConnection = new SoapUIAMFConnection();
      amfConnection.connect(context.expand(amfRequest.getEndpoint()));
      return amfConnection;
    }
  }
コード例 #2
0
ファイル: WssEntryBase.java プロジェクト: SmartBear/soapui
  protected void addPropertyExpansions(PropertyExpansionsResult result) {
    if (StringUtils.hasContent(config.getUsername())) {
      result.extractAndAddAll("username");
    }

    if (StringUtils.hasContent(config.getPassword())) {
      result.extractAndAddAll("password");
    }
  }
コード例 #3
0
ファイル: HttpUtils.java プロジェクト: hborham/soapui
  public static String extractHttpHeaderParameter(String headerString, String parameterName) {
    if (!StringUtils.hasContent(headerString) || !StringUtils.hasContent(parameterName))
      return null;

    int ix = headerString.indexOf(parameterName + "=\"");
    if (ix > 0) {
      int ix2 = headerString.indexOf('"', ix + parameterName.length() + 2);
      if (ix2 > ix) return headerString.substring(ix + parameterName.length() + 2, ix2);
    }

    return null;
  }
コード例 #4
0
 private String determineSuggestedDirectory(Project project) {
   String currentDirectory =
       StringUtils.hasContent(project.getResourceRoot())
           ? project.getResourceRoot()
           : project.getPath();
   if (!StringUtils.hasContent(currentDirectory)) {
     return System.getProperty("user.dir", ".");
   } else if (holder.getModelItem() instanceof AbstractWsdlModelItem) {
     String expandedPath =
         PathUtils.expandPath(
             currentDirectory, ((AbstractWsdlModelItem) (holder.getModelItem())));
     return FilenameUtils.normalize(expandedPath);
   } else {
     return currentDirectory;
   }
 }
コード例 #5
0
ファイル: AbstractToolsAction.java プロジェクト: TouK/soapuii
  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;
  }
コード例 #6
0
ファイル: WadlImporter.java プロジェクト: SmartBear/soapui
  private Param resolveParameter(Param param) {
    String href = param.getHref();
    if (!StringUtils.hasContent(href)) {
      return param;
    }

    try {
      Application app = application;

      if (!href.startsWith("#")) {
        ApplicationDocument applicationDocument = loadReferencedWadl(href);
        app = applicationDocument.getApplication();
      }

      if (app != null) {
        int ix = href.lastIndexOf('#');
        if (ix >= 0) {
          href = href.substring(ix + 1);
        }

        for (Param p : application.getParamList()) {
          if (p.getId().equals(href)) {
            return p;
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    return null;
  }
コード例 #7
0
ファイル: WadlImporter.java プロジェクト: SmartBear/soapui
  private Representation resolveRepresentation(Representation representation) {
    String href = representation.getHref();
    if (!StringUtils.hasContent(href)) {
      return representation;
    }

    try {
      Application app = application;

      if (!href.startsWith("#")) {
        ApplicationDocument applicationDocument = loadReferencedWadl(href);
        app = applicationDocument.getApplication();
      }

      if (app != null) {
        int ix = href.lastIndexOf('#');
        if (ix >= 0) {
          href = href.substring(ix + 1);
        }

        for (Representation m : application.getRepresentationList()) {
          if (m.getId().equals(href)) {
            return m;
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    return representation;
  }
コード例 #8
0
ファイル: WadlImporter.java プロジェクト: SmartBear/soapui
  private Method resolveMethod(Method method) {
    String href = method.getHref();
    if (!StringUtils.hasContent(href)) {
      return method;
    }

    for (Method m : application.getMethodList()) {
      if (m.getId().equals(href.substring(1))) {
        return m;
      }
    }

    try {
      ApplicationDocument applicationDocument = loadReferencedWadl(href);
      if (applicationDocument != null) {
        int ix = href.lastIndexOf('#');
        if (ix > 0) {
          href = href.substring(ix + 1);
        }

        for (Method m : application.getMethodList()) {
          if (m.getId().equals(href)) {
            return m;
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    return method;
  }
コード例 #9
0
  public String createXmlRepresentation(TypedContent typedContent) {
    String content = typedContent == null ? null : typedContent.getContentAsString();
    if (!StringUtils.hasContent(content)) {
      return "<xml/>";
    }

    try {
      // XmlObject.Factory.parse( new ByteArrayInputStream(
      // content.getBytes() ) );
      XmlUtils.createXmlObject(new ByteArrayInputStream(content.getBytes()));
      return content;
    } catch (Exception e) {
      // fall through, this wasn't xml
    }

    try {
      Tidy tidy = new Tidy();
      tidy.setXmlOut(true);
      tidy.setShowWarnings(false);
      tidy.setErrout(new PrintWriter(new StringWriter()));
      // tidy.setQuiet(true);
      tidy.setNumEntities(true);
      tidy.setQuoteNbsp(true);
      tidy.setFixUri(false);

      Document document = tidy.parseDOM(new ByteArrayInputStream(content.getBytes()), null);
      StringWriter writer = new StringWriter();
      XmlUtils.serializePretty(document, writer);
      return writer.toString();
    } catch (Throwable e) {
      SoapUI.logError(e);
    }
    return null;
  }
コード例 #10
0
  public XmlObject getRequestXmlObject() throws XmlException {
    if (requestXmlObject == null && StringUtils.hasContent(getRequestContent()))
      // requestXmlObject = XmlObject.Factory.parse( getRequestContent() );
      requestXmlObject =
          XmlUtils.createXmlObject(getRequestContent(), XmlUtils.createDefaultXmlOptions());

    return requestXmlObject;
  }
コード例 #11
0
ファイル: WadlImporter.java プロジェクト: SmartBear/soapui
 private String getFirstTitle(List<Doc> list, String defaultTitle) {
   for (Doc doc : list) {
     if (StringUtils.hasContent(doc.getTitle())) {
       return doc.getTitle();
     }
   }
   return defaultTitle;
 }
コード例 #12
0
ファイル: JMSUtils.java プロジェクト: pellcorp/soapui
 private static boolean checkIfJMS(Request request) {
   try {
     String endpoint = request.getEndpoint();
     return StringUtils.hasContent(endpoint)
         && endpoint.startsWith(JMSEndpoint.JMS_ENDPIONT_PREFIX);
   } catch (NullPointerException e) {
     SoapUI.logError(e);
   }
   return false;
 }
コード例 #13
0
    public void actionPerformed(ActionEvent e) {
      String name = UISupport.prompt("Specify unique property name", "Add Property", "");
      if (StringUtils.hasContent(name)) {
        if (holder.hasProperty(name)) {
          UISupport.showErrorMessage("Property name [" + name + "] already exists..");
          return;
        }

        ((MutableTestPropertyHolder) holder).addProperty(name);
      }
    }
コード例 #14
0
  public XmlBeansPropertiesTestPropertyHolder(ModelItem modelItem, PropertiesTypeConfig config) {
    this.modelItem = modelItem;
    this.config = config;

    for (int c = 0; c < config.sizeOfPropertyArray(); c++) {
      PropertyConfig propertyConfig = config.getPropertyArray(c);
      if (StringUtils.hasContent(propertyConfig.getName())) {
        addProperty(propertyConfig, false, null);
      } else {
        config.removeProperty(c);
        c--;
      }
    }
  }
コード例 #15
0
  protected void prepareRequestStep(HttpRequestTestStep requestStep) {
    AbstractHttpRequest<?> httpRequest = requestStep.getHttpRequest();
    if (StringUtils.hasContent(endpoint)) {
      httpRequest.setEndpoint(endpoint);
    } else if (StringUtils.hasContent(host)) {
      try {
        String ep = Tools.replaceHost(httpRequest.getEndpoint(), host);
        httpRequest.setEndpoint(ep);
      } catch (Exception e) {
        log.error("Failed to set host on endpoint", e);
      }
    }

    if (StringUtils.hasContent(username)) {
      httpRequest.setUsername(username);
    }

    if (StringUtils.hasContent(password)) {
      httpRequest.setPassword(password);
    }

    if (StringUtils.hasContent(domain)) {
      httpRequest.setDomain(domain);
    }

    if (httpRequest instanceof WsdlRequest) {

      if (wssPasswordType != null && wssPasswordType.length() > 0) {
        ((WsdlRequest) httpRequest)
            .setWssPasswordType(
                wssPasswordType.equals("Digest")
                    ? WsdlTestRequest.PW_TYPE_DIGEST
                    : WsdlTestRequest.PW_TYPE_TEXT);
      }
    }
  }
コード例 #16
0
 private Set<String> getResponseStatuses(RestMethod method) {
   Set<String> statuses = new HashSet<>();
   for (RestRepresentation repr : method.getRepresentations()) {
     if (repr.getType() == RestRepresentation.Type.RESPONSE) {
       for (Object item : repr.getStatus()) {
         String status = item.toString();
         if (StringUtils.hasContent(status)) {
           statuses.add(status);
         }
       }
     }
   }
   if (deploymentSetting.proxyIntegration && statuses.isEmpty()) {
     statuses.add(deploymentSetting.defaultResponse);
   }
   return statuses;
 }
コード例 #17
0
  @Override
  public void filterAbstractHttpRequest(SubmitContext context, AbstractHttpRequest<?> request) {
    HttpRequestBase httpMethod =
        (HttpRequestBase) context.getProperty(BaseHttpRequestTransport.HTTP_METHOD);

    String strURL = request.getEndpoint();
    strURL = PropertyExpander.expandProperties(context, strURL);
    try {
      if (StringUtils.hasContent(strURL)) {
        URI uri = new URI(strURL, request.getSettings().getBoolean(HttpSettings.ENCODED_URLS));
        context.setProperty(BaseHttpRequestTransport.REQUEST_URI, uri);
        httpMethod.setURI(HttpUtils.createUri(uri));
      }
    } catch (Exception e) {
      SoapUI.logError(e);
    }
  }
コード例 #18
0
  public int addPropertiesFromFile(String propFile) {
    if (!StringUtils.hasContent(propFile)) {
      return 0;
    }

    try {
      InputStream input = null;

      File file = new File(propFile);
      if (file.exists()) {
        input = new FileInputStream(file);
      } else if (propFile.toLowerCase().startsWith("http://")
          || propFile.toLowerCase().startsWith("https://")) {
        UrlWsdlLoader loader = new UrlWsdlLoader(propFile, getModelItem());
        loader.setUseWorker(false);
        input = loader.load();
      }

      if (input != null) {
        if (overrideProperties == null) {
          overrideProperties = new Properties();
        }

        int sz = overrideProperties.size();
        overrideProperties.load(input);

        for (Object key : overrideProperties.keySet()) {
          String name = key.toString();
          if (!hasProperty(name)) {
            addProperty(name);
          }
        }

        return overrideProperties.size() - sz;
      }
    } catch (Exception e) {
      SoapUI.logError(e);
    }

    return 0;
  }
コード例 #19
0
ファイル: WssEntryBase.java プロジェクト: SmartBear/soapui
  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;
  }
コード例 #20
0
  @Override
  public void perform(RestMockService mockService, Object param) {
    XFormDialog dialog = ADialogBuilder.buildDialog(Form.class);
    dialog.setOptions(Form.HTTP_METHOD, RestRequestInterface.HttpMethod.getMethodsAsStringArray());
    dialog.setValue(Form.HTTP_METHOD, RestRequestInterface.HttpMethod.GET.name());

    JTextFieldFormField formField = (JTextFieldFormField) dialog.getFormField(Form.RESOURCE_PATH);
    formField.getComponent().requestFocus();

    while (dialog.show()) {
      String resourcePath = dialog.getValue(Form.RESOURCE_PATH);
      String httpMethod = dialog.getValue(Form.HTTP_METHOD);

      if (StringUtils.hasContent(resourcePath)) {
        mockService.addEmptyMockAction(
            RestRequestInterface.HttpMethod.valueOf(httpMethod), resourcePath);
        break;
      }
      UISupport.showInfoMessage("The resource path can not be empty");
    }
  }
コード例 #21
0
  @Override
  protected boolean runRunner() throws Exception {
    WsdlProject project =
        (WsdlProject)
            ProjectFactoryRegistry.getProjectFactory("wsdl")
                .createNew(getProjectFile(), getProjectPassword());

    String pFile = getProjectFile();

    project.getSettings().setString(ProjectSettings.SHADOW_PASSWORD, null);

    File tmpProjectFile = new File(System.getProperty("java.io.tmpdir"));
    tmpProjectFile = new File(tmpProjectFile, project.getName() + "-project.xml");

    project.beforeSave();
    project.saveIn(tmpProjectFile);

    pFile = tmpProjectFile.getAbsolutePath();

    String endpoint = StringUtils.hasContent(localEndpoint) ? localEndpoint : project.getName();

    log.info("Creating WAR file with endpoint [" + endpoint + "]");

    MockAsWar mockAsWar =
        new MockAsWar(
            pFile,
            getSettingsFile(),
            getOutputFolder(),
            warFile,
            includeLibraries,
            includeActions,
            includeListeners,
            endpoint,
            enableWebUI,
            project);

    mockAsWar.createMockAsWarArchive();
    log.info("WAR Generation complete");
    return true;
  }
コード例 #22
0
ファイル: HttpRequestFilter.java プロジェクト: jwalter/soapui
  protected String getEncodedValue(
      String value, String encoding, boolean isDisableUrlEncoding, boolean isPreEncoded)
      throws UnsupportedEncodingException {

    // get default encoding if there is no encoding set
    if (!StringUtils.hasContent(encoding)) {
      encoding = System.getProperty("file.encoding");
    }

    if (isAlreadyEncoded(value, encoding)) {
      // Already encoded so we don't do anything
      return value;
    } else if (isDisableUrlEncoding || isPreEncoded) {
      // If encoding is disabled or it is pre-encoded then we don't encode
      return value;
    } else {
      // encoding NOT disabled neither it is pre-encoded, so we encode here
      String encodedValue = URLEncoder.encode(value, encoding);
      // URLEncoder replaces space with "+", but we want "%20".
      return encodedValue.replaceAll("\\+", "%20");
    }
  }
コード例 #23
0
  private void overrideRequest(
      SubmitContext context,
      AbstractHttpRequestInterface<?> wsdlRequest,
      EndpointDefaults def,
      String requestUsername,
      String requestPassword,
      String requestDomain,
      String defUsername,
      String defPassword,
      String defDomain,
      com.eviware.soapui.config.CredentialsConfig.AuthType.Enum authType) {
    String username = StringUtils.hasContent(defUsername) ? defUsername : requestUsername;
    String password = StringUtils.hasContent(defPassword) ? defPassword : requestPassword;

    if (StringUtils.hasContent(username) || StringUtils.hasContent(password)) {
      // only set if not set in request
      String wssType = def.getWssType();
      String wssTimeToLive = def.getWssTimeToLive();

      if (wssType == null) {
        String domain = StringUtils.hasContent(defDomain) ? defDomain : requestDomain;
        HttpAuthenticationRequestFilter.initRequestCredentials(
            context, username, project.getSettings(), password, domain, authType);
      }

      if (StringUtils.hasContent(wssType) || StringUtils.hasContent(wssTimeToLive)) {
        try {
          // set to null so existing don't get removed
          if (wssTimeToLive != null && wssTimeToLive.length() == 0) {
            wssTimeToLive = null;
          }

          WssAuthenticationRequestFilter.setWssHeaders(
              context, username, password, wssType, wssTimeToLive);
        } catch (Exception e) {
          SoapUI.logError(e);
        }
      }
    }
  }
コード例 #24
0
  public String createXmlRepresentation(HttpResponse response) {
    try {
      String content = response.getContentAsString().trim();
      if (!StringUtils.hasContent(content)) return null;

      // remove nulls - workaround for bug in xmlserializer!?
      content = content.replaceAll("\\\\u0000", "");
      JSON json = JSONSerializer.toJSON(content);
      JsonXmlSerializer serializer = new JsonXmlSerializer();
      serializer.setTypeHintsEnabled(false);
      serializer.setRootName(
          HttpUtils.isErrorStatus(response.getStatusCode()) ? "Fault" : "Response");
      URL url = response.getURL();
      serializer.setNamespace("", url.getProtocol() + "://" + url.getHost() + url.getPath());
      content = serializer.write(json);
      content = XmlUtils.prettyPrintXml(content);

      return content;
    } catch (Throwable e) {
      if (!(e instanceof JSONException)) e.printStackTrace();
    }
    return "<xml/>";
  }
コード例 #25
0
ファイル: XmlBeans2Action.java プロジェクト: SmartBear/soapui
  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;
  }
コード例 #26
0
ファイル: HttpRequestFilter.java プロジェクト: jwalter/soapui
  @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);
          }
        }
      }
    }
  }
コード例 #27
0
ファイル: WadlImporter.java プロジェクト: SmartBear/soapui
  private RestMethod initMethod(RestResource newResource, Method method) {
    // build name
    String name = getFirstTitle(method.getDocList(), method.getName());
    String id = method.getId();
    if (StringUtils.hasContent(id) && !id.trim().equals(name.trim())) {
      name += " - " + method.getId();
    }

    // ensure unique name
    if (newResource.getRestMethodByName(name) != null) {
      int cnt = 0;
      String orgName = name;

      while (newResource.getRestMethodByName(name) != null) {
        cnt++;
        name = orgName + "-" + cnt;
      }
    }

    // add to resource
    RestMethod restMethod = newResource.addNewMethod(name);
    restMethod.setMethod(RestRequestInterface.HttpMethod.valueOf(method.getName()));

    if (method.getRequest() != null) {
      for (Param param : method.getRequest().getParamList()) {
        param = resolveParameter(param);
        if (param != null) {
          RestParamProperty p = restMethod.addProperty(param.getName());
          initParam(param, p);
        }
      }

      for (Representation representation : method.getRequest().getRepresentationList()) {
        representation = resolveRepresentation(representation);
        addRepresentationFromConfig(
            restMethod, representation, RestRepresentation.Type.REQUEST, null);
      }
    }

    for (Response response : method.getResponseList()) {
      for (Representation representation : response.getRepresentationList()) {
        addRepresentation(response, restMethod, representation);
      }
      if (!isWADL11) {
        NodeList children = response.getDomNode().getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
          Node n = children.item(i);
          if ("fault".equals(n.getNodeName())) {
            String content = XmlUtils.serialize(n, false);
            try {
              Map<Object, Object> map = new HashMap<Object, Object>();
              XmlCursor cursor = response.newCursor();
              cursor.getAllNamespaces(map);
              cursor.dispose();
              XmlOptions options = new XmlOptions();
              options.setLoadAdditionalNamespaces(map);
              // XmlObject obj = XmlObject.Factory.parse(
              // content.replaceFirst( "<(([a-z]+:)?)fault ",
              // "<$1representation " ), options );
              XmlObject obj =
                  XmlUtils.createXmlObject(
                      content.replaceFirst("<(([a-z]+:)?)fault ", "<$1representation "), options);
              RepresentationDocument representation =
                  (RepresentationDocument) obj.changeType(RepresentationDocument.type);
              addRepresentation(response, restMethod, representation.getRepresentation());
            } catch (XmlException e) {
            }
          }
        }
      }
    }

    restMethod.addNewRequest("Request 1");
    return restMethod;
  }
コード例 #28
0
  private void complementRequest(
      SubmitContext context,
      AbstractHttpRequestInterface<?> httpRequest,
      EndpointDefaults def,
      String requestUsername,
      String requestPassword,
      String requestDomain,
      String defUsername,
      String defPassword,
      String defDomain,
      com.eviware.soapui.config.CredentialsConfig.AuthType.Enum authType) {
    String username = StringUtils.hasContent(requestUsername) ? requestUsername : defUsername;
    String password = StringUtils.hasContent(requestPassword) ? requestPassword : defPassword;

    if (httpRequest instanceof WsdlRequest) {
      WsdlRequest wsdlRequest = (WsdlRequest) httpRequest;
      // only set if not set in request
      String wssType =
          StringUtils.isNullOrEmpty(wsdlRequest.getWssPasswordType())
              ? def.getWssType()
              : (StringUtils.hasContent(username) && StringUtils.hasContent(password))
                  ? null
                  : wsdlRequest.getWssPasswordType();

      String wssTimeToLive =
          StringUtils.isNullOrEmpty(wsdlRequest.getWssTimeToLive()) ? def.getWssTimeToLive() : null;

      if (!StringUtils.hasContent(wssType)
          && (StringUtils.hasContent(username) || StringUtils.hasContent(password))) {
        String domain = StringUtils.hasContent(requestDomain) ? requestDomain : defDomain;
        HttpAuthenticationRequestFilter.initRequestCredentials(
            context, username, project.getSettings(), password, domain, authType);
      } else if (StringUtils.hasContent(wssType) || StringUtils.hasContent(wssTimeToLive)) {
        try {
          // set to null so existing don't get removed
          if (wssTimeToLive != null && wssTimeToLive.length() == 0) {
            wssTimeToLive = null;
          }

          if (StringUtils.hasContent(username) || StringUtils.hasContent(password)) {
            WssAuthenticationRequestFilter.setWssHeaders(
                context, username, password, wssType, wssTimeToLive);
          }
        } catch (Exception e) {
          SoapUI.logError(e);
        }
      }
    } else {
      if ((StringUtils.hasContent(username) || StringUtils.hasContent(password))) {
        String domain = StringUtils.hasContent(requestDomain) ? requestDomain : defDomain;
        HttpAuthenticationRequestFilter.initRequestCredentials(
            context, username, project.getSettings(), password, domain, authType);
      }
    }
  }
コード例 #29
0
ファイル: WadlImporter.java プロジェクト: SmartBear/soapui
  public static String extractParams(URL param, RestParamsPropertyHolder params) {
    String path = param.getPath();
    String[] items = path.split("/");

    int templateParamCount = 0;
    StringBuffer resultPath = new StringBuffer();

    for (int i = 0; i < items.length; i++) {
      String item = items[i];
      try {
        String[] matrixParams = item.split(";");
        if (matrixParams.length > 0) {
          item = matrixParams[0];
          for (int c = 1; c < matrixParams.length; c++) {
            String matrixParam = matrixParams[c];

            int ix = matrixParam.indexOf('=');
            if (ix == -1) {
              params
                  .addProperty(URLDecoder.decode(matrixParam, "Utf-8"))
                  .setStyle(ParameterStyle.MATRIX);
            } else {
              String name = matrixParam.substring(0, ix);
              RestParamProperty property = params.addProperty(URLDecoder.decode(name, "Utf-8"));
              property.setStyle(ParameterStyle.MATRIX);
              property.setValue(URLDecoder.decode(matrixParam.substring(ix + 1), "Utf-8"));
            }
          }
        }

        Integer.parseInt(item);
        RestParamProperty prop = params.addProperty("param" + templateParamCount++);
        prop.setStyle(ParameterStyle.TEMPLATE);
        prop.setValue(item);

        item = "{" + prop.getName() + "}";
      } catch (Exception e) {
      }

      if (StringUtils.hasContent(item)) {
        resultPath.append('/').append(item);
      }
    }

    String query = ((URL) param).getQuery();
    if (StringUtils.hasContent(query)) {
      items = query.split("&");
      for (String item : items) {
        try {
          int ix = item.indexOf('=');
          if (ix == -1) {
            params.addProperty(URLDecoder.decode(item, "Utf-8")).setStyle(ParameterStyle.QUERY);
          } else {
            String name = item.substring(0, ix);
            RestParamProperty property = params.addProperty(URLDecoder.decode(name, "Utf-8"));
            property.setStyle(ParameterStyle.QUERY);
            property.setValue(URLDecoder.decode(item.substring(ix + 1), "Utf-8"));
          }
        } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
        }
      }
    }

    return resultPath.toString();
  }
コード例 #30
0
 public String getDescription() {
   String description = config.getDescription();
   return StringUtils.hasContent(description) ? description : "";
 }