示例#1
0
 /**
  * Get the content body.
  *
  * @return the content
  */
 public String getContent() {
   if (StringUtils.hasText(content)) {
     return content;
   } else if (StringUtils.hasText(contentResourcePath) && contentType.startsWith("text")) {
     try {
       return FileUtils.readToString(
           new PathMatchingResourcePatternResolver()
               .getResource(contentResourcePath)
               .getInputStream(),
           Charset.forName(charsetName));
     } catch (IOException e) {
       throw new CitrusRuntimeException("Failed to read SOAP attachment file resource", e);
     }
   } else {
     try {
       byte[] binaryData =
           FileUtils.readToString(getDataHandler().getInputStream(), Charset.forName(charsetName))
               .getBytes(Charset.forName(charsetName));
       if (encodingType.equals(SoapAttachment.ENCODING_BASE64_BINARY)) {
         return Base64.encodeBase64String(binaryData);
       } else if (encodingType.equals(SoapAttachment.ENCODING_HEX_BINARY)) {
         return Hex.encodeHexString(binaryData).toUpperCase();
       } else {
         throw new CitrusRuntimeException(
             String.format(
                 "Unsupported encoding type '%s' for SOAP attachment - choose one of %s or %s",
                 encodingType,
                 SoapAttachment.ENCODING_BASE64_BINARY,
                 SoapAttachment.ENCODING_HEX_BINARY));
       }
     } catch (IOException e) {
       throw new CitrusRuntimeException("Failed to read SOAP attachment data input stream", e);
     }
   }
 }
  /**
   * Method removes a Spring bean definition from the XML application context file. Bean definition
   * is identified by its id or bean name.
   *
   * @param project
   * @param id
   */
  public void removeBeanDefinition(File configFile, Project project, String id) {
    Source xsltSource;
    Source xmlSource;
    try {
      xsltSource =
          new StreamSource(new ClassPathResource("transform/delete-bean.xsl").getInputStream());
      xsltSource.setSystemId("delete-bean");

      List<File> configFiles = new ArrayList<>();
      configFiles.add(configFile);
      configFiles.addAll(getConfigImports(configFile, project));

      for (File file : configFiles) {
        xmlSource = new StringSource(FileUtils.readToString(new FileInputStream(configFile)));

        // create transformer
        Transformer transformer = transformerFactory.newTransformer(xsltSource);
        transformer.setParameter("bean_id", id);

        // transform
        StringResult result = new StringResult();
        transformer.transform(xmlSource, result);
        FileUtils.writeToFile(format(result.toString(), project.getSettings().getTabSize()), file);
        return;
      }
    } catch (IOException e) {
      throw new ApplicationRuntimeException(UNABLE_TO_READ_TRANSFORMATION_SOURCE, e);
    } catch (TransformerException e) {
      throw new ApplicationRuntimeException(FAILED_TO_UPDATE_BEAN_DEFINITION, e);
    }
  }
  /**
   * Method adds a new Spring bean definition to the XML application context file.
   *
   * @param project
   * @param jaxbElement
   */
  public void addBeanDefinition(File configFile, Project project, Object jaxbElement) {
    Source xsltSource;
    Source xmlSource;
    try {
      xsltSource =
          new StreamSource(new ClassPathResource("transform/add-bean.xsl").getInputStream());
      xsltSource.setSystemId("add-bean");
      xmlSource = new StringSource(FileUtils.readToString(new FileInputStream(configFile)));

      // create transformer
      Transformer transformer = transformerFactory.newTransformer(xsltSource);
      transformer.setParameter(
          "bean_content",
          getXmlContent(jaxbElement)
              .replaceAll("(?m)^(.)", getTabs(1, project.getSettings().getTabSize()) + "$1"));

      // transform
      StringResult result = new StringResult();
      transformer.transform(xmlSource, result);
      FileUtils.writeToFile(
          format(result.toString(), project.getSettings().getTabSize()), configFile);
      return;
    } catch (IOException e) {
      throw new ApplicationRuntimeException(UNABLE_TO_READ_TRANSFORMATION_SOURCE, e);
    } catch (TransformerException e) {
      throw new ApplicationRuntimeException(FAILED_TO_UPDATE_BEAN_DEFINITION, e);
    }
  }
  /**
   * @see
   *     com.consol.citrus.actions.ReceiveMessageAction#validateMessage(org.springframework.integration.Message,
   *     com.consol.citrus.context.TestContext)
   */
  @Override
  protected void validateMessage(Message<?> receivedMessage, TestContext context) {
    try {
      super.validateMessage(receivedMessage, context);

      if (attachmentData != null) {
        controlAttachment.setContent(context.replaceDynamicContentInString(attachmentData));
      } else if (attachmentResourcePath != null) {
        controlAttachment.setContent(
            context.replaceDynamicContentInString(
                FileUtils.readToString(
                    FileUtils.getFileResource(attachmentResourcePath, context))));
      } else {
        return; // no attachment expected, no validation
      }

      // handle variables in content id
      if (controlAttachment.getContentId() != null) {
        controlAttachment.setContentId(
            context.replaceDynamicContentInString(controlAttachment.getContentId()));
      }

      // handle variables in content type
      if (controlAttachment.getContentType() != null) {
        controlAttachment.setContentType(
            context.replaceDynamicContentInString(controlAttachment.getContentType()));
      }

      attachmentValidator.validateAttachment(receivedMessage, controlAttachment);
    } catch (IOException e) {
      throw new CitrusRuntimeException(e);
    }
  }
