idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
28,300
public T xpath ( String xPathExpression , Object controlValue ) { validate ( xPathExpression , controlValue ) ; return self ; }
Adds XPath message element validation .
31
7
28,301
public T jsonPath ( String jsonPathExpression , Object controlValue ) { validate ( jsonPathExpression , controlValue ) ; return self ; }
Adds JsonPath message element validation .
31
8
28,302
public T namespace ( String prefix , String namespaceUri ) { getXpathVariableExtractor ( ) . getNamespaces ( ) . put ( prefix , namespaceUri ) ; xmlMessageValidationContext . getNamespaces ( ) . put ( prefix , namespaceUri ) ; return self ; }
Adds explicit namespace declaration for later path validation expressions .
62
10
28,303
public T namespaces ( Map < String , String > namespaceMappings ) { getXpathVariableExtractor ( ) . getNamespaces ( ) . putAll ( namespaceMappings ) ; xmlMessageValidationContext . getNamespaces ( ) . putAll ( namespaceMappings ) ; return self ; }
Sets default namespace declarations on this action builder .
63
10
28,304
public T selector ( Map < String , Object > messageSelector ) { getAction ( ) . setMessageSelectorMap ( messageSelector ) ; return self ; }
Sets message selector elements .
35
6
28,305
public T validator ( MessageValidator < ? extends ValidationContext > ... validators ) { Stream . of ( validators ) . forEach ( getAction ( ) :: addValidator ) ; return self ; }
Sets explicit message validators for this receive action .
45
11
28,306
@ SuppressWarnings ( "unchecked" ) public T validator ( String ... validatorNames ) { Assert . notNull ( applicationContext , "Citrus application context is not initialized!" ) ; for ( String validatorName : validatorNames ) { getAction ( ) . addValidator ( applicationContext . getBean ( validatorName , MessageValidator . class ) ) ; } return self ; }
Sets explicit message validators by name .
90
9
28,307
public T headerValidator ( HeaderValidator ... validators ) { Stream . of ( validators ) . forEach ( headerValidationContext :: addHeaderValidator ) ; return self ; }
Sets explicit header validator for this receive action .
40
11
28,308
@ SuppressWarnings ( "unchecked" ) public T headerValidator ( String ... validatorNames ) { Assert . notNull ( applicationContext , "Citrus application context is not initialized!" ) ; for ( String validatorName : validatorNames ) { headerValidationContext . addHeaderValidator ( applicationContext . getBean ( validatorName , HeaderValidator . class ) ) ; } return self ; }
Sets explicit header validators by name .
92
9
28,309
@ SuppressWarnings ( "unchecked" ) public T dictionary ( String dictionaryName ) { Assert . notNull ( applicationContext , "Citrus application context is not initialized!" ) ; DataDictionary dictionary = applicationContext . getBean ( dictionaryName , DataDictionary . class ) ; getAction ( ) . setDataDictionary ( dictionary ) ; return self ; }
Sets explicit data dictionary by name .
81
8
28,310
public T extractFromHeader ( String headerName , String variable ) { if ( headerExtractor == null ) { headerExtractor = new MessageHeaderVariableExtractor ( ) ; getAction ( ) . getVariableExtractors ( ) . add ( headerExtractor ) ; } headerExtractor . getHeaderMappings ( ) . put ( headerName , variable ) ; return self ; }
Extract message header entry as variable .
80
8
28,311
public T extractFromPayload ( String path , String variable ) { if ( JsonPathMessageValidationContext . isJsonPathExpression ( path ) ) { getJsonPathVariableExtractor ( ) . getJsonPathExpressions ( ) . put ( path , variable ) ; } else { getXpathVariableExtractor ( ) . getXpathExpressions ( ) . put ( path , variable ) ; } return self ; }
Extract message element via XPath or JSONPath from message payload as new test variable .
93
18
28,312
public T validationCallback ( ValidationCallback callback ) { if ( callback instanceof ApplicationContextAware ) { ( ( ApplicationContextAware ) callback ) . setApplicationContext ( applicationContext ) ; } getAction ( ) . setValidationCallback ( callback ) ; return self ; }
Adds validation callback to the receive action for validating the received message with Java code .
58
17
28,313
protected AbstractMessageContentBuilder getMessageContentBuilder ( ) { if ( getAction ( ) . getMessageBuilder ( ) != null && getAction ( ) . getMessageBuilder ( ) instanceof AbstractMessageContentBuilder ) { return ( AbstractMessageContentBuilder ) getAction ( ) . getMessageBuilder ( ) ; } else { PayloadTemplateMessageBuilder messageBuilder = new PayloadTemplateMessageBuilder ( ) ; getAction ( ) . setMessageBuilder ( messageBuilder ) ; return messageBuilder ; } }
Get message builder if already registered or create a new message builder and register it
102
15
28,314
private XpathMessageValidationContext getXPathValidationContext ( ) { if ( xmlMessageValidationContext instanceof XpathMessageValidationContext ) { return ( ( XpathMessageValidationContext ) xmlMessageValidationContext ) ; } else { XpathMessageValidationContext xPathContext = new XpathMessageValidationContext ( ) ; xPathContext . setNamespaces ( xmlMessageValidationContext . getNamespaces ( ) ) ; xPathContext . setControlNamespaces ( xmlMessageValidationContext . getControlNamespaces ( ) ) ; xPathContext . setIgnoreExpressions ( xmlMessageValidationContext . getIgnoreExpressions ( ) ) ; xPathContext . setSchema ( xmlMessageValidationContext . getSchema ( ) ) ; xPathContext . setSchemaRepository ( xmlMessageValidationContext . getSchemaRepository ( ) ) ; xPathContext . setSchemaValidation ( xmlMessageValidationContext . isSchemaValidationEnabled ( ) ) ; xPathContext . setDTDResource ( xmlMessageValidationContext . getDTDResource ( ) ) ; getAction ( ) . getValidationContexts ( ) . remove ( xmlMessageValidationContext ) ; getAction ( ) . getValidationContexts ( ) . add ( xPathContext ) ; xmlMessageValidationContext = xPathContext ; return xPathContext ; } }
Gets the validation context as XML validation context an raises exception if existing validation context is not a XML validation context .
296
23
28,315
private ScriptValidationContext getScriptValidationContext ( ) { if ( scriptValidationContext == null ) { scriptValidationContext = new ScriptValidationContext ( messageType . toString ( ) ) ; getAction ( ) . getValidationContexts ( ) . add ( scriptValidationContext ) ; } return scriptValidationContext ; }
Creates new script validation context if not done before and gets the script validation context .
72
17
28,316
private JsonPathMessageValidationContext getJsonPathValidationContext ( ) { if ( jsonPathValidationContext == null ) { jsonPathValidationContext = new JsonPathMessageValidationContext ( ) ; getAction ( ) . getValidationContexts ( ) . add ( jsonPathValidationContext ) ; } return jsonPathValidationContext ; }
Creates new JSONPath validation context if not done before and gets the validation context .
77
17
28,317
protected List < ValidationContext > parseValidationContexts ( Element messageElement , BeanDefinitionBuilder builder ) { List < ValidationContext > validationContexts = new ArrayList <> ( ) ; if ( messageElement != null ) { String messageType = messageElement . getAttribute ( "type" ) ; if ( ! StringUtils . hasText ( messageType ) ) { messageType = Citrus . DEFAULT_MESSAGE_TYPE ; } else { builder . addPropertyValue ( "messageType" , messageType ) ; } HeaderValidationContext headerValidationContext = new HeaderValidationContext ( ) ; validationContexts . add ( headerValidationContext ) ; String headerValidator = messageElement . getAttribute ( "header-validator" ) ; if ( StringUtils . hasText ( headerValidator ) ) { headerValidationContext . addHeaderValidator ( headerValidator ) ; } String headerValidatorExpression = messageElement . getAttribute ( "header-validators" ) ; if ( StringUtils . hasText ( headerValidatorExpression ) ) { Stream . of ( headerValidatorExpression . split ( "," ) ) . map ( String :: trim ) . forEach ( headerValidationContext :: addHeaderValidator ) ; } XmlMessageValidationContext xmlMessageValidationContext = getXmlMessageValidationContext ( messageElement ) ; validationContexts . add ( xmlMessageValidationContext ) ; XpathMessageValidationContext xPathMessageValidationContext = getXPathMessageValidationContext ( messageElement , xmlMessageValidationContext ) ; if ( ! xPathMessageValidationContext . getXpathExpressions ( ) . isEmpty ( ) ) { validationContexts . add ( xPathMessageValidationContext ) ; } JsonMessageValidationContext jsonMessageValidationContext = getJsonMessageValidationContext ( messageElement ) ; validationContexts . add ( jsonMessageValidationContext ) ; JsonPathMessageValidationContext jsonPathMessageValidationContext = getJsonPathMessageValidationContext ( messageElement ) ; if ( ! jsonPathMessageValidationContext . getJsonPathExpressions ( ) . isEmpty ( ) ) { validationContexts . add ( jsonPathMessageValidationContext ) ; } ScriptValidationContext scriptValidationContext = getScriptValidationContext ( messageElement , messageType ) ; if ( scriptValidationContext != null ) { validationContexts . add ( scriptValidationContext ) ; } ManagedList < RuntimeBeanReference > validators = new ManagedList <> ( ) ; String messageValidator = messageElement . getAttribute ( "validator" ) ; if ( StringUtils . hasText ( messageValidator ) ) { validators . add ( new RuntimeBeanReference ( messageValidator ) ) ; } String messageValidatorExpression = messageElement . getAttribute ( "validators" ) ; if ( StringUtils . hasText ( messageValidatorExpression ) ) { Stream . of ( messageValidatorExpression . split ( "," ) ) . map ( String :: trim ) . map ( RuntimeBeanReference :: new ) . forEach ( validators :: add ) ; } if ( ! validators . isEmpty ( ) ) { builder . addPropertyValue ( "validators" , validators ) ; } String dataDictionary = messageElement . getAttribute ( "data-dictionary" ) ; if ( StringUtils . hasText ( dataDictionary ) ) { builder . addPropertyReference ( "dataDictionary" , dataDictionary ) ; } } else { validationContexts . add ( new HeaderValidationContext ( ) ) ; } return validationContexts ; }
Parse message validation contexts .
782
6
28,318
protected List < VariableExtractor > getVariableExtractors ( Element element ) { List < VariableExtractor > variableExtractors = new ArrayList <> ( ) ; parseExtractHeaderElements ( element , variableExtractors ) ; Element extractElement = DomUtils . getChildElementByTagName ( element , "extract" ) ; if ( extractElement != null ) { Map < String , String > extractFromPath = new HashMap <> ( ) ; List < Element > messageValueElements = DomUtils . getChildElementsByTagName ( extractElement , "message" ) ; messageValueElements . addAll ( DomUtils . getChildElementsByTagName ( extractElement , "body" ) ) ; VariableExtractorParserUtil . parseMessageElement ( messageValueElements , extractFromPath ) ; if ( ! CollectionUtils . isEmpty ( extractFromPath ) ) { VariableExtractorParserUtil . addPayloadVariableExtractors ( element , variableExtractors , extractFromPath ) ; } } return variableExtractors ; }
Constructs a list of variable extractors .
231
9
28,319
private JsonMessageValidationContext getJsonMessageValidationContext ( Element messageElement ) { JsonMessageValidationContext context = new JsonMessageValidationContext ( ) ; if ( messageElement != null ) { Set < String > ignoreExpressions = new HashSet < String > ( ) ; List < ? > ignoreElements = DomUtils . getChildElementsByTagName ( messageElement , "ignore" ) ; for ( Iterator < ? > iter = ignoreElements . iterator ( ) ; iter . hasNext ( ) ; ) { Element ignoreValue = ( Element ) iter . next ( ) ; ignoreExpressions . add ( ignoreValue . getAttribute ( "path" ) ) ; } context . setIgnoreExpressions ( ignoreExpressions ) ; addSchemaInformationToValidationContext ( messageElement , context ) ; } return context ; }
Construct the basic Json message validation context .
182
9
28,320
private XmlMessageValidationContext getXmlMessageValidationContext ( Element messageElement ) { XmlMessageValidationContext context = new XmlMessageValidationContext ( ) ; if ( messageElement != null ) { addSchemaInformationToValidationContext ( messageElement , context ) ; Set < String > ignoreExpressions = new HashSet < String > ( ) ; List < ? > ignoreElements = DomUtils . getChildElementsByTagName ( messageElement , "ignore" ) ; for ( Iterator < ? > iter = ignoreElements . iterator ( ) ; iter . hasNext ( ) ; ) { Element ignoreValue = ( Element ) iter . next ( ) ; ignoreExpressions . add ( ignoreValue . getAttribute ( "path" ) ) ; } context . setIgnoreExpressions ( ignoreExpressions ) ; parseNamespaceValidationElements ( messageElement , context ) ; //Catch namespace declarations for namespace context Map < String , String > namespaces = new HashMap < String , String > ( ) ; List < ? > namespaceElements = DomUtils . getChildElementsByTagName ( messageElement , "namespace" ) ; if ( namespaceElements . size ( ) > 0 ) { for ( Iterator < ? > iter = namespaceElements . iterator ( ) ; iter . hasNext ( ) ; ) { Element namespaceElement = ( Element ) iter . next ( ) ; namespaces . put ( namespaceElement . getAttribute ( "prefix" ) , namespaceElement . getAttribute ( "value" ) ) ; } context . setNamespaces ( namespaces ) ; } } return context ; }
Construct the basic Xml message validation context .
345
9
28,321
private void addSchemaInformationToValidationContext ( Element messageElement , SchemaValidationContext context ) { String schemaValidation = messageElement . getAttribute ( "schema-validation" ) ; if ( StringUtils . hasText ( schemaValidation ) ) { context . setSchemaValidation ( Boolean . valueOf ( schemaValidation ) ) ; } String schema = messageElement . getAttribute ( "schema" ) ; if ( StringUtils . hasText ( schema ) ) { context . setSchema ( schema ) ; } String schemaRepository = messageElement . getAttribute ( "schema-repository" ) ; if ( StringUtils . hasText ( schemaRepository ) ) { context . setSchemaRepository ( schemaRepository ) ; } }
Adds information about the validation of the message against a certain schema to the context
167
15
28,322
private XpathMessageValidationContext getXPathMessageValidationContext ( Element messageElement , XmlMessageValidationContext parentContext ) { XpathMessageValidationContext context = new XpathMessageValidationContext ( ) ; parseXPathValidationElements ( messageElement , context ) ; context . setControlNamespaces ( parentContext . getControlNamespaces ( ) ) ; context . setNamespaces ( parentContext . getNamespaces ( ) ) ; context . setIgnoreExpressions ( parentContext . getIgnoreExpressions ( ) ) ; context . setSchema ( parentContext . getSchema ( ) ) ; context . setSchemaRepository ( parentContext . getSchemaRepository ( ) ) ; context . setSchemaValidation ( parentContext . isSchemaValidationEnabled ( ) ) ; context . setDTDResource ( parentContext . getDTDResource ( ) ) ; return context ; }
Construct the XPath message validation context .
194
8
28,323
private JsonPathMessageValidationContext getJsonPathMessageValidationContext ( Element messageElement ) { JsonPathMessageValidationContext context = new JsonPathMessageValidationContext ( ) ; //check for validate elements, these elements can either have script, jsonPath or namespace validation information //for now we only handle jsonPath validation Map < String , Object > validateJsonPathExpressions = new HashMap <> ( ) ; List < ? > validateElements = DomUtils . getChildElementsByTagName ( messageElement , "validate" ) ; if ( validateElements . size ( ) > 0 ) { for ( Iterator < ? > iter = validateElements . iterator ( ) ; iter . hasNext ( ) ; ) { Element validateElement = ( Element ) iter . next ( ) ; extractJsonPathValidateExpressions ( validateElement , validateJsonPathExpressions ) ; } context . setJsonPathExpressions ( validateJsonPathExpressions ) ; } return context ; }
Construct the JSONPath message validation context .
215
8
28,324
private ScriptValidationContext getScriptValidationContext ( Element messageElement , String messageType ) { ScriptValidationContext context = null ; boolean done = false ; List < ? > validateElements = DomUtils . getChildElementsByTagName ( messageElement , "validate" ) ; if ( validateElements . size ( ) > 0 ) { for ( Iterator < ? > iter = validateElements . iterator ( ) ; iter . hasNext ( ) ; ) { Element validateElement = ( Element ) iter . next ( ) ; Element scriptElement = DomUtils . getChildElementByTagName ( validateElement , "script" ) ; // check for nested validate script child node if ( scriptElement != null ) { if ( ! done ) { done = true ; } else { throw new BeanCreationException ( "Found multiple validation script definitions - " + "only supporting a single validation script for message validation" ) ; } context = new ScriptValidationContext ( messageType ) ; String type = scriptElement . getAttribute ( "type" ) ; context . setScriptType ( type ) ; String filePath = scriptElement . getAttribute ( "file" ) ; if ( StringUtils . hasText ( filePath ) ) { context . setValidationScriptResourcePath ( filePath ) ; if ( scriptElement . hasAttribute ( "charset" ) ) { context . setValidationScriptResourceCharset ( scriptElement . getAttribute ( "charset" ) ) ; } } else { context . setValidationScript ( DomUtils . getTextValue ( scriptElement ) ) ; } } } } return context ; }
Construct the message validation context .
346
6
28,325
private void extractXPathValidateExpressions ( Element validateElement , Map < String , Object > validateXpathExpressions ) { //check for xpath validation - old style with direct attribute String pathExpression = validateElement . getAttribute ( "path" ) ; if ( StringUtils . hasText ( pathExpression ) && ! JsonPathMessageValidationContext . isJsonPathExpression ( pathExpression ) ) { //construct pathExpression with explicit result-type, like boolean:/TestMessage/Value if ( validateElement . hasAttribute ( "result-type" ) ) { pathExpression = validateElement . getAttribute ( "result-type" ) + ":" + pathExpression ; } validateXpathExpressions . put ( pathExpression , validateElement . getAttribute ( "value" ) ) ; } //check for xpath validation elements - new style preferred List < ? > xpathElements = DomUtils . getChildElementsByTagName ( validateElement , "xpath" ) ; if ( xpathElements . size ( ) > 0 ) { for ( Iterator < ? > xpathIterator = xpathElements . iterator ( ) ; xpathIterator . hasNext ( ) ; ) { Element xpathElement = ( Element ) xpathIterator . next ( ) ; String expression = xpathElement . getAttribute ( "expression" ) ; if ( StringUtils . hasText ( expression ) ) { //construct expression with explicit result-type, like boolean:/TestMessage/Value if ( xpathElement . hasAttribute ( "result-type" ) ) { expression = xpathElement . getAttribute ( "result-type" ) + ":" + expression ; } validateXpathExpressions . put ( expression , xpathElement . getAttribute ( "value" ) ) ; } } } }
Extracts xpath validation expressions and fills map with them
387
12
28,326
private void extractJsonPathValidateExpressions ( Element validateElement , Map < String , Object > validateJsonPathExpressions ) { //check for jsonPath validation - old style with direct attribute String pathExpression = validateElement . getAttribute ( "path" ) ; if ( JsonPathMessageValidationContext . isJsonPathExpression ( pathExpression ) ) { validateJsonPathExpressions . put ( pathExpression , validateElement . getAttribute ( "value" ) ) ; } //check for jsonPath validation elements - new style preferred ValidateMessageParserUtil . parseJsonPathElements ( validateElement , validateJsonPathExpressions ) ; }
Extracts jsonPath validation expressions and fills map with them
143
12
28,327
protected void addImportedSchemas ( Schema schema ) throws WSDLException , IOException , TransformerException , TransformerFactoryConfigurationError { for ( Object imports : schema . getImports ( ) . values ( ) ) { for ( SchemaImport schemaImport : ( Vector < SchemaImport > ) imports ) { // Prevent duplicate imports if ( ! importedSchemas . contains ( schemaImport . getNamespaceURI ( ) ) ) { importedSchemas . add ( schemaImport . getNamespaceURI ( ) ) ; Schema referencedSchema = schemaImport . getReferencedSchema ( ) ; if ( referencedSchema != null ) { ByteArrayOutputStream bos = new ByteArrayOutputStream ( ) ; Source source = new DOMSource ( referencedSchema . getElement ( ) ) ; Result result = new StreamResult ( bos ) ; TransformerFactory . newInstance ( ) . newTransformer ( ) . transform ( source , result ) ; Resource schemaResource = new ByteArrayResource ( bos . toByteArray ( ) ) ; addImportedSchemas ( referencedSchema ) ; schemaResources . add ( schemaResource ) ; } } } } }
Recursively add all imported schemas as schema resource . This is necessary when schema import are located in jar files . If they are not added immediately the reference to them is lost .
244
37
28,328
protected void addIncludedSchemas ( Schema schema ) throws WSDLException , IOException , TransformerException , TransformerFactoryConfigurationError { List < SchemaReference > includes = schema . getIncludes ( ) ; for ( SchemaReference schemaReference : includes ) { String schemaLocation ; URI locationURI = URI . create ( schemaReference . getSchemaLocationURI ( ) ) ; if ( locationURI . isAbsolute ( ) ) { schemaLocation = schemaReference . getSchemaLocationURI ( ) ; } else { schemaLocation = schema . getDocumentBaseURI ( ) . substring ( 0 , schema . getDocumentBaseURI ( ) . lastIndexOf ( ' ' ) + 1 ) + schemaReference . getSchemaLocationURI ( ) ; } schemaResources . add ( new FileSystemResource ( schemaLocation ) ) ; } }
Recursively add all included schemas as schema resource .
177
12
28,329
public NamespaceContext buildContext ( Message receivedMessage , Map < String , String > namespaces ) { SimpleNamespaceContext simpleNamespaceContext = new SimpleNamespaceContext ( ) ; //first add default namespace definitions if ( namespaceMappings . size ( ) > 0 ) { simpleNamespaceContext . setBindings ( namespaceMappings ) ; } Map < String , String > dynamicBindings = XMLUtils . lookupNamespaces ( receivedMessage . getPayload ( String . class ) ) ; if ( ! CollectionUtils . isEmpty ( namespaces ) ) { //dynamic binding of namespaces declarations in root element of received message for ( Entry < String , String > binding : dynamicBindings . entrySet ( ) ) { //only bind namespace that is not present in explicit namespace bindings if ( ! namespaces . containsValue ( binding . getValue ( ) ) ) { simpleNamespaceContext . bindNamespaceUri ( binding . getKey ( ) , binding . getValue ( ) ) ; } } //add explicit namespace bindings simpleNamespaceContext . setBindings ( namespaces ) ; } else { simpleNamespaceContext . setBindings ( dynamicBindings ) ; } return simpleNamespaceContext ; }
Construct a basic namespace context from the received message and explicit namespace mappings .
253
15
28,330
public void addMessageSelectorFactory ( MessageSelectorFactory < ? > factory ) { if ( factory instanceof BeanFactoryAware ) { ( ( BeanFactoryAware ) factory ) . setBeanFactory ( beanFactory ) ; } this . factories . add ( factory ) ; }
Add message selector factory to list of delegates .
59
9
28,331
public static void resolveValidationMatcher ( String fieldName , String fieldValue , String validationMatcherExpression , TestContext context ) { String expression = VariableUtils . cutOffVariablesPrefix ( cutOffValidationMatchersPrefix ( validationMatcherExpression ) ) ; if ( expression . equals ( "ignore" ) ) { expression += "()" ; } int bodyStart = expression . indexOf ( ' ' ) ; if ( bodyStart < 0 ) { throw new CitrusRuntimeException ( "Illegal syntax for validation matcher expression - missing validation value in '()' function body" ) ; } String prefix = "" ; if ( expression . indexOf ( ' ' ) > 0 && expression . indexOf ( ' ' ) < bodyStart ) { prefix = expression . substring ( 0 , expression . indexOf ( ' ' ) + 1 ) ; } String matcherValue = expression . substring ( bodyStart + 1 , expression . length ( ) - 1 ) ; String matcherName = expression . substring ( prefix . length ( ) , bodyStart ) ; ValidationMatcherLibrary library = context . getValidationMatcherRegistry ( ) . getLibraryForPrefix ( prefix ) ; ValidationMatcher validationMatcher = library . getValidationMatcher ( matcherName ) ; ControlExpressionParser controlExpressionParser = lookupControlExpressionParser ( validationMatcher ) ; List < String > params = controlExpressionParser . extractControlValues ( matcherValue , null ) ; List < String > replacedParams = replaceVariablesAndFunctionsInParameters ( params , context ) ; validationMatcher . validate ( fieldName , fieldValue , replacedParams , context ) ; }
This method resolves a custom validationMatcher to its respective result .
360
13
28,332
public static boolean isValidationMatcherExpression ( String expression ) { return expression . startsWith ( Citrus . VALIDATION_MATCHER_PREFIX ) && expression . endsWith ( Citrus . VALIDATION_MATCHER_SUFFIX ) ; }
Checks if expression is a validation matcher expression .
59
11
28,333
private static String cutOffValidationMatchersPrefix ( String expression ) { if ( expression . startsWith ( Citrus . VALIDATION_MATCHER_PREFIX ) && expression . endsWith ( Citrus . VALIDATION_MATCHER_SUFFIX ) ) { return expression . substring ( Citrus . VALIDATION_MATCHER_PREFIX . length ( ) , expression . length ( ) - Citrus . VALIDATION_MATCHER_SUFFIX . length ( ) ) ; } return expression ; }
Cut off validation matchers prefix and suffix .
117
9
28,334
public BeanInvocation sayHello ( String message ) { BeanInvocation invocation = new BeanInvocation ( ) ; try { invocation . setMethod ( HelloService . class . getMethod ( "sayHello" , String . class ) ) ; invocation . setArgs ( new Object [ ] { message } ) ; } catch ( NoSuchMethodException e ) { throw new CitrusRuntimeException ( "Failed to access remote service method" , e ) ; } return invocation ; }
Creates bean invocation for hello service call .
98
9
28,335
public void apply ( CitrusAppConfiguration configuration ) { setPackages ( configuration . getPackages ( ) ) ; setTestClasses ( configuration . getTestClasses ( ) ) ; setIncludes ( configuration . getIncludes ( ) ) ; addDefaultProperties ( configuration . getDefaultProperties ( ) ) ; }
Applies configuration with settable properties at runtime .
66
10
28,336
public static String getRandomString ( int numberOfLetters , char [ ] alphabet , boolean includeNumbers ) { StringBuilder builder = new StringBuilder ( ) ; int upperRange = alphabet . length - 1 ; // make sure first character is not a number builder . append ( alphabet [ generator . nextInt ( upperRange ) ] ) ; if ( includeNumbers ) { upperRange += NUMBERS . length ; } for ( int i = 1 ; i < numberOfLetters ; i ++ ) { int letterIndex = generator . nextInt ( upperRange ) ; if ( letterIndex > alphabet . length - 1 ) { builder . append ( NUMBERS [ letterIndex - alphabet . length ] ) ; } else { builder . append ( alphabet [ letterIndex ] ) ; } } return builder . toString ( ) ; }
Static random number generator aware string generating method .
170
9
28,337
public ValidationMatcher getValidationMatcher ( String validationMatcherName ) throws NoSuchValidationMatcherException { if ( ! members . containsKey ( validationMatcherName ) ) { throw new NoSuchValidationMatcherException ( "Can not find validation matcher " + validationMatcherName + " in library " + name + " (" + prefix + ")" ) ; } return members . get ( validationMatcherName ) ; }
Try to find validationMatcher in library by name .
94
11
28,338
public boolean knowsValidationMatcher ( String validationMatcherName ) { // custom libraries: if ( validationMatcherName . contains ( ":" ) ) { String validationMatcherPrefix = validationMatcherName . substring ( 0 , validationMatcherName . indexOf ( ' ' ) + 1 ) ; if ( ! validationMatcherPrefix . equals ( prefix ) ) { return false ; } return members . containsKey ( validationMatcherName . substring ( validationMatcherName . indexOf ( ' ' ) + 1 , validationMatcherName . indexOf ( ' ' ) ) ) ; } else { // standard citrus-library without prefix: return members . containsKey ( validationMatcherName . substring ( 0 , validationMatcherName . indexOf ( ' ' ) ) ) ; } }
Does this library know a validationMatcher with the given name .
169
13
28,339
private boolean containsNumericMatcher ( String matcherExpression ) { for ( String numericMatcher : numericMatchers ) { if ( matcherExpression . contains ( numericMatcher ) ) { return true ; } } return false ; }
Checks for numeric matcher presence in expression .
51
10
28,340
private WebSocketMessage < ? > receive ( WebSocketEndpointConfiguration config , long timeout ) { long timeLeft = timeout ; WebSocketMessage < ? > message = config . getHandler ( ) . getMessage ( ) ; String path = endpointConfiguration . getEndpointUri ( ) ; while ( message == null && timeLeft > 0 ) { timeLeft -= endpointConfiguration . getPollingInterval ( ) ; long sleep = timeLeft > 0 ? endpointConfiguration . getPollingInterval ( ) : endpointConfiguration . getPollingInterval ( ) + timeLeft ; if ( LOG . isDebugEnabled ( ) ) { String msg = "Waiting for message on '%s' - retrying in %s ms" ; LOG . debug ( String . format ( msg , path , ( sleep ) ) ) ; } try { Thread . sleep ( sleep ) ; } catch ( InterruptedException e ) { LOG . warn ( String . format ( "Thread interrupted while waiting for message on '%s'" , path ) , e ) ; } message = config . getHandler ( ) . getMessage ( ) ; } if ( message == null ) { throw new ActionTimeoutException ( String . format ( "Action timed out while receiving message on '%s'" , path ) ) ; } return message ; }
Receive web socket message by polling on web socket handler for incoming message .
271
15
28,341
private Stack < String > parseTargets ( ) { Stack < String > stack = new Stack < String > ( ) ; String [ ] targetTokens = targets . split ( "," ) ; for ( String targetToken : targetTokens ) { stack . add ( targetToken . trim ( ) ) ; } return stack ; }
Converts comma delimited string to stack .
67
9
28,342
private void loadBuildPropertyFile ( Project project , TestContext context ) { if ( StringUtils . hasText ( propertyFilePath ) ) { String propertyFileResource = context . replaceDynamicContentInString ( propertyFilePath ) ; log . info ( "Reading build property file: " + propertyFileResource ) ; Properties fileProperties ; try { fileProperties = PropertiesLoaderUtils . loadProperties ( new PathMatchingResourcePatternResolver ( ) . getResource ( propertyFileResource ) ) ; for ( Entry < Object , Object > entry : fileProperties . entrySet ( ) ) { String propertyValue = entry . getValue ( ) != null ? context . replaceDynamicContentInString ( entry . getValue ( ) . toString ( ) ) : "" ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Set build property from file resource: " + entry . getKey ( ) + "=" + propertyValue ) ; } project . setProperty ( entry . getKey ( ) . toString ( ) , propertyValue ) ; } } catch ( IOException e ) { throw new CitrusRuntimeException ( "Failed to read build property file" , e ) ; } } }
Loads build properties from file resource and adds them to ANT project .
254
15
28,343
public static String build ( String messageSelector , Map < String , Object > messageSelectorMap , TestContext context ) { if ( StringUtils . hasText ( messageSelector ) ) { return context . replaceDynamicContentInString ( messageSelector ) ; } else if ( ! CollectionUtils . isEmpty ( messageSelectorMap ) ) { return MessageSelectorBuilder . fromKeyValueMap ( context . resolveDynamicValuesInMap ( messageSelectorMap ) ) . build ( ) ; } return "" ; }
Build message selector from string expression or from key value map . Automatically replaces test variables .
109
18
28,344
public static MessageSelectorBuilder fromKeyValueMap ( Map < String , Object > valueMap ) { StringBuffer buf = new StringBuffer ( ) ; Iterator < Entry < String , Object > > iter = valueMap . entrySet ( ) . iterator ( ) ; if ( iter . hasNext ( ) ) { Entry < String , Object > entry = iter . next ( ) ; String key = entry . getKey ( ) ; String value = entry . getValue ( ) . toString ( ) ; buf . append ( key + " = '" + value + "'" ) ; } while ( iter . hasNext ( ) ) { Entry < String , Object > entry = iter . next ( ) ; String key = entry . getKey ( ) ; String value = entry . getValue ( ) . toString ( ) ; buf . append ( " AND " + key + " = '" + value + "'" ) ; } return new MessageSelectorBuilder ( buf . toString ( ) ) ; }
Static builder method using a key value map .
209
9
28,345
public Map < String , String > toKeyValueMap ( ) { Map < String , String > valueMap = new HashMap < String , String > ( ) ; String [ ] tokens ; if ( selectorString . contains ( " AND" ) ) { String [ ] chunks = selectorString . split ( " AND" ) ; for ( String chunk : chunks ) { tokens = escapeEqualsFromXpathNodeTest ( chunk ) . split ( "=" ) ; valueMap . put ( unescapeEqualsFromXpathNodeTest ( tokens [ 0 ] . trim ( ) ) , tokens [ 1 ] . trim ( ) . substring ( 1 , tokens [ 1 ] . trim ( ) . length ( ) - 1 ) ) ; } } else { tokens = escapeEqualsFromXpathNodeTest ( selectorString ) . split ( "=" ) ; valueMap . put ( unescapeEqualsFromXpathNodeTest ( tokens [ 0 ] . trim ( ) ) , tokens [ 1 ] . trim ( ) . substring ( 1 , tokens [ 1 ] . trim ( ) . length ( ) - 1 ) ) ; } return valueMap ; }
Constructs a key value map from selector string representation .
238
11
28,346
private void doAutoSleep ( ) { if ( autoSleep > 0 ) { log . info ( "Sleeping " + autoSleep + " milliseconds" ) ; try { Thread . sleep ( autoSleep ) ; } catch ( InterruptedException e ) { log . error ( "Error during doc generation" , e ) ; } log . info ( "Returning after " + autoSleep + " milliseconds" ) ; } }
Sleep amount of time in between iterations .
88
8
28,347
private void send ( Message message , String destinationName , TestContext context ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "Sending JMS message to destination: '" + destinationName + "'" ) ; } endpointConfiguration . getJmsTemplate ( ) . send ( destinationName , session -> { javax . jms . Message jmsMessage = endpointConfiguration . getMessageConverter ( ) . createJmsMessage ( message , session , endpointConfiguration , context ) ; endpointConfiguration . getMessageConverter ( ) . convertOutbound ( jmsMessage , message , endpointConfiguration , context ) ; return jmsMessage ; } ) ; log . info ( "Message was sent to JMS destination: '" + destinationName + "'" ) ; }
Send message using destination name .
166
6
28,348
private void send ( Message message , Destination destination , TestContext context ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "Sending JMS message to destination: '" + endpointConfiguration . getDestinationName ( destination ) + "'" ) ; } endpointConfiguration . getJmsTemplate ( ) . send ( destination , session -> { javax . jms . Message jmsMessage = endpointConfiguration . getMessageConverter ( ) . createJmsMessage ( message , session , endpointConfiguration , context ) ; endpointConfiguration . getMessageConverter ( ) . convertOutbound ( jmsMessage , message , endpointConfiguration , context ) ; return jmsMessage ; } ) ; log . info ( "Message was sent to JMS destination: '" + endpointConfiguration . getDestinationName ( destination ) + "'" ) ; }
Send message using destination .
180
5
28,349
protected void configureMessageController ( ApplicationContext context ) { if ( context . containsBean ( MESSAGE_CONTROLLER_BEAN_NAME ) ) { HttpMessageController messageController = context . getBean ( MESSAGE_CONTROLLER_BEAN_NAME , HttpMessageController . class ) ; EndpointAdapter endpointAdapter = httpServer . getEndpointAdapter ( ) ; HttpEndpointConfiguration endpointConfiguration = new HttpEndpointConfiguration ( ) ; endpointConfiguration . setMessageConverter ( httpServer . getMessageConverter ( ) ) ; endpointConfiguration . setHeaderMapper ( DefaultHttpHeaderMapper . inboundMapper ( ) ) ; endpointConfiguration . setHandleAttributeHeaders ( httpServer . isHandleAttributeHeaders ( ) ) ; endpointConfiguration . setHandleCookies ( httpServer . isHandleCookies ( ) ) ; endpointConfiguration . setDefaultStatusCode ( httpServer . getDefaultStatusCode ( ) ) ; messageController . setEndpointConfiguration ( endpointConfiguration ) ; if ( endpointAdapter != null ) { messageController . setEndpointAdapter ( endpointAdapter ) ; } } }
Post process message controller .
244
5
28,350
protected void configureMessageConverter ( ApplicationContext context ) { if ( context . containsBean ( MESSAGE_CONVERTER_BEAN_NAME ) ) { HttpMessageConverter messageConverter = context . getBean ( MESSAGE_CONVERTER_BEAN_NAME , HttpMessageConverter . class ) ; if ( messageConverter instanceof DelegatingHttpEntityMessageConverter ) { ( ( DelegatingHttpEntityMessageConverter ) messageConverter ) . setBinaryMediaTypes ( httpServer . getBinaryMediaTypes ( ) ) ; } } }
Post process message converter .
136
5
28,351
private List < HandlerInterceptor > adaptInterceptors ( List < Object > interceptors , ApplicationContext context ) { List < HandlerInterceptor > handlerInterceptors = new ArrayList < HandlerInterceptor > ( ) ; if ( context . containsBean ( LOGGING_INTERCEPTOR_BEAN_NAME ) ) { LoggingHandlerInterceptor loggingInterceptor = context . getBean ( LOGGING_INTERCEPTOR_BEAN_NAME , LoggingHandlerInterceptor . class ) ; handlerInterceptors . add ( loggingInterceptor ) ; } if ( interceptors != null ) { for ( Object interceptor : interceptors ) { if ( interceptor instanceof MappedInterceptor ) { handlerInterceptors . add ( new MappedInterceptorAdapter ( ( MappedInterceptor ) interceptor , new UrlPathHelper ( ) , new AntPathMatcher ( ) ) ) ; } else if ( interceptor instanceof HandlerInterceptor ) { handlerInterceptors . add ( ( HandlerInterceptor ) interceptor ) ; } else if ( interceptor instanceof WebRequestInterceptor ) { handlerInterceptors . add ( new WebRequestHandlerInterceptorAdapter ( ( WebRequestInterceptor ) interceptor ) ) ; } else { log . warn ( "Unsupported interceptor type: {}" , interceptor . getClass ( ) . getName ( ) ) ; } } } return handlerInterceptors ; }
Adapts object list to handler interceptors .
300
9
28,352
public TransformActionBuilder source ( Resource xmlResource , Charset charset ) { try { action . setXmlData ( FileUtils . readToString ( xmlResource , charset ) ) ; } catch ( IOException e ) { throw new CitrusRuntimeException ( "Failed to read xml resource" , e ) ; } return this ; }
Set the XML document as resource
74
6
28,353
public TransformActionBuilder xslt ( Resource xsltResource , Charset charset ) { try { action . setXsltData ( FileUtils . readToString ( xsltResource , charset ) ) ; } catch ( IOException e ) { throw new CitrusRuntimeException ( "Failed to read xstl resource" , e ) ; } return this ; }
Set the XSLT document as resource
83
8
28,354
public DataSet createDataSet ( final Message response , final MessageType messageType ) { try { if ( response . getPayload ( ) instanceof DataSet ) { return response . getPayload ( DataSet . class ) ; } else if ( isReadyToMarshal ( response , messageType ) ) { return marshalResponse ( response , messageType ) ; } else { return new DataSet ( ) ; } } catch ( final SQLException e ) { throw new CitrusRuntimeException ( "Failed to read dataSet from response message" , e ) ; } }
Converts Citrus result set representation to db driver model result set .
122
14
28,355
private DataSet marshalResponse ( final Message response , final MessageType messageType ) throws SQLException { String dataSet = null ; if ( response instanceof JdbcMessage || response . getPayload ( ) instanceof OperationResult ) { dataSet = response . getPayload ( OperationResult . class ) . getDataSet ( ) ; } else { try { JdbcMarshaller jdbcMarshaller = new JdbcMarshaller ( ) ; jdbcMarshaller . setType ( messageType . name ( ) ) ; Object object = jdbcMarshaller . unmarshal ( new StringSource ( response . getPayload ( String . class ) ) ) ; if ( object instanceof OperationResult && StringUtils . hasText ( ( ( OperationResult ) object ) . getDataSet ( ) ) ) { dataSet = ( ( OperationResult ) object ) . getDataSet ( ) ; } } catch ( CitrusRuntimeException e ) { dataSet = response . getPayload ( String . class ) ; } } if ( isJsonResponse ( messageType ) ) { return new JsonDataSetProducer ( Optional . ofNullable ( dataSet ) . orElse ( "[]" ) ) . produce ( ) ; } else if ( isXmlResponse ( messageType ) ) { return new XmlDataSetProducer ( Optional . ofNullable ( dataSet ) . orElse ( "<dataset></dataset>" ) ) . produce ( ) ; } else { throw new CitrusRuntimeException ( "Unable to create dataSet from data type " + messageType . name ( ) ) ; } }
Marshals the given message to the requested MessageType
352
10
28,356
public boolean canValidate ( Document doc ) { XsdSchema schema = schemaMappingStrategy . getSchema ( schemas , doc ) ; return schema != null ; }
Find the matching schema for document using given schema mapping strategy .
38
12
28,357
protected void addCitrusSchema ( String schemaName ) throws IOException , SAXException , ParserConfigurationException { Resource resource = new PathMatchingResourcePatternResolver ( ) . getResource ( "classpath:com/consol/citrus/schema/" + schemaName + ".xsd" ) ; if ( resource . exists ( ) ) { addXsdSchema ( resource ) ; } }
Adds Citrus message schema to repository if available on classpath .
88
13
28,358
private void copyToStream ( String txt , OutputStream stream ) throws IOException { if ( txt != null ) { stream . write ( txt . getBytes ( ) ) ; } }
Copy character sequence to outbput stream .
41
9
28,359
public void addControl ( Control control ) { if ( controls == null ) { controls = new FormData . Controls ( ) ; } this . controls . add ( control ) ; }
Adds new form control .
37
5
28,360
public List < SimpleJsonSchema > filter ( List < JsonSchemaRepository > schemaRepositories , JsonMessageValidationContext jsonMessageValidationContext , ApplicationContext applicationContext ) { if ( isSchemaRepositorySpecified ( jsonMessageValidationContext ) ) { return filterByRepositoryName ( schemaRepositories , jsonMessageValidationContext ) ; } else if ( isSchemaSpecified ( jsonMessageValidationContext ) ) { return getSchemaFromContext ( jsonMessageValidationContext , applicationContext ) ; } else { return mergeRepositories ( schemaRepositories ) ; } }
Filters the all schema repositories based on the configuration in the jsonMessageValidationContext and returns a list of relevant schemas for the validation
128
28
28,361
private List < SimpleJsonSchema > getSchemaFromContext ( JsonMessageValidationContext jsonMessageValidationContext , ApplicationContext applicationContext ) { try { SimpleJsonSchema simpleJsonSchema = applicationContext . getBean ( jsonMessageValidationContext . getSchema ( ) , SimpleJsonSchema . class ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Found specified schema: \"" + jsonMessageValidationContext . getSchema ( ) + "\"." ) ; } return Collections . singletonList ( simpleJsonSchema ) ; } catch ( NoSuchBeanDefinitionException e ) { throw new CitrusRuntimeException ( "Could not find the specified schema: \"" + jsonMessageValidationContext . getSchema ( ) + "\"." , e ) ; } }
Extracts the the schema specified in the jsonMessageValidationContext from the application context
180
18
28,362
private List < SimpleJsonSchema > filterByRepositoryName ( List < JsonSchemaRepository > schemaRepositories , JsonMessageValidationContext jsonMessageValidationContext ) { for ( JsonSchemaRepository jsonSchemaRepository : schemaRepositories ) { if ( Objects . equals ( jsonSchemaRepository . getName ( ) , jsonMessageValidationContext . getSchemaRepository ( ) ) ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "Found specified schema-repository: \"" + jsonMessageValidationContext . getSchemaRepository ( ) + "\"." ) ; } return jsonSchemaRepository . getSchemas ( ) ; } } throw new CitrusRuntimeException ( "Could not find the specified schema repository: " + "\"" + jsonMessageValidationContext . getSchemaRepository ( ) + "\"." ) ; }
Filters the schema repositories by the name configured in the jsonMessageValidationContext
197
16
28,363
private List < SimpleJsonSchema > mergeRepositories ( List < JsonSchemaRepository > schemaRepositories ) { return schemaRepositories . stream ( ) . map ( JsonSchemaRepository :: getSchemas ) . flatMap ( List :: stream ) . collect ( Collectors . toList ( ) ) ; }
Merges the list of given schema repositories to one unified list of json schemas
70
16
28,364
public static final void injectAll ( final Object target , final Citrus citrusFramework ) { injectAll ( target , citrusFramework , citrusFramework . createTestContext ( ) ) ; }
Creates new Citrus test context and injects all supported components and endpoints to target object using annotations .
40
22
28,365
public static final void injectAll ( final Object target , final Citrus citrusFramework , final TestContext context ) { injectCitrusFramework ( target , citrusFramework ) ; injectEndpoints ( target , context ) ; }
Injects all supported components and endpoints to target object using annotations .
48
15
28,366
private Map < String , String > getCustomHeaders ( HttpHeaders httpHeaders , Map < String , Object > mappedHeaders ) { Map < String , String > customHeaders = new HashMap <> ( ) ; for ( Map . Entry < String , List < String > > header : httpHeaders . entrySet ( ) ) { if ( ! mappedHeaders . containsKey ( header . getKey ( ) ) ) { customHeaders . put ( header . getKey ( ) , StringUtils . collectionToCommaDelimitedString ( header . getValue ( ) ) ) ; } } return customHeaders ; }
Message headers consist of standard HTTP message headers and custom headers . This method assumes that all header entries that were not initially mapped by header mapper implementations are custom headers .
136
33
28,367
private HttpHeaders createHttpHeaders ( HttpMessage httpMessage , HttpEndpointConfiguration endpointConfiguration ) { HttpHeaders httpHeaders = new HttpHeaders ( ) ; endpointConfiguration . getHeaderMapper ( ) . fromHeaders ( new org . springframework . messaging . MessageHeaders ( httpMessage . getHeaders ( ) ) , httpHeaders ) ; Map < String , Object > messageHeaders = httpMessage . getHeaders ( ) ; for ( Map . Entry < String , Object > header : messageHeaders . entrySet ( ) ) { if ( ! header . getKey ( ) . startsWith ( MessageHeaders . PREFIX ) && ! MessageHeaderUtils . isSpringInternalHeader ( header . getKey ( ) ) && ! httpHeaders . containsKey ( header . getKey ( ) ) ) { httpHeaders . add ( header . getKey ( ) , header . getValue ( ) . toString ( ) ) ; } } if ( httpHeaders . getFirst ( HttpMessageHeaders . HTTP_CONTENT_TYPE ) == null ) { httpHeaders . add ( HttpMessageHeaders . HTTP_CONTENT_TYPE , composeContentTypeHeaderValue ( endpointConfiguration ) ) ; } return httpHeaders ; }
Creates HttpHeaders based on the outbound message and the endpoint configurations header mapper .
271
20
28,368
private HttpEntity < ? > createHttpEntity ( HttpHeaders httpHeaders , Object payload , HttpMethod method ) { if ( httpMethodSupportsBody ( method ) ) { return new HttpEntity <> ( payload , httpHeaders ) ; } else { return new HttpEntity <> ( httpHeaders ) ; } }
Composes a HttpEntity based on the given parameters
73
11
28,369
private HttpMessage convertOutboundMessage ( Message message ) { HttpMessage httpMessage ; if ( message instanceof HttpMessage ) { httpMessage = ( HttpMessage ) message ; } else { httpMessage = new HttpMessage ( message ) ; } return httpMessage ; }
Converts the outbound Message object into a HttpMessage
59
12
28,370
private boolean httpMethodSupportsBody ( HttpMethod method ) { return HttpMethod . POST . equals ( method ) || HttpMethod . PUT . equals ( method ) || HttpMethod . DELETE . equals ( method ) || HttpMethod . PATCH . equals ( method ) ; }
Determines whether the given message type supports a message body
64
12
28,371
private String composeContentTypeHeaderValue ( HttpEndpointConfiguration endpointConfiguration ) { return ( endpointConfiguration . getContentType ( ) . contains ( "charset" ) || ! StringUtils . hasText ( endpointConfiguration . getCharset ( ) ) ) ? endpointConfiguration . getContentType ( ) : endpointConfiguration . getContentType ( ) + ";charset=" + endpointConfiguration . getCharset ( ) ; }
Creates the content type header value enriched with charset information if possible
93
14
28,372
public static void setPropertyValue ( BeanDefinitionBuilder builder , String propertyValue , String propertyName ) { if ( StringUtils . hasText ( propertyValue ) ) { builder . addPropertyValue ( propertyName , propertyValue ) ; } }
Sets the property value on bean definition in case value is set properly .
50
15
28,373
public static void setConstructorArgValue ( BeanDefinitionBuilder builder , String propertyValue ) { if ( StringUtils . hasText ( propertyValue ) ) { builder . addConstructorArgValue ( propertyValue ) ; } }
Sets the property value on bean definition as constructor argument in case value is not null .
47
18
28,374
public static BeanDefinitionHolder registerBean ( String beanId , Class < ? > beanClass , ParserContext parserContext , boolean shouldFireEvents ) { return registerBean ( beanId , BeanDefinitionBuilder . genericBeanDefinition ( beanClass ) . getBeanDefinition ( ) , parserContext , shouldFireEvents ) ; }
Creates new bean definition from bean class and registers new bean in parser registry . Returns bean definition holder .
70
21
28,375
public static BeanDefinitionHolder registerBean ( String beanId , BeanDefinition beanDefinition , ParserContext parserContext , boolean shouldFireEvents ) { if ( parserContext . getRegistry ( ) . containsBeanDefinition ( beanId ) ) { return new BeanDefinitionHolder ( parserContext . getRegistry ( ) . getBeanDefinition ( beanId ) , beanId ) ; } BeanDefinitionHolder configurationHolder = new BeanDefinitionHolder ( beanDefinition , beanId ) ; BeanDefinitionReaderUtils . registerBeanDefinition ( configurationHolder , parserContext . getRegistry ( ) ) ; if ( shouldFireEvents ) { BeanComponentDefinition componentDefinition = new BeanComponentDefinition ( configurationHolder ) ; parserContext . registerComponent ( componentDefinition ) ; } return configurationHolder ; }
Registers bean definition in parser registry and returns bean definition holder .
168
13
28,376
private static boolean isDesignerMethod ( Method method ) { Class < ? > [ ] parameterTypes = method . getParameterTypes ( ) ; for ( Class < ? > parameterType : parameterTypes ) { if ( parameterType . isAssignableFrom ( TestDesigner . class ) ) { return true ; } } return false ; }
Searches for method parameter of type test designer .
70
11
28,377
private static boolean isDesignerClass ( Class < ? > type ) { return Stream . of ( type . getDeclaredFields ( ) ) . anyMatch ( field -> TestDesigner . class . isAssignableFrom ( field . getType ( ) ) ) ; }
Searches for field of type test designer .
58
10
28,378
private static boolean isRunnerMethod ( Method method ) { Class < ? > [ ] parameterTypes = method . getParameterTypes ( ) ; for ( Class < ? > parameterType : parameterTypes ) { if ( parameterType . isAssignableFrom ( TestRunner . class ) ) { return true ; } } return false ; }
Searches for method parameter of type test runner .
68
11
28,379
private static boolean isRunnerClass ( Class < ? > type ) { return Stream . of ( type . getDeclaredFields ( ) ) . anyMatch ( field -> TestRunner . class . isAssignableFrom ( field . getType ( ) ) ) ; }
Searches for field of type test runner .
56
10
28,380
public static String getValueFromScript ( String scriptEngine , String code ) { try { ScriptEngine engine = new ScriptEngineManager ( ) . getEngineByName ( scriptEngine ) ; if ( engine == null ) { throw new CitrusRuntimeException ( "Unable to find script engine with name '" + scriptEngine + "'" ) ; } return engine . eval ( code ) . toString ( ) ; } catch ( ScriptException e ) { throw new CitrusRuntimeException ( "Failed to evaluate " + scriptEngine + " script" , e ) ; } }
Evaluates script code and returns a variable value as result .
119
13
28,381
public static String cutOffSingleQuotes ( String variable ) { if ( StringUtils . hasText ( variable ) && variable . length ( ) > 1 && variable . charAt ( 0 ) == ' ' && variable . charAt ( variable . length ( ) - 1 ) == ' ' ) { return variable . substring ( 1 , variable . length ( ) - 1 ) ; } return variable ; }
Cut off single quotes prefix and suffix .
83
8
28,382
public static String cutOffDoubleQuotes ( String variable ) { if ( StringUtils . hasText ( variable ) && variable . length ( ) > 1 && variable . charAt ( 0 ) == ' ' && variable . charAt ( variable . length ( ) - 1 ) == ' ' ) { return variable . substring ( 1 , variable . length ( ) - 1 ) ; } return variable ; }
Cut off double quotes prefix and suffix .
83
8
28,383
public static String cutOffVariablesPrefix ( String variable ) { if ( variable . startsWith ( Citrus . VARIABLE_PREFIX ) && variable . endsWith ( Citrus . VARIABLE_SUFFIX ) ) { return variable . substring ( Citrus . VARIABLE_PREFIX . length ( ) , variable . length ( ) - Citrus . VARIABLE_SUFFIX . length ( ) ) ; } return variable ; }
Cut off variables prefix
103
4
28,384
public static String cutOffVariablesEscaping ( String variable ) { if ( variable . startsWith ( Citrus . VARIABLE_ESCAPE ) && variable . endsWith ( Citrus . VARIABLE_ESCAPE ) ) { return variable . substring ( Citrus . VARIABLE_ESCAPE . length ( ) , variable . length ( ) - Citrus . VARIABLE_ESCAPE . length ( ) ) ; } return variable ; }
Cut off variables escaping
103
4
28,385
public static boolean isVariableName ( final String expression ) { if ( expression == null || expression . length ( ) == 0 ) { return false ; } if ( expression . startsWith ( Citrus . VARIABLE_PREFIX ) && expression . endsWith ( Citrus . VARIABLE_SUFFIX ) ) { return true ; } return false ; }
Checks whether a given expression is a variable name .
78
11
28,386
public static String replaceVariablesInString ( final String str , TestContext context , boolean enableQuoting ) { StringBuffer newStr = new StringBuffer ( ) ; boolean isVarComplete ; StringBuffer variableNameBuf = new StringBuffer ( ) ; int startIndex = 0 ; int curIndex ; int searchIndex ; while ( ( searchIndex = str . indexOf ( Citrus . VARIABLE_PREFIX , startIndex ) ) != - 1 ) { int control = 0 ; isVarComplete = false ; curIndex = searchIndex + Citrus . VARIABLE_PREFIX . length ( ) ; while ( curIndex < str . length ( ) && ! isVarComplete ) { if ( str . indexOf ( Citrus . VARIABLE_PREFIX , curIndex ) == curIndex ) { control ++ ; } if ( ( ! Character . isJavaIdentifierPart ( str . charAt ( curIndex ) ) && ( str . charAt ( curIndex ) == Citrus . VARIABLE_SUFFIX . charAt ( 0 ) ) ) || ( curIndex + 1 == str . length ( ) ) ) { if ( control == 0 ) { isVarComplete = true ; } else { control -- ; } } if ( ! isVarComplete ) { variableNameBuf . append ( str . charAt ( curIndex ) ) ; } ++ curIndex ; } final String value = context . getVariable ( variableNameBuf . toString ( ) ) ; if ( value == null ) { throw new NoSuchVariableException ( "Variable: " + variableNameBuf . toString ( ) + " could not be found" ) ; } newStr . append ( str . substring ( startIndex , searchIndex ) ) ; if ( enableQuoting ) { newStr . append ( "'" + value + "'" ) ; } else { newStr . append ( value ) ; } startIndex = curIndex ; variableNameBuf = new StringBuffer ( ) ; isVarComplete = false ; } newStr . append ( str . substring ( startIndex ) ) ; return newStr . toString ( ) ; }
Replace all variable expression in a string with its respective value . Variable values are enclosed with quotes if enabled .
455
22
28,387
protected Vertx createVertx ( VertxEndpointConfiguration endpointConfiguration ) { final Vertx [ ] vertx = new Vertx [ 1 ] ; final Future loading = new FutureFactoryImpl ( ) . future ( ) ; Handler < AsyncResult < Vertx > > asyncLoadingHandler = new Handler < AsyncResult < Vertx > > ( ) { @ Override public void handle ( AsyncResult < Vertx > event ) { vertx [ 0 ] = event . result ( ) ; loading . complete ( ) ; log . info ( "Vert.x instance started" ) ; } } ; if ( endpointConfiguration . getPort ( ) > 0 ) { if ( log . isDebugEnabled ( ) ) { log . debug ( String . format ( "Creating new Vert.x instance '%s:%s' ..." , endpointConfiguration . getHost ( ) , endpointConfiguration . getPort ( ) ) ) ; } VertxOptions vertxOptions = new VertxOptions ( ) ; vertxOptions . setClusterPort ( endpointConfiguration . getPort ( ) ) ; vertxOptions . setClusterHost ( endpointConfiguration . getHost ( ) ) ; vertxFactory . clusteredVertx ( vertxOptions , asyncLoadingHandler ) ; } else { if ( log . isDebugEnabled ( ) ) { log . debug ( String . format ( "Creating new Vert.x instance '%s:%s' ..." , endpointConfiguration . getHost ( ) , 0L ) ) ; } VertxOptions vertxOptions = new VertxOptions ( ) ; vertxOptions . setClusterPort ( 0 ) ; vertxOptions . setClusterHost ( endpointConfiguration . getHost ( ) ) ; vertxFactory . clusteredVertx ( vertxOptions , asyncLoadingHandler ) ; } // Wait for full loading while ( ! loading . isComplete ( ) ) { try { log . debug ( "Waiting for Vert.x instance to startup" ) ; Thread . sleep ( 250L ) ; } catch ( InterruptedException e ) { log . warn ( "Interrupted while waiting for Vert.x instance startup" , e ) ; } } return vertx [ 0 ] ; }
Creates new Vert . x instance with default factory . Subclasses may overwrite this method in order to provide special Vert . x instance .
455
27
28,388
protected int getDateValueOffset ( String offsetString , char c ) { ArrayList < Character > charList = new ArrayList < Character > ( ) ; int index = offsetString . indexOf ( c ) ; if ( index != - 1 ) { for ( int i = index - 1 ; i >= 0 ; i -- ) { if ( Character . isDigit ( offsetString . charAt ( i ) ) ) { charList . add ( 0 , offsetString . charAt ( i ) ) ; } else { StringBuffer offsetValue = new StringBuffer ( ) ; offsetValue . append ( "0" ) ; for ( int j = 0 ; j < charList . size ( ) ; j ++ ) { offsetValue . append ( charList . get ( j ) ) ; } if ( offsetString . charAt ( i ) == ' ' ) { return Integer . valueOf ( "-" + offsetValue . toString ( ) ) ; } else { return Integer . valueOf ( offsetValue . toString ( ) ) ; } } } } return 0 ; }
Parse offset string and add or subtract date offset value .
223
12
28,389
private String createReportContent ( String suiteName , List < TestResult > results , ReportTemplates templates ) throws IOException { final StringBuilder reportDetails = new StringBuilder ( ) ; for ( TestResult result : results ) { Properties detailProps = new Properties ( ) ; detailProps . put ( "test.class" , result . getClassName ( ) ) ; detailProps . put ( "test.name" , StringEscapeUtils . escapeXml ( result . getTestName ( ) ) ) ; detailProps . put ( "test.duration" , "0.0" ) ; if ( result . isFailed ( ) ) { detailProps . put ( "test.error.cause" , Optional . ofNullable ( result . getCause ( ) ) . map ( Object :: getClass ) . map ( Class :: getName ) . orElse ( result . getFailureType ( ) ) ) ; detailProps . put ( "test.error.msg" , StringEscapeUtils . escapeXml ( result . getErrorMessage ( ) ) ) ; detailProps . put ( "test.error.stackTrace" , Optional . ofNullable ( result . getCause ( ) ) . map ( cause -> { StringWriter writer = new StringWriter ( ) ; cause . printStackTrace ( new PrintWriter ( writer ) ) ; return writer . toString ( ) ; } ) . orElse ( result . getFailureStack ( ) ) ) ; reportDetails . append ( PropertyUtils . replacePropertiesInString ( templates . getFailedTemplate ( ) , detailProps ) ) ; } else { reportDetails . append ( PropertyUtils . replacePropertiesInString ( templates . getSuccessTemplate ( ) , detailProps ) ) ; } } Properties reportProps = new Properties ( ) ; reportProps . put ( "test.suite" , suiteName ) ; reportProps . put ( "test.cnt" , Integer . toString ( results . size ( ) ) ) ; reportProps . put ( "test.skipped.cnt" , Long . toString ( results . stream ( ) . filter ( TestResult :: isSkipped ) . count ( ) ) ) ; reportProps . put ( "test.failed.cnt" , Long . toString ( results . stream ( ) . filter ( TestResult :: isFailed ) . count ( ) ) ) ; reportProps . put ( "test.success.cnt" , Long . toString ( results . stream ( ) . filter ( TestResult :: isSuccess ) . count ( ) ) ) ; reportProps . put ( "test.error.cnt" , "0" ) ; reportProps . put ( "test.duration" , "0.0" ) ; reportProps . put ( "tests" , reportDetails . toString ( ) ) ; return PropertyUtils . replacePropertiesInString ( templates . getReportTemplate ( ) , reportProps ) ; }
Create report file for test class .
641
7
28,390
private void createReportFile ( String reportFileName , String content , File targetDirectory ) { if ( ! targetDirectory . exists ( ) ) { if ( ! targetDirectory . mkdirs ( ) ) { throw new CitrusRuntimeException ( "Unable to create report output directory: " + getReportDirectory ( ) + ( StringUtils . hasText ( outputDirectory ) ? "/" + outputDirectory : "" ) ) ; } } try ( Writer fileWriter = new FileWriter ( new File ( targetDirectory , reportFileName ) ) ) { fileWriter . append ( content ) ; fileWriter . flush ( ) ; } catch ( IOException e ) { log . error ( "Failed to create test report" , e ) ; } }
Creates the JUnit report file
155
7
28,391
public ProcessingReport validate ( Message message , List < JsonSchemaRepository > schemaRepositories , JsonMessageValidationContext validationContext , ApplicationContext applicationContext ) { return validate ( message , jsonSchemaFilter . filter ( schemaRepositories , validationContext , applicationContext ) ) ; }
Validates the given message against a list of JsonSchemaRepositories under consideration of the actual context
61
21
28,392
private GraciousProcessingReport validate ( Message message , List < SimpleJsonSchema > jsonSchemas ) { if ( jsonSchemas . isEmpty ( ) ) { return new GraciousProcessingReport ( true ) ; } else { List < ProcessingReport > processingReports = new LinkedList <> ( ) ; for ( SimpleJsonSchema simpleJsonSchema : jsonSchemas ) { processingReports . add ( validate ( message , simpleJsonSchema ) ) ; } return new GraciousProcessingReport ( processingReports ) ; } }
Validates a message against all schemas contained in the given json schema repository
117
15
28,393
private ProcessingReport validate ( Message message , SimpleJsonSchema simpleJsonSchema ) { try { JsonNode receivedJson = objectMapper . readTree ( message . getPayload ( String . class ) ) ; return simpleJsonSchema . getSchema ( ) . validate ( receivedJson ) ; } catch ( IOException | ProcessingException e ) { throw new CitrusRuntimeException ( "Failed to validate Json schema" , e ) ; } }
Validates a given message against a given json schema
101
10
28,394
protected Message invokeEndpointAdapter ( MailMessage mail ) { if ( splitMultipart ) { return split ( mail . getPayload ( MailRequest . class ) . getBody ( ) , mail . getHeaders ( ) ) ; } else { return getEndpointAdapter ( ) . handleMessage ( mail ) ; } }
Invokes the endpoint adapter with constructed mail message and headers .
68
12
28,395
private Message split ( BodyPart bodyPart , Map < String , Object > messageHeaders ) { MailMessage mailRequest = createMailMessage ( messageHeaders , bodyPart . getContent ( ) , bodyPart . getContentType ( ) ) ; Stack < Message > responseStack = new Stack <> ( ) ; if ( bodyPart instanceof AttachmentPart ) { fillStack ( getEndpointAdapter ( ) . handleMessage ( mailRequest . setHeader ( CitrusMailMessageHeaders . MAIL_CONTENT_TYPE , bodyPart . getContentType ( ) ) . setHeader ( CitrusMailMessageHeaders . MAIL_FILENAME , ( ( AttachmentPart ) bodyPart ) . getFileName ( ) ) ) , responseStack ) ; } else { fillStack ( getEndpointAdapter ( ) . handleMessage ( mailRequest . setHeader ( CitrusMailMessageHeaders . MAIL_CONTENT_TYPE , bodyPart . getContentType ( ) ) ) , responseStack ) ; } if ( bodyPart . hasAttachments ( ) ) { for ( AttachmentPart attachmentPart : bodyPart . getAttachments ( ) . getAttachments ( ) ) { fillStack ( split ( attachmentPart , messageHeaders ) , responseStack ) ; } } return responseStack . isEmpty ( ) ? null : responseStack . pop ( ) ; }
Split mail message into several messages . Each body and each attachment results in separate message invoked on endpoint adapter . Mail message response if any should be sent only once within test case . However latest mail response sent by test case is returned others are ignored .
286
49
28,396
private void registerJsonSchemaRepository ( Element element , ParserContext parserContext ) { BeanDefinitionBuilder builder = BeanDefinitionBuilder . genericBeanDefinition ( JsonSchemaRepository . class ) ; addLocationsToBuilder ( element , builder ) ; parseSchemasElement ( element , builder , parserContext ) ; parserContext . getRegistry ( ) . registerBeanDefinition ( element . getAttribute ( ID ) , builder . getBeanDefinition ( ) ) ; }
Registers a JsonSchemaRepository definition in the parser context
101
14
28,397
private void registerXmlSchemaRepository ( Element element , ParserContext parserContext ) { BeanDefinitionBuilder builder = BeanDefinitionBuilder . genericBeanDefinition ( XsdSchemaRepository . class ) ; BeanDefinitionParserUtils . setPropertyReference ( builder , element . getAttribute ( "schema-mapping-strategy" ) , "schemaMappingStrategy" ) ; addLocationsToBuilder ( element , builder ) ; parseSchemasElement ( element , builder , parserContext ) ; parserContext . getRegistry ( ) . registerBeanDefinition ( element . getAttribute ( ID ) , builder . getBeanDefinition ( ) ) ; }
Registers a XsdSchemaRepository definition in the parser context
140
14
28,398
private boolean isXmlSchemaRepository ( Element element ) { String schemaRepositoryType = element . getAttribute ( "type" ) ; return StringUtils . isEmpty ( schemaRepositoryType ) || "xml" . equals ( schemaRepositoryType ) ; }
Decides whether the given element is a xml schema repository .
57
12
28,399
private void addLocationsToBuilder ( Element element , BeanDefinitionBuilder builder ) { Element locationsElement = DomUtils . getChildElementByTagName ( element , LOCATIONS ) ; if ( locationsElement != null ) { List < Element > locationElements = DomUtils . getChildElementsByTagName ( locationsElement , LOCATION ) ; List < String > locations = locationElements . stream ( ) . map ( locationElement -> locationElement . getAttribute ( "path" ) ) . collect ( Collectors . toList ( ) ) ; if ( ! locations . isEmpty ( ) ) { builder . addPropertyValue ( LOCATIONS , locations ) ; } } }
Adds the locations contained in the given locations element to the BeanDefinitionBuilder
141
14