示例#5
0
  /**
   * Resolve dynamic string content in attachment
   *
   * @param context Test context used to resolve dynamic content
   */
  public void resolveDynamicContent(TestContext context) {
    // handle variables in content id
    if (contentId != null) {
      contentId = context.replaceDynamicContentInString(contentId);
    }

    // handle variables in content type
    if (contentType != null) {
      contentType = context.replaceDynamicContentInString(contentType);
    }

    if (StringUtils.hasText(content)) {
      content = context.replaceDynamicContentInString(content);
    } else if (contentResourcePath != null) {
      contentResourcePath = context.replaceDynamicContentInString(contentResourcePath);

      if (contentType.startsWith("text")) {
        try {
          content =
              context.replaceDynamicContentInString(
                  FileUtils.readToString(
                      new PathMatchingResourcePatternResolver()
                          .getResource(contentResourcePath)
                          .getInputStream(),
                      Charset.forName(charsetName)));
        } catch (IOException e) {
          throw new CitrusRuntimeException("Failed to read SOAP attachment file resource", e);
        }
      }
    }
  }
 /**
  * Expect fault detail from file resource.
  *
  * @param resource
  * @return
  */
 public AssertSoapFaultDefinition faultDetailResource(Resource resource) {
   try {
     action.getFaultDetails().add(FileUtils.readToString(resource));
   } catch (IOException e) {
     throw new CitrusRuntimeException("Failed to read fault detail resource", e);
   }
   return this;
 }
 /**
  * Adds a fault detail from file resource.
  *
  * @param resource
  * @return
  */
 public SendSoapFaultActionDefinition faultDetailResource(Resource resource) {
   try {
     soapFaultMessageBuilder.getFaultDetails().add(FileUtils.readToString(resource));
   } catch (IOException e) {
     throw new CitrusRuntimeException("Failed to read fault detail resource", e);
   }
   return this;
 }
  /**
   * Adds message header data as file resource. Message header data is used in SOAP messages for
   * instance as header XML fragment.
   *
   * @param resource
   */
  public SendMessageActionDefinition header(Resource resource) {
    try {
      soapFaultMessageBuilder.setMessageHeaderData(FileUtils.readToString(resource));
    } catch (IOException e) {
      throw new CitrusRuntimeException("Failed to read header resource", e);
    }

    return this;
  }
示例#9
0
  @Override
  protected SoapMessage createMessage(TestContext context, String messageType) {
    Message message = super.createMessage(context, getMessageType());

    SoapMessage soapMessage = new SoapMessage(message).mtomEnabled(mtomEnabled);
    try {
      for (SoapAttachment attachment : attachments) {
        attachment.resolveDynamicContent(context);

        if (mtomEnabled) {
          String messagePayload = soapMessage.getPayload(String.class);
          String cid = CID_MARKER + attachment.getContentId();

          if (attachment.isMtomInline() && messagePayload.contains(cid)) {
            byte[] attachmentBinaryData =
                FileUtils.readToString(
                        attachment.getInputStream(), Charset.forName(attachment.getCharsetName()))
                    .getBytes(Charset.forName(attachment.getCharsetName()));
            if (attachment.getEncodingType().equals(SoapAttachment.ENCODING_BASE64_BINARY)) {
              log.info("Adding inline base64Binary data for attachment: %s", cid);
              messagePayload =
                  messagePayload.replaceAll(cid, Base64.encodeBase64String(attachmentBinaryData));
            } else if (attachment.getEncodingType().equals(SoapAttachment.ENCODING_HEX_BINARY)) {
              log.info("Adding inline hexBinary data for attachment: %s", cid);
              messagePayload =
                  messagePayload.replaceAll(
                      cid, Hex.encodeHexString(attachmentBinaryData).toUpperCase());
            } else {
              throw new CitrusRuntimeException(
                  String.format(
                      "Unsupported encoding type '%s' for SOAP attachment: %s - choose one of %s or %s",
                      attachment.getEncodingType(),
                      cid,
                      SoapAttachment.ENCODING_BASE64_BINARY,
                      SoapAttachment.ENCODING_HEX_BINARY));
            }
          } else {
            messagePayload =
                messagePayload.replaceAll(
                    cid,
                    String.format(
                        "<xop:Include xmlns:xop=\"http://www.w3.org/2004/08/xop/include\" href=\"%s\"/>",
                        cid));
            soapMessage.addAttachment(attachment);
          }

          soapMessage.setPayload(messagePayload);
        } else {
          soapMessage.addAttachment(attachment);
        }
      }
    } catch (IOException e) {
      throw new CitrusRuntimeException(e);
    }

    return soapMessage;
  }
示例#10
0
  @Override
  public void doExecute(TestContext context) {
    try {
      ClassLoader parent = getClass().getClassLoader();
      GroovyClassLoader loader = new GroovyClassLoader(parent);

      assertScriptProvided();

      String rawCode =
          StringUtils.hasText(script)
              ? script.trim()
              : FileUtils.readToString(FileUtils.getFileResource(scriptResourcePath, context));
      String code = context.replaceDynamicContentInString(rawCode.trim());

      // load groovy code
      Class<?> groovyClass = loader.parseClass(code);
      // Instantiate an object from groovy code
      GroovyObject groovyObject = (GroovyObject) groovyClass.newInstance();

      // only apply default script template in case we have feature enabled and code is not a class,
      // too
      if (useScriptTemplate && groovyObject.getClass().getSimpleName().startsWith("script")) {
        // build new script with surrounding template
        code =
            TemplateBasedScriptBuilder.fromTemplateResource(
                    FileUtils.getFileResource(scriptTemplatePath, context))
                .withCode(code)
                .build();

        groovyClass = loader.parseClass(code);
        groovyObject = (GroovyObject) groovyClass.newInstance();
      }

      if (log.isDebugEnabled()) {
        log.debug("Executing Groovy script:\n" + code);
      }

      // execute the Groovy script
      if (groovyObject instanceof ScriptExecutor) {
        ((ScriptExecutor) groovyObject).execute(context);
      } else {
        groovyObject.invokeMethod("run", new Object[] {});
      }

      log.info("Groovy script execution successfully");
    } catch (CitrusRuntimeException e) {
      throw e;
    } catch (Exception e) {
      throw new CitrusRuntimeException(e);
    }
  }
  /**
   * Method updates existing Spring bean definitions in a XML application context file. Bean
   * definition is identified by its type defining class.
   *
   * @param project
   * @param type
   * @param jaxbElement
   */
  public void updateBeanDefinitions(
      File configFile, Project project, Class<?> type, Object jaxbElement) {
    Source xsltSource;
    Source xmlSource;
    try {
      xsltSource =
          new StreamSource(
              new ClassPathResource("transform/update-bean-type.xsl").getInputStream());
      xsltSource.setSystemId("update-bean");

      List<File> configFiles = new ArrayList<>();
      configFiles.add(configFile);
      configFiles.addAll(getConfigImports(configFile, project));

      LSParser parser = XMLUtils.createLSParser();
      GetSpringBeansFilter getBeanFilter = new GetSpringBeansFilter(type, null);
      parser.setFilter(getBeanFilter);

      for (File file : configFiles) {
        parser.parseURI(file.toURI().toString());
        if (!CollectionUtils.isEmpty(getBeanFilter.getBeanDefinitions())) {
          xmlSource = new StringSource(FileUtils.readToString(new FileInputStream(file)));

          String beanElement = type.getAnnotation(XmlRootElement.class).name();
          String beanNamespace = type.getPackage().getAnnotation(XmlSchema.class).namespace();

          // create transformer
          Transformer transformer = transformerFactory.newTransformer(xsltSource);
          transformer.setParameter("bean_element", beanElement);
          transformer.setParameter("bean_namespace", beanNamespace);
          transformer.setParameter(
              "bean_content",
              getXmlContent(jaxbElement)
                  .replaceAll("(?m)^(\\s<)", getTabs(1, project.getSettings().getTabSize()) + "$1")
                  .replaceAll("(?m)^(</)", getTabs(1, project.getSettings().getTabSize()) + "$1"));

          // transform
          StringResult result = new StringResult();
          transformer.transform(xmlSource, result);
          FileUtils.writeToFile(
              format(result.toString(), project.getSettings().getTabSize()), file);
          return;
        }
      }
    } catch (IOException e) {
      throw new ApplicationRuntimeException(UNABLE_TO_READ_TRANSFORMATION_SOURCE, e);
    } catch (TransformerException e) {
      throw new ApplicationRuntimeException(FAILED_TO_UPDATE_BEAN_DEFINITION, e);
    }
  }
  /**
   * Sets the control attachment with content resource.
   *
   * @param contentId
   * @param contentType
   * @param contentResource
   * @return
   */
  public ReceiveSoapMessageActionDefinition attachment(
      String contentId, String contentType, Resource contentResource) {
    SoapAttachment attachment = new SoapAttachment();
    attachment.setContentId(contentId);
    attachment.setContentType(contentType);

    try {
      attachment.setContent(FileUtils.readToString(contentResource));
    } catch (IOException e) {
      throw new CitrusRuntimeException("Failed to read attachment content resource", e);
    }

    getAction().getAttachments().add(attachment);

    return this;
  }
示例#13
0
  /**
   * Static construction method from Spring mime attachment.
   *
   * @param attachment
   * @return
   */
  public static SoapAttachment from(Attachment attachment) {
    SoapAttachment soapAttachment = new SoapAttachment();
    soapAttachment.setContentId(attachment.getContentId());
    soapAttachment.setContentType(attachment.getContentType());

    if (attachment.getContentType().startsWith("text")) {
      try {
        soapAttachment.setContent(FileUtils.readToString(attachment.getInputStream()).trim());
      } catch (IOException e) {
        throw new CitrusRuntimeException("Failed to read SOAP attachment content", e);
      }
    } else {
      // Binary content
      soapAttachment.setDataHandler(attachment.getDataHandler());
    }

    soapAttachment.setCharsetName(Citrus.CITRUS_FILE_ENCODING);

    return soapAttachment;
  